In Foundry, a fuzz test is any test function that takes parameters: forge calls it with many generated inputs (256 runs by default), and if an assertion fails it shrinks the input to a minimal counterexample. An invariant test is a function prefixed invariant_ that must hold after any sequence of calls: forge deploys your setUp() state, then makes random calls to target contracts (256 runs of 500 calls each by default) and checks every invariant as it goes. Use bound() to keep fuzz inputs meaningful, and route invariant calls through a handler contract with ghost variables so the fuzzer explores realistic states instead of reverting.
This guide builds both kinds of test for one small contract, then covers configuration and the mistakes that make fuzz suites pass without testing anything. If you're still choosing a framework, see how Foundry compares with Hardhat.
The contract under test
A minimal ETH vault on Ethereum or any EVM chain:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Vault {
mapping(address => uint256) public balanceOf;
uint256 public totalDeposits;
function deposit() external payable {
balanceOf[msg.sender] += msg.value;
totalDeposits += msg.value;
}
function withdraw(uint256 amount) external {
balanceOf[msg.sender] -= amount; // reverts on underflow in 0.8
totalDeposits -= amount;
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "transfer failed");
}
}
How do I write a fuzz test?
Add parameters to a test. Foundry generates values for them, mixing random numbers with "interesting" values it collects from your contracts: boundaries like 0 and type(uint256).max, constants from bytecode and values seen in storage.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Test} from "forge-std/Test.sol";
import {Vault} from "../src/Vault.sol";
contract VaultFuzzTest is Test {
Vault vault;
address user = makeAddr("user");
function setUp() public {
vault = new Vault();
}
function testFuzz_DepositThenWithdrawAll(uint96 amount) public {
vm.deal(user, amount);
vm.startPrank(user);
vault.deposit{value: amount}();
vault.withdraw(amount);
vm.stopPrank();
assertEq(user.balance, amount);
assertEq(vault.balanceOf(user), 0);
}
function testFuzz_PartialWithdraw(uint256 depositAmt, uint256 withdrawAmt) public {
depositAmt = bound(depositAmt, 1, 1_000_000 ether);
withdrawAmt = bound(withdrawAmt, 0, depositAmt);
vm.deal(user, depositAmt);
vm.startPrank(user);
vault.deposit{value: depositAmt}();
vault.withdraw(withdrawAmt);
vm.stopPrank();
assertEq(vault.balanceOf(user), depositAmt - withdrawAmt);
assertEq(vault.totalDeposits(), depositAmt - withdrawAmt);
}
function testFuzz_CannotWithdrawMoreThanBalance(uint96 depositAmt, uint256 extra) public {
extra = bound(extra, 1, type(uint128).max);
vm.deal(user, depositAmt);
vm.startPrank(user);
vault.deposit{value: depositAmt}();
vm.expectRevert(); // arithmetic underflow (Panic 0x11)
vault.withdraw(uint256(depositAmt) + extra);
vm.stopPrank();
}
}
Three habits are visible here:
- Choose narrow types. A
uint96amount can't overflow when added to other amounts, so the fuzzer doesn't waste runs on inputs that fail for boring reasons. - Assert a property, not a value. "Withdrawing everything returns the full deposit" is true for every input. Example tests check one point; fuzz tests check a rule.
- Test the failure side too. A fuzz test that only checks the happy path will miss a missing check.
When a run fails, forge prints the shrunk counterexample with its calldata and arguments, for example [FAIL: assertion failed; counterexample: calldata=0x... args=[0]]. Rerun just that test with forge test --mt testFuzz_PartialWithdraw -vvvv to see the full trace. If the failure is a revert, decode the revert reason from the trace. Failing inputs are saved under cache/fuzz and replayed first on the next run, so a fixed bug stays fixed.
Should I use bound or vm.assume?
Prefer bound(x, min, max). It maps every generated value into the range, so every run counts. vm.assume(condition) throws the input away and asks for another. That's fine for rare exclusions:
vm.assume(recipient != address(0) && recipient != address(vault));
It's a problem for anything restrictive. vm.assume(amount > 1 ether && amount < 2 ether) on a uint256 rejects almost everything, and the test fails once it hits max_test_rejects (65,536 by default).
To guarantee specific values are tried, Foundry supports fixtures: a function or public array named fixture plus the parameter name, such as fixtureAmount for a parameter called amount, whose values the fuzzer mixes into the inputs.
How do invariant tests work?
A fuzz test checks one call with random inputs. An invariant test checks random sequences of calls. For each run, forge restores the state after setUp(), then makes depth calls. Each call picks a target contract, a function, arguments and a msg.sender at random. After each call, every invariant_* function in the test contract is run, and any failure is reported with the call sequence that caused it, shrunk to as few calls as possible.
By default every contract deployed in setUp() is a target. Pointing the fuzzer straight at Vault mostly produces withdraw calls from random addresses with no balance, which revert. With fail_on_revert = false (the default for invariants) those are discarded, and you get a suite that runs 128,000 calls and explores almost nothing.
Handlers and ghost variables
A handler is a contract that wraps the target, picks a realistic actor, bounds the inputs so calls succeed, and records what happened in ghost variables: state the test tracks but the contract doesn't.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {CommonBase} from "forge-std/Base.sol";
import {StdCheats} from "forge-std/StdCheats.sol";
import {StdUtils} from "forge-std/StdUtils.sol";
import {Vault} from "../src/Vault.sol";
contract VaultHandler is CommonBase, StdCheats, StdUtils {
Vault public vault;
address[] public actors;
uint256 public ghost_deposited;
uint256 public ghost_withdrawn;
mapping(bytes4 => uint256) public calls;
constructor(Vault _vault) {
vault = _vault;
actors.push(makeAddr("alice"));
actors.push(makeAddr("bob"));
actors.push(makeAddr("carol"));
}
function actorCount() external view returns (uint256) {
return actors.length;
}
function deposit(uint256 actorSeed, uint256 amount) external {
address actor = actors[bound(actorSeed, 0, actors.length - 1)];
amount = bound(amount, 0, 100 ether);
vm.deal(actor, amount);
vm.prank(actor);
vault.deposit{value: amount}();
ghost_deposited += amount;
calls[this.deposit.selector]++;
}
function withdraw(uint256 actorSeed, uint256 amount) external {
address actor = actors[bound(actorSeed, 0, actors.length - 1)];
amount = bound(amount, 0, vault.balanceOf(actor));
vm.prank(actor);
vault.withdraw(amount);
ghost_withdrawn += amount;
calls[this.withdraw.selector]++;
}
}
The handler inherits only the forge-std pieces it needs, not Test, so forge doesn't treat it as a test contract. The invariant test targets the handler only:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Test} from "forge-std/Test.sol";
import {Vault} from "../src/Vault.sol";
import {VaultHandler} from "./VaultHandler.sol";
contract VaultInvariantTest is Test {
Vault vault;
VaultHandler handler;
function setUp() public {
vault = new Vault();
handler = new VaultHandler(vault);
targetContract(address(handler));
// Only fuzz the actions. Public getters like actors(i) would
// revert on out-of-range indexes and trip fail_on_revert.
bytes4[] memory selectors = new bytes4[](2);
selectors[0] = VaultHandler.deposit.selector;
selectors[1] = VaultHandler.withdraw.selector;
targetSelector(FuzzSelector({addr: address(handler), selectors: selectors}));
}
// ETH can be force-sent to any contract, so solvency is >=, not ==.
function invariant_VaultIsSolvent() public view {
assertGe(address(vault).balance, vault.totalDeposits());
}
function invariant_AccountingMatchesGhosts() public view {
assertEq(vault.totalDeposits(), handler.ghost_deposited() - handler.ghost_withdrawn());
}
function invariant_BalancesSumToTotal() public view {
uint256 sum;
for (uint256 i; i < handler.actorCount(); i++) {
sum += vault.balanceOf(handler.actors(i));
}
assertEq(sum, vault.totalDeposits());
}
}
Other target helpers from StdInvariant (inherited through Test) let you shape the campaign further: excludeSelector, excludeContract, targetSender and excludeSender do what their names say. Define afterInvariant() for a check that runs once at the end of each run, such as "every actor can withdraw their full balance".
This is the kind of suite that catches bugs spread across several calls. Forget to update one of the two counters on some code path, and invariant_BalancesSumToTotal or the ghost check fails with the exact sequence that got there. Add an actor contract whose receive() calls back into the vault, and the same invariants test the defences described in preventing reentrancy in Solidity. For tokens, the classic invariants are "total supply equals the sum of balances" and "no transfer changes total supply", which pair well with writing an ERC-20 with OpenZeppelin.
How do I configure runs and depth?
Defaults are tuned for a fast local loop. Raise them in CI with a profile:
# foundry.toml
[profile.default.fuzz]
runs = 256
max_test_rejects = 65536
[profile.default.invariant]
runs = 256
depth = 500
fail_on_revert = true # handlers bound inputs, so any revert is a surprise
shrink_run_limit = 5000
[profile.ci.fuzz]
runs = 10000
[profile.ci.invariant]
runs = 1000
depth = 1000
forge test --mt invariant_ -vvv # invariants only
FOUNDRY_PROFILE=ci forge test # long CI campaign
forge test --mt testFuzz_ --fuzz-seed 42 # reproducible inputs
Individual tests can override settings with a comment above the function, such as /// forge-config: default.fuzz.runs = 5000. Failing invariant sequences are persisted under cache/invariant and replayed first. Recent Foundry releases also add a coverage-guided mode (enabled with corpus_dir) and options such as check_interval and max_time_delay; check forge --version and the Foundry docs for what your version supports.
What to check before trusting a green suite
- Read the call metrics. Invariant runs print per-function call and revert counts (
show_metricsis on by default). Ifwithdrawreverts 95% of the time, the handler isn't bounding properly. Thecallsmapping above gives you the same view in your own logs. - Make invariants fail on purpose. Introduce a bug (skip
totalDeposits -= amount) and confirm the suite catches it. A test that can't fail is decoration. - Turn on
fail_on_revertonce handlers are bounded. Otherwise a function that always reverts looks like a function that's always safe. - Model multiple actors and time. Use several addresses, and
vm.warporvm.rollinside handlers when logic depends on time or blocks. - Fuzz forks too. For upgradeable proxy contracts, run invariants against a fork after a simulated upgrade.
- Know the limits. Fuzzing samples the input space; it doesn't prove properties. Symbolic tools such as Halmos and separate fuzzers such as Echidna or Medusa complement Foundry for high-value code.
Summary
| Fuzz test | Invariant test | |
|---|---|---|
| Declared as | Test function with parameters | invariant_ function plus setUp() targets |
| What's random | Arguments of one call | Sequence, functions, arguments and senders |
| Default size | 256 runs | 256 runs × 500 calls |
| Key tools | bound, vm.assume, fixtures | Handlers, ghost variables, targetContract, targetSelector |
| Failure output | Shrunk input | Shrunk call sequence |
| Biggest pitfall | vm.assume rejecting most inputs | Calls reverting so nothing is explored |
Get the weekly commit
New blockchain deep dives every week.