ERC-721 – How to Return an Array of Structs from Solidity Contracts

arrayserc-721mappingstakingstruct

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

Best Answer

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;