Answer the question
In order to leave comments, you need to log in
Is it possible to iterate over a map in Solidity?
For example, there is an example of a smart wallet contract. You can put ether into your account, you can withdraw it. I want to be able to destroy the contract but at the same time send it back to everyone who kept the ether
pragma solidity >=0.4.22 <0.7.0;
import "../Owner.sol";
contract Wallet is Owner {
mapping (address => uint) private balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint money) public payable {
require(balances[msg.sender] >= money);
balances[msg.sender] -= money;
msg.sender.transfer(money);
}
function balance() public view returns (uint) {
return balances[msg.sender];
}
function kill() public isOwner { //onlyOwner is custom modifier
// не знаю что тут делать
for (uint i = 0; i < balances.length; i++) {
}
selfdestruct(msg.sender); // `owner` is the owners address
}
}
Answer the question
In order to leave comments, you need to log in
In the current version of the contract, there is no way to find out all the funds stored in the wallet, because there is no way to extract indexes from mapping (they are not there), so you need to additionally store an array of all owners.
In the kill method loop - iterate over all owners and send the funds. In addition, protection against reentrancy is needed - pull out the value of balances, then reset the value in mapping and only after that call transfer.
Another tip: when there is a cycle for an indefinite number of elements, then you can get stuck on too much gas consumption for one transaction. In this case, the way out is to split kill() into two methods. One method will return a given number of owners of funds, the second method will actually call selfdesctruct when withdrawing all funds.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question