I'm working on a staking contract, where the APY will be generated dynamically from a balance of the "rewards contract".
#1 Deposits 50 #2 Deposits 50 Rewards pool - 200 tokens
After a year 100 tokens will be visible on the UI as rewards for both users, because their share is 50%-50% in the pool. (If they didn't claim). If #3 deposits 100 tokens, then the APY will change, and the UI will show 50-50 tokens for #1-#2. The first 2 users lost 50-50 tokens.
Everytime a user deposits/claims the APY changes, so the task is to save the unclaimed rewards when the balance of the "rewards contract" & staking contract changes.
I thought it will be a good idea to use a loop to save the unclaimed rewards to a variable:
function saveRewards() internal {
for (uint i = 0; i < farmerIndexes.length; i++) {
farm.farmers[farmerIndexes[i]].rewards = farm.farmers[farmerIndexes[i]].rewards.add(calculateRewards(farmerIndexes[i]));
}
lastUpdate = block.timestamp;
}
I'm afraid after 100+ users the gas will be very high, and at some point the transaction will fail. How can I achieve this?