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.
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:
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:
| System | Useful invariants |
|---|---|
| Vault | shares represent claim on assets; no negative balances |
| Lending | collateralization bounds; liquidations reduce bad debt |
| AMM | reserves never go negative; fees monotonic |
| Bridge | message 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.startPrankto model callersvm.warp/vm.rollfor time and block logicvm.expectRevertto pin down failure modesvm.assumeto 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:
- Write a failing test that exploits it.
- Patch.
- Keep the test forever.
That’s how audits keep compounding.
Further reading#
- Foundry cheatcodes reference: https://book.getfoundry.sh/cheatcodes/