Created
July 31, 2023 21:56
-
-
Save Jesserc/fb9f7d46186eb40c76933211435516f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
struct InnerStruct { | |
uint256 innerValue; | |
bytes data; | |
} | |
struct OuterStruct { | |
uint256 outerValue; | |
InnerStruct inner; | |
} | |
contract NestedStructContract { | |
OuterStruct public data; | |
function bytes_encoded() public pure returns (bytes memory out) { | |
out = abi.encode(OuterStruct(10e18, InnerStruct(10e18, bytes("hello solidity")))); | |
} | |
function decodeNestedStruct(bytes memory _data) public pure returns (OuterStruct memory) { | |
return abi.decode(_data, (OuterStruct)); | |
} | |
} | |
///// FORGE TEST FILE ///// | |
// SPDX-License-Identifier: MIT | |
pragma solidity 0.8.20; | |
import "forge-std/Test.sol"; | |
import "../src/test.sol"; | |
contract EncodeDecodeTest is Test { | |
NestedStructContract public nested; | |
function setUp() public { | |
nested = new NestedStructContract(); | |
} | |
function testEncodeAndDecode() public view { | |
bytes memory _data = nested.bytes_encoded(); | |
console.log(""); // this is to create a padding | |
console.log(""); | |
console.log(""); | |
console.log("=============== Logging encoded nested struct ==============="); | |
console.logBytes(_data); | |
console.log("=============== Logging encoded nested struct ends here ==============="); | |
console.log(""); | |
console.log(""); | |
console.log(""); | |
OuterStruct memory _value; | |
_value = nested.decodeNestedStruct(_data); | |
console.log("============== Decoding nested struct =============="); | |
// console.log("");` | |
console.logString(string(_value.inner.data)); // get string from nested struct | |
console.log(_value.inner.innerValue); | |
console.log(_value.outerValue); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment