Open this lesson in your favourite AI. It'll walk you through the why, explain the demo, and quiz you on the try-it list.
Forking lets you point your toy at mainnet state — every contract, every storage slot, every account balance — and run your protocol against the real world without paying gas or risking funds. This is how protocol engineers get a realistic adversary: real MEV bots watching, real liquidations triggering, real oracle prices moving. A protocol that survives a forked simulation isn't proven, but a protocol that fails one definitely isn't ready.
Anvil with --fork-url boots a local node mirroring mainnet at a specific block. Foundry tests can deploy your toy into that state and call mainnet contracts (Uniswap, Aave, Chainlink) as if they were local. The integration cost drops to zero.
curl -L https://foundry.paradigm.xyz | bash && foundryup). Start anvil --fork-url $MAINNET_RPC_URL. Run cast balance vitalik.eth against the fork and verify it returns a real number.--fork-block-number to pin to a specific block. Re-run your test. Results should be deterministic. Now you can write tests that assume specific market conditions.Use these three in order. Each builds on the one before.
In one paragraph, explain what mainnet forking is and why protocol engineers rely on it.
Walk me through what Anvil actually does when I run `--fork-url`. Where does state come from, and what happens when I call a contract method?
Design a test suite for a protocol that's sensitive to MEV. How would you simulate a sandwich attack against your protocol using a mainnet fork?
# Start anvil forking mainnet at block 19000000
anvil --fork-url $MAINNET_RPC_URL --fork-block-number 19000000
# In another shell, run forge tests against the fork
forge test --fork-url http://localhost:8545 --fork-block-number 19000000 -vv
# Or for a one-shot test:
forge test --match-test test_swap_against_real_uniswap \
--fork-url $MAINNET_RPC_URL --fork-block-number 19000000