Skip to content
Business logic Audit finding Intermediate

Users can have positions with a margin lower than the allowed minimum margin

The protocol enforces a minimum margin when opening positions but not when closing them, allowing a position to be left with a margin below the minimum. This could cause rounding errors in fee and PnL calculations and make liquidation impractical.

mstpr-brainbot Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-05-elfi-protocol-judging/issues/249

The protocol has acknowledged this issue.

Found by

mstpr-brainbot

Summary

Opening very small positions is not allowed. However, closing positions such that the remaining margin is minimal (dust) is possible

Vulnerability Detail

When positions are opened, it is strictly checked whether the position's initial margin is higher than the minimum allowed margin:

Solidity
function _validatePlaceOrder(IOrder.PlaceOrderParams calldata params) internal view {
            //..
            -> if (params.isCrossMargin && params.orderMargin < AppTradeConfig.getTradeConfig().minOrderMarginUSD) {
                revert Errors.PlaceOrderWithParamsError();
            }
        }
    }

However, positions can be closed in such a way that the remaining margin is lower than the minimum order margin in USD. There are no checks to ensure that the leftover margin will be higher than the minimum order margin in USD.

Coded PoC:

TypeScript
it("Closing positions can end up the position in dust", async function () {
		const wbtcAmount = precision.token(10);
		await deposit(fixture, {
			account: user0,
			token: wbtc,
			amount: wbtcAmount,
		});

		const orderMargin = precision.token(100_000); // 4btc$
		usdc.connect(user0).approve(diamondAddr, orderMargin);
		const executionFee = precision.token(2, 15);
		const tx = await orderFacet.connect(user0).createOrderRequest(
			{
				symbol: btcUsd,
				orderSide: OrderSide.LONG,
				posSide: PositionSide.INCREASE,
				orderType: OrderType.MARKET,
				stopType: StopType.NONE,
				isCrossMargin: true,
				marginToken: wbtcAddr,
				qty: 0,
				leverage: precision.rate(5),
				triggerPrice: 0,
				acceptablePrice: 0,
				executionFee: executionFee,
				placeTime: 0,
				orderMargin: orderMargin,
				isNativeToken: false,
			},
			{
				value: executionFee,
			}
		);

		await tx.wait();

		const requestId = await marketFacet.getLastUuid(ORDER_ID_KEY);

		const tokenPrice = precision.price(25000);
		const usdcPrice = precision.price(1); // 1$
		const oracle = [
			{
				token: wbtcAddr,
				targetToken: ethers.ZeroAddress,
				minPrice: tokenPrice,
				maxPrice: tokenPrice,
			},
			{
				token: usdcAddr,
				targetToken: ethers.ZeroAddress,
				minPrice: usdcPrice,
				maxPrice: usdcPrice,
			},
		];

		await orderFacet.connect(user3).executeOrder(requestId, oracle);

		let positionInfo = await positionFacet.getSinglePosition(
			user0.address,
			btcUsd,
			wbtcAddr,
			true
		);

		const tx2 = await orderFacet.connect(user0).createOrderRequest(
			{
				symbol: btcUsd,
				orderSide: OrderSide.SHORT,
				posSide: PositionSide.DECREASE,
				orderType: OrderType.MARKET,
				stopType: StopType.NONE,
				isCrossMargin: true,
				marginToken: wbtcAddr,
				qty: positionInfo.qty - BigInt(5),
				leverage: precision.rate(5),
				triggerPrice: 0,
				acceptablePrice: 0,
				executionFee: executionFee,
				placeTime: 0,
				orderMargin: orderMargin,
				isNativeToken: false,
			},
			{
				value: executionFee,
			}
		);

		await tx2.wait();

		const requestId2 = await marketFacet.getLastUuid(ORDER_ID_KEY);

		await orderFacet.connect(user3).executeOrder(requestId2, oracle);

		positionInfo = await positionFacet.getSinglePosition(
			user0.address,
			btcUsd,
			wbtcAddr,
			true
		);

		console.log("Leftover position qty", positionInfo.qty);
	});

Impact

When positions have small amount of margin and overall qty there will be rounding errors on calculating the positions fees,pnl and many other things. Also, liquidations might not be possible for these accounts because of rounding errors or because its profitability to liquidate such small margined accounts.

Code Snippet

https://github.com/sherlock-audit/2024-05-elfi-protocol/blob/8a1a01804a7de7f73a04d794bf6b8104528681ad/elfi-perp-contracts/contracts/process/OrderProcess.sol#L363-L412

https://github.com/sherlock-audit/2024-05-elfi-protocol/blob/8a1a01804a7de7f73a04d794bf6b8104528681ad/elfi-perp-contracts/contracts/process/DecreasePositionProcess.sol#L60-L204

Tool used

Manual Review

Recommendation

Check whether the remaining margin is higher the allowed min margin

Discussion

0xELFi

Yes, we are considering retaining a smaller margin when users reduce their positions or change their leverage

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

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 close-position logic lacks a check that the remaining margin after a decrease is at least the minimum order margin.

Impact

Small margin and quantity positions may suffer rounding errors in fee and PnL calculations, and liquidations might not be possible due to rounding errors or unprofitability.

What the attacker needed

A funded account; ability to open and close positions

The fix

The protocol should check that the remaining margin after a decrease is at least the minimum order margin.

How it was found

  1. Deposit collateral and open a cross-margin long position with margin above the minimum.
  2. Execute the order to create the position.
  3. Create a decrease order that reduces the position quantity, leaving a very small remaining quantity.
  4. Execute the decrease order.
  5. Observe that the remaining position has a margin below the minimum allowed.

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 protocol requires a minimum margin (collateral) to open a position. The report shows that by partially closing a position, a user can leave a tiny leftover margin below that minimum. This tiny amount can cause calculation errors and make it hard to liquidate the position.

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 mstpr-brainbot

View all

43 more disclosed reports, best first.

More from Elfi

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.