Crypto Training
Foundry for Security: Fuzzing, Invariants, and the Cheatcodes That Matter
A Forge test file can hold a fuzzed property, an exploit against forked mainnet state and the regression that keeps a fixed bug fixed. This post shows each on running code, with the configuration keys and cheatcodes checked against Foundry v1.10.0.
Reading code produces hypotheses, and a hypothesis that stays in your notes helps nobody once the engagement ends. Foundry is the shortest path we know from "this looks wrong" to a file that fails until the bug is fixed and keeps failing if it comes back, because the test, the attacker contract and the mainnet fork are all written in Solidity and run in one command.
The commands, configuration keys and cheatcodes below were checked against the documentation for Foundry v1.10.0, released on 19 November 2026. The outputs were produced with Forge 1.9.0 and forge-std v1.17.0.
A fuzz test that states a property#
Suppose a vault accepts an ERC-20 and credits depositors. The property is that a depositor is credited what the vault received, which is a different number from what the depositor asked to send whenever the token takes a fee.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
contract Vault {
IERC20 public immutable token;
mapping(address => uint256) public credit;
uint256 public totalCredit;
constructor(IERC20 token_) {
token = token_;
}
/// Vulnerable: credits the argument, whatever actually arrived.
function deposit(uint256 amount) external {
require(token.transferFrom(msg.sender, address(this), amount), "transfer failed");
credit[msg.sender] += amount;
totalCredit += amount;
}
function withdraw(uint256 amount) external {
credit[msg.sender] -= amount;
totalCredit -= amount;
require(token.transfer(msg.sender, amount), "transfer failed");
}
}
The test uses a token that keeps 1% of every transfer. Any function with parameters is a fuzz test, and Forge calls it 256 times by default with generated inputs.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Test} from "forge-std/Test.sol";
import {Vault, IERC20} from "../src/Vault.sol";
/// Test double: takes a 1% fee on every transfer, as some real tokens do.
contract FeeToken {
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function mint(address to, uint256 amount) external {
balanceOf[to] += amount;
}
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
return true;
}
function transfer(address to, uint256 amount) external returns (bool) {
_move(msg.sender, to, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
allowance[from][msg.sender] -= amount;
_move(from, to, amount);
return true;
}
function _move(address from, address to, uint256 amount) internal {
uint256 fee = amount / 100;
balanceOf[from] -= amount;
balanceOf[to] += amount - fee;
}
}
contract VaultTest is Test {
FeeToken internal token;
Vault internal vault;
address internal alice = makeAddr("alice");
function setUp() public {
token = new FeeToken();
vault = new Vault(IERC20(address(token)));
}
function testFuzz_depositCreditsWhatArrived(uint256 amount) public {
amount = bound(amount, 1, 1e30);
token.mint(alice, amount);
vm.startPrank(alice);
token.approve(address(vault), amount);
uint256 balanceBefore = token.balanceOf(address(vault));
vault.deposit(amount);
vm.stopPrank();
uint256 received = token.balanceOf(address(vault)) - balanceBefore;
assertEq(vault.credit(alice), received, "credit must equal tokens received");
}
}
forge test --match-test testFuzz_depositCreditsWhatArrived fails on the first input (output shortened):
[FAIL: credit must equal tokens received: 724610455838143868003384817550 != 717364351279762429323350969375;
counterexample: calldata=0x15887551... args=[1838763837513982151319545286569953730486724610455838143868003384817550 [1.838e69]]]
testFuzz_depositCreditsWhatArrived(uint256) (runs: 1, μ: 229167, ~: 229167)
Tip: Run `forge test --rerun` to retry only the 1 failed test
Fuzz seed: 0x7db2204c3dedfb87c2c3d19d9cbee2ad094a75ab0194cd924917cc629a378bf3 (use `--fuzz-seed` to reproduce)
The vault recorded a claim 1% larger than its balance, so the last depositor to withdraw cannot be paid. The fix is to credit the balance delta, after which the same test passes all 256 runs:
function deposit(uint256 amount) external {
uint256 balanceBefore = token.balanceOf(address(this));
require(token.transferFrom(msg.sender, address(this), amount), "transfer failed");
uint256 received = token.balanceOf(address(this)) - balanceBefore;
credit[msg.sender] += received;
totalCredit += received;
}
Two details in the test deserve attention. bound(amount, 1, 1e30) maps every generated value into the range, whereas vm.assume(amount <= 1e30) would discard almost every 256-bit input and eventually hit max_test_rejects. The documentation's rule is bound for ranges and assume for excluding a few specific values. The assertion also compares two numbers the test measured (credit and the balance delta), and an assertion that only repeats the contract's own arithmetic would have passed.
The fee-on-transfer case is one of several token behaviours that deserve a test double. Adversarial Token Integration and the ERC-20 integration checklist list the rest.
Reproducing a failure and keeping it#
Forge writes each fuzz counterexample to cache/fuzz/failures/ and each failing invariant sequence to cache/invariant/failures/, and replays them before generating new inputs, so a failure does not disappear on the next run. forge test --rerun runs only the tests that failed last time. The seed printed at the end reproduces the whole campaign with --fuzz-seed, with the caveat from the docs that the Foundry version, the configuration and the worker count have to match as well.
Local runs and CI want different budgets, and profiles handle that:
[fuzz]
runs = 256
[invariant]
runs = 256
depth = 500
[profile.ci.fuzz]
runs = 10000
[profile.ci.invariant]
runs = 1000
depth = 500
FOUNDRY_PROFILE=ci forge test selects the heavier profile. A test can also override a key for itself with a comment such as /// forge-config: default.fuzz.runs = 5000 above the function.
Once the bug is fixed, the counterexample belongs in the repository as an ordinary test with the concrete input, next to the fuzz test that found it. The cache directory is local state and should not be the only place the evidence lives.
Invariants: say what must always be true#
A fuzz test checks one call. An invariant test lets Forge call a set of target functions in random order for depth steps and checks a property after every step, which is how bugs that need three or four calls get found. Good properties relate several pieces of state.
| System | Properties worth encoding |
|---|---|
| Vault | tokens held cover total credit, and a deposit followed by a full withdrawal never returns more than was deposited |
| Lending | user borrow shares sum to the market total, and an account with no collateral has no debt (both are in Morpho Blue's suite) |
| AMM | the fee-adjusted reserve product never falls across a swap (the K check in Uniswap v2) |
| Bridge | a message id executes at most once, and supply minted on the destination never exceeds what is locked on the source |
The settings that change what a green result means are these:
Key in [invariant] | Default | Why it matters for security work |
|---|---|---|
runs, depth | 256, 500 | number of sequences and calls per sequence |
fail_on_revert | false | when false, a reverting call does not fail the test, so a campaign can pass while doing almost nothing |
show_metrics | true | prints calls, reverts and discards per target function. Read it before trusting a pass |
check_interval | 1 | checks the property after every call. Larger values are faster and can miss a break that is repaired before the next check |
max_time_delay, max_block_delay | unset | lets the fuzzer advance time and blocks between calls, for interest, vesting and TWAP logic |
corpus_dir | unset | enables coverage-guided fuzzing and keeps inputs that reached new code between runs |
One release note is relevant if you maintain a suite: from v1.10.0, an invariant run may start from a state that an earlier run reached, so handlers and afterInvariant hooks that assume a fresh setUp state can fail after an upgrade.
Choosing properties and writing handlers that are able to break them is a topic of its own, covered in Invariant-First Auditing with a worked failure.
Watch: fuzzing and invariants in Foundry#
Patrick Collins' video explains the difference between stateless fuzz tests and stateful invariant tests and shows both finding bugs in small contracts.
Cheatcodes by job#
The cheatcode reference is long, and security tests keep coming back to a small part of it, grouped here by what you are trying to do.
| Job | Cheatcodes | Typical use in a review |
|---|---|---|
| Act as someone | vm.prank, vm.startPrank, vm.stopPrank, makeAddr, deal, hoax | separate attacker, victim and keeper addresses, funded with ETH or ERC-20 balances |
| Move time | vm.warp, vm.roll, skip | timelocks, interest accrual, same-block versus next-block behaviour |
| Pin an outcome | vm.expectRevert, vm.expectEmit, vm.expectCall | assert the exact custom error, event or external call, so a test cannot pass for the wrong reason |
| Use real state | vm.createSelectFork, vm.rollFork | run against deployed bytecode at a pinned block |
| Rewrite state | vm.store, vm.load, vm.etch, vm.mockCall | reach a precondition quickly, or replace a dependency with hostile code |
| Branch | vm.snapshotState, vm.revertToState | try two attack paths from the same starting state (snapshot and revertTo are deprecated aliases) |
| Observe | vm.record, vm.accesses, vm.startStateDiffRecording, vm.recordLogs | list the storage slots and events a call touched |
| Shape inputs | bound, vm.assume | ranges and exclusions for fuzz inputs |
State-rewriting cheatcodes are the ones to be careful with. A PoC that reaches its precondition through vm.store proves the bug only if you can also show a real path to that state, and a triager will ask for it.
Fork tests: real bytecode at a pinned block#
Mocks encode what you believe a dependency does. A fork test runs against what it does. The example below pins mainnet at block 21,000,000 and checks a behaviour that integrations still get wrong: USDT's transfer returns no data, so a caller compiled against the standard interface reverts when it tries to decode a bool.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Test} from "forge-std/Test.sol";
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
}
contract Payer {
function pay(IERC20 token, address to, uint256 amount) external {
// The interface promises a bool. Mainnet USDT returns nothing.
token.transfer(to, amount);
}
}
contract UsdtForkTest is Test {
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
Payer internal payer;
function setUp() public {
vm.createSelectFork(vm.envString("ETH_RPC_URL"), 21_000_000);
payer = new Payer();
deal(USDT, address(payer), 100e6);
}
function test_usdtTransferReturnsNoData() public {
vm.expectRevert();
payer.pay(IERC20(USDT), makeAddr("bob"), 1e6);
}
}
Run with -vvvv, the trace shows the mechanism (cheatcode frames removed, addresses shortened):
[78477] UsdtForkTest::test_usdtTransferReturnsNoData()
├─ [67541] Payer::pay(0xdAC17F958D2ee523a2206206994597C13D831ec7, bob: [0x1D96...1d3e], 1000000 [1e6])
│ ├─ [41601] 0xdAC17F958D2ee523a2206206994597C13D831ec7::transfer(bob: [0x1D96...1d3e], 1000000 [1e6])
│ │ ├─ emit Transfer(from: Payer: [0x5615...b72f], to: bob: [0x1D96...1d3e], amount: 1000000 [1e6])
│ │ └─ ← [Stop]
│ └─ ← [Revert] EvmError: Revert
└─ ← [Stop]
The token call succeeds and ends with [Stop] where a compliant token would show [Return] true, and the revert comes one frame up, in the caller. This behaviour is why wrappers such as OpenZeppelin's SafeERC20 exist, and forge lint flags unchecked ERC-20 transfers in source files under erc20-unchecked-transfer. Reading traces at this level is most of what debugging a PoC consists of.
The same three lines of setup are how public exploit reproductions start. The DeFiHackLabs test for the Euler incident opens with cheats.createSelectFork("mainnet", 16_817_995), the block before the first attack transaction, and then replays the attacker's calls (source, our walkthrough). Always pin the block, since a test against latest changes meaning every twelve seconds. For a transaction that is already on chain, cast run <hash> replays it and prints the same kind of trace, as shown in Transaction Forensics with TX Graph.
Newer modes, as of v1.10.0#
Three additions change what Forge can do for a reviewer, and two of them are labelled MVP in the documentation, so expect their interfaces to move.
Coverage-guided fuzzing#
Setting corpus_dir under [fuzz] or [invariant] makes Forge keep and mutate inputs that reached new code, and forge fuzz replay --corpus-dir <dir> replays a saved corpus deterministically in CI.
Symbolic tests#
forge test --symbolic runs functions named check* or prove* with symbolic inputs through an SMT solver and reports a concrete counterexample when it finds one. A pass holds only within the configured bounds. Halmos vs Lean explains what that kind of result does and does not establish.
Mutation testing#
forge test --mutate changes the source in small ways and reports which changes no test noticed. For an auditor it is a quick measure of how much a project's green test suite is worth.
From finding to regression test#
The habit that makes audit work accumulate is short. Write the failing test before the report, with the property stated in the assertion message. Hand it over with the finding so that the fix review starts from a red test. Keep it in the suite after the fix, together with the fuzz or invariant test that would catch the next variant. The audit workflow post shows where each of those steps sits in an engagement.
Sources#
- Foundry v1.10.0 release notes, for the current version and the change to invariant run state.
- Forge testing overview, for fuzz tests, seeds,
boundandassume, and the symbolic mode. - Testing configuration reference, for every
[fuzz]and[invariant]key and default quoted above. - Cheatcodes reference, for each cheatcode in the table.
- Fork testing guide, fuzz corpus workflow and mutation testing guide.
- DeFiHackLabs, a public collection of exploit reproductions written as Foundry fork tests.