-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncoding.sol
More file actions
81 lines (69 loc) · 2.61 KB
/
Encoding.sol
File metadata and controls
81 lines (69 loc) · 2.61 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
// SPDX-License—Identifier:MIT
pragma solidity ^0.8.0;
contract Encoding {
function combineStrings() public pure returns (string memory) {
return string(abi.encodePacked("Hello Everyone"));
}
// globally availible methods & units
// When we send a transaction, it is "compiled" down to bytecode and sent in a "data" to the blockchain.
// That data object now governs how future transactions will interact with it.
function encodeNumber() public pure returns (bytes memory) {
bytes memory number = abi.encode(1);
return number;
}
function encodeString() public pure returns (bytes memory) {
bytes memory someString = abi.encode("some string");
return someString;
}
//Saved a lot of gas
function encodeStringPacked() public pure returns (bytes memory) {
bytes memory someString = abi.encodePacked("some string");
return someString;
}
//Gives same output as encodePacked
function encodeStringBytes() public pure returns (bytes memory) {
bytes memory someString = bytes("some string");
return someString;
}
//this function helps in decoding the bytes to string
function decodeString() public pure returns (string memory) {
// bytes memory encodedString = encodeString();
string memory someString = abi.decode(
/*from*/ encodeString(),
/*to*/ (string)
);
return someString;
}
function multiEncode() public pure returns (bytes memory) {
bytes memory someString = abi.encode(
"some string is bigger",
"it's bigger"
);
return someString;
}
//Even bigger bytes object because it includes two strings
function multiDecode() public pure returns (string memory, string memory) {
(string memory someString, string memory someOtherString) = abi.decode(
multiEncode(),
(string, string)
);
return (someString, someOtherString);
}
function multiEncodePacked() public pure returns (bytes memory) {
bytes memory someString = abi.encodePacked(
"some string",
"is bigger",
"it's bigger"
);
return someString;
}
// This doesn't work!
function multiDecodePacked() public pure returns (string memory) {
string memory someString = abi.decode(multiEncodePacked(), (string));
return someString;
}
function multiStringCastPacked() public pure returns (string memory) {
string memory someString = string(multiEncodePacked());
return someString;
}
}