sherlock-audit / 2023-12-flatmoney-judging

11 stars 9 forks source link

GoSlang - Profits are calculated incorrectly when a user is in profit. #62

Closed sherlock-admin2 closed 8 months ago

sherlock-admin2 commented 8 months ago

GoSlang

medium

Profits are calculated incorrectly when a user is in profit.

Summary

The protocol makes sure to maximize users losses and minimize users profits this is done when calculating the PNL of a user with the _profitLoss() function.

Vulnerability Detail

in the event that PNL is negative they make sure to round towards a larger loss by subtracting 1, but this does not work when the user is in profit as they are already getting rounded down since solidity always round towards zero the users profit will be rounded down and then get subtracted one leaving the user with less profit than they should have had.

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

Impact

User that are in profit get rounded down and subtracted one instead of just getting rounded down leading to loss of funds for the user.

Code Snippet

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;
        }
    }

Tool used

Manual Review

Recommendation

Check if the user is in profit or loss and handle the cases separately, if the user is in profit do not subtract one and if the user is in loss subtract one.

Duplicate of #286

sherlock-admin commented 8 months ago

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

takarez commented:

invalid: should provide POC