From 1d87947c5cf1cdc0003639932474d5c7972fa2a4 Mon Sep 17 00:00:00 2001 From: Krishang Shah <93703995+kamuik16@users.noreply.github.com> Date: Tue, 27 Feb 2024 19:57:22 +0530 Subject: [PATCH] Nested Struct encoding example (#1129) * feat: example for cast balance --erc20 * feat: nested struct encoding example * updates * added cast-encode and forge create example --- src/misc/struct-encoding.md | 79 +++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/src/misc/struct-encoding.md b/src/misc/struct-encoding.md index f4c509d56..52fd0c4d6 100644 --- a/src/misc/struct-encoding.md +++ b/src/misc/struct-encoding.md @@ -61,3 +61,82 @@ The ABI of the `f` function in this contract is: ``` which reads: The function `f` takes 1 input of type `tuple` with two components of type `address` and `uint256`. + +**Nested Struct Encoding:** +Here's a more complex example with nested structs: + +```solidity +pragma solidity 0.8.21; + +contract Test { + struct nestedStruct { + address addr; + uint256 amount; + } + + struct MyStruct { + string nestedStructName; + uint256 nestedStructCount; + nestedStruct _nestedStruct; + } + + function f(MyStruct memory t) public pure {} +} +``` +The ABI of the `f` function in this contract is: + +```json +{ + "inputs": [ + { + "name": "t", + "type": "tuple", + "internalType": "struct Test.MyStruct", + "components": [ + { + "name": "nestedStructName", + "type": "string", + "internalType": "string" + }, + { + "name": "nestedStructCount", + "type": "uint256", + "internalType": "uint256" + }, + { + "name": "_nestedStruct", + "type": "tuple", + "internalType": "struct Test.nestedStruct", + "components": [ + { + "name": "addr", + "type": "address", + "internalType": "address" + }, + { + "name": "amount", + "type": "uint256", + "internalType": "uint256" + } + ] + } + ] + } + ], + "name": "f", + "outputs": [], + "stateMutability": "pure", + "type": "function" +} +``` +which reads: The function `f` takes 1 input of type tuple with three components: a string, a uint256, and another tuple representing the nested struct with components addr of type address and amount of type uint256. + +To encode `MyStruct` to pass it as a parameter to the function `f`: +```bash +cast abi-encode "f((string,uint256,(address,uint256)))" "(example,1,(0x...,1))" +``` + +To deploy a contract accepting `MyStruct` as an argument: +```bash +forge create src/Test.sol:Test --constructor-args "(example,1,(0x...,1))" +``` \ No newline at end of file