sherlock-audit / 2023-12-flatmoney-judging

9 stars 7 forks source link

cheatcode - Not checking Negative Values #285

Closed sherlock-admin closed 5 months ago

sherlock-admin commented 5 months ago

cheatcode

medium

Not checking Negative Values

The problematic code in the executeAdjust function is related to the calculation of the new margin and size of the position without checking for negative values. Here is the problematic part of the code:

uint256 newMargin = (marginAdjustment + PerpMath
    ._getPositionSummary({
        position: position,
        nextFundingEntry: cumulativeFunding,
        price: adjustPrice
    })
    .marginAfterSettlement).toUint256();

uint256 newAdditionalSize = (int256(position.additionalSize) + announcedAdjust.additionalSizeAdjustment)
    .toUint256();

In the above code, marginAdjustment and announcedAdjust.additionalSizeAdjustment are cast to uint256 without checking if the resulting values are negative, which could lead to underflows and thus incorrect, extremely large values due to the way Solidity handles unsigned integers.

Mitigation Code

To mitigate this issue, checks should be added to ensure that the resulting values for newMargin and newAdditionalSize are not negative before casting them to uint256. Here is the mitigation code:

int256 newMarginInt = marginAdjustment + PerpMath
    ._getPositionSummary({
        position: position,
        nextFundingEntry: cumulativeFunding,
        price: adjustPrice
    })
    .marginAfterSettlement;

int256 newAdditionalSizeInt = int256(position.additionalSize) + announcedAdjust.additionalSizeAdjustment;

if (newMarginInt < 0 || newAdditionalSizeInt < 0) {
    revert("New margin or size adjustment results in negative value");
}

uint256 newMargin = uint256(newMarginInt);
uint256 newAdditionalSize = uint256(newAdditionalSizeInt);

Impact

sherlock-admin commented 5 months ago

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

takarez commented:

invalid

nevillehuang commented 4 months ago

Invalid, associated logic performed here where margin adjustment is negative