CALL DELEGATECALL STATICCALL
Bài toán
Muốn hiểu EVM thực thi logic và kiểm soát state thế nào, thay vì chỉ gọi Solidity như một Java method.
Vấn đề
Nếu hiểu sai execution context, gas hoặc ABI, backend và contract có thể trả kết quả sai, mất phí hoặc có lỗ hổng.
Giải pháp và lý thuyết
CALL changes msg.sender to calling contract and writes to callee storage. DELEGATECALL preserves caller msg.sender and operates on caller storage. STATICCALL disallows state changes.
So sánh với Java
Java bytecode chạy trên JVM trong tiến trình của ứng dụng; EVM bytecode được các node thực thi theo quy tắc đồng thuận, có gas metering và trạng thái blockchain.
Lab — CALL DELEGATECALL STATICCALL
Prerequisites
- Foundry (forge/cast/anvil)
- Không cần ví mainnet hoặc token thật
Steps
cd solutionforge buildforge test -vvvforge test --gas-report- Run
forge test -vvvvto inspect traces; note delegatecall executes target code in caller storage/context, and storage layout compatibility is mandatory.
Expected output
forge buildthành công- Các test functions trong
test/Lab.t.solđều PASS - Không có transaction mainnet
Troubleshooting
forge: command not found: cài Foundry theo tài liệu chính thứcsolcdownload fails: kiểm tra kết nối, compiler 0.8.24- Assertion fails: dùng
forge test -vvvvđể đọc call trace
Exercises — CALL DELEGATECALL STATICCALL
- Đọc
solution/src/Lab.sol, tự viết lại contract vàostarter/src/Lab.sol. - Tự viết test tương ứng, không copy solution; chạy
forge test. - Thêm một negative test có
requirehoặc revert hợp lý và giải thích trace. - Run
forge test -vvvvto inspect traces; note delegatecall executes target code in caller storage/context, and storage layout compatibility is mandatory.
Acceptance: Build thành công; tests pass; ghi chú vì sao EVM có hành vi như vậy.
Interview — CALL DELEGATECALL STATICCALL
Q1. EVM khác JVM thế nào? EVM thực thi deterministic smart-contract bytecode có gas accounting và state được đồng thuận; JVM chạy ứng dụng trong một runtime riêng.
Q2. Vì sao cần inspect trace? Trace cho thấy external calls, revert, gas và execution context để debug lỗi không thấy được chỉ từ source.
Q3. Điều gì xảy ra khi transaction revert? State changes trong reverted execution bị rollback, nhưng gas đã dùng vẫn tiêu thụ; nếu lỗi ở subcall được catch thì outer execution có thể tiếp tục.