Ethers.js – Troubleshooting: Not Able to Read State Variable Array in Smart Contract Using Hardhat and Ethers

dapp-debuggingethers.jshardhat

I am trying to get the output array 'stakings' from the TokenFarm.sol file, using the following way

const tx = await tokenFarm
          .connect(address1)
          .stakeTokens({ value: ethers.utils.parseEther("1.0") });
    
        const stakings = await tokenFarm.stakings();
        console.log(stakings)

Here is the stakings array defined in my contract

struct Stake {
        uint256 id;
        address person;
        uint256 amount;
        uint256 createdAt;
    }

    mapping (uint256 => Stake) public idToStake;
    mapping(address => Stake[]) public userToStakes;

    Stake[] public stakings;

    address[] public stakers;

    IERC20 public gvToken;

But I am not able to get the expected array value as output in my js file, I am getting this following error:

missing argument: passed to contract (count=0, expectedCount=1, code=MISSING_ARGUMENT, version=contracts/5.6.0)

Best Answer

The default getter for your array has the following form :

function stakings(uint256 index) public view returns (Stake) {
    return stakings[index];
}

When you are calling const stakings = await tokenFarm.stakings(); you are not providing any parameter, when the getter does expect one: the index of the element you want to read from the array.

So, let's say you want to read the element at index 0 in the array, you would use :

 const staking = await tokenFarm.stakings(0);

Now, I suspect that you are looking for a getter to return the whole array. (view functions are subject to block gas limit, and can fail if your array is too big) But Something like this might be useful for you :

function getStakings() public view returns (Stake[] memory) {
    return stakings;
}

That you would call with :

const stakings = await tokenFarm.getStakings();
Related Topic