-
Notifications
You must be signed in to change notification settings - Fork 288
/
Precision-loss.sol
73 lines (57 loc) · 2.45 KB
/
Precision-loss.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
import "forge-std/Test.sol";
/*
Name: Precision Loss - rounding down to zero
Description:
Support all the ERC20 tokens, as those tokens may have different decimal places.
For example, USDT and USDC have 6 decimals. So, in the calculations, one must be careful.
Mitigation:
Avoid any situation that if the numerator is smaller than the denominator, the result will be zero.
Rounding down related issues can be avoided in many ways:
1.Using libraries for rounding up/down as expected
2.Requiring result is not zero or denominator is <= numerator
3.Refactor operations for avoiding first dividing then multiplying, when first dividing then multiplying, precision lost is amplified
REF:
https://twitter.com/1nf0s3cpt/status/1675805135061286914
https://github.com/sherlock-audit/2023-02-surge-judging/issues/244
https://github.com/sherlock-audit/2023-02-surge-judging/issues/122
https://dacian.me/precision-loss-errors#heading-rounding-down-to-zero
*/
contract ContractTest is Test {
SimplePool SimplePoolContract;
function setUp() public {
SimplePoolContract = new SimplePool();
}
function testRounding_error() public view {
SimplePoolContract.getCurrentReward();
}
receive() external payable {}
}
contract SimplePool {
uint public totalDebt;
uint public lastAccrueInterestTime;
uint public loanTokenBalance;
constructor() {
totalDebt = 10000e6; //debt token is USDC and has 6 digit decimals.
lastAccrueInterestTime = block.timestamp - 1;
loanTokenBalance = 500e18;
}
function getCurrentReward() public view returns (uint _reward) {
// Get the time passed since the last interest accrual
uint _timeDelta = block.timestamp - lastAccrueInterestTime; //_timeDelta=1
// If the time passed is 0, return 0 reward
if (_timeDelta == 0) return 0;
// Calculate the supplied value
// uint _supplied = totalDebt + loanTokenBalance;
//console.log(_supplied);
// Calculate the reward
_reward = (totalDebt * _timeDelta) / (365 days * 1e18);
console.log("Current reward", _reward);
// 31536000 is the number of seconds in a year
// 365 days * 1e18 = 31_536_000_000_000_000_000_000_000
//_totalDebt * _timeDelta / 31_536_000_000_000_000_000_000_000
// 10_000_000_000 * 1 / 31_536_000_000_000_000_000_000_000 // -> 0
_reward;
}
}