In my stacking smart contract, User can staken any ERC20 token :

 struct Token {
        address tokenAddress;
        uint256 stakedAmount;
        uint256 lastTransactionDate;


//stakingUserBalance between adress token and amount
mapping(address => mapping(address => Token)) public stakingUserBalance;

For the Dapp, I need to return all tokens stacked by user. So, I choose to return an array of Token.

 function getUserStakedTokens(address userAddress) public view returns(Token[] memory){

Is it possible to loop on each token store on mapping when I know the userAddress ? To loop on my mapping for specific user, do I need an Array ?

Thanks for your help ?

1 Answer 1


It is not possible to look over a mapping in solidity. This is because technically, every key exists with zero value by default. If you want to get the list of all the tokens a user has staked you'll need to maintain a array of token addresses for each user.

mapping (address => address[]) userToTokenAddress;

Every time the user stakes a token, check if the user has already staked the token, if not, append it to the userToTokenAddress list.

// rest of the staking logic

If you want to remove the token address from the array when the user withdraws all of that particular token, you'll have to restructure it differently. Alternatively, you can just check if the balance of each token is non-zero off-chain, so you can get a filtered list of valid staked tokens.

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.