sherlock-audit / 2024-03-flat-money-fix-review-contest-judging

3 stars 2 forks source link

Dudex_2004 - The `newAverageEntryPrice` for `averagePrice` is calculating incorrectly. #26

Closed sherlock-admin4 closed 4 months ago

sherlock-admin4 commented 4 months ago

Dudex_2004

high

The newAverageEntryPrice for averagePrice is calculating incorrectly.

Summary

See details.

Vulnerability Detail

The updateGlobalPositionData updates the global position data for all users . However we know that the averagePrice is the price for opening new position for user. But when we updating the new averagePrice for all users it is very less than it should be because everytime when the sizeOpenedTotal is increasing then the newAverageEntryPrice is decreasing or when the _additionalSizeDelta is changing. So the problem is here that after some point when there will be much sizeOpenedTotal then this newAverageEntryPrice will be zero or very less then initialial averagePrice . Let's analyze how ?

1) Lets say initially averagePrice = 1000. 2) The sizeOpenedTotal = 10 , and the price of underlying asset is 100. 3) Now if we want to update newAverageEntryPrice for 2 more opened position (_additionalSizeDelta) with (5 + 5 eth) = 10 , then it will be halft of previous averagePrice which was 1000 let see how.

int256 averageEntryPrice = int256(_globalPositions.averagePrice);
int256 newAverageEntryPrice = ((averageEntryPrice * sizeOpenedTotal) +
                (int256(_price) * _additionalSizeDelta)) / (sizeOpenedTotal + _additionalSizeDelta);

4) newAverageEntryPrice will be = ((1000* 10) + (100 + 10))/(10 + 10) = 505.5 ,which is half of previous averageEntryPrice.

 _globalPositions = FlatcoinStructs.GlobalPositions({
                marginDepositedTotal: newMarginDepositedTotal,
                sizeOpenedTotal: (int256(_globalPositions.sizeOpenedTotal) + _additionalSizeDelta).toUint256(),
                averagePrice: uint256(newAverageEntryPrice)
            });

5) So now we can say that averagePrice will be decreasing for all users everytime when the _additionalSizeDelta changes or if the sizeOpenedTotal is increasing.

Impact

averagePrice can be zero or very less for users if there will be much sizeOpenedTotal .

Code Snippet

https://github.com/sherlock-audit/2024-03-flat-money-fix-review-contest/blob/main/flatcoin-v1/src/FlatcoinVault.sol#L199C12-L201C1

Tool used

Manual Review

Recommendation

Please make sure that the averagePrice should be little bit higher for all users everytime when the sizeOpenedTotal is increasing rather than decreasing.