M06-L04 — BSC testnet deployment
1. Bài toán
Safely deploy contracts without risking real BNB or broadcasting to the wrong chain.
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
Never put testnet keys in git; use dedicated low-value accounts.
Core concepts
forge build: compile Solidity and produce ABI/bytecode artifacts.forge test -vv: run isolated tests against a local EVM.anvil: run an ephemeral JSON-RPC development chain.cast: query RPC or inspect encoded transactions.- Gas, state changes, events and reverts must be asserted independently.
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: Use Anvil for dry run; verify chain ID 97 before --broadcast; inspect deployment receipt and code.
Study solution/src/TrainingVault.sol and solution/test/Lab.t.sol, then reproduce behavior from starter/.
6. Expected output
forge buildcompletes without compilation errors.forge testreports passing tests (not verified in this authoring environment).- Deposit/withdraw accounting remains consistent; invalid operations revert.
- For network deployment, no transaction is broadcast unless chain ID equals 97.
7. Exercises
- Add a zero-value and over-withdraw revert test.
- Write a gas snapshot and compare before/after an optimization.
- Explain how a reverted external call affects local state.
- 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.