Consider this example of a very simple savings contract, where users send Dai, which the contract converts to cDai. At any time users are free to withdraw their share of the accrued interest. I cannot figure out how to do this without iterating over an unbounded loop.


User A sends 100 Dai to the contract, which converts the Dai to cDai. One week later, user B sends 100 Dai to the contract, which again is converted to cDai. Another week passes, and user A wishes to withdraw his accrued interest.

Assume current value of the cDai is 203 Dai. 200 Dai principal, 3 Dai interest.

User A has locked up his Dai for twice as long (two weeks) as user B (one week), therefore he is owed twice as much interest- i.e. of the 3 Dai interest he should get 2.

Interest allocated to user A is calculated this way:

Total interest (3) * number of weeks user A has held it (2) / number of weeks all users have held it (3)

Here's my question. How to do the above, without iterating over an unbounded loop, which is extremely bad practice in ethereum? How do you figure out that total number of weeks all users have held it is 3, without looping over every individual user, and taking the difference between deposit time and current time?

Is there some other way to arrive at the answer of user A is owed 2 Dai interest?

1 Answer 1


I figured it out :)

You keep a running total of the average timestamp that each user deposits- only needs to be updated when each new user joins. You then take the difference between this average and the current timestamp, and multiply by number of users. This gives you the total time held by all users, without looping.

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.