Cyfrin / 2023-07-foundry-defi-stablecoin

37 stars 32 forks source link

Rounding error vulnerability in liquidate() when calculating bonusCollateral value. #1146

Open codehawks-bot opened 1 year ago

codehawks-bot commented 1 year ago

Rounding error vulnerability in liquidate() when calculating bonusCollateral value.

Severity

Low Risk

Relevant GitHub Links

https://github.com/Cyfrin/foundry-defi-stablecoin-codehawks/blob/c573394cf3f21f73ef974388138193609f432c7f/src/DSCEngine.sol#L251

Summary

Rounding error vulnerability in liquidate() when calculating bonusCollateral value.

Vulnerability Details

PoC:

uint256 bonusCollateral = (tokenAmountFromDebtCovered * LIQUIDATION_BONUS) / LIQUIDATION_PRECISION;

tokenAmountFromDebtCovered = 9 LIQUIDATION_BONUS = 10 LIQUIDATION_PRECISION = 100

So:

bonusCollateral = (tokenAmountFromDebtCovered LIQUIDATION_BONUS) / LIQUIDATION_PRECISION = (9 10) / 100 = 0.99 = 0 (after rounding)

Impact

When calculating:

uint256 totalCollateralToRedeem = tokenAmountFromDebtCovered + bonusCollateral;

bonusCollateral will be zero, which will cause the updated values of the following to be incorrect:

s_collateralDeposited IERC20(tokenCollateralAddress).transfer(to, amountCollateral)

Tools Used

VSC, manual.

Recommendations

Implement rounding error mitigation, for example fixed-point math libraries, or manually implement fixed-point math calculations.