11J ethereum hardhat : Forking other networks
Tags: blockchain, ethereum, hardhat
Published: 2022-07-27 16:08:42

• [Forking from mainnet](#index1)  
• [Pinning a block](#index2)  
• [Custom HTTP headers](#index3)  
• [Impersonating accounts](#index4)  
• [Resetting the fork](#index5)  
• [Using a custom hardfork history](#index6)   
• [hardhat Tutorials , hardhat 教程](#index98)   
• [Contact 联系方式](#index99)

# <span id='index1'>• Forking from mainnet</span>  

The easiest way to try this feature is to start a node from the command line:

```
npx hardhat node --fork https://eth-mainnet.alchemyapi.io/v2/<key>
```

You can also configure Hardhat Network to always do this:

```js
networks: {
  hardhat: {
    forking: {
      url: "https://eth-mainnet.alchemyapi.io/v2/<key>",
    }
  }
}
```

(Note that you'll need to replace the `<key>` component of the URL with your personal Alchemy API key.)

By accessing any state that exists on mainnet, Hardhat Network will pull the data and expose it transparently as if it was available locally.

# <span id='index2'>• Pinning a block</span>  

Hardhat Network will by default fork from the latest mainnet block. While this might be practical depending on the context, to set up a test suite that depends on forking we recommend forking from a specific block number.

There are two reasons for this:

- The state your tests run against may change between runs. This could cause your tests or scripts to behave differently.
- Pinning enables caching. Every time data is fetched from mainnet, Hardhat Network caches it on disk to speed up future access. If you don't pin the block, there's going to be new data with each new block and the cache won't be useful. We measured up to 20x speed improvements with block pinning.

**You will need access to a node with archival data for this to work.** This is why we recommend [Alchemy], since their free plans include archival data.

To pin the block number:

```js
networks: {
  hardhat: {
    forking: {
      url: "https://eth-mainnet.alchemyapi.io/v2/<key>",
      blockNumber: 14390000
    }
  }
}
```

If you are using the `node` task, you can also specify a block number with the `--fork-block-number` flag:

```
npx hardhat node --fork https://eth-mainnet.alchemyapi.io/v2/<key> --fork-block-number 14390000
```

# <span id='index3'>• Custom HTTP headers</span>  

You can add extra HTTP headers that will be used in any request made to the forked node. One reason to do this is for authorization: instead of including your credentials in the URL, you can use a bearer token via a custom HTTP header:

```js
networks: {
  hardhat: {
    forking: {
      url: "https://ethnode.example.com",
      httpHeaders: {
        "Authorization": "Bearer <key>"
      }
    }
  }
}
```

# <span id='index4'>• Impersonating accounts</span>  

Hardhat Network allows you to impersonate any address. This lets you send transactions from that account even if you don't have access to its private key.

The easiest way to do this is with the `ethers.getImpersonatedSigner` method, which is added to the `ethers` object by the [`hardhat-ethers`](/hardhat-runner/plugins/nomiclabs-hardhat-ethers) plugin:

```js
const impersonatedSigner = await ethers.getImpersonatedSigner("0x1234567890123456789012345678901234567890");
await impersonatedSigner.sendTransaction(...);
```

Alternatively, you can use the [`impersonateAccount`](</hardhat-network-helpers/docs/reference#impersonateaccount(address)>) helper and then obtain the signer for that address:

```js
const helpers = require("@nomicfoundation/hardhat-network-helpers");

const address = "0x1234567890123456789012345678901234567890";
await helpers.impersonateAccount(address);
const impersonatedSigner = await ethers.getSigner(address);
```

# <span id='index5'>• Resetting the fork</span>  

You can manipulate forking during runtime to reset back to a fresh forked state, fork from another block number or disable forking by calling `hardhat_reset`:

```ts
await network.provider.request({
  method: "hardhat_reset",
  params: [
    {
      forking: {
        jsonRpcUrl: "https://eth-mainnet.alchemyapi.io/v2/<key>",
        blockNumber: 14390000,
      },
    },
  ],
});
```

You can disable forking by passing empty params:

```ts
await network.provider.request({
  method: "hardhat_reset",
  params: [],
});
```

This will reset Hardhat Network, starting a new instance in the state described [here](../reference/#initial-state).

# <span id='index6'>• Using a custom hardfork history</span>  

If you're forking an unusual network, and if you want to execute EVM code in the context of a historical block retrieved from that network, then you will need to configure Hardhat Network to know which hardforks to apply to which blocks. (If you're forking a well-known network, Hardhat Network will automatically choose the right hardfork for the execution of your EVM code, based on known histories of public networks, so you can safely ignore this section.)

To supply Hardhat Network with a hardfork activation history for your custom chain, use the `networks.hardhat.chains` config field:

```js
networks: {
  hardhat: {
    chains: {
      99: {
        hardforkHistory: {
          berlin: 10000000,
          london: 20000000,
        },
      }
    }
  }
}
```

In this context, a "historical block" is one whose number is prior to the block you forked from. If you try to run code in the context of a historical block, _without_ having a hardfork history, then an error will be thrown. The known hardfork histories of most public networks are assumed as defaults.

If you run code in the context of a _non_-historical block, then Hardhat Network will simply use the hardfork specified by the `hardfork` field on its config, eg `networks: { hardhat: { hardfork: "london" } }`, rather than consulting the hardfork history configuration.

See also [the `chains` entry in the Hardhat Network configuration reference](../reference/#chains).
 
# <span id='index98'>• hardhat Tutorials , hardhat 教程</span>  
CN 中文 Github  [hardhat 教程 : github.com/565ee/hardhat_CN](https://github.com/565ee/hardhat_CN)  
CN 中文 CSDN    [hardhat 教程 : blog.csdn.net/wx468116118](https://blog.csdn.net/wx468116118/category_11923442.html)  
EN 英文 Github  [hardhat Tutorials : github.com/565ee/hardhat_EN](https://github.com/565ee/hardhat_EN)  

# <span id='index99'>• Contact 联系方式</span>  
Homepage   : [565.ee](https://565.ee)  
GitHub     : [github.com/565ee](https://github.com/565ee)  
Email      : 565.eee@gmail.com  
Facebook   : [facebook.com/565.ee](https://facebook.com/565.ee)  
Twitter    : [twitter.com/565_eee](https://twitter.com/565_eee)  
Telegram   : [t.me/ee_565](https://t.me/ee_565)