Complete guide for optimizing gas costs by batching multiple contract calls into a single transaction.
Overview
Multicall allows you to batch multiple contract read operations into a single RPC call, significantly reducing network overhead and improving performance.
Benefits
⚡ Faster: Single RPC call instead of multiple
💰 Cheaper: Reduced network overhead
🎯 Atomic: All calls execute in the same block
📊 Efficient: Perfect for dashboards and analytics
Initialize Multicall
import{SomniaAgentKit,SOMNIA_NETWORKS}from'somnia-agent-kit';// Initialize SDKconstkit=newSomniaAgentKit({network:SOMNIA_NETWORKS.testnet,contracts:{agentRegistry:process.env.AGENT_REGISTRY_ADDRESS!,agentManager:process.env.AGENT_MANAGER_ADDRESS!,agentExecutor:process.env.AGENT_EXECUTOR_ADDRESS!,agentVault:process.env.AGENT_VAULT_ADDRESS!,},});awaitkit.initialize();// Get multicall instance (recommended)constmulticall=kit.getMultiCall();
Basic Usage
Batch Contract Reads
Advanced Usage
Batch with Error Handling
Get Block Information
Complete Example: Dashboard Data
Complete Example: Portfolio Tracker
Performance Comparison
Without Multicall (Sequential)
With Multicall (Batched)
Best Practices
1. Batch Related Calls
2. Use tryAggregate for Optional Data
3. Limit Batch Size
4. Cache Multicall Results
5. Handle Errors Gracefully
Multicall Contract
The SDK uses the Multicall3 contract deployed on Somnia:
// Some calls might fail (agent doesn't exist, etc.)
const results = await multicall.tryAggregate(false, calls);
results.forEach((result, index) => {
if (result.success) {
// Process successful result
} else {
// Handle failure gracefully
console.log(`Call ${index} failed`);
}
});
// Don't batch too many calls at once
const BATCH_SIZE = 50;
for (let i = 0; i < allCalls.length; i += BATCH_SIZE) {
const batch = allCalls.slice(i, i + BATCH_SIZE);
const results = await multicall.aggregate(batch);
// Process batch results
}