Crypto Training

Foundry for Security: Fuzzing, Invariants, and the Cheatcodes That Matter

Foundry turns security ideas into executable checks. Fuzz what you fear, encode invariants, and keep exploit tests as regression armor.

Crypto Training2026-02-052 min read

Foundry security loop illustration

Reading code finds bugs. Executable security checks keep them dead.

Foundry is great for this because the loop is fast:

  • write a harness
  • fuzz inputs
  • inspect traces
  • lock a regression

A small example: delta-based ERC-20 receive#

Let’s say your protocol integrates “ERC-20” tokens. You don’t assume transfers are pure.

You can encode that as a property:

SOLIDITY
function test_receive_is_delta_based(uint256 amount) public {
    amount = bound(amount, 1, 1e24);

    uint256 beforeBal = token.balanceOf(address(vault));
    token.mint(address(this), amount);
    token.approve(address(vault), amount);

    vault.deposit(amount);

    uint256 afterBal = token.balanceOf(address(vault));
    assertGt(afterBal - beforeBal, 0);
}

This isn’t about token minting being realistic. It’s about capturing the invariant you want: credit is based on what arrived.

Invariants: say what must always be true#

When I write invariants, I aim for relationships, not examples.

Here’s a table that helps:

SystemUseful invariants
Vaultshares represent claim on assets; no negative balances
Lendingcollateralization bounds; liquidations reduce bad debt
AMMreserves never go negative; fees monotonic
Bridgemessage ids consumed exactly once; domain separated

Cheatcodes I actually use in audits#

I’m not going to list all cheatcodes. The useful ones for security work are:

  • vm.prank / vm.startPrank to model callers
  • vm.warp / vm.roll for time and block logic
  • vm.expectRevert to pin down failure modes
  • vm.assume to constrain fuzz domains

The goal is to force your mental model into code.

Watch: fuzzing and invariants in Foundry#

If you want a fast mental model for why fuzzing and invariants catch real bugs (and how to structure them), this talk is worth the time.

The audit move that pays off#

When you find a bug:

  1. Write a failing test that exploits it.
  2. Patch.
  3. Keep the test forever.

That’s how audits keep compounding.

Further reading#