Multicall
Batch multiple contract read calls into one RPC with multicall
Loading...
Batch multiple contract read calls into one RPC with multicall
Multicall executes multiple contract read calls in a single RPC round-trip using the Multicall3 contract (or deployless execution). Each call is ABI-encoded and decoded; results are returned in order with success/failure per call.
import ( "github.com/ethereum/go-ethereum/common" "github.com/ChefBingbong/viem-go/abi" "github.com/ChefBingbong/viem-go/actions/public")parsedABI, _ := abi.Parse(erc20ABI)
results, err := public.Multicall(ctx, publicClient, public.MulticallParameters{ Contracts: []public.MulticallContract{ { Address: common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), ABI: parsedABI, FunctionName: "balanceOf", Args: []any{ownerAddr}, }, { Address: common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), ABI: parsedABI, FunctionName: "totalSupply", }, }, AllowFailure: func() *bool { b := true; return &b }(),})if err != nil { log.Fatal(err)}for i, r := range results { if r.Status == "success" { fmt.Println(i, r.Result) } else { fmt.Println(i, r.Error) }}[]MulticallContractcommon.Address), ABI (*abi.ABI), FunctionName (string), Args ([]any). Each element is one contract call.*booltrue"failure" and an error; the whole multicall does not fail. If false, the first failure aborts the multicall.int1024*common.Address*uint64 or BlockTagboolfalseint4([]MulticallResult, error). MulticallResult has Status ("success" or "failure"), Result (any), and Error (error).