Introduction to Forking the Mainnet

Published by Mario Oettler on

When developing or auditing smart contracts, it is sometimes necessary to test them against existing smart contracts like decentralized exchanges, flash loans, etc.

In order to do that, we have three possibilities:

  1. Find the smart contracts on a public testnet: Here, we need to deploy our smart contract to the testnet and try to interact with the contracts we need to interact with. This is a bit slow, and we need to get test-ETH first. Besides, we don’t have complete control over the other smart contracts, and it is not said that the contract in question is there at all.
  2. Set up a local testnet (either virtually or real) and clone all contracts from the mainnet. Here, we might have control over all contracts, but this is a cumbersome process as we need to compile and deploy all other contracts first. Another problem is that the state (balance of certain accounts, stored data, etc.) differs from the mainnet.
  3. Fork the mainnet virtually. This option is the most convenient one. We have access to all contracts on the mainnet and we can impersonate arbitrary accounts or assign arbitrary balances to accounts. This gives us full control over the whole (virtual) network. The downside is that we need to connect to an archive node. But there are a few archive nodes available that have some free plans.

In the following topics, we learn how to fork the mainnet with hardhat, impersonate an account, and assign an arbitrary balance to an account.

Categories: