Multicall Batching

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 SDK
const kit = new SomniaAgentKit({
  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!,
  },
});

await kit.initialize();

// Get multicall instance (recommended)
const multicall = 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

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:

See Also

Last updated