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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
| // Certora规范语言
// 使用SMT求解器验证智能合约
methods {
function swap(uint256 amount0In, uint256 amount1In, address to, bytes calldata data) external;
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
}
// 确保swap遵循恒定乘积公式
RULE invariant CONSTANT_PRODUCT
calldataarg uint256 amount0In;
calldataarg uint256 amount1In;
address to;
bytes data;
{
env e;
require e.msg.value == 0;
uint256 reserve0Before;
uint256 reserve1Before;
reserve0Before, reserve1Before = getReserves();
swap(e, amount0In, amount1In, to, data);
uint256 reserve0After;
uint256 reserve1After;
reserve0After, reserve1After = getReserves();
// 恒定乘积公式:reserve0 * reserve1 应该保持不变
assert(reserve0Before * reserve1Before == reserve0After * reserve1After,
"Invariant violated: constant product formula");
}
// 确保swap不会导致储备量变为0
RULE invariant NO_ZERO_RESERVES
calldataarg uint256 amount0In;
calldataarg uint256 amount1In;
address to;
bytes data;
{
env e;
swap(e, amount0In, amount1In, to, data);
uint256 reserve0;
uint256 reserve1;
reserve0, reserve1 = getReserves();
assert(reserve0 > 0 && reserve1 > 0, "Reserves cannot be zero");
}
// 验证转账函数
FUNCTION transfer(address to, uint256 amount)
creates
evm(uint256 balance) = balanceOf(to),
evm(uint256 balance) = balanceOf(msg.sender)
updates
balanceOf(to) = toBalance => toBalance >= balance,
balanceOf(msg.sender) = fromBalance => fromBalance <= balance;
// 确保总供应量不变
RULE invariant TOTAL_SUPPLY
{
env e;
uint256 totalBefore = totalSupply();
// 执行任意操作
havoc(e);
uint256 totalAfter = totalSupply();
assert(totalBefore == totalAfter, "Total supply changed");
}
|