Why Fuzzing Exists and Why You Should Care
Unit tests check what you thought to test. Fuzzers check what you didn't. That distinction cost protocols hundreds of millions of dollars in 2022 and 2023. The Euler Finance hack — $197M in March 2023 — exploited a logic flaw in the donateToReserves function that a well-written invariant test would have surfaced. The invariant? "A user's health factor should never decrease after donating collateral." Nobody wrote that test.
Fuzzing is property-based testing at the EVM level. You define what should always be true — your invariants — and the fuzzer generates thousands of input sequences trying to break them. When it breaks one, you have a counterexample you can replay, minimize, and fix. That's the whole loop.
There are three fuzzers worth your time right now: Echidna, Medusa, and Foundry's built-in fuzzer. Each has a distinct use case. This guide focuses on Echidna because it's the most battle-tested for serious invariant testing, then covers where Medusa and Foundry's approach differ.
Echidna: Setup and First Run
Echidna is a Haskell-based fuzzer from Trail of Bits. Install it via their pre-built binaries or use the Docker image if you want zero dependency pain:
docker pull trailofbits/echidna
docker run -it -v $(pwd):/src trailofbits/echidna
If you're on macOS with Homebrew:
brew install echidna
Your Solidity contract needs to be reachable from a test contract that Echidna can instrument. The test contract inherits your target contract and defines invariant functions prefixed with echidna_. These functions return bool — if they ever return false, Echidna reports a violation.
Here's a minimal example with a token contract that has a hidden bug:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract BuggyToken {
mapping(address => uint256) public balances;
uint256 public totalSupply;
function mint(address to, uint256 amount) external {
balances[to] += amount;
// Bug: totalSupply not updated
}
function burn(address from, uint256 amount) external {
require(balances[from] >= amount);
balances[from] -= amount;
totalSupply -= amount;
}
}
contract EchidnaTokenTest is BuggyToken {
address constant USER = address(0x1234);
function echidna_supply_matches_balances() public view returns (bool) {
return totalSupply >= balances[USER];
}
function echidna_no_free_money() public view returns (bool) {
return balances[USER] <= totalSupply;
}
}
Run it with:
echidna EchidnaTokenTest.sol --contract EchidnaTokenTest
Echidna will call mint and burn in random sequences and break echidna_no_free_money almost immediately — because minting increases a user's balance without updating totalSupply, the invariant fails. It gives you the exact call sequence. You fix it. Done.
Writing Invariants That Actually Find Bugs
The fuzzer is only as good as the properties you give it. Weak invariants catch nothing. Here are the categories that matter:
Balance Invariants
"The sum of all user balances must equal totalSupply" is the canonical one. Every token contract should have this. Write a version that tracks a subset of known addresses Echidna controls, not the whole mapping (you can't iterate mappings).
address[] internal actors;
function echidna_total_supply_preserved() public view returns (bool) {
uint256 sum = 0;
for (uint i = 0; i < actors.length; i++) {
sum += balances[actors[i]];
}
return sum <= totalSupply;
}
Access Control Invariants
"Non-owners should never be able to call admin functions" catches tx.origin authentication bugs and broken modifier logic. Write a function that tries calling pause() or setOwner() from a non-privileged address, then checks that state didn't change.
Economic Invariants
For DeFi, your most valuable invariants are economic: "After any sequence of deposits and withdrawals, the vault's total assets must be >= total shares outstanding times the initial exchange rate." This class of invariant would have caught the Cream Finance $130M October 2021 flash loan manipulation — the exchange rate invariant breaks under recursive calls.
Reentrancy Invariants
Add a reentrancy guard check as an invariant. Track a locked boolean that flips during execution, and assert it's never true when external calls return. Echidna can't directly catch reentrancy mid-call, but you can structure invariants to detect the aftermath — inconsistent state that only occurs if a reentrant call succeeded.
Echidna Config: Don't Use Defaults
The default config leaves performance on the table. Create a echidna.yaml:
testLimit: 100000
seqLen: 100
coverage: true
corpusDir: corpus
workers: 4
testMode: property
testLimit: 100000 runs 100k test cases — the default of 10k is too low for complex contracts. seqLen: 100 lets Echidna chain 100 transactions per test sequence, which is essential for catching bugs that require multi-step setup. coverage: true generates a coverage report so you know which branches your invariants actually reach. The corpusDir saves interesting inputs so reruns build on previous runs instead of starting cold.
For DeFi protocols with complex state machines, I'd push testLimit to 500k and run it overnight. The compute is cheap. The exploit is not.
Medusa: When to Switch
Medusa is Trail of Bits' newer Go-based fuzzer. It supports the same test contract pattern as Echidna but adds parallel execution with better performance on modern multi-core machines, and native Foundry project compatibility. If you're running Foundry 0.2.x for your build system, Medusa slots in cleaner.
The interface is nearly identical:
medusa fuzz --compilation-target EchidnaTokenTest.sol
Switch to Medusa if: you need faster iteration on large contract suites, you want native Go extensibility for custom mutators, or your Echidna runs are hitting memory limits on complex state. For most projects, Echidna is still the default choice because of its larger community and more mature tooling around corpus management.
Foundry Fuzz: Different Animal
Foundry's built-in fuzzer (via forge test with the fuzz keyword) is function-level fuzzing, not invariant fuzzing. It randomizes inputs to a single function call. That's useful for catching edge cases in individual functions but it won't catch bugs that require a sequence of interactions — which is where most DeFi exploits live.
function testFuzz_transfer(address to, uint256 amount) public {
vm.assume(to != address(0));
vm.assume(amount <= token.balanceOf(address(this)));
uint256 beforeBalance = token.balanceOf(to);
token.transfer(to, amount);
assertEq(token.balanceOf(to), beforeBalance + amount);
}
Foundry also supports stateful invariant testing via invariant_ prefixed functions — this is closer to Echidna's model. But Echidna's corpus management and coverage-guided mutation are more mature. Use Foundry fuzz for quick property checks during development. Use Echidna for the serious pre-audit invariant campaign.
What Fuzzing Misses
Fuzzing is not a complete security solution. Here's what it won't catch reliably:
- Logic bugs with no on-chain state violation — if your invariants are wrong or incomplete, the fuzzer has nothing to break
- Oracle manipulation attacks — price oracle manipulation requires a specific real-world trigger (flash loan + thin liquidity) that fuzzers don't model unless you explicitly write a mock attacker contract
- Access control misconfiguration — if you forgot to restrict a function but your invariants don't check for unauthorized state changes, it passes
- Front-running and MEV vectors — transaction ordering attacks don't show up in single-threaded fuzzer runs
- Upgrade safety bugs — storage layout collisions in proxy upgrades require static analysis, not fuzzing
The Nomad Bridge $190M exploit in August 2022 came from an initialization bug — a single storage slot set to zero that allowed any message to be proved valid. A fuzzer with the right invariant would have found it. But most teams fuzzing Nomad would have written invariants around message processing logic, not initialization state. The coverage gap is a human problem, not a tooling problem.
Fuzzing + AI Auditing: The Actual Workflow
Here's the workflow I'd actually run before deploying anything with real value:
- Run Slither 0.10.x for static analysis — catches obvious issues in seconds
- Run AI auditing for vulnerability class detection and pattern matching across the whole codebase
- Write Echidna invariants for your core economic and access control properties
- Run Echidna with 100k+ test cases and review the coverage report
- Fix anything that breaks, then decide if you need a manual audit based on TVL and complexity
The AI layer catches vulnerability patterns — delegatecall into untrusted contracts, tx.origin authentication, unchecked arithmetic in Solidity versions before 0.8.x, reentrancy via call() — faster than you can read the code. Fuzzing then validates your invariants hold under adversarial input sequences. These are complementary, not redundant.
SmartContractAuditor.ai detects reentrancy, integer overflow, access control flaws, oracle manipulation patterns, and proxy storage collisions in under 60 seconds — free to start at https://contractgenius.vercel.app. Run it before you write your Echidna invariants — it'll tell you which attack surfaces to prioritize.
Comparison: Echidna vs Medusa vs Foundry Fuzz
| Tool | Type | Best For | Learning Curve | CI Integration |
|---|---|---|---|---|
| Echidna | Stateful invariant fuzzer | DeFi protocol invariants, pre-audit campaigns | Medium | Good (Docker) |
| Medusa | Stateful invariant fuzzer | Foundry-native projects, large suites | Medium | Excellent |
| Foundry Fuzz | Function-level + stateful | Per-function property checks during dev | Low | Native |
| AI Auditing | Static + pattern analysis | Fast vulnerability class detection, all projects | None | API available |
Start Here If You've Never Fuzzed Before
Write one invariant. Just one. Pick the most obvious property your contract should have — "total supply never exceeds the cap", "only owner can upgrade", "user can always withdraw what they deposited". Get Echidna running on it with the Docker image so you don't fight dependencies. Run it for 10 minutes. If it breaks, you just found a real bug before it cost you anything. If it doesn't break, extend the invariant or add a new one.
The team that wrote the Euler exploit had access to the same tools you have. The difference is whether you actually run them.
Related Articles
Continue exploring smart contract security with these related insights
Cyfrin Codehawks Competitive Audit vs AI: Which Wins?
Cyfrin Codehawks puts your code in front of hundreds of security researchers competing for prize money. That finds real bugs. But it also takes 4–8 weeks, costs $20k minimum, and leaves your contract exposed during the wait. Here's how to use competitive audits and AI auditing together without wasting time or money.
The AI Arms Race Hitting Crypto Right Now And Why Your Smart Contracts Are on the Front Line
Lazarus Group stole $1.5 billion from Bybit using AI-powered social engineering. Meanwhile, Claude AI found a 4-year-old vulnerability in Zcash before attackers could exploit it. Here's what that means for every Web3 developer deploying smart contracts right now.
The DAO Hack 2016 Explained: $60M Reentrancy
In June 2016, an attacker drained 3.6 million ETH from The DAO — roughly $60M at the time — using a reentrancy bug so simple it fits in ten lines of code. This wasn't a cryptographic breakthrough or a zero-day in the EVM. It was a function that made an external call before it updated a balance. Eight years later, variants of that same pattern still appear in production contracts.
Explore more insights on smart contract security andblockchain vulnerabilities