1

I want to detect in my JS script that the code is running against a forked network, and therefore run conditional code based on this.

In hardhat.config.js I have added to networks:

networks: {
    hardhat: {
      accounts,
      forking: {
        url: "https://polygon-mumbai.g.alchemy.com/v2/<key>",
      },
    },
}

I start my node which forks mumbai using the below command:

hh node --fork https://polygon-mumbai.g.alchemy.com/v2/<key> --port 7545 --verbose --fork-block-number 28885869

I have a JS script that needs to detect whether the it is being run on hardhat's local network, or the forked mumbai network. This is obviously very important because the state of the fork will be very different to the state of the hh local network, which is a blank slate. For example, there will be contracts that are deployed on mumbai that i need to interact with, that wont be deployed on the hh local network, and so I must deploy them only if the local network is active.

How can i detect in my JS script that the code is running on a forked network? I have tried passing in a custom chainId like so:

networks: {
    hardhat: {
      accounts,
      forking: {
        url: "https://polygon-mumbai.g.alchemy.com/v2/<key>",
        chainId: 12345
      },
    },
}

And then in my JS code:

const { chainId } = await ethers.provider.getNetwork();
console.log(chainId);
if (chainId == 12345) {...do something...}

but obv this doesn't work because both the fork and the hh local network use 31337 as their chainId...

I feel like this is a pretty key feature so there must be a way?

1

1 Answer 1

1

This will work

import { ethers, deployments, network } from 'hardhat';

console.log(network.config.forking.enabled);

and you will get true as log if you used forking:true in your hardhat config.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.