Solidity Mapping Iteration

Viewed 69

i'm new with solidity and i'm currently struggling iterating through a mapping index to get the values from a Struct

struct Stakes {
    uint256 stakeDate;
    uint256 stakeAmount;
}

mapping (address => Stakes[]) public addressToStaked;


function stake (uint256 _amount) public {
require(_amount > 0, "You must stake more than 0");
addressToStaked[msg.sender].push(Stakes(block.timestamp, _amount)); 
}

function returnStaked () public view returns (uint256[][] memory) {
uint256[][] memory result;
for (uint256 i = 0; i < 2; i++){
    result[i] = [addressToStaked[msg.sender][i].stakeDate, addressToStaked[msg.sender][i].stakeAmount];
}
return result;
}

As shown on the code, i'm able to push the Struct Values into the mapping, but when i try to read the values as in the returnStaked function i get the error:

TypeError: Type uint256[2] memory is not implicitly convertible to expected type uint256[] memory.

1 Answers

I am not sure but i think you can't iterate through mapping to get values.. if you want to get the stake for the particular address .. below code will work..

function returnStaked (address addressStaked) public view returns (Stakes[] memory) {
   return addressToStaked[addressStaked];
}

I will list some links for your references and if i found the way to do it.. i will update here...

https://solidity-by-example.org/app/iterable-mapping/

https://ethereum.stackexchange.com/questions/15337/can-we-get-all-elements-stored-in-a-mapping-in-the-contract

https://programtheblockchain.com/posts/2018/03/09/understanding-ethereum-smart-contract-storage/

Related