Foundry笔记

Last updated on 21 hours ago

安装

1
curl -L https://foundry.paradigm.xyz | bash

如果实在 Windows 中,则需要使用 git bash

Hello 项目

  • 创建项目

    1
    forge init hello_foundry

    如果没有配置 git,则需要用--no-git

    1
    forge init hello_foundry --no-git

    创建的项目为:

    1
    2
    3
    4
    5
    6
    7
    $ cd hello_foundry
    $ tree . -d -L 1
    .
    ├── lib
    ├── script
    ├── src
    └── test
  • 构建项目

    1
    forge build
  • 运行测试

    1
    forge test

创建项目

1
forge init hello_foundry

如果没有配置 git config,则需要使用forge init hello_foundry --not-git创建,或者使用git config --global user.name "your_name"git config --global user.email "your_email"进行 git 配置

在创建时还可以使用--template选择模板

1
forge init --template https://github.com/foundry-rs/forge-template hello_template

创建好后,可以使用forge buildforge test进行构建和测试。

在现有项目工作

  • 克隆项目
1
git clone ...
  • 安装依赖项
1
2
cd project
forge install

目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.
├── foundry.toml
├── lib
│   └── forge-std
│   ├── LICENSE-APACHE
│   ├── LICENSE-MIT
│   ├── README.md
│   ├── foundry.toml
│   ├── lib
│   └── src
├── script
│   └── Counter.s.sol
├── src
│   └── Counter.sol
└── test
└── Counter.t.sol

7 directories, 8 files

测试

使用 solidity 编写测试脚本

编写测试需要使用Forge 标准库(forge-std)的 Test 合约

1
import "forge-std/Test.sol";

测试的基础写法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
pragma solidity 0.8.10;

import "forge-std/Test.sol";

// 继承Test
contract ContractBTest is Test {
uint256 testNumber;

// setUp 在每个测试用例运行之前调用的可选函数
function setUp() public {
testNumber = 42;
}

// test 前缀开头的函数表示一个测试用例
function testNumberIs42() public {
// 断言
assertEq(testNumber, 42);
}

// testFail 作为test用例的反面,如果函数没有revert,则失败
function testFailSubtract43() public {
testNumber -= 43;
}
}

// 抽象合约用于共享设置
abstract contract HelperContract {
address constant IMPORTANT_ADDRESS = 0x543d...;
SomeContract someContract;
constructor() {...}
}
// 共享HelperContract的设置
contract MyContractTest is Test, HelperContract {
function setUp() public {
someContract = new SomeContract(0, IMPORTANT_ADDRESS);
...
}
}
contract MyOtherContractTest is Test, HelperContract {
function setUp() public {
someContract = new SomeContract(1000, IMPORTANT_ADDRESS);
...
}
}