solidity-foundry-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Foundry Development Guide

Foundry开发指南

When to Apply

适用场景

Apply this skill when working on Solidity projects using the Foundry toolkit. This includes setting up new projects, writing unit and integration tests, performing fuzz and invariant testing, simulating mainnet conditions via fork testing, and managing deployments using Solidity scripts.
当你使用Foundry工具包开发Solidity项目时,可应用本技能。这包括搭建新项目、编写单元测试与集成测试、执行模糊测试和不变量测试、通过分叉测试模拟主网环境,以及使用Solidity脚本管理部署。

Project Setup

项目搭建

Initialize a project with
forge init
. Manage dependencies using
forge install <author>/<repo>
. Configure
foundry.toml
for remappings, optimizer settings, and EVM versions. Use
remappings.txt
to simplify imports (e.g.,
@openzeppelin/=lib/openzeppelin-contracts/contracts/
).
使用
forge init
初始化项目。通过
forge install <author>/<repo>
管理依赖。配置
foundry.toml
以设置重定向、优化器参数和EVM版本。使用
remappings.txt
简化导入(例如:
@openzeppelin/=lib/openzeppelin-contracts/contracts/
)。

Testing Best Practices

测试最佳实践

Test Structure

测试结构

Tests should inherit from
forge-std/Test.sol
. Use
setUp()
for state initialization.
  • test_Xxx
    : Standard test case.
  • testFuzz_Xxx
    : Fuzz test case.
  • testFail_Xxx
    : Test expected to fail (prefer
    vm.expectRevert
    ).
测试合约应继承自
forge-std/Test.sol
。使用
setUp()
进行状态初始化。
  • test_Xxx
    :标准测试用例。
  • testFuzz_Xxx
    :模糊测试用例。
  • testFail_Xxx
    :预期会失败的测试(推荐使用
    vm.expectRevert
    )。

Fuzz Testing

模糊测试

Foundry automatically provides random inputs for function arguments in
testFuzz
functions. Use
vm.assume()
to filter inputs or
bound(uint256 x, uint256 min, uint256 max)
to constrain values.
Foundry会自动为
testFuzz
函数的参数提供随机输入。使用
vm.assume()
过滤输入,或使用
bound(uint256 x, uint256 min, uint256 max)
限制数值范围。

Invariant Testing

不变量测试

Stateful fuzzing that ensures properties hold across multiple transactions.
  • targetContract(address)
    : Define the contract to test.
  • handler
    : Use a dedicated contract to manage complex call sequences and state transitions.
一种状态化模糊测试,确保在多笔交易执行过程中,指定属性始终成立。
  • targetContract(address)
    :定义要测试的合约。
  • handler
    :使用专用合约管理复杂的调用序列和状态转换。

Fork Testing

分叉测试

Simulate mainnet state by providing a RPC URL.
  • vm.createFork(url)
    : Create a fork.
  • vm.selectFork(id)
    : Switch to a fork.
  • vm.rollFork(blockNumber)
    : Pin the fork to a specific block.
通过提供RPC URL模拟主网状态。
  • vm.createFork(url)
    :创建分叉。
  • vm.selectFork(id)
    :切换到指定分叉。
  • vm.rollFork(blockNumber)
    :将分叉固定到指定区块高度。

Essential Cheatcodes

核心Cheatcodes

CheatcodeDescription
vm.prank(addr)
Sets
msg.sender
for the next call.
vm.startPrank(addr)
Sets
msg.sender
for all subsequent calls until
stopPrank
.
vm.deal(addr, amt)
Sets the balance of an address.
vm.expectRevert(bytes)
Expects the next call to revert with a specific error.
vm.expectEmit(bool,bool,bool,bool)
Expects the next call to emit a specific event.
vm.warp(timestamp)
Sets the block timestamp.
vm.roll(blockNumber)
Sets the block number.
vm.sign(pk, digest)
Generates an ECDSA signature.
vm.label(addr, name)
Labels an address for better trace readability.
vm.record()
Starts recording all storage reads and writes.
vm.getCode(path)
Returns the creation bytecode of a contract.
Cheatcode描述
vm.prank(addr)
设置下一次调用的
msg.sender
vm.startPrank(addr)
设置后续所有调用的
msg.sender
,直到调用
stopPrank
vm.deal(addr, amt)
设置指定地址的余额。
vm.expectRevert(bytes)
预期下一次调用会触发指定错误的回滚。
vm.expectEmit(bool,bool,bool,bool)
预期下一次调用会触发指定事件。
vm.warp(timestamp)
设置区块时间戳。
vm.roll(blockNumber)
设置区块高度。
vm.sign(pk, digest)
生成ECDSA签名。
vm.label(addr, name)
为地址添加标签,提升追踪可读性。
vm.record()
开始记录所有存储的读取和写入操作。
vm.getCode(path)
返回合约的创建字节码。

Deployment Workflow

部署工作流

Use
forge script
for Solidity-based deployments.
  • Dry-run:
    forge script script/Deploy.s.sol --rpc-url $RPC_URL
  • Broadcast:
    forge script script/Deploy.s.sol --rpc-url $RPC_URL --broadcast --verify
  • Use
    --verify
    with
    --etherscan-api-key
    for automatic source verification.
使用
forge script
实现基于Solidity的部署。
  • 试运行:
    forge script script/Deploy.s.sol --rpc-url $RPC_URL
  • 广播部署:
    forge script script/Deploy.s.sol --rpc-url $RPC_URL --broadcast --verify
  • 结合
    --verify
    --etherscan-api-key
    实现源码自动验证。

Debugging

调试

  • Verbosity:
    -v
    (logs),
    -vv
    (traces for failed tests),
    -vvv
    (traces for all tests),
    -vvvv
    (setup traces),
    -vvvvv
    (full stack traces).
  • forge debug
    : Interactive debugger for a specific transaction.
  • console.log
    : Use
    forge-std/console.sol
    for print debugging.
  • 日志详细程度:
    -v
    (日志)、
    -vv
    (失败测试的追踪信息)、
    -vvv
    (所有测试的追踪信息)、
    -vvvv
    (初始化过程追踪)、
    -vvvvv
    (完整堆栈追踪)。
  • forge debug
    :针对特定交易的交互式调试器。
  • console.log
    :使用
    forge-std/console.sol
    实现打印调试。

Configuration Profiles

配置配置文件

Use profiles in
foundry.toml
to manage different build configurations.
toml
[profile.via_ir]
via_ir = true
test = 'src'
out = 'via_ir-out'

[profile.deterministic]
block_number = 17722462
block_timestamp = 1689711647
bytecode_hash = 'none'
cbor_metadata = false
foundry.toml
中使用配置文件管理不同的构建配置。
toml
[profile.via_ir]
via_ir = true
test = 'src'
out = 'via_ir-out'

[profile.deterministic]
block_number = 17722462
block_timestamp = 1689711647
bytecode_hash = 'none'
cbor_metadata = false

Enhanced with MCP

结合MCP增强功能

Leverage
solidity-agent-toolkit
MCP tools for a streamlined workflow:
  • compile_contract
    : Fast compilation and artifact generation.
  • run_tests
    : Execute the full test suite.
  • run_single_test
    : Target specific test cases for faster iteration.
  • gas_snapshot
    : Generate and compare gas reports.
  • dry_run_deploy
    : Simulate deployments to catch errors before broadcasting.
利用
solidity-agent-toolkit
MCP工具优化工作流:
  • compile_contract
    :快速编译并生成工件。
  • run_tests
    :执行完整测试套件。
  • run_single_test
    :针对特定测试用例执行,提升迭代速度。
  • gas_snapshot
    :生成并对比Gas消耗报告。
  • dry_run_deploy
    :模拟部署,在广播前捕获错误。

References

参考资料

Detailed command references and patterns can be found in Foundry Cheatsheet.
详细的命令参考和模式可在Foundry速查表中找到。