Search code examples
blockchainethereumsoliditysmartcontractsether

Soldity: Iterate through address mapping


I am looking for a way to iterate through a mapping in Solidity. For example I have this mapping:

mapping (address => uint) private shares;

And I want to iterate in a function through all addresses and send them ether according to their shares.

Something like:

function giveOutEth() onlyOwner returns (bool success){
for(uint i=0; i < shares.length ; i++){
//get the address and send a value
}

}

How can I achieve this?

Thanks


Solution

  • I recieved an answer by drlecks:

    contract  Holders{
    
    uint _totalHolders; // you should initialize this to 0 in the constructor
    mapping (uint=> address ) private holders;
    mapping (address => uint) private shares;
    
    function GetShares(uint shares) public {
        ... 
        holders[_totalHolders] = msg.sender;
        shares[msg.sender] = shares; 
        _totalHolders++;
        ...
    } 
    
    function PayOut() public {
        ...
        uint shares;
        for(uint i = 0 ; i<_totalHolders; i++) {
            shares = shares[holders[i]];
            ...
        }
        ... 
    } 
    

    }

    but keep in mind that it will consume gas, and maybe its better that the stake holders withdraw their ETH and pay for gas themselfs.