DemocracyEarth / ubi

Universal Basic Income token.
224 stars 39 forks source link

Apply Accruing Rate Retroactively #68

Closed 0xferit closed 3 years ago

0xferit commented 3 years ago

This is the minimal change and its test to make accruing tokens happen retroactively while preventing negative balance withdrawals.

This ensures users who started accruing at the same time, end up with the same amount of tokens.

Edge case: If accruing rate slows down, some users who withdrawn recently might see a negative balance available to withdraw. This is a temporary situation and the system acts as if the user has withdrawn his/her tokens in advance. After a while balance becomes positive again.

Key change:

function getAccruedValue(address human) public view returns (uint256 accrued) {
    uint totalAccured = accruedPerSecond * (block.timestamp - accruedSince[human]);

    // If this human does not have started to accrue, or current available balance to withdraw is negative, return 0.
    if (accruedSince[human] == 0 || withdrawn[human] >= totalAccured) return 0;

    else return totalAccured - withdrawn[human];
  }

And also accruedSince[human] now stores the initial accruing timestamp.

fnanni-0 commented 3 years ago

@ferittuncer I think that += should go here https://github.com/ferittuncer/ubi/blob/4697614453a20854d5a851e4cefd4a4b814aa99c/contracts/UBI.sol#L93.

Look what happens when someone calls mintAccrued() 10 times in a row in the same block.

santisiri commented 3 years ago

@fnanni-0 i think that makes sense. you can do a PR with the modification as well.. and a test case would be dope.

0xferit commented 3 years ago

Yeah, I did not notice it. Let me commit the fix. Thanks @fnanni-0