M06-L01 · Foundry Testing And Deployment

— Foundry setup and toolchain

M06-L01 — Foundry setup and toolchain

1. Bài toán

Set up a reproducible local EVM development environment.

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

Toolchain versions must be pinned and test networks isolated.

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: Run forge build, forge test, anvil, and cast chain-id. Compare ephemeral local accounts to real keys.

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.