0
0
Blockchain / Solidityprogramming~10 mins

Fork testing (mainnet fork) in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Fork testing lets you try out changes on a copy of the real blockchain. This helps you check if your code works without risking real money.

You want to test a smart contract upgrade safely before using it on the real network.
You need to debug a transaction that failed on the main blockchain.
You want to simulate how your decentralized app behaves with real blockchain data.
You are developing a new feature and want to see its effect on current blockchain state.
You want to test interactions with existing contracts without spending real tokens.
Syntax
Blockchain / Solidity
npx hardhat node --fork <MAINNET_RPC_URL> --fork-block-number <BLOCK_NUMBER>

Replace <MAINNET_RPC_URL> with your Ethereum mainnet provider URL.

The --fork-block-number option lets you pick a specific block to fork from.

Examples
This starts a local blockchain forked from the latest mainnet block.
Blockchain / Solidity
npx hardhat node --fork https://mainnet.infura.io/v3/YOUR_INFURA_KEY
This forks the mainnet at block number 17,000,000 for consistent testing.
Blockchain / Solidity
npx hardhat node --fork https://eth-mainnet.alchemyapi.io/v2/YOUR_ALCHEMY_KEY --fork-block-number 17000000
Sample Program

This script runs on a forked mainnet. It shows your account address, balance, and reads the name of the DAI token from the real contract.

Blockchain / Solidity
import { ethers } from "hardhat";

async function main() {
  const [deployer] = await ethers.getSigners();
  console.log("Using account:", deployer.address);

  // Check balance on forked mainnet
  const balance = await deployer.getBalance();
  console.log("Balance:", ethers.utils.formatEther(balance), "ETH");

  // Example: Interact with an existing contract on fork
  const daiAddress = "0x6B175474E89094C44Da98b954EedeAC495271d0F"; // DAI token
  const daiAbi = ["function name() view returns (string)"];
  const dai = new ethers.Contract(daiAddress, daiAbi, deployer);
  const name = await dai.name();
  console.log("DAI token name:", name);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
OutputSuccess
Important Notes

Fork testing requires a mainnet RPC URL from providers like Infura or Alchemy.

Balances and contract states reflect the chosen block number at fork time.

Transactions on the fork do not affect the real mainnet and cost no real ETH.

Summary

Fork testing creates a safe copy of the mainnet blockchain for testing.

It helps you try code with real blockchain data without risk.

Use it to debug, test upgrades, and simulate real user interactions.