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?