1

I have a mapping defined in my contract like below.

mapping(address => uint256) public stakers

I need to loop through it to get all of them for my frontend and other contract.

function getStakers() external returns(address[] memory, uint256[] memory) {
  // I need something like below
  for(i=0; i < stakers.length; i++) {
    sAddress[i] = address_from_mapping;
    sAmount[i] = uint256_from_mapping;
  }
  return (sAddress, sAmount);
}

Not sure how to implement it and also making it gas efficient as much as possible.

1 Answer 1

1

You can't call .length on stakers, since it's a mapping an not an array.

What I suggest you do is to use a struct and return an array of tuples.

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Stakers {

    struct Staker {
        address addrs;
        uint amount;
    }

    Staker[] public stakers;

    function addStaker(address _addr, uint _amount) external {
        stakers.push(Staker(_addr, _amount));
    }

    function getStakers() external view returns(Staker[] memory) {
        return stakers;
    }

}

You'll still be able to use the tuple return values in your front end.

Let me know if this helps.

1
  • That solve this problem, but I have other use case. For example, we also fetch amount for a single address provided, we check existence of an address and add or remove amount based on some condition.
    – SanjayDefi
    Commented Nov 25, 2022 at 3:09

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.