Hardhat Custom ChainId – How to Set for Localhost When Forking Network

blockchain-forkclihardhatnodessolidity

I am trying to fork polygon testnet (mumbai) for local development and run my forked node with a custom chainId. This is so that my JS scripts can identify the chain that is running, and therefore execute the appropriate code (eg deploy contracts, use correct addresses etc).

In my hardhat.config.js i have this:

networks: {
   mumbai_fork: {
      url: "http://127.0.0.1:7545",
      chainId: 7545,
    },
}

As you can see, I am trying to set the chainId to my custom value, 7545. When I fork the network using this:

npx hardhat node --fork https://polygon-mumbai.g.alchemy.com/v2/<my-key> --port 7545 --verbose

I want the resulting node to run with the chainId of 7545.

However, when I run my JS scripts, I get the error:

Error HH101: Hardhat was set to use chain id 7545, but connected to a chain with id 31337.

How do I run my forked node with a chainId of 7545 and then connect hardhat to my custom 7545 chain on localhost:7545? It would be great if there was a flag I could append to the CLI command when starting the node, something like --chainid 7545?

Best Answer

Unfortunately, this is not possible, even though there is an issue open for more than two years.

If you configure the network in the hardhat.config.js, it will either have the wrong chainId, or it won't be a hardhat network, which will then make it impossible to use hardhat network helpers, or any hardhat_ prefixed chain command.

The only feasible solution I currently see is to use Anvil. Start it in another terminal and configure it from your tests.

No bad word about Hardhat here... 😬

Related Topic