Ethers.js Struct Parameter – How to Call Function with Struct Parameter

data-typesencodefunctioncallencodingethers.jsstruct

My solidity:

contract Test {

    struct Num {
        uint value;
    }

    function double(Num calldata num) external pure returns(Num memory) {
        return Num({ value: num.value * 2 });
    }
}

My ethers:

await test.double(2); // doesn't work
await test.double([ 2 ]); // doesn't work
await test.double({ value: 2 }); // doesn't work
await test.double(ethers.BigNumber.from(2)); // doesn't work
await test.double([ ethers.BigNumber.from(2) ]); // doesn't work
await test.double({ value: ethers.BigNumber.from(2) }); // doesn't work

If I call a function that returns a Num type (with a value of 5 for example), I get:

[
  BigNumber { value: "5" },
  value: BigNumber { value: "5" }
]

So I also tried:

const params = [ ethers.BigNumber.from("2"), value: ethers.BigNumber.from("2") ]
await test.double(params);

But this doesn't even compile…

I also looked here: https://docs.ethers.io/v5/api/utils/abi/coder/#AbiCoder-decode

enter image description here

This seems to return the type of structure I need. So I also tried:

let params = ethers.utils.defaultAbiCoder.encode(
    [ 'uint value' ],
    [ 2 ]
);
params = ethers.utils.defaultAbiCoder.decode([ "uint value" ], params);
await test.double(params) // doesn't work

But this doesn't work either…

Help?

Best Answer

For struct, you use an object to insert argument:

const data = {
    value: 100,
}
const tx = await test.double(data);
console.log(tx);

I tried and got the output:

[ 
BigNumber { value: "200" }, 
value: BigNumber { value: "200" } 
]
Related Topic