Search code examples
error-handlingsolidityrounding-erroruintevm

How to handle rounding errors in solidity code? Avoid precision loss or keep track of precision losses?


How to handle rounding errors in solidity code? Avoid precision loss or keep track of precision losses.

Example, if i have some calculated(includes a division) factors stored in a variable when a user is doing let's say staking, and when he redeems, the calculated factors will be used to calculate his returns.

However given that the calculated factors had some precision loss, the user will get some wei amount lesser than he should be getting. How do we handle this? How do major protocol cater for this? Do we simply accept the loss of wei amounts of the token?

I looked up for some protocol like 0x, https://github.com/0xProject/protocol/blob/b19e29e03d8a6bf5d797af18c3ce227594994f55/contracts/utils/contracts/src/v08/LibMathV08.sol#L134C2-L134C2

However I cannot understand what the target parameter means.


Solution

  • I guess there's no straight way of getting around the rounding errors in solidity.

    One simple way to reduce the errors is just using a large multiplier and doing the divisions in the end