-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPack.sol
More file actions
82 lines (68 loc) · 2.22 KB
/
Pack.sol
File metadata and controls
82 lines (68 loc) · 2.22 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
pragma solidity ^0.8.22;
contract Packbad {
uint80 public a;
uint256 public b;
uint80 public c;
uint256 public d;
address public e;
function calls() public {
a = 12;
c = 34;
e = address(0x1234567890);
}
}
contract Packgood {
uint256 public a;
uint256 public b;
uint80 public c;
uint80 public d;
address public e;
function calls() public {
a = 12;
c = 34;
e = address(0x1234567890);
}
}
contract Packbest {
uint256 public a;
uint256 public b;
uint160 public cd;
address public e;
function calls() public {
pack(12, 34);
e = address(0x1234567890);
}
function pack(uint80 x, uint80 y) private {
cd = (uint160(x) << 80) | uint160(y);
}
function unpack() external view returns (uint80, uint80) {
uint80 x = uint80(cd >> 80);
uint80 y = uint80(cd);
return (x, y);
}
}
contract Unpacked_Struct {
struct unpackedStruct {
uint64 time; // Takes one slot - although it only uses 64 bits (8 bytes) out of 256 bits (32 bytes).
uint256 money; // This will take a new slot because it is a complete 256 bits (32 bytes) value and thus cannot be packed with the previous value.
address person; // An address occupies only 160 bits (20 bytes).
}
// Starts at slot 0
unpackedStruct details =
unpackedStruct(53_000, 21_000, address(0xdeadbeef));
function unpack() external view returns (unpackedStruct memory) {
return details;
}
}
contract Packed_Struct {
struct packedStruct {
uint64 time; // In this case, both `time` (64 bits) and `person` (160 bits) are packed in the same slot since they can both fit into 256 bits (32 bytes)
address person; // Same slot as `time`. Together they occupy 224 bits (28 bytes) out of 256 bits (32 bytes).
uint256 money; // This will take a new slot because it is a complete 256 bits (32 bytes) value and thus cannot be packed with the previous value.
}
// Starts at slot 0
packedStruct details = packedStruct(53_000, address(0xdeadbeef), 21_000);
function unpack() external view returns (packedStruct memory) {
return details;
}
}