0

i'm having an issue when trying to return an array of structs from a getter function i've made.

The smart contract is an ERC721 Staking Contract.

This is the getter function:

function getNftInfo(uint256[] calldata tokenIds) public view returns (uint256[] memory){
     
      uint256 tokenId;
      uint256[] memory tmp = new uint256[](tokenIds.length);
      for (uint i = 0; i < tokenIds.length; i++) {
          tokenId = tokenIds[i];
          Stake storage staked = vault[tokenId];
          tmp[i] = staked;
      }

      return tmp;
  }

This is the struct and the mapping:

 struct Stake {
        uint256 tokenId;
        uint256 lockPeriod;
        uint256 startDate;
        address owner;
    }
   
    mapping(uint256 => Stake) public vault; 

When a user insert the staked tokenIds (ex. [1,345,10]) the return should be =>

[
  {1, lockperiod,StartDate,owner},
  {245, lockperiod,StartDate,owner},
  {10, lockperiod,StartDate,owner},
]

This is the error:

from solidity:
TypeError: Type struct CustomStakingV2.Stake storage pointer is not implicitly convertible to expected type uint256.
   --> CustomStakingV2.sol:109:20:
    |
109 |           tmp[i] = staked;
    |                    ^^^^^^

Someone could help me please? Thank you

2 Answers 2

0

You are trying to assign 'Stake' which is a struct to tmp which is a uint256. That is not possible.

Instead of doing this, you can try

  function getNftInfo(uint256[] calldata tokenIds) public view returns (Stake[] memory){

  uint256 tokenId;
  Stake[] memory tmp = new Stake[](tokenIds.length);
  for (uint i = 0; i < tokenIds.length; i++) {
      tokenId = tokenIds[i];
      Stake storage staked = vault[tokenId];
      tmp[i] = staked;
  }
  return tmp; 
2
  • I've tried your code, that's the return: { "0": "tuple(uint256,uint256,uint256,address)[]: 1,1657616003,1657615943,0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2,2,1657616003,1657615943,0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2" } It seems only 1 object with an array inside with the 2 answer concatenated, am i wrong? Jul 12, 2022 at 9:12
  • That looks correct. . Assign the function return to another Stake[] and see if it gives you the expected result(it should).
    – AoS
    Jul 14, 2022 at 23:56
0

You can try

function getNftInfo(uint256[] calldata tokenIds) public view returns (Stake[] memory){

    Stake[] memory tmp = new Stake[](tokenIds.length);
    for (uint i = 0; i < tokenIds.length; i++) {
        tmp[i] = vault[tokenIds[i]];
    }
    
    return tmp;
}

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.