How to Fork Ethereum Mainnet With Hardhat
Tags: web3, webdev, programming, blockchain
Published: 2023-02-08 01:09:27

During the development or review of smart contracts, it may be necessary to evaluate your smart contracts against pre-existing smart contracts such as decentralized exchanges or flash loans without the cost of spending real ether. 
In this article, you will learn how to fork Ethereum mainnet  using Hardhat.

**What is Hardhat?**
Hardhat is an Ethereum development environment for professionals, it comes with tools such as Hardhat runner, network, and VSCode extension that make development flexible, extensible, and fast.

**Why Fork Ethereum Mainnet?**
- It allows manipulating the signer even if you don’t have access to its private key.
- It allows testing a contract with access controls, address is all needed to impersonate it.
- It allows testing mainnet smart contracts without using real ethers.
- It allows you to write script impersonating mainnet account. 

**Prerequisite:**

Install node and npm


**Create New Hardhat Project**

We will be using a hardhat project, you can feel free to skip this if you already have.

- **Create folder project:** Open your terminal and enter the command below.

```
mkdir mainnet-fork-tutorial
cd mainnet-fork-tutorial
```
 

- **Initiate npm in the project:** Initialize npm in the created project.

```
npm init -y
```

- **Install hardhat**

```
npm install --save-dev hardhat
```

- **In the same directory where you installed Hardhat run:**

```
npx hardhat
```

Select `create a JavaScript project` with your keyboard and hit enter, to create a fresh hardhat project; this might take time depending on your internet connection.

- **Install dotenv:** we will be using dotenv to store environment variables.

```bash
npm i dotenv
```
**Create API Key**

We need an remote procedure call (RPC) node, Hardhat recommends we make use [Alchemy](https://auth.alchemy.com/) because they offer Full archive nodes; which are a type of node that contains all the information about a blockchain from the genesis or original block.

- **Create an alchemy account:** Create your free alchemy account at https://auth.alchemy.com/signup and confirm your email.

![Create an alchemy account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7e0yq7tf2agf9m7sm8hp.png)

- **Create an app:** In your alchemy dashboard, click on + CREATE APP button. This brings a popup to create a new app. Fill in the name and description in the form and click CREATE APP button. Example:

1. Name: mainnet-fork
2.  Description: Description of what your app does so you can keep track.
3.  Chain: Ethereum (default selection)
4.  Network: Mainnet (default selection)

![Create an app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/108n5i901ii4yku7h4nn.jpg)

- **View key:** Once your new app is created, the pop disappears. The app appeared under the Personal Apps table. Locate the newly created app in the table and click on the view key button. Copy the API KEY.

![COPY HTTPS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ljh4t3v548gg9ntsaqx5.png)

**Fork Ethereum mainnet**

Open the newly created **mainnet-fork-tutorial** project with your favorite editor.

- **Create .env file:** create a .env file in the root of mainnet-fork-tutorial project.

```
MAINNET_RPC_URL=your_app_api_url_from_alchemy
```

- **Edit hardhat.config.js:** Edit `hardhat.config.js` we will be adding a new network called hardhat in module.exports object.

```
require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config();

module.exports = {
  solidity: "0.8.17",
  networks: {
    hardhat: {
      forking: {
        url: process.env.MAINNET_RPC_URL,
      },
      chainId: 1,
    },
  },
};
```

You can also pin the block number:

```
networks: {
  hardhat: {
    forking: {
      url: process.env.MAINNET_RPC_URL,
      blockNumber: 14390000
    }
  }
}
```

- **Run Network:** In your terminal, enter the command below to start hardhat node.

```
npx hardhat node
```

![Congratulations you just forked mainnet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yved34gkvlgg2ed6vdc1.png)

**Conclusion**
Now you have forked mainnet locally, you can take it a step further by deploying smart contract or [Impersonate a mainnet Accounts With Hardhat](https://medium.com/coinmonks/impersonating-accounts-with-hardhat-21212c94dcec), the use case is unlimited. 

**Resources:**

[Forking other networks | Ethereum development environment for professionals by Nomic Foundation](https://hardhat.org/hardhat-network/docs/guides/forking-other-networks)

[How to Fork Ethereum Mainnet](https://docs.alchemy.com/docs/how-to-fork-ethereum-mainnet)