sherlock-audit / 2023-12-flatmoney-judging

11 stars 9 forks source link

Bony - Wrong calculation in `PerpMath._profitLoss` #257

Closed sherlock-admin closed 7 months ago

sherlock-admin commented 8 months ago

Bony

medium

Wrong calculation in PerpMath._profitLoss

Summary

PerpMath._profitLoss function doesn't calculate the PnL correctly

Vulnerability Detail

    function _profitLoss(FlatcoinStructs.Position memory position, uint256 price) internal pure returns (int256 pnl) {
        int256 priceShift = int256(price) - int256(position.lastPrice);
        int256 profitLossTimesTen = (int256(position.additionalSize) * (priceShift) * 10) / int256(price);

        if (profitLossTimesTen % 10 != 0) {
            return profitLossTimesTen / 10 - 1;
        } else {
            return profitLossTimesTen / 10;
        }
    }

We can think of the following condition A.

We can also think of the following condition B.

Impact

Incorrect calculation of _profitLoss will lead to user fund loss

Code Snippet

https://github.com/sherlock-audit/2023-12-flatmoney/blob/bba4f077a64f43fbd565f8983388d0e985cb85db/flatcoin-v1/src/libraries/PerpMath.sol#L175

Tool used

Manual Review

Recommendation

    function _profitLoss(FlatcoinStructs.Position memory position, uint256 price) internal pure returns (int256 pnl) {
        int256 priceShift = int256(price) - int256(position.lastPrice);
        int256 profitLossTimesTen = (int256(position.additionalSize) * (priceShift) * 10) / int256(price);

-       if (profitLossTimesTen % 10 != 0) {
-           return profitLossTimesTen / 10 - 1;
-       } else {
-           return profitLossTimesTen / 10;
-       }
+       return profitLossTimesTen / 10;
    }

Duplicate of #286

sherlock-admin commented 7 months ago

1 comment(s) were left on this issue during the judging contest.

takarez commented:

valid: function is not being accurate as of current implemenation; medium(8)