Is there a way to encode a struct?
See original GitHub issueIs there a way to encode a struct before passing it as a function argument? I want to be able to do it in JS, preferably using ethers. I couldn’t figure it out from the docs and past issues. Thank you for your help.
Let’s say this is my contract:
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
contract MyContract {
struct MyStruct {
address a;
uint b;
bool c;
}
function myFunction(bytes memory _data) public {
MyStruct memory data = abi.decode(_data, (MyStruct));
// Do stuff with data.a, data.b, and data.c....
}
}
and here is my JS
const ethers = require('ethers');
const pk = '0x...';
const provider = 'http://localhost:8545';
const myContractAddress = '0x...';
const abi = require('./build/MyContract.abi.json');
const wallet = new ethers.Wallet(pk, new ethers.providers.JsonRpcProvider(provider));
const myContract = new ethers.Contract(myContractAddress, abi, wallet);
(async function() {
const a = '0x...';
const b = '123123123123132123123';
const c = true;
// TODO: How do I encode the struct?
const myStructData = '???';
const tx = await myContract.myFunction(
myStructData,
{ gasLimit: ethers.utils.parseUnits('1000000', 'wei') }
);
})().catch(console.error);
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (2 by maintainers)
Top Results From Across the Web
Encode a struct with solidity - Ethereum Stack Exchange
Just define a data member as struct and assign values, it will be properly encoded. In case you want to send this as...
Read more >Encoding and decoding structs of - json - Stack Overflow
You can't encode os.File because that struct doesn't have a single exported field so there is NO accessible data to be encoded. You...
Read more >Encoding Structs — Let's Go Further (Sample)
Changing keys in the JSON object One of the nice things about encoding structs in Go is that you can customize the JSON...
Read more >Encoding and Decoding Custom Types - Apple Developer
The simplest way to make a type codable is to declare its properties using types that are already Codable . These types include...
Read more >Go Structs and JSON
It's very easy to encode a Go struct into JSON, or decode JSON into a struct. Go also provides us some control over...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This worked for me:
@ajb413 @ricmoo thanks for the info, learn more about ethers.js(the encode() helper call is very useful) 😃