solidity – How to Calculate Percentage in ERC-20 Token Contracts

erc-20mathsafemathsoliditytokens

I want to calculate user reward per day.

uint256 totalBalance = 111;
uint256 rewardPerDay = 1000;

function calculateReward(uint256 userBalance) public view returns (uint256) {
    
    uint256 poolShare = userBalance * 1000 / totalBalance;
    uint256 reward = poolShare * rewardPerDay / (1000);
    return reward;

}

The problem is, if

user no.1 userBalance = 28, poolShare = 25.22% , reward = 252

user no.2 userBalance = 83 ,poolShare = 74,77% , reward = 747

There is 1 token remaining, 1000 – (252 + 747) = 1;

How can i solve this?
User no.2 should receive 748, user no.1 should receive 252

Best Answer

This kind of rounding issues are quite typical in crypto projects. You have two options: 1) Try to decide who should get more (or less) 2) Do something else with the leftovers (also called dust).

Often it's simply not worth it to start calculating who should get more - especially as calculations are not accurate in Solidity (due to no decimal numbers). So what happens is that usually projects simply collect the dust and use it for something else. Maybe they give it back to the users in some fashion, keep it as internal fee or use it for some cause. The dust is usually such as tiny amount that it really doesn't matter for users.

Related Topic