Skip to content
Business logic Audit finding Advanced

Margin Balance can be forced to be < 0 even realizing upnl indirectly

The margin withdrawal check allows a user to withdraw all margin as long as equity (margin plus unrealised profit) meets the intended margin, leaving margin at zero. When the user later closes another position, the close logic refunds a margin delta that was already withdrawn, letting the attacker extract more than they deposited.

dan__vinci Follow

Originally disclosed on Code4rena

Submitted by dan__vinci

perps/types/Position.sol #L90-L128

The protocol currently prevents users from RemovingMargin such that the margin balance is negative this way even if the equity i.e. profit of the account is good enough the user can’t realize their upnl without closing the position.

function removeMargin(address account, uint256 subaccount, uint256 amount)
        external
        onlySenderOrOperator(account, PerpsOperatorRoles.WITHDRAW_MARGIN)
    {
        ClearingHouse storage clearingHouse = StorageLib.loadClearingHouse();

        __MarginUpdateCache__ memory cache;

        // load account
        (cache.assets, cache.positions) = clearingHouse.getAccount(account, subaccount);

        if (amount == 0) revert InvalidWithdraw();
        if (cache.positions.length == 0) revert InvalidWithdraw();

        // realize funding payment
        cache.fundingPayment = ClearingHouseLib.realizeFundingPayment(cache.assets, cache.positions);

        // settle margin update
        int256 remainingMargin = StorageLib.loadCollateralManager().settleMarginUpdate({
            account: account,
            subaccount: subaccount,
            marginDelta: -amount.toInt256(),
            fundingPayment: cache.fundingPayment
        });

        // assert post withdraw margin requirement (margin + upnl) >= max(intendedMargin, totalNotional / 10)
        // where intendedMargin is the sum of notional / leverage for open positions
     @>>>   clearingHouse.assertPostWithdrawalMarginRequired({
            assets: cache.assets,
            positions: cache.positions,
            margin: remainingMargin
        });

        // set position update (note: this will just be the new position.lastCumulativeFunding)
        clearingHouse.setPositions({
            tradedAsset: "",
            account: account,
            subaccount: subaccount,
            assets: cache.assets,
            positions: cache.positions
        });

        emit MarginRemoved(account, subaccount, amount, remainingMargin, StorageLib.incNonce());
    }
  function assertPostWithdrawalMarginRequired(
        ClearingHouse storage self,
        DynamicArrayLib.DynamicArray memory assets,
        Position[] memory positions,
        int256 margin
    ) internal view {
        if (margin < 0) revert MarginRequirementUnmet();

        (uint256 intendedMargin, int256 upnl) = _getIntendedMarginAndUpnl(self, assets, positions);
        uint256 totalNotional = self.getNotionalAccountValue(assets, positions);

        intendedMargin = intendedMargin.max(totalNotional / 10);

        if (margin + upnl < intendedMargin.toInt256()) revert MarginRequirementUnmet();
    }

But a malicious user can still systematically perform this by having multiple positions and one in good profit enough equity currently. The protocol allows a user to call removeMargin(...) and withdraw their entire posted margin as long as the account equity (margin + upnl) meets assertPostWithdrawalMarginRequired(). However, assertPostWithdrawalMarginRequired() permits margin to become 0 so long as margin + upnl >= intendedMargin.

Later, the user will close one of his other positions. The closing flow returns a marginDelta amount (proportional refund of the original IM slice) into the account’s free collateral. Because the user previously withdrew their margin, this returned marginDelta becomes newly available free collateral that the attacker can immediately withdraw — effectively extracting more than they had originally deposited while positions were opened without real collateral backing.

This creates a replayable drain: withdraw margin while in profit → close (or partially close) positions to trigger marginDelta refunds → withdraw the refunded margin → repeat.

function _close(Position memory self, Side side, uint256 quoteTraded, uint256 baseTraded)
        private
        pure
        returns (PositionUpdateResult memory result)
    {
        __CloseCache__ memory cache; //@audit this is the cache nigga

        //@audit-info the closeSize we want to close is the self.amount.min
        cache.closeSize = self.amount.min(baseTraded);

        // pro rate quote amounts by close
        cache.closedOpenNotional = self.openNotional.fullMulDiv(cache.closeSize, self.amount);
        cache.currentNotional = quoteTraded.fullMulDiv(cache.closeSize, baseTraded);
        result.rpnl = _pnl(self.isLong, cache.closedOpenNotional, cache.currentNotional);

        //@audit-info we have this marginDelta -closedOpenNotional
       @>> result.marginDelta = -cache.closedOpenNotional.fullMulDiv(1e18, self.leverage).toInt256();

        self.openNotional -= cache.closedOpenNotional;
        self.amount -= cache.closeSize; //@audit-info we reduced the value as appropriately

        quoteTraded -= cache.currentNotional;
        baseTraded -= cache.closeSize; //@audit-info we reduce this guy too appropriately

        if (self.isLong) result.oiDelta.long = -cache.closeSize.toInt256();
        else result.oiDelta.short = -cache.closeSize.toInt256();

        if (result.sideClose = self.amount == 0) {
            // reverse open
            if (baseTraded > 0) { //@audit-info if we have a remaining order to push into the system
                result.marginDelta = _open(self, side, quoteTraded, baseTraded); //@audit-info we get the marginDelta
                if (self.isLong) result.oiDelta.long += baseTraded.toInt256();
                else result.oiDelta.short += baseTraded.toInt256();
            } else {
                // full close, set to defaults
                delete self.lastCumulativeFunding;
                delete self.isLong;
            }
        }
    }

The root cause is that the way finalMarginDelta is calculated, it depends on the equity of the user. Blindly any user with enough equity more than the intendedMargin can easily perform this attack.

 function rebalanceClose(
        ClearingHouse storage self,
        DynamicArrayLib.DynamicArray memory assets,
        Position[] memory positions,
        int256 margin,
        int256 marginDelta
    ) internal view returns (int256 finalMargin, int256 finalMarginDelta) {
        (uint256 intendedMargin, int256 upnl) = _getIntendedMarginAndUpnl(self, assets, positions);

        // full close
        if (intendedMargin == 0) {
            if (margin < 0) return (margin, 0);
            else return (0, -margin);
        }

        int256 equity = margin + upnl;

        // finalMarginDelta = MAX(marginDelta, MIN(intendedMargin - equity, 0))
        // marginDelta on a decrease is -(closedOpenNotional / leverage), where
        // closedOpenNotional = position.openNotional * closedAmount / position.amount
       @>> finalMarginDelta = marginDelta.max((intendedMargin.toInt256() - equity).min(0));
        finalMargin = margin + finalMarginDelta;
    }

If the (intendedMargin.toInt256() - equity) is less than the marginDelta which we use to open the position initially, the marginDelta is returned directly regardless if it was already consumed by removeMargin.

Impact

This bug is a critical bug as a user with enough equity upnl in one position can realize it indirectly with closing off another position.

Recommended mitigation steps

On close, do not refund marginDelta if that portion of IM was already withdrawn. When calculating finalMarginDelta to return on close, cap the refund to the actual reserved IM remaining for that position.

View detailed Proof of Concept


The original report as published on Code4rena, by dan__vinci. 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 close logic calculates the margin refund based on the original position size and leverage without checking whether that margin was already withdrawn, so the refund is paid out twice.

Impact

A user with enough unrealised profit could extract more funds than they deposited, potentially draining the protocol.

What the attacker needed

Multiple open positions; at least one position in profit; ability to call removeMargin

The fix

On close, cap the margin refund to the actual reserved initial margin remaining for that position, and do not refund margin that was already withdrawn.

How it was found

  1. Open multiple positions with margin.
  2. Call removeMargin to withdraw the entire posted margin while the account equity (margin + upnl) still meets the intended margin requirement.
  3. Close one of the other positions, which returns a marginDelta refund into free collateral.
  4. Withdraw the refunded margin, extracting more than originally deposited.
  5. Repeat the process to drain funds.

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.

In a perpetual futures exchange, users post collateral (margin) to back their positions. This report shows that a user can take back all their margin while still holding a profitable position, then close another position to get a refund of margin they already took out, effectively draining extra funds.

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 dan__vinci

View all

1 more disclosed report, best first.

More from GTE Perps and Launchpad

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.