forked from OpenSpace100/blockchain-tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestTransientStorage.sol
More file actions
87 lines (72 loc) · 1.84 KB
/
Copy pathtestTransientStorage.sol
File metadata and controls
87 lines (72 loc) · 1.84 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
pragma solidity ^0.8.26;
// Make sure EVM version and VM set to Cancun
// Storage - data is stored on the blockchain
// Memory - data is cleared out after a function call
// Transient storage - data is cleared out after a transaction
interface ITest {
function setX(uint x) external returns (uint256);
function val() external view returns (uint256);
function test() external;
}
contract Callback {
uint256 public v;
fallback() external {
// v = ITest(msg.sender).val();
ITest(msg.sender).setX(1);
}
// 分别调用以下两个合约的 test 方法
// ReentrancyGuard gas 78468
// ReentrancyGuardTransient 29991
function test(address target) external {
ITest(target).test();
}
}
// 对比两个合约的 Gas
// TestStorage addr
// TestTransientStorage
contract TestStorage {
uint256 public val;
// gas 49818
function test() public {
val = 123;
}
}
contract TestTransientStorage {
uint256 public transient val;
// gas 24518
function test() public {
val = 123;
}
}
contract ReentrancyGuard {
uint256 public val;
uint256 private locked = 1;
modifier nonReentrant() {
require(locked == 1, "REENTRANCY");
locked = 2;
_;
locked = 1;
}
function setX(uint _x) public nonReentrant {
val = _x;
// Ignore call error
bytes memory b = "";
msg.sender.call(b);
}
}
contract ReentrancyGuardTransient {
uint256 public val;
uint256 private transient locked;
modifier nonReentrant() virtual {
require(locked == 0, "REENTRANCY");
locked = 1;
_;
locked = 0;
}
function setX(uint _x) external nonReentrant {
val = _x;
// Ignore call error
bytes memory b = "";
msg.sender.call(b);
}
}