Fuzzing e invariantes
Testes de propriedades
Fuzzing e invariantes é uma aula grátis de Web3 & DApp Development Fundamentals no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Web3 & DApp Development Fundamentals, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Beyond Hardcoded Inputs
Unit tests check specific inputs you thought of. But bugs often hide in inputs you did not think of. Property-based testing flips this: you state a property that should always hold, and the tool generates many random inputs trying to break it.
Foundry supports two flavors: fuzz tests and invariant tests.
Writing a Fuzz Test
A fuzz test is simply a test function with parameters. Foundry automatically calls it many times with randomized argument values, hunting for a counterexample.
function testFuzzDeposit(uint256 amount) public {
vm.assume(amount > 0 && amount < 1e30);
vault.deposit(amount);
assertEq(vault.balanceOf(address(this)), amount);
}Bounding Inputs
Random inputs may be unrealistic. Constrain them with:
vm.assume(cond)— discard runs that fail the conditionbound(x, min, max)— map any value into a range
Prefer bound for ranges since assume can waste runs by rejecting too many inputs.
function testFuzz(uint256 x) public {
x = bound(x, 1, 1000); // always in [1, 1000]
// ...
}What Makes a Good Property
A good fuzz property is a statement that must hold for all valid inputs. Examples:
- Depositing then withdrawing returns the same amount
- Total supply never changes on a transfer
- A user can never withdraw more than they deposited
Think in terms of universal truths, not specific values.
function testFuzzTransferConservesSupply(uint256 amt) public {
uint256 supplyBefore = token.totalSupply();
token.transfer(bob, bound(amt, 0, token.balanceOf(address(this))));
assertEq(token.totalSupply(), supplyBefore);
}Reading Fuzz Output
When a fuzz test fails, Foundry prints the exact counterexample that broke the property and the number of runs. It also stores a corpus so the failing input is replayed on future runs until you fix it.
$ forge test
[FAIL. Reason: assertion failed]
Counterexample: calldata=0x..., args=[115792089237316195...]Configuring the Fuzzer
Control fuzzing in foundry.toml. The runs setting is how many random inputs each fuzz test gets. More runs increase confidence but take longer.
# foundry.toml
[fuzz]
runs = 1000
max_test_rejects = 65536Invariant Testing
Invariants go a step further. Instead of one function call, Foundry executes long random sequences of calls to your contract, then checks that a property still holds after every sequence.
Invariant functions are named with the invariant_ prefix.
function invariant_totalSupplyConstant() public {
assertEq(token.totalSupply(), INITIAL_SUPPLY);
}Handlers
For meaningful invariant tests you usually write a handler contract that exposes a curated set of actions. The fuzzer calls the handler's functions in random order, keeping the call sequences valid and focused.
Register target contracts with targetContract in setUp().
function setUp() public {
handler = new Handler(token);
targetContract(address(handler));
}Ghost Variables
Handlers often track ghost variables: bookkeeping totals updated as actions run. Invariants compare the contract's real state against these ghost values.
For example, summing every deposit in the handler and asserting it equals the vault's total assets catches accounting drift.
// inside handler
uint256 public ghostTotalDeposited;
function deposit(uint256 a) external {
vault.deposit(a);
ghostTotalDeposited += a;
}Fuzz vs Invariant
Knowing which to reach for:
- Fuzz tests a single function against random arguments — good for input validation and pure logic
- Invariant tests random sequences of actions — good for stateful systems like vaults, AMMs, and token accounting
Use both: fuzz for unit-level properties, invariants for system-level guarantees.
Best Practices
Effective property testing:
- State properties as universal truths, not examples
- Use
boundover heavyassume - Increase
runsfor critical contracts - Write focused handlers for invariants
- Track ghost variables for accounting checks
Property tests catch the edge cases humans miss.
Quick Check
What is the key difference between a fuzz test and an invariant test in Foundry?
Recap
You learned property-based testing:
- Fuzz tests take parameters; Foundry generates random inputs
- Use
boundandvm.assumeto constrain inputs - Invariant tests run random call sequences via handlers
- Ghost variables track expected state for accounting invariants
- Counterexamples are saved and replayed
Next: the cast and anvil CLI tools.
Perguntas Frequentes
A aula “Fuzzing e invariantes” é grátis?
Sim — o texto completo de “Fuzzing e invariantes” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Web3 & DApp Development Fundamentals, atualize para CoddyKit PRO. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
O que vou aprender em “Fuzzing e invariantes”?
Testes de propriedades Você pratica Web3 & DApp Development Fundamentals com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Web3 & DApp Development Fundamentals?
Nenhuma experiência prévia é necessária. Web3 & DApp Development Fundamentals no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Fuzzing e invariantes”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Web3 & DApp Development Fundamentals?
Sim. Cada aula de Web3 & DApp Development Fundamentals inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Foundry versus Hardhat
- Testes com forge
- Fuzzing e invariantes
- cast e anvil