Hardhat Mainnet Forking: Test Against Real DeFi Protocols

Hardhat Mainnet Forking: Test Against Real DeFi Protocols

Testing DeFi protocols in isolation is like testing a race car on a treadmill. Your unit tests pass, your mocks behave perfectly, and then you deploy to mainnet and discover that Uniswap's liquidity math doesn't work the way your mock assumed. Hardhat mainnet forking solves this by letting you run your tests against a real, live snapshot of the blockchain — complete state, real contract addresses, actual token balances, genuine protocol behavior.

This guide covers everything you need to use Hardhat's forking feature effectively: setting up forks of Ethereum mainnet and Arbitrum, impersonating whale accounts, managing fork state between tests, integrating with Aave and Uniswap, and keeping test suites fast enough to run in CI.

What Mainnet Forking Actually Does

When you enable forking in Hardhat, it spins up a local Hardhat Network node that fetches state from a real chain via an archive RPC endpoint. The first time your test calls balanceOf on USDC, Hardhat fetches that slot from the archive node and caches it locally. Subsequent reads hit the local cache. Writes happen only on the local fork — the real chain is never touched.

The result: you get a deterministic, fully controllable copy of mainnet at a specific block number, with every contract, every token balance, and every storage slot exactly as it was at that block.

Setting Up Your Fork

Install Hardhat if you haven't already, then configure forking in hardhat.config.ts:

import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";

const config: HardhatUserConfig = {
  solidity: "0.8.24",
  networks: {
    hardhat: {
      forking: {
        url: process.env.MAINNET_RPC_URL!,
        blockNumber: 19_800_000, // Pin to a specific block
        enabled: true,
      },
      chainId: 1,
    },
    arbitrum_fork: {
      url: "http://127.0.0.1:8545",
      chainId: 42161,
    },
  },
};

export default config;

You need an archive node RPC. Alchemy and Infura both offer archive access. For Arbitrum forking:

networks: {
  hardhat: {
    forking: {
      url: process.env.ARBITRUM_RPC_URL!,
      blockNumber: 200_000_000,
    },
    chainId: 42161,
  },
},

Pinning the block number is critical for reproducible tests. Without it, your fork moves forward as the chain does, and a test that passed yesterday might fail today because a whale moved liquidity.

Impersonating Accounts

The most powerful feature of mainnet forking is account impersonation. You can take control of any address — a Binance hot wallet, a protocol treasury, a whale — and send transactions as them.

import { ethers, network } from "hardhat";
import { IERC20 } from "../typechain-types";

const USDC_ADDRESS = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
const USDC_WHALE = "0x47ac0Fb4F2D84898e4D9E7b4DaB3C24507a6D503"; // Binance

async function impersonateAndFundUSDC(recipient: string, amount: bigint) {
  // Tell Hardhat to allow transactions from this address
  await network.provider.request({
    method: "hardhat_impersonateAccount",
    params: [USDC_WHALE],
  });

  // Fund the impersonated account with ETH for gas
  await network.provider.send("hardhat_setBalance", [
    USDC_WHALE,
    "0x56BC75E2D63100000", // 100 ETH in hex
  ]);

  const whaleSigner = await ethers.getImpersonatedSigner(USDC_WHALE);
  const usdc = await ethers.getContractAt("IERC20", USDC_ADDRESS, whaleSigner);
  
  await usdc.transfer(recipient, amount);

  // Always stop impersonation when done
  await network.provider.request({
    method: "hardhat_stopImpersonatingAccount",
    params: [USDC_WHALE],
  });
}

This is invaluable for seeding test accounts with realistic token balances without needing to set up mock ERC-20 contracts.

Testing Against Uniswap V3

Here's a complete example of testing a contract that swaps tokens via Uniswap V3:

import { expect } from "chai";
import { ethers, network } from "hardhat";
import { MySwapper } from "../typechain-types";

const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
const SWAP_ROUTER = "0xE592427A0AEce92De3Edee1F18E0157C05861564";
const WETH_WHALE = "0x06920C9fC643De77B99cB7670A944AD31eaAA260";

describe("MySwapper — mainnet fork", () => {
  let swapper: MySwapper;
  let testAccount: any;

  before(async () => {
    [testAccount] = await ethers.getSigners();

    // Deploy our contract
    const MySwapper = await ethers.getContractFactory("MySwapper");
    swapper = await MySwapper.deploy(SWAP_ROUTER);

    // Seed test account with 10 WETH
    await network.provider.request({
      method: "hardhat_impersonateAccount",
      params: [WETH_WHALE],
    });
    await network.provider.send("hardhat_setBalance", [
      WETH_WHALE,
      "0x56BC75E2D63100000",
    ]);

    const whaleSigner = await ethers.getImpersonatedSigner(WETH_WHALE);
    const weth = await ethers.getContractAt("IERC20", WETH, whaleSigner);
    await weth.transfer(testAccount.address, ethers.parseEther("10"));

    await network.provider.request({
      method: "hardhat_stopImpersonatingAccount",
      params: [WETH_WHALE],
    });
  });

  it("swaps WETH for USDC at a reasonable rate", async () => {
    const weth = await ethers.getContractAt("IERC20", WETH, testAccount);
    const usdc = await ethers.getContractAt("IERC20", USDC);

    const amountIn = ethers.parseEther("1");
    await weth.approve(swapper.target, amountIn);

    const usdcBefore = await usdc.balanceOf(testAccount.address);
    await swapper.connect(testAccount).swapExactInput(
      WETH,
      USDC,
      amountIn,
      0, // amountOutMinimum — set to 0 for testing only
      3000 // pool fee tier
    );
    const usdcAfter = await usdc.balanceOf(testAccount.address);

    const received = usdcAfter - usdcBefore;
    // At the pinned block, 1 ETH should be worth at least $2000
    expect(received).to.be.greaterThan(2000n * 10n ** 6n);
  });
});

Testing Against Aave V3

Aave is another common integration target. Here's how to test supplying and borrowing:

const AAVE_POOL = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
const DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F";
const DAI_WHALE = "0x60FaAe176336dAb62e284Fe19B885B095d29fB7";

describe("Aave V3 supply and borrow", () => {
  it("supplies DAI and receives aDAI", async () => {
    const [user] = await ethers.getSigners();

    // Fund user with DAI
    await network.provider.request({
      method: "hardhat_impersonateAccount",
      params: [DAI_WHALE],
    });
    await network.provider.send("hardhat_setBalance", [DAI_WHALE, "0x56BC75E2D63100000"]);
    
    const whaleSigner = await ethers.getImpersonatedSigner(DAI_WHALE);
    const dai = await ethers.getContractAt("IERC20", DAI, whaleSigner);
    const supplyAmount = ethers.parseEther("10000");
    await dai.transfer(user.address, supplyAmount);

    await network.provider.request({
      method: "hardhat_stopImpersonatingAccount",
      params: [DAI_WHALE],
    });

    // Supply to Aave
    const pool = await ethers.getContractAt("IAaveV3Pool", AAVE_POOL, user);
    const daiUser = await ethers.getContractAt("IERC20", DAI, user);
    await daiUser.approve(AAVE_POOL, supplyAmount);
    
    await pool.supply(DAI, supplyAmount, user.address, 0);

    // Verify aDAI received
    const aDAI_ADDRESS = "0x018008bfb33d285247A21d44E50697654f754e63";
    const adai = await ethers.getContractAt("IERC20", aDAI_ADDRESS);
    const balance = await adai.balanceOf(user.address);
    
    expect(balance).to.be.closeTo(supplyAmount, ethers.parseEther("1"));
  });
});

Managing Fork State Between Tests

The biggest footgun in forking tests is state bleed between test cases. When test A deposits into Aave and test B expects a fresh state, you get false failures.

The solution is snapshots:

describe("Protocol integration suite", () => {
  let snapshotId: string;

  beforeEach(async () => {
    snapshotId = await network.provider.send("evm_snapshot", []);
  });

  afterEach(async () => {
    await network.provider.send("evm_revert", [snapshotId]);
  });

  it("test A — modifies state", async () => {
    // This test deposits into Aave, moves time forward, etc.
    // After the test, state is reverted to the snapshot
  });

  it("test B — starts from clean fork state", async () => {
    // Sees the same state as test A did — no bleed
  });
});

For more complex scenarios, you can take a snapshot at the before hook level (after expensive setup like impersonation and token seeding) and revert to that specific snapshot between tests:

describe("Vault tests", () => {
  let setupSnapshotId: string;
  let vault: MyVault;
  let user: any;
  let usdc: any;

  before(async () => {
    // Expensive setup: deploy vault, seed tokens, etc.
    [user] = await ethers.getSigners();
    vault = await deployVault();
    usdc = await seedUSDC(user.address, 100_000n * 10n ** 6n);
    
    // Take snapshot after setup, before any test mutations
    setupSnapshotId = await network.provider.send("evm_snapshot", []);
  });

  beforeEach(async () => {
    // Reset to post-setup state before each test
    await network.provider.send("evm_revert", [setupSnapshotId]);
    // Re-take snapshot since revert consumes it
    setupSnapshotId = await network.provider.send("evm_snapshot", []);
  });

  it("deposits correctly", async () => { /* ... */ });
  it("withdraws correctly", async () => { /* ... */ });
  it("handles zero balance", async () => { /* ... */ });
});

Resetting the Fork

Sometimes you need to reset to a completely different block, or reset to no fork at all:

// Reset fork to a new block number
await network.provider.request({
  method: "hardhat_reset",
  params: [
    {
      forking: {
        jsonRpcUrl: process.env.MAINNET_RPC_URL,
        blockNumber: 19_900_000,
      },
    },
  ],
});

// Reset to local network (no fork)
await network.provider.request({
  method: "hardhat_reset",
  params: [],
});

This is useful when you have a test suite that tests behavior across different protocol states — before and after a governance proposal executed, for example.

Time Manipulation on Forks

Many DeFi protocols are time-sensitive. Vesting schedules, TWAP calculations, lock periods — all depend on block timestamps. You can fast-forward time on the fork:

// Advance time by 30 days (in seconds)
await network.provider.send("evm_increaseTime", [30 * 24 * 60 * 60]);
await network.provider.send("evm_mine", []); // Mine a block to apply the time change

// Or jump to a specific timestamp
await network.provider.send("evm_setNextBlockTimestamp", [
  Math.floor(Date.now() / 1000) + 86400 * 30,
]);
await network.provider.send("evm_mine", []);

Performance Considerations

Forking tests are dramatically slower than pure local tests because they make RPC calls on cache misses. Here's how to keep them manageable:

Pin your block number. Hardhat caches RPC responses on disk per block number. If you don't pin, every test run fetches fresh data. With a pinned block, the cache warms up on the first run and subsequent runs are much faster.

Use --network hardhat explicitly. This ensures you're using the in-process Hardhat Network, not spawning a separate node.

Group fork tests into a dedicated suite. Keep mainnet forking tests in a separate directory and run them separately from your unit tests in CI. Unit tests should run on every commit; fork tests can run nightly or on PR merge.

// package.json
{
  "scripts": {
    "test:unit": "hardhat test test/unit/**/*.ts",
    "test:fork": "hardhat test test/fork/**/*.ts",
    "test:ci": "npm run test:unit && npm run test:fork"
  }
}

Limit RPC calls in fixtures. Every unique storage slot you touch is a potential RPC call. Batch your setup — seed all token balances in one before block rather than in each individual test.

Consider a dedicated archive node. Public endpoints have rate limits. A dedicated Alchemy or Infura plan (or a self-hosted Erigon node) makes a big difference for CI.

Using Fixtures for Reusable Fork State

Hardhat's loadFixture utility works with forking and handles snapshot/revert automatically:

import { loadFixture } from "@nomicfoundation/hardhat-toolbox/network-helpers";

async function deployAndSeedFixture() {
  const [owner, user1, user2] = await ethers.getSigners();
  
  // Deploy contracts
  const vault = await deployVault(owner);
  
  // Seed with real tokens via impersonation
  await seedFromWhale(USDC, USDC_WHALE, user1.address, 50_000n * 10n**6n);
  await seedFromWhale(WETH, WETH_WHALE, user2.address, ethers.parseEther("20"));
  
  return { vault, owner, user1, user2 };
}

describe("Vault with real tokens", () => {
  it("accepts USDC deposits", async () => {
    const { vault, user1 } = await loadFixture(deployAndSeedFixture);
    // test logic
  });

  it("accepts WETH deposits", async () => {
    const { vault, user2 } = await loadFixture(deployAndSeedFixture);
    // Each test gets a fresh snapshot — loadFixture handles it
  });
});

Forking L2s: Arbitrum and Optimism

The same approach works for L2s. For Arbitrum:

// hardhat.config.ts
networks: {
  hardhat: {
    forking: {
      url: process.env.ARBITRUM_RPC_URL!, // e.g., https://arb-mainnet.g.alchemy.com/v2/...
      blockNumber: 200_000_000,
    },
    chainId: 42161,
  },
},

Keep in mind that Arbitrum contract addresses differ from mainnet. Uniswap V3's SwapRouter on Arbitrum is 0xE592427A0AEce92De3Edee1F18E0157C05861564 — same address as mainnet in this case, but USDC and WETH addresses differ. Always verify addresses for the specific chain you're forking.

Continuous Monitoring After Deployment

Mainnet fork tests give you confidence at deployment time, but DeFi protocols evolve. Governance proposals change parameters, liquidity shifts, price oracles update. A test that passes against block 19,800,000 might represent a protocol state that no longer exists.

This is where continuous post-deployment monitoring fills the gap that fork tests leave behind. HelpMeTest can run your integration scenarios continuously against your live deployed contracts, alerting you when actual mainnet behavior diverges from expected — without requiring you to constantly update your pinned block numbers. It complements your Hardhat fork tests by catching runtime drift that static fork snapshots miss.

Key Takeaways

Hardhat mainnet forking is the right tool when you need to test interactions with real deployed protocols without spending real money or waiting for real block times. The patterns that make it work well are:

  • Always pin to a specific block number for reproducibility
  • Use evm_snapshot / evm_revert to isolate test state
  • Impersonate accounts to seed realistic token balances
  • Cache RPC responses by keeping your block number stable across CI runs
  • Separate fork tests from unit tests and run them on different schedules

The combination of fast unit tests for your own logic and fork tests for protocol integrations gives you the coverage you need to ship DeFi contracts with confidence.

Read more

Start now free