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},
]
```
Someone could help me please?
Thank you
We cannot get an array of structs currently in solidity as far as I have checked around on the internet, instead return an array of individual properties of the struct and access using their index ( as a workaround ). Kindly refer this answer also.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
/**
* @title Storage
* @dev Store & retrieve value in a variable
* @custom:dev-run-script ./scripts/deploy_with_ethers.ts
*/
contract Storage {
struct Stake {
uint256 tokenId;
uint256 lockPeriod;
uint256 startDate;
address owner;
}
mapping(uint256 => Stake) public vault;
function loadData(uint256 tokenId, uint256 lockPeriod, uint256 startDate, address owner) public {
Stake memory newStake = Stake(tokenId, lockPeriod, startDate, owner);
vault[tokenId] = newStake;
}
function getNftInfo(uint256[] calldata tokenIdsInput) public view returns (uint256[] memory tokenIdsReturn,
uint256[] memory lockPeriodsReturn,
uint256[] memory startDatesReturn,
address[] memory ownersReturn){
uint256 tokenId;
uint256[] memory tokenIds = new uint256[](tokenIdsInput.length);
uint256[] memory lockPeriods = new uint256[](tokenIdsInput.length);
uint256[] memory startDates = new uint256[](tokenIdsInput.length);
address[] memory owners = new address[](tokenIdsInput.length);
for (uint i = 0; i < tokenIdsInput.length; i++) {
tokenId = tokenIdsInput[i];
Stake storage staked = vault[tokenId];
tokenIds[i] = staked.tokenId;
lockPeriods[i] = staked.lockPeriod;
startDates[i] = staked.startDate;
owners[i] = staked.owner;
}
return (tokenIds,
lockPeriods,
startDates,
owners);
}
}