Foundry开发框架 #
一、Foundry简介 #
Foundry是用Rust编写的高性能以太坊开发框架,编译和测试速度极快。
1.1 特点 #
| 特点 | 说明 |
|---|---|
| 高性能 | Rust编写,速度极快 |
| Solidity测试 | 使用Solidity编写测试 |
| 模糊测试 | 内置模糊测试支持 |
| Gas快照 | Gas消耗分析 |
二、安装与配置 #
2.1 安装 #
bash
# macOS/Linux
curl -L https://foundry.paradigm.xyz | bash
foundryup
# 验证安装
forge --version
cast --version
anvil --version
2.2 创建项目 #
bash
forge init my-foundry-project
cd my-foundry-project
2.3 项目结构 #
text
my-foundry-project/
├── src/ # 合约目录
│ └── Counter.sol
├── test/ # 测试目录
│ └── Counter.t.sol
├── script/ # 脚本目录
│ └── Counter.s.sol
├── lib/ # 依赖库
└── foundry.toml # 配置文件
2.4 配置文件 #
toml
# foundry.toml
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc = "0.8.20"
optimizer = true
optimizer_runs = 200
[profile.default.rpc_endpoints]
sepolia = "${SEPOLIA_RPC_URL}"
三、编写合约 #
3.1 创建合约 #
solidity
// src/Token.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract Token is ERC20 {
constructor(string memory name, string memory symbol, uint256 supply)
ERC20(name, symbol)
{
_mint(msg.sender, supply * 10 ** decimals());
}
}
3.2 编译合约 #
bash
forge build
四、测试合约 #
4.1 编写测试 #
solidity
// test/Token.t.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "forge-std/Test.sol";
import "../src/Token.sol";
contract TokenTest is Test {
Token public token;
address public owner;
address public user;
function setUp() public {
owner = address(this);
user = address(0x1);
token = new Token("MyToken", "MTK", 1000000);
}
function test_Name() public {
assertEq(token.name(), "MyToken");
}
function test_Symbol() public {
assertEq(token.symbol(), "MTK");
}
function test_BalanceOf() public {
assertEq(token.balanceOf(owner), 1000000 * 10 ** 18);
}
function test_Transfer() public {
token.transfer(user, 100 * 10 ** 18);
assertEq(token.balanceOf(user), 100 * 10 ** 18);
}
// 模糊测试
function testFuzz_Transfer(uint256 amount) public {
vm.assume(amount <= token.balanceOf(owner));
token.transfer(user, amount);
assertEq(token.balanceOf(user), amount);
}
}
4.2 运行测试 #
bash
forge test
4.3 测试输出 #
bash
forge test -vvv # 详细输出
forge test --gas-report # Gas报告
五、部署合约 #
5.1 部署脚本 #
solidity
// script/DeployToken.s.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "forge-std/Script.sol";
import "../src/Token.sol";
contract DeployToken is Script {
function run() external {
vm.startBroadcast();
Token token = new Token("MyToken", "MTK", 1000000);
vm.stopBroadcast();
}
}
5.2 部署命令 #
bash
# 本地部署
forge script script/DeployToken.s.sol --broadcast
# 测试网部署
forge script script/DeployToken.s.sol --rpc-url $SEPOLIA_RPC_URL --broadcast --private-key $PRIVATE_KEY
六、常用命令 #
| 命令 | 说明 |
|---|---|
forge build |
编译合约 |
forge test |
运行测试 |
forge script |
部署合约 |
forge install |
安装依赖 |
forge update |
更新依赖 |
forge snapshot |
Gas快照 |
cast |
链交互工具 |
anvil |
本地节点 |
七、总结 #
Foundry要点:
| 功能 | 说明 |
|---|---|
| 编译 | 极快的编译速度 |
| 测试 | Solidity编写测试 |
| 模糊测试 | 内置模糊测试 |
| 部署 | 灵活的部署脚本 |
接下来,让我们学习测试与部署!
最后更新:2026-03-27