Skip to main content

Command Palette

Search for a command to run...

Mainnet forking

Published
•1 min read•View as Markdown

Ok so sometimes testing and working with smart contracts in the testnet doesn't work. This is because there are some smart contracts that are only deployed in the mainnet and thus we need some way to interact with such smart contracts and get hold of the mainnet functionality without actually using the mainnet.

This is possible with the help of hardhat. The hardhat provides a functionality of mainnet forking

Hence basically we are creating our own private hardhat network that forks the mainnet.

This can be done using the following steps:

npm install --save-dev hardhat and also install all its dependencies

Now npx hardhat

Once everything is done go to the hardhat.config.js file and write the following code. In our case we are forking the polygon mainnet

For this pick up an endpoint from the Alchemy of polygon mainnet

require("@nomicfoundation/hardhat-toolbox");

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.8.10",
  networks: {
    hardhat: {
      forking: {
        enabled: true,
        url: "https://polygon-mainnet.g.alchemy.com/v2/S-cF3Pyunr77RoGtc9Igwd9vY7mJLGP5",
      },
      chainId: 137,
    },
  },
};

Now inside the terminal write the following command:

npx hardhat node --network hardhat

This will give us a bunch of account addresses and their private keys

More from this blog

Dhruv's Web development journey

64 posts