I need to loop though all of the members of a map and change their property (which is a struct).
the way i'm doing this is when adding a member to the map object also save it's address inside an array and later loop through the array and load the user's struct from the map then do changes.
struct Users {
address user;
uint balance;
uint bonus;
}
mapping (address => Users) instructors;
address[] public allUsers;
function setInstructor(address _address, uint balance, uint _bonus) onlyOwner public {
Users storage instructor = instructors[_address];
instructor.user = _address;
instructor.balance = _balance;
instructor.bonus = _bonus;
allUsers.push(_address) -1;
}
function addBalance(_amount) onlyOwner public {
uint length = allUsers.length;
for (uint i = 0; i < length ; i++) {
Users[allUsers[i]].balance = Users[allUsers[i]].balance + (Users[allUsers[i]].bonus * _amount);
}
}
I was wondering if there is a better way to this? because user's can go pretty a lot and a for loop is expensive in terms of gas usage.
should i user a external server to do the loop?
x.push(y) -1
seems to be a pretty solid indication of users who don't quite understand what they're doing. Do you understand what you're doing?uint amount
, which you increment in functionaddBalance
. Then, implement functiongetBalance(address _user)
which will returnUsers[_user].balane + Users[_user].bonus * amount
.[_user].bonus
can be changed by user at anytime.