1

I have a contract with the following mapping:

mapping (uint16 => uint256[]) public barLengthToBarIndexForSale;

What's the best way to retrieve the length of an array for a given key on the frontend using truffle?

Something like this...

barERC721Inst.barLengthToBarIndexForSale(5).length;

... seems to not work.

Using an additional function in my contract to retrieve the length...

    function getBarLengthToBarIndexForSaleLength(uint16 _length) external view returns (uint) {
    return barLengthToBarIndexForSale[_length].length;
}

...seems also not to work :(

I tried calling it on the frontend like this:

barERC721Inst.barLengthToBarAmtForSale.call(5)

and

barERC721Inst.barLengthToBarAmtForSale(5)

both throw errors.

Any help is appreciated.

1
  • Your second approach should work just fine. The only think I would change is the name of the input argument - from _length to _index. Other than that, you'll need to explain what exactly "seems also not to work". Commented Jul 27, 2018 at 11:29

1 Answer 1

2

You could just write a getter function in your contract that returns the length of the array. Be sure to make it view.

function getSize(uint16 key) public view returns (uint){
    return barLengthToBarAmtForSale[5].length
}

if not possible (the contract is already deployed) then you could "try" looping through the array (it cost no gas) until you get an error. This is a bit dirty, but should work.

Hope it helps.

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.