typescriptethereumintegrationadvanced
Batch Read with Multicall
Batch multiple contract reads into a single RPC call using viem's multicall.
All snippets
Code
typescript
import { createPublicClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";
const client = createPublicClient({
chain: mainnet,
transport: http(),
});
const erc20Abi = parseAbi([
"function name() view returns (string)",
"function decimals() view returns (uint8)",
"function totalSupply() view returns (uint256)",
]);
const results = await client.multicall({
contracts: [
{ address: "0xA0b8...eB48", abi: erc20Abi, functionName: "name" },
{ address: "0xA0b8...eB48", abi: erc20Abi, functionName: "decimals" },
{ address: "0xA0b8...eB48", abi: erc20Abi, functionName: "totalSupply" },
],
});
console.log(results);
// => [{ result: "USD Coin" }, { result: 6n }, { result: 1000000...n }]Explanation
Multicall batches multiple read-only calls into a single RPC request via a Multicall3 contract. This reduces network round-trips and is essential when querying many token balances or metadata in one go.
multicallviembatchtypescript