Invariant testing in Foundry
Invariant testing calls your contract in random sequences and checks a property after every call — it finds bugs that require state built over multiple transactions, which fuzzing cannot.
Procedure
- State each invariant as a boolean that must always hold:
function invariant_solvent() public {
assertGe(token.balanceOf(address(vault)), vault.totalDebt());
}
function invariant_supplyBacksShares() public {
assertEq(vault.totalAssets(), depositToken.balanceOf(address(vault)));
}
- Write a handler that bounds the actions the fuzzer may take, so sequences are realistic:
contract Handler is Test {
function deposit(uint256 amount) public {
amount = bound(amount, 1, 1e24);
deal(address(token), address(this), amount);
vault.deposit(amount, address(this));
}
}
- Restrict calls to the handler, not the vault directly:
targetContract(address(handler))insetUp— otherwise the fuzzer makes unpayable calls. - Configure depth and runs:
[invariant]
runs = 256
depth = 50
fail_on_revert = false
call_override = false
- Exclude unpayable selectors with
targetSelector(FuzzSelector({addr: addr, selectors: sels})). - Add tolerance for dust in invariants:
assertApproxEqAbs(..., 2). - Reproduce failures with the exported sequence: Foundry prints the call sequence; replay with
forge test --match-test invariant_x -vvvv. - Model at least three actors (
address(0x1)..(0x3)) so multi-user interactions are explored. - Run longer in CI:
forge test --match-test invariant --fuzz-runs 5000overnight. - Keep invariants in a dedicated
test/invariant/dir so they are not confused with unit tests.
Pitfalls
fail_on_revert = truewith a handler that can revert on valid-but-unpayable calls aborts runs; handle the revert inside the handler instead.- Targeting the vault directly rather than a handler, so the fuzzer passes
type(uint256).maxand everything reverts. - An invariant that is tautological (
x == x) or reads only constants — it passes forever and proves nothing. - Forgetting that
msg.senderin the invariant test is the test contract; a rule that only the owner may call is never exercised unless the handler pranks. - Too shallow depth (default 15) to build the state the bug needs.
Verification
forge test --match-test invariant -vv
Pass: invariant_x runs the configured number of sequences and depth with no counterexample. On failure Foundry prints the exact call sequence to replay.
Report each invariant, its runs/depth, and the sequence when one breaks.