codehawks-2023-07-dsc-l05

[L-05] Precision loss when calculating the health factor

보고서

Summary

곱셈을 하기 전 나눗셈을 하여 반올림으로 인해 정밀도가 떨어질 수 있다.

Keyword

arithmetic error, rounding error, precision, loss of precision

Vulnerability

_calculateHealthFactor에서, 곱하기 전에 나눗셈을 하여 반올림 이슈가 발생할 수 있다.

1e18을 곱하기 전에 먼저 LIQUIDATION_PRECISION로 나눗셈을 한다. 따라서 계산 결과가 반올림으로 인해 정밀도가 떨어질 수 있다.

    function _calculateHealthFactor(uint256 totalDscMinted, uint256 collateralValueInUsd)
        internal
        pure
        returns (uint256)
    {
        if (totalDscMinted == 0) return type(uint256).max;
@>      uint256 collateralAdjustedForThreshold = (collateralValueInUsd * LIQUIDATION_THRESHOLD) / LIQUIDATION_PRECISION; //@audit Division (by LIQUIDATION_PRECISION) before multiplication
@>      return (collateralAdjustedForThreshold * 1e18) / totalDscMinted; //@audit Multiplication (by 1e18) after division
    }

Impact

계산의 정밀도가 떨어진다.

Mitigation

곱셈을 먼저 모아서 처리한 후 나눗셈을 한다.

    function _calculateHealthFactor(uint256 totalDscMinted, uint256 collateralValueInUsd)
        internal
        pure
        returns (uint256)
    {
        if (totalDscMinted == 0) return type(uint256).max;
-       uint256 collateralAdjustedForThreshold = (collateralValueInUsd * LIQUIDATION_THRESHOLD) / LIQUIDATION_PRECISION;
-       return (collateralAdjustedForThreshold * 1e18) / totalDscMinted;
 
+       return (collateralValueInUsd * LIQUIDATION_THRESHOLD * 1e18) / (LIQUIDATION_PRECISION * totalDscMinted);
    }

tags: bughunting, codehawks, smart contract, solidity, arithmetic error, rounding error, loss of precision, severity low