# How to divide and allocate the amount to token holders without loops?

I have a smart contract that keeps record of the people holding the tokens in form of array of addresses. An owner of the smart contract, whenever, sends some ethers to the contract these ethers shall be divided among all token holders depending on how much they hold the tokens and accordingly these fund will be divided. We will allocate the funds to each holder in a form of mapping and once they want to redeem the pending reward will be sent to them.

My code is currently using a for loop to divide the received deposit among all token holders by iterating over the complete array of holders.Since using loop will eventually goes out of gas limit, so what should be the suggested approach here? How can we divide an amount among all token holders without looping/much gas?

You can use the amortisation of work pattern in order to do so. There is a detailed article that describe the similar case.

``````const uint pointMultiplier = 10e18;
struct Account {
uint balance;
uint lastDividendPoints;
}
uint totalSupply;
uint totalDividendPoints;
uint unclaimedDividends;
function dividendsOwing(address account) internal returns(uint) {
var newDividendPoints = totalDividendPoints - accounts[account].lastDividendPoints;
return (accounts[account].balance * newDividendPoints) / pointMultiplier;
}
var owing = dividendsOwing(account);
if(owing > 0) {
unclaimedDividends -= owing;
accounts[account].balance += owing;
accounts[account].lastDividendPoints = totalDividendPoints;
}
_;
}
function disburse(uint amount) {
totalDividendPoints += (amount * pointsMultiplier / totalSupply);
totalSupply += amount;
unclaimedDividends += amount;
}
``````

Basically you make users to claim their own dividends with `updateAccount` modifier and only store `totalDividendPoints` and `unclaimedDividends`

• will it keep a record that token holders that become holders late don't get deposits from earlier funds? for instance we had a fund of 10 ethers to be distributed to 5 people and all of them claimed it except two, later on we get another token holder and he claim immediately, will he get from the portion of early to people or technically he should get 0 ? Sep 1, 2019 at 12:46
• Do you have a fixed totalSupply? Sep 1, 2019 at 14:26
• Yes total supply is fixed but I want to give dividends to those who were token holders at the moment I sent funds to contract, and the fund that I will send shall be divided among all exiting token holders, and for others who come late shall not get any amount from earlier funds Sep 1, 2019 at 15:07
• then if you wanna use it like this you should keep track of every dividend distribution and how many users participated in each of those distributions. And then let users to claim them one by one Sep 4, 2019 at 13:24