Categories
Crypto hardhat

How to use ethereum-multicall on a local hardhat node

ethers-multicall actually uses MakerDAO multicall contracts for multicall functionality. On a local chain this contract is not deployed, therefore the request fails with

Uncaught (in promise) Error: invalid contract address or ENS name (argument="addressOrName", value=undefined, code=INVALID_ARGUMENT, version=contracts/5.6.2)

To fix this issue, the MakerDAO-s multicall contract needs to be deployed on the local node.

  • Copy the Multicall.sol contract to your local project. The contract is available in MakerDAO repository
  • Add this contract to your deployments. Be sure to only deploy to localhost.
const deploy: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
    // @ts-ignore
    const { deployments, getNamedAccounts, network } = hre
    const chainId = network.config.chainId ?? 31337

    // only deploy to local chain
    if (chainId !== LOCAL_CHAIN_ID) return

    const { deployer } = await getNamedAccounts()
    const { deploy  } = deployments

    console.log("--- deploying Multicall")
    await deploy("Multicall", {
        from: deployer,
        args: [],
        log: true,
        waitConfirmations: 1,
    })
    console.log("---")
}

Result of the deployment:

--- deploying Multicall
deploying "Multicall" (tx: 0x5305de50721abf4b55da6cc4147d72abc5efb5b1e41de984ca6e9456905c26f4)...: deployed at 0x5FbDB2315678afecb367f032d93F642f64180aa3 with 646671 gas
---

Make the ethereum-multicall use this contract for local chain

import { setMulticallAddress } from "ethers-multicall"

setMulticallAddress(LOCAL_CHAIN_ID, "0x5FbDB2315678afecb367f032d93F642f64180aa3")

Now when using multicall on localhost, the contract queries are forwarded to the correct multicall contract, and they return without error.

Note

Please note that ethers-multicall is all or nothing. If one call fails, the whole batch fails. Consider ethereum-multicall or MakerDAO-s multicall.js, which use the Multicall2 contract. This contract returns both successful and failed calls.


Source code

Mint a Knowledge Token to access the example Typescript project with Multicall2 deployment to a hardhat local node. Also included is a React frontend that reads values from a contract with ethereum-multicall.