M06-L03 · Foundry Testing And Deployment

— Fuzzing and stateful invariants

M06-L03 — Fuzzing and stateful invariants

1. Bài toán

A single happy-path test misses unexpected values and long call sequences.

2. Vấn đề

Without automated validation, contract mistakes are immutable or expensive to fix once deployed. In Ethereum-compatible chains a transaction that succeeds on one chain may be dangerous on another if the deployment target is wrong.

3. Giải pháp

Use Foundry for repeatable compile, local EVM execution, tests, gas snapshots and guarded deployment. Separate read-only simulation from transaction broadcast.

4. Lý thuyết

Fuzzing explores many inputs; invariants require stateful handlers for meaningful sequence coverage.

Core concepts

5. Lab chi tiết

Prerequisites: Foundry with forge, cast, anvil; bash; Solidity 0.8.24.

cd solution
forge build
forge test -vv
forge test --gas-report

Task: Fuzz deposits with uint96 inputs, then verify vault solvency. Extend with stateful handler and ghost accounting.

Study solution/src/TrainingVault.sol and solution/test/Lab.t.sol, then reproduce behavior from starter/.

6. Expected output

7. Exercises

  1. Add a zero-value and over-withdraw revert test.
  2. Write a gas snapshot and compare before/after an optimization.
  3. Explain how a reverted external call affects local state.
  4. Introduce a regression in a local copy and demonstrate a failing test.

8. Interview

Why not only use unit tests? Fuzz and invariant tests probe a wider state space, but neither proves absence of all vulnerabilities.

What does --broadcast do? It submits signed transactions; do not use on a mainnet without an explicit deployment review.

What is the difference between forge test and anvil? Forge runs tests in a managed EVM; Anvil exposes a persistent local JSON-RPC endpoint.

Dependencies

M04-L01 to M04-L05, M05-L01 to M05-L05.

Deliverables

starter/, solution/, Solidity source, tests, shell scripts and this study guide.