5

I am trying to figure out how to have the balance of all players reset to (amount) when a certain condition happens. This is the function that will update a specific player balance. How do I make it reset the balance of all players at once?

mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) withdrawns;

// add deposit to curent deposit, and update joined timer
   investments[_customerAddress] = investments[_customerAddress].add(_incomingTronix);
   joined[_customerAddress] = block.timestamp;

   emit Invest(_customerAddress, _incomingTronix);
}
1
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – eth
    Commented Mar 26, 2019 at 1:55

1 Answer 1

2

For resetting the balance stored in mapping, you have to record the mapping entries, because you cannot use .length property with mappings. So one thing you can do to maintain array of addresses along with the mapping. Like so:

mapping(address => uint256) investments;
address [] investers;

Whenever you add something in the investments mapping, you can also push that address to investors array. Then you can do reset logic something like that:

function resetBalance(uint256 value)public {
    for (uint i=0; i< investers.length ; i++){
        investments[investers[i]] = value;
    }
}

Which can reset the balance with value. For sure you can use any logic you want here. Also this same approach can be use with all other players.

Since mapping are not behaving like arrays so we cannot directly get the value of from mapping, we must need to track keys of mapping.

Hope it helps...

3
  • Not sure how to push addresses to the array though.
    – Zetal
    Commented Mar 26, 2019 at 2:13
  • when first time you set the key value pair in mapping like this: investments[msg.sender] = value;. Right after this you can do investors.push(msg.sender). Commented Mar 26, 2019 at 2:17
  • I was going to say that's a very expensive operation iterating through each mapping value! But I just remember, you actually get a gas refund for deleting elements :) Commented Jul 30, 2021 at 20:22

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.