6

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?

2 Answers 2

5

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" } 
]
2
  • Doesn't work for me. I get Error: call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="double((uint256))", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.6.0) Commented Oct 26, 2022 at 11:36
  • 2
    Actually, forget my last comment. That error was related to something else. Yes, your answer does work. Thanks! Commented Oct 26, 2022 at 14:27
0

If you are attempting to pass an argument to a struct, just try with square brackets, like so:

await contractName.functionFoo([exampleNumber]);

If a function returns a struct and you would like to interact with a key within it, you could also try:

let response = await contractName.functionFoo([exampleNumber])
// the number from the struct is now stored at response[0]

I recently wrote a contract that utilised structs and this is a snippet from my test file.

I hope I helped you, buddy! Keep hacking! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.