Building a DeFi Exploit Detection Lab: Foundry Invariant Tests That Would Have Caught $100M in Hacks

Your smart contracts passed every unit test. All edge cases covered. Code coverage: 98%. Then someone calls three functions in a sequence nobody imagined, and $40 million disappears. Unit tests ver...

By · · 1 min read
Building a DeFi Exploit Detection Lab: Foundry Invariant Tests That Would Have Caught $100M in Hacks

Source: DEV Community

Your smart contracts passed every unit test. All edge cases covered. Code coverage: 98%. Then someone calls three functions in a sequence nobody imagined, and $40 million disappears. Unit tests verify what you expect. Invariant tests find what you didn't. This guide shows you how to build invariant tests modeled on real 2026 DeFi exploits — oracle manipulation, flash loan attacks, and access control failures — so your protocol doesn't become the next post-mortem. Why Unit Tests Aren't Enough Unit tests answer: "Does function X produce output Y for input Z?" Invariant tests answer: "Does property P hold after any sequence of function calls?" The difference matters because DeFi exploits rarely break a single function. They break assumptions between functions — calling borrow() after manipulating the oracle that borrow() depends on, or using flashLoan() to enter a state that withdraw() never expected. // A unit test catches this: function test_withdraw_reverts_if_insufficient_balance() pu