Skip to content
Business logic Audit finding Intermediate

Excessive trading fees can result in 99.9% collateral loss for the trader

The slippage fee calculation in the liquidity pool scales linearly with trade size without any upper bound, so for very large trades the total fee (open plus close) can exceed the trader's collateral. An attacker (or any user) could open and close a large position and lose essentially all of their collateral to fees.

bytes032 Follow

Originally disclosed on Code4rena

Submitted by bytes032

This issue can lead to traders losing all their collateral due to excessive fees when opening and closing larger trades.

Proof of Concept

When the exchange opens/closes trades, it defines the order fees to be paid by the user using the orderFee function. The function takes into account both the hedging fee, which covers the cost of managing the risk associated with holding the position, and the trading fee, which accounts for the costs incurred when executing the trade.

The function works as follows:

  1. It first calculates the delta, a factor representing the rate at which the position size changes.
  2. Then, it computes the futuresSizeDelta by multiplying the input sizeDelta with the calculated delta.
  3. It calls the perpMarket.orderFee function to get the hedgingFee and a boolean flag, isInvalid, which indicates if the trade is invalid.
  4. It checks if the trade is valid by ensuring isInvalid is not set to true. If the trade is invalid, it will throw an exception.
  5. It retrieves the markPrice from the exchange.getMarkPrice function, which represents the current market price of the asset.
  6. The function calculates the valueExchanged by multiplying the markPrice with the absolute value of sizeDelta. This represents the total value of the trade.
  7. It computes the tradeFee using the getSlippageFee function, which calculates the fee based on the size of the trade.
  8. The tradingFee is calculated by multiplying the tradeFee with valueExchanged.
  9. Finally, the function returns the sum of the hedgingFee and tradingFee as the total fee for the trade.

By combining both the hedging fee and trading fee, the orderFee function comprehensively calculates the costs associated for the trade.

The problem here lies in the getSlippageFee (LiquidityPool.sol#L367-L374) function. The purpose of the getSlippageFee function is to calculate the slippage fee for a trade based on the change in position size, represented by the input sizeDelta. The slippage fee is a cost associated with executing a trade that accounts for the potential price impact and liquidity changes due to the size of the order. It helps ensure that the trading platform can effectively manage the impact of large trades on the market.

    function getSlippageFee(int256 sizeDelta) public view returns (uint256) {
        // ceil(s/100) * baseFee

        uint256 size = sizeDelta.abs();
        uint256 region = size / standardSize;

        if (size % standardSize != 0) region += 1;
        return region * baseTradingFee;
    }

The function works as follows:

  1. It first calculates the absolute value of sizeDelta to ensure the size is a positive value, regardless of whether the trade is a buy or sell.
  2. It then divides the size by standardSize (set by default to (LiquidityPool.sol#L142) 1e20), to determine the number of regions the trade occupies. This constant value represents the size of a “standard” trade, which is used to categorize trades into different regions based on their size.
  3. If there is a remainder after dividing size by the constant value, it increments the region by 1. This ensures that even partial regions are taken into account when calculating the fee.
  4. Finally, the function calculates the slippage fee by multiplying the region with baseTradingFee (currently set (TestSystem.sol#L202) to 6e15 in the test suite). This constant value represents the base fee for each region.

By calculating the slippage fee based on the size of the trade, the getSlippageFee function helps account for the potential impact of the trade on the market. The larger the trade, the more regions it occupies, resulting in a higher slippage fee. This approach incentivizes traders to be mindful of the size of their trades and the potential impact they may have on market liquidity and pricing.

The issue is that region can get really big (depending on the trade) so that the openTrade/closeTrades orderFee could >= 100% meaning all the collateral of the user will be used to pay taxes.

While I completely understand the intent of higher taxes for bigger trades, I think there should be a limit where the trade won’t get opened if a certain threshold is passed.

I’ve built a PoC with Foundry using the protocol test suite with a few comments here and there to represent the following cases:

    function depositToPool(address user, uint256 sum) internal {
        susd.mint(user, sum);
        vm.startPrank(user);
        susd.approve(address(pool), sum);
        pool.deposit(sum, user);
        vm.stopPrank();
    }

    function openShort(uint256 amount, uint256 collateral, address user)
        internal
        returns (uint256 positionId, Exchange.TradeParams memory tradeParams)
    {
        tradeParams.amount = amount;
        tradeParams.collateral = address(susd);
        tradeParams.collateralAmount = collateral;
        tradeParams.minCost = 0;

        vm.startPrank(user);
        susd.approve(address(exchange), collateral);
        (positionId,) = exchange.openTrade(tradeParams);
        vm.stopPrank();
    }

     function testSimpleShortCloseTrade() public {
        depositToPool(user_2, 1000e18 * 25000);
        uint256 pricingConstant = exchange.PRICING_CONSTANT();
        uint256 expectedPrice = initialPrice.mulDivDown(initialPrice, pricingConstant);
        uint256 multiplier = 165;
        uint256 collateralAmount = (expectedPrice * 2) * multiplier; // 200% Collateral ratio
        uint256 shortAmount = multiplier * 1e18;
        susd.mint(user_1, collateralAmount);
        console.log("CollateralAmount", collateralAmount / 1e18);
        console.log("ShortAmount", shortAmount / 1e18);
        console.log("User_1 sUSD balance", susd.balanceOf(user_1) / 1e18);

        console.log("*** OPEN TAX ***");
        (uint256 positionId,) = openShort(shortAmount, collateralAmount, user_1);
        console.log("*** OPEN TAX ***\n");

        console.log("*** CLOSE TAX ***");
        closeShort(positionId, shortAmount, type(uint256).max, collateralAmount, user_1);
        console.log("*** CLOSE TAX ***");

        console.log("User_1 sUSD balance", susd.balanceOf(user_1) / 1e18);
    }

I’m going to use the formula (orderFee * 2) / collateralAmount to calculate the tax percentage. For each case, I’ll just modify the multiplier variable.

Case 1: (multiplier 165) CollateralAmount 237600 ShortAmount 165 The tax % is: 1,7996633

Running the tests, yields the following results.

Case 2: (multiplier 1650) CollateralAmount 2376000 ShortAmount 1650 The tax % is: 10,8

Running the tests yields the following results.

Case 3: (multiplier 16500) CollateralAmount 23760000 ShortAmount 16500 The tax % is: 99,6

Case 3 proves the point that a user can potentially lose all his collateral just by paying taxes when opening/closing a trade.

Tools Used

Manual review, Foundry

Recommended Mitigation Steps

This invariant is heavily influenced by the calculation in LiquidityPool.sol#L371. In case 1 the region is 1, in case 2 is 16 and in case 3 is 165.

To address this issue, a protocol-wide maximum amount of taxes to be paid in a trade (total of open + close) should be established. If the calculated fee exceeds this threshold, the transaction should be reverted instead of opening the trade for the user. This will help protect traders from losing all their collateral due to excessive trading fees.

mubaris (Polynomial) confirmed


The original report as published on Code4rena, by bytes032. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the slippage fee function multiplies a per-region base fee by the number of size regions without any maximum cap, so the total fee can exceed the collateral for large trades.

Impact

A trader could lose up to 99.9% of their collateral to fees when opening and closing a large trade, as demonstrated in the proof of concept.

What the attacker needed

Sufficient collateral to open a large trade; access to the trading function

The fix

A protocol-wide maximum total fee (open plus close) should be established, and transactions exceeding it should be reverted.

How it was found

  1. Deposit funds into the liquidity pool to provide liquidity.
  2. Set a large trade size (multiplier) and calculate the required collateral.
  3. Open a short trade with that size and collateral.
  4. Close the short trade.
  5. Observe that the total fees (open plus close) consume nearly all of the collateral.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

A trading platform charges a fee each time you open or close a trade. The fee grows with the size of the trade, but there is no cap. If you trade a very large amount, the fees for opening and closing can add up to more than the money you put in, so you lose almost everything.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by bytes032

View all

7 more disclosed reports, best first.

More from Polynomial Protocol contest

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.