Search code examples
ethers.jsdecentralized-applications

How to define an array of structs return type in ethers.js ABI


Currently I got this abi:

const stakingAbi = [
    'function getStakes(address user) external view returns (Stake[] memory)',
    'function stake7Days(uint128 _amount) external whenNotPaused',
    'function stake14Days(uint128 _amount) external whenNotPaused',
    'function stake30Days(uint128 _amount) external whenNotPaused',
    'function stake90Days(uint128 _amount) external whenNotPaused'
]

The Stake struct looks like this:

struct Stake {
    uint16 bonusPercentage;
    uint40 unlockTimestamp;
    uint128 amount;
    bool withdrawn;
}

Currently the getStakes function doesn't work because Ethers doesn't know what Stake[] is, how do I define this in the ABI?


Solution

  • Specifying structs in the human-readable ABI format is still not supported in ethers.js. See https://github.com/ethers-io/ethers.js/issues/315

    You would need to use the JSON ABI format: https://docs.ethers.io/v5/api/utils/abi/formats/#abi-formats--solidity

    Alternatively, you work around it by returning an array of tuples:

    function getStakes(address user) external view returns (tuple(uint16 bonusPercentage, uint40 unlockTimestamp, uint128 amount, bool withdrawn)[] memory)
    

    Or tuple of arrays:

    function getStakes(address user) external view returns (uint16[] memory, uint40[] memory, uint128[] memory, bool[] memory)