Skip to content

Commit

Permalink
Nested Struct encoding example (#1129)
Browse files Browse the repository at this point in the history
* feat: example for cast balance --erc20

* feat: nested struct encoding example

* updates

* added cast-encode and forge create example
  • Loading branch information
kamuik16 authored Feb 27, 2024
1 parent 0a6de25 commit 1d87947
Showing 1 changed file with 79 additions and 0 deletions.
79 changes: 79 additions & 0 deletions src/misc/struct-encoding.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))"
```

0 comments on commit 1d87947

Please sign in to comment.