Created
April 23, 2025 08:05
-
-
Save bh2smith/4c4480290d88f43b0cc36c8e296ee25c to your computer and use it in GitHub Desktop.
Example Multicall
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
createPublicClient, | |
decodeFunctionResult, | |
encodeFunctionData, | |
http, | |
parseAbi, | |
} from "viem"; | |
import { mainnet } from "viem/chains"; | |
const multicallAbi = [ | |
{ | |
type: 'function', | |
name: 'aggregate', | |
inputs: [ | |
{ | |
name: 'calls', | |
type: 'tuple[]', | |
components: [ | |
{ name: 'target', type: 'address' }, | |
{ name: 'callData', type: 'bytes' }, | |
], | |
}, | |
], | |
outputs: [ | |
{ name: 'blockNumber', type: 'uint256' }, | |
{ name: 'returnData', type: 'bytes[]' }, | |
], | |
stateMutability: 'view', | |
}, | |
] as const; | |
const run = async (): Promise<void> => { | |
const client = createPublicClient({ | |
chain: mainnet, | |
transport: http(), | |
}); | |
const MULTICALL_ADDRESS = "0x5ba1e12693dc8f9c48aad8770482f4739beed696"; // Mainnet Multicall v2 | |
const calls = [ | |
{ | |
target: "0x6b175474e89094c44da98b954eedeac495271d0f" as `0x${string}`, // DAI contract | |
callData: encodeFunctionData({ | |
abi: parseAbi(["function totalSupply() view returns (uint256)"]), | |
functionName: "totalSupply", | |
}), | |
}, | |
{ | |
target: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" as `0x${string}`, // USDC contract | |
callData: encodeFunctionData({ | |
abi: parseAbi(["function name() view returns (string)"]), | |
functionName: "name", | |
}), | |
}, | |
] as const; | |
const result = await client.readContract({ | |
address: MULTICALL_ADDRESS, | |
abi: multicallAbi, | |
functionName: "aggregate", | |
args: [calls], | |
}); | |
console.log(result); | |
const [, returnData] = result; | |
const daiTotalSupply = decodeFunctionResult({ | |
abi: parseAbi(["function totalSupply() view returns (uint256)"]), | |
functionName: "totalSupply", | |
data: returnData[0], | |
}); | |
const usdcName = decodeFunctionResult({ | |
abi: parseAbi(["function name() view returns (string)"]), | |
functionName: "name", | |
data: returnData[1], | |
}); | |
console.log({ daiTotalSupply, usdcName }); | |
}; | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment