Repository navigation
Expand file tree
/
Copy pathCounterFallback.sol
More file actions
116 lines (80 loc) · 2.25 KB
/
Copy pathCounterFallback.sol
File metadata and controls
116 lines (80 loc) · 2.25 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
pragma solidity ^0.8.0;
library StorageSlot {
struct AddressSlot {
address value;
}
function getAddressSlot(
bytes32 slot
) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
}
contract Counter {
uint private counter;
function add(uint256 i) public {
counter += 1;
}
function get() public view returns(uint) {
return counter;
}
}
contract CounterV2 {
uint private counter;
uint public counter2;
function add(uint256 i) public {
counter += i;
}
function get() public view returns(uint) {
return counter;
}
function add2(uint256 i) public {
counter2 += i;
}
function get2() public view returns(uint) {
return counter2;
}
function upgradesdgasTo(address _implementation) external {
}
}
contract CounterProxy {
bytes32 private constant IMPLEMENTATION_SLOT =
bytes32(uint(keccak256("eip1967.proxy.implementation")) - 1);
constructor() {
}
function _delegate(address _implementation) internal virtual {
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
// 代理到 Counter
function _fallback() private {
_delegate(_getImplementation());
}
fallback() external payable {
_fallback();
}
receive() external payable {
_fallback();
}
function _getImplementation() private view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
function _setImplementation(address _implementation) private {
require(_implementation.code.length > 0, "implementation is not contract");
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = _implementation;
}
function upgradeTo(address _implementation) external {
_setImplementation(_implementation);
}
}