Skip to content
Business logic Audit finding Advanced

Close price impact has no depth floor: a close at depleted pool depth confiscates the trader's whole margin account or freezes it for days

A close priced at a tiny positive pool depth is charged a price-impact fee that grows without bound as depth approaches zero, so a trader's ordinary close can consume its entire clearinghouse balance, including free settlement it never put at risk. An attacker can deliberately set the depth to one lot above zero with its own close, and a trader that bounds the charge instead has its funds frozen until another party acts.

v4rvl Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#99959 [SC-High] Close price impact has no depth floor: a close at depleted pool depth confiscates the trader's whole margin account or freezes it for days

Submitted on Nov 15th 2026 at 22:00:22 UTC by @v4rvl for Audit Competition | Plether

Description

Summary

A trader's ordinary full close at a pool depth of 56,264,010 atoms (56.264010 USDG) takes its whole clearinghouse balance. Its cash changes by -99992490996 atoms and it keeps no claim. The same close one lot earlier, at depth 0, leaves it 99,992,490,996 atoms to withdraw and a claim of 26,972,709,004 atoms. With 1,000,000 USDG more free settlement in the account, the cash change is -1099992490996 atoms. With a finite charge bound on the order, the close is refused and the same 99,992,490,996 atoms stay locked through 7 days of marks. In a pool that was never degraded and holds no trader claims, a 10-lot minority close pays 9,962,348 atoms of price impact instead of 3,911,183 at price 1.00, and at price 1.98 the trader loses its whole account (cash change -1006941136 atoms against -8525196 in the control).

The fresh VPI charge of a close is k * (S_post^2 - S_pre^2) / (2D). D is the pool's economic depth: pool assets minus outstanding trader claims, floored at zero. The engine skips this charge only when D == 0 exactly, to "keep protective exits live". At any D >= 1 atom the full curve applies, so the charge jumps from zero to millions of USDG one lot above the exemption. The close planner collects the charge from the account's realized gain, its margin, its action reserve and its entire free settlement balance. That balance is money the trader holds in the clearinghouse but has not put at risk in the position. While the engine is in degraded mode, an account with an open position cannot withdraw that free balance first.

Any account can set D to within one lot of zero with an ordinary close of its own:

  • a winner sizes its profit-taking close so the cash payout leaves one lot of depth
  • or, while claims exceed pool assets, a loser closes just enough lots to cover the deficit.

The next trader who closes on the minority side then loses one of two things:

  • with no finite maxActionChargeAssets on the order, its whole clearinghouse balance
  • with a finite bound, nothing at first: the close is refused, and its whole balance stays locked for as long as the depth stays small. Nothing moves the depth unless some other party acts.

Measured on the repository's own fixture, at the pinned commit, with public calls only:

  • Whole balance. The pool is short of its claims. A loser covers the deficit, leaving D = 56.264010 USDG. The victim's ordinary close of a 30,000-unit short that is 27,000 USDG in profit is charged 4,257,776.863043 USDG of VPI.
    • The victim loses its whole account: -99,992.490996 USDG.
    • Control: the same close one lot earlier, at D = 0. The victim keeps 99,992.490996 USDG and is owed a 26,972.709004 USDG claim.
    • With 1,000,000 USDG more free settlement in the account, it loses -1,099,992.490996 USDG.
  • Winner sets the depth, no prior claim. The large winner takes its profit in a sized close (payout in cash, D left at 1,269.718366 USDG). The victim's close follows.
    • Victim: -126,965.2 USDG versus the honest order.
    • Winner: 506,419.089446 USDG in cash and no claim. In the honest order it ended with a 511,673.487903 USDG claim against 427,408.896198 USDG of pool assets, so the pool could not settle it (claim settlement is all-or-nothing, packages/perps/ACCOUNTING_SPEC.md:770) until it gained another 511,673.487903 - 427,408.896198 = 84,264.591705 USDG.
    • The LP side gains 133,965.514188 USDG.
    • Every party's ATTACK minus CONTROL sums to 0.
  • Bounded order: frozen. The same victim with maxActionChargeAssets = 1,000 USDG: the close is refused (ConstraintViolation) now, after 24 hours and after 7 days of hourly marks.
    • The free balance cannot be withdrawn (CfdEngine__DegradedMode).
    • D stays at 56.264010 USDG throughout.
    • It ends only when another trader closes a losing position. In the control, the same bounded close executes and the victim withdraws 99,992.490996 USDG at once.

The same charge without degraded mode. The cause is wider than the neighbourhood of zero. Opens are admitted only while skew <= 40 % of D (the release maxSkewRatio), which bounds the price impact of any trade at about k * maxSkewRatio = 0.4 % of notional. LP redemptions lower D afterwards and reserve only the book's maximum liability, not the depth the skew was admitted against. A close is then priced at a depth no open would have been admitted at. Measured in a pool that was never degraded, has no trader claims and had no owner call after configuration (second test):

  • Ordinary price 1.00. The junior LP that holds the short book redeems to its cap through ordinary 1-hour epochs. A 1,000 USDG minority close then pays 9.962348 USDG of VPI (99 bp) instead of 3.911183 USDG (39 bp). The redeeming LP ends 6.954520 USDG better than in the control, from this one small close.
  • Price 1.90. The same close pays 359.214025 USDG (18.9 % of its notional, more than its 200 USDG margin). Victim -359.975623 USDG against -8.183315 USDG in the control. The redeeming LP gains 364.016655 USDG.
  • Price 1.98. The victim loses its whole 1,000 USDG account (-1,006.941136 USDG). The rest of the 1,948.555894 USDG charge is waived.
  • Bounded order. With maxActionChargeAssets = 10 USDG at 1.90, the close is refused now and after 1, 7 and 30 days. The trader cannot close at all until new LP deposits restore depth.
  • The market cannot trade the skew back. After the redemptions the pool holds little more than its reserve. A skew-reducing open would be paid a rebate from pool cash, so every size (10, 50, 200, 1,000 lots) is refused at commit with SOLVENCY_EXCEEDED. A skew-increasing open is refused with SKEW_TOO_HIGH. In the control all of them execute. The inflated charge lasts until a new LP deposit of about the redeemed size activates.

Vulnerability Detail

Root cause

  1. The fresh close VPI is skipped only at exactly zero depth. packages/perps/src/libraries/CloseAccountingLib.sol:105-110:
Solidity
        // With no economic depth, keep protective exits live without creating a fresh charge or rebate.
        // The lifetime clamp below still recovers any previously received negative VPI.
        if (inputs.poolDepthAssets != 0) {
            state.vpiDeltaAssets = CfdMath.calculateVPI(
                inputs.preSkewAssets, inputs.postSkewAssets, inputs.poolDepthAssets, inputs.vpiFactor
            );
        }
  1. The curve is k * S^2 / (2D) with no bound as D -> 0+. packages/perps/src/CfdMath.sol:129-139:
Solidity
        uint256 skewWad = skewAssets * 1e12;
        uint256 depthWad = depthAssets * 1e12;
        ...
        uint256 sqSkewOverDepthWad = (skewWad * skewWad) / depthWad;
        ...
        uint256 costWad = (vpiFactorWad * sqSkewOverDepthWad) / WAD / 2;
        return (true, costWad / 1e12);
  1. D is pool assets net of trader claims. packages/perps/src/libraries/CfdEnginePlanLib.sol:1339-1341 calls computeNetPoolDepthAssets(snap.poolAssets, snap.totalTraderClaimBalanceAssets), and packages/perps/src/libraries/PositionRiskAccountingLib.sol:21-26 returns physicalAssets > traderClaimsAssets ? physicalAssets - traderClaimsAssets : 0.

    • Every realized loss raises D by its amount.
    • Every fresh payout and every recorded claim lowers it.
    • A trader therefore sets D to within one lot by choosing the size of its own close.
  2. A positive VPI becomes an action charge. It is collected from the price gain first, then from every cash source of the account, including all free settlement. packages/perps/src/libraries/CfdEnginePlanLib.sol:1041-1058 and :1093-1133:

Solidity
        int256 actionNetAssets = cs.vpiDeltaAssets
            + int256(cs.executionFeeAssets + cs.frozenSpreadAssets + delta.pendingCarryAssets - delta.realizedCarryAssets);
        ...
            delta.actionChargeWithheldAssets = delta.priceGainAssets < delta.actionChargeAssessedAssets
                ? delta.priceGainAssets : delta.actionChargeAssessedAssets;
        ...
        uint256 collectibleFreeSettlementAssets = snap.accountBuckets.freeSettlementAssets + releasedVpiReserveAssets;
        ...
        uint256 freeConsumedAssets = actionChargeAfterReserveAssets < collectibleFreeSettlementAssets
            ? actionChargeAfterReserveAssets : collectibleFreeSettlementAssets;

The function's own documentation (CfdEnginePlanLib.sol:790-792) lists "new price gain, dedicated VPI backing, spendable action reserve, free settlement, safely released pledge". Only the remainder above all of these is waived on a full close.

  1. In degraded mode an account with an open position cannot withdraw its free balance before closing. packages/perps/src/CfdEngineSettlementSidecar.sol:274-276:
Solidity
        if (engine.degradedMode()) {
            revert ICfdEngineTypes.CfdEngine__DegradedMode();
        }

Depth near zero always implies degraded mode: the latch is set when cash net of claims falls below maximum liability (CfdEngine.sol:1353-1368).

  1. A trader can bound the action charge per order (ExecutionBounds.maxActionChargeAssets, enforced at CfdOrderPolicyEvaluatorBase.sol:509-513 on a charge that includes the close VPI, :412-414). With a bound, the close fails instead of executing. Steps 4 and 5 then leave the whole account locked until some other party raises D.

  2. Opens tie skew to depth. Nothing keeps the tie afterwards. packages/perps/src/libraries/CfdEnginePlanLib.sol:473-480:

Solidity
        uint256 maxSkewAssets = Math.mulDiv(netDepthAssets, snap.riskParams.maxSkewRatio, CfdMath.WAD);
        if (
            inputs.postSkewAssets > maxSkewAssets
                && (inputs.postSkewAssets >= inputs.preSkewAssets || orderSideIsPostOpenHeavy)
        ) {
            delta.revertCode = CfdEnginePlanTypes.OpenRevertCode.SKEW_TOO_HIGH;
            return;
        }

The redemption reserve and the open-side solvency check then lock the state in. A skew-reducing open receives its rebate from pool cash and must leave the settlement buffer intact (CfdEnginePlanLib.sol:729-734, :770-772). At a pool redeemed to its reserve it does not, so the opens that would lower the skew are refused.

A junior redemption is capped by _juniorSettlementCapacity (packages/perps/src/HousePool.sol:1205-1217): min(freeAssets, juniorPrincipal, ratioCap), where free assets set aside the book's maximum liability. Maximum liability is n * entry for one side and n * (CAP - entry) for the other (CfdMath.sol:76-90). It is not skew / maxSkewRatio. After redemptions to that cap, D is about the maximum liability, and the close charge per unit of notional is about k * skew / D: 1 % at price 1.00 (2.5 times the admitted bound), and without bound as the majority's entry price approaches the cap. Closes have no skew or depth admission of their own.

History of the guard

The zero-depth branch was added together with claim-net depth, in the commit "fix(perps): use net risk depth and fingerprint calendar changes (#118)" ("Subtract outstanding trader claims consistently in carry, skew limits, VPI ... and define zero-depth admission and close behavior"). That commit fixed the 2026-10-15 scan item "Deferred trader claims inflate open skew capacity and reduce VPI". Subtracting claims is what lets D reach a few USDG while positions are open. The guard added in the same fix covers only D == 0, so one atom above it the protective-exit rule it states does not hold.

Impact

Program impact rows claimed, quoted from the program's list:

  • Critical: "Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield"
  • High: "Temporary freezing of funds for at least 24 hours"

First test (victim frank, amounts in USDG):

arm depth D at the victim's close victim, control victim, attack where it goes
Claim path, ordinary close 56.264010 keeps 99,992.490996 + claim 26,972.709004 -99,992.490996 (whole account) pool
Claim path, +1,000,000 free settlement 56.264010 not run (the arm 0 control close leaves free settlement untouched) -1,099,992.490996, the whole account: 1,000,000 + 99,992.490996 = 1,099,992.490996 pool
Winner sets D, no claim 1,269.718366 +26,972.709004 cash -99,992.490996 (-126,965.200000 vs control) LP side +133,965.514188, winner's 511,673.487903 claim becomes 506,419.089446 cash
Bounded order (1,000 USDG) 56.264010 for 7 days closes, withdraws 99,992.490996 99,992.490996 locked, close refused none (frozen)
Protection, unlimited limits 56.264010 (as first row) whole account, 99,992.490996 lost pool
Claimant settles, then closes 56.264010 close first, then settle: -200,663.810904 -689,715.944605, that is 689,715.944605 - 200,663.810904 = 489,052.133701 worse pool

Second test, never-degraded pool, no claims (victim is a 10-lot long, 1,000 USDG funded):

price depth D at the victim's close (USDG) close VPI, control close VPI, attack victim, attack vs control (USDG) redeeming LP that holds the short book (USDG)
1.00 393,682.29 3.91 (39 bp) 9.96 (99 bp) -10.36 vs -4.31 +6.95
1.50 131,229.53 5.86 (39 bp) 44.80 (298 bp) -45.40 vs -6.46 +42.67
1.90 20,722.52 7.42 (39 bp) 359.21 (1,890 bp) -359.98 vs -8.18 +364.02
1.98 3,979.62 7.73 (39 bp) 1,948.56 assessed -1,006.94 (whole account) vs -8.53 +865.47

How the numbers fit together.

  • frank's 30,000-unit short is 27,000 USDG in profit at 1.90 (realized PnL 27,000.000000 USDG in the preview). The close VPI at D = 56.264010 USDG is 4,257,776.863043 USDG.
  • The planner withholds the whole 27,000.000000 USDG gain, collects the account's entire 99,992.490996 USDG balance, and waives the rest.
  • In the control (D = 0) there is no fresh VPI. The fee and the clawback of the rebate received at open come out of the gain, and the rest becomes a claim: 27,000.000000 - 22.800000 - 4.490996 = 26,972.709004 USDG.
  • In the winner arm, frank ends 126,965.200000 USDG worse than in the control, gina 1,747.421088 USDG worse, and the winner's face value (cash plus claim) is 5,252.893100 USDG lower. Their sum is the LP side's gain: 126,965.200000 + 1,747.421088 + 5,252.893100 = 133,965.514188 (the sum of all deltas is asserted zero).
  • What the winner gains is payment, not face value. In the control the pool ends with 427,408.896198 USDG of assets against the winner's 511,673.487903 USDG claim.
  • So in the control this part of its winnings cannot be paid: 511,673.487903 - 427,408.896198 = 84,264.591705 USDG.
  • In the attack the victims' balances are in the pool, the winner holds 506,419.089446 USDG in cash and no claim, and the pool keeps 49,700.922483 USDG.

Why the control isolates the cause. Each control runs the same accounts, the same orders and the same final price. Only the depth at the victim's close differs: 0 versus one lot above 0. The protocol itself treats D = 0 as "no fresh charge" (packages/perps/src/libraries/CloseAccountingLib.sol:105), so the loss is the discontinuity, not the market move.

Mapping to the program rows.

  • "Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield": the victim's free settlement is at-rest user funds that its position never put at risk. It moves to the pool by a public sequence in which another account chooses the depth. In the winner arm, that account receives cash it could not otherwise obtain.
  • The same row for the never-degraded pool: the party that redeems is the party that receives. An LP that holds the majority book redeems to the cap at no cost beyond the epochs. Every minority close that follows pays it 2.5 times the admitted price impact at an ordinary price, and the position's whole margin near the cap.
  • "Temporary freezing of funds for at least 24 hours": for a victim that bounds its order. Its 99,992.490996 USDG stays locked through 7 days of marks (measured), and only another party's action ends it.

Severity. Critical is claimed for the arms where the victim's order carries no finite charge bound, because the balance leaves the victim. Where the victim bounds its order, the measured outcome is the High row (the freeze). The direct beneficiary of the confiscation is the pool side, and the account that sets the depth gains payment of winnings rather than face value (see Limits).

Limits

  • Duration of the never-degraded arm. It ends when new LP capital of about the redeemed size is deposited and activates (measured: 400,000 USDG at price 1.00 and 800,000 USDG at 1.90 bring the charge back under 50 bp). Trading cannot end it, because rebalancing opens are refused in that state.
  • Never-degraded arm. At an ordinary price the excess is 99 - 39 = 60 bp of the close's notional. It exceeds 5 % of notional only at prices between the measured 1.50 (298 bp) and 1.90 (1,890 bp), and the position's 200 USDG margin only near 1.90 (359.214025 USDG charged), with the majority book entered there. The redeeming LP must hold most of the junior tranche. The charge of that arm is collected from the position's margin, reserve and gain. Free settlement can be withdrawn first while the engine is not degraded.
  • State (degraded arms). It needs a pool close to exhausted: a large one-sided winner, LPs redeemed to their cap, and a price path that pays one side and then the other. The whitepaper states this sequential path is reachable and not reserved for (packages/perps/WHITEPAPER.md:272-279: "Reserving 1 at inception did not fund this sequential path"). D near zero always comes with degraded mode.
  • Order bound. A victim whose order carries a finite maxActionChargeAssets is not confiscated. Its close is refused, and its harm is the freeze above. The repository's own fork test and most of its protection tests pass type(uint256).max (test/fork/PerpsFork.t.sol:300, and 23 of 31 CloseFinancialLimits in packages/perps/test). The integration guide leaves the bound to the user's policy (packages/perps/WORKING_WITH_AI_AGENTS.md:90-91).
  • Ordering. Orders execute in FIFO. The account that sets D cannot jump a close already queued. It sets D first, and the next minority-side close is hit, including keeper-triggered take-profit closes.
  • Honest twin. An honest winner taking profit, or an honest loser closing, can leave D small by chance, and the next honest closer suffers the same loss. The defect is in the pricing. A deliberate actor only removes the chance.
  • Repetition. Each confiscation raises D by the amount taken. A further victim is charged heavily only if someone lowers D again. In the winner arm, the winner's remaining gain was too small, and the second victim lost 1,747.421088 USDG.
  • Partial closes are refused by the post-close health check at this depth. Liquidations compute no fresh VPI.

References

  • Target: https://github.com/immunefi-team/audit-comp-plether/tree/a82d4fefb02768e5b3bddcc97dee371eee24fea8
  • Code: packages/perps/src/libraries/CloseAccountingLib.sol:105-110, packages/perps/src/CfdMath.sol:129-139, packages/perps/src/libraries/CfdEnginePlanLib.sol:473-480, packages/perps/src/libraries/CfdEnginePlanLib.sol:1041-1058, packages/perps/src/libraries/CfdEnginePlanLib.sol:1093-1133, packages/perps/src/CfdEngineSettlementSidecar.sol:274-276, packages/perps/src/HousePool.sol:1205-1217.

Relation to the documentation

  • packages/perps/SECURITY.md:1438-1440 (Known Limitations, VPI): "VPI depends on live canonical assets net of outstanding trader claims", and "Protective closes create no fresh VPI charge or rebate at zero depth".
  • packages/perps/ACCOUNTING_SPEC.md:665-669: "Protective closes and liquidations remain available ... A zero-depth close creates no fresh VPI charge or rebate".
  • packages/perps/SECURITY.md:1505, the degraded runbook: "Let closes and liquidations continue".

These promise a live, uncharged exit at zero depth. None states that one atom above zero the same close costs many times its notional and the trader's unrelated free balance.

Relation to earlier findings

  • The 2026-10-15 scan item "Deferred trader claims inflate open skew capacity and reduce VPI" was fixed by subtracting claims from depth and adding the zero-depth branch (#118). This report shows that fix is incomplete: the exemption covers D == 0 only, while claim-net depth now reaches a few USDG.
  • The scan item "Temporary pool liquidity can reduce a skew-increasing close charge" is the opposite direction (raising D to lower one's own charge).

Proof of Concept

Proof of Concept

Steps to reproduce (first test)

Book: release risk configuration (VPI factor 1 %, skew limit 40 %, fee 4 bp). Junior LP is the fixture's 1,000,000 USDG depositor (bob).

  1. At price 1.00: carol LONG 300,000 units, dave SHORT 300,000 + 270,000 = 570,000, erin LONG 300,000 (300,000 USDG margin), frank SHORT 30,000, gina SHORT 20,000 (OrderRouter.commitOrder and executeOrder).
  2. bob redeems junior shares up to his own getPendingTrancheState().maxJuniorWithdrawAssets (requestRedeem, settleLpEpoch, claimRedeem).
  3. Mark 0.50: carol closes in profit and is paid in cash.
  4. Mark 1.90.
  5. Then one of two paths:
    • Winner path (test 2): dave closes floor(D / gainPerLot) lots. The payout is cash and leaves D one lot above zero.
    • Claim path (tests 1, 3-5): dave closes more than the free cash and receives a claim (D = 0). Then erin closes deficit / lossPerLot + 1 lots, leaving D one lot above zero.
  6. frank closes his whole position with an ordinary close order.

First test: degraded pool, depth one lot above zero

Save the file below as packages/perps/test/perps/TinyDepthCloseVpi.t.sol and run, from packages/perps:

forge test --match-path test/perps/TinyDepthCloseVpi.t.sol -vv

The test uses the repository's OrderRouterPythTestBase fixture and the production V3 entrypoint OrderRouter.commitOrder(OrderRequest) with explicit ExecutionBounds.

  • Owner calls: the release risk configuration in setup only.
  • Tokens: minted only to fund accounts before they deposit.
  • No storage writes, no mocked calls.

Every arm is compared with a control on the same timeline at the same final price.

Full source of packages/perps/test/perps/TinyDepthCloseVpi.t.sol:

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

import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.sol";
import {ICfdEngineAdminHost} from "@plether/perps/interfaces/ICfdEngineAdminHost.sol";
import {ICfdEngineTypes} from "@plether/perps/interfaces/ICfdEngineTypes.sol";
import {IHousePool} from "@plether/perps/interfaces/IHousePool.sol";
import {IPositionProtectionActions} from "@plether/perps/interfaces/IPositionProtectionActions.sol";
import {PositionProtectionTypes} from "@plether/perps/interfaces/PositionProtectionTypes.sol";
import {MockPyth} from "@plether/test-utils/MockPyth.sol";

import {console2} from "forge-std/console2.sol";

import {OrderRouterPythTestBase} from "./shared/OrderRouterTestBase.sol";

/// A voluntary close priced at a small positive economic depth D = pool assets - trader claims is charged
/// k * (S_post^2 - S_pre^2) / (2D) of VPI (skipped only at D == 0) and the charge is collected from the account's
/// realized gain, margin and entire free settlement. Public entrypoints only; tokens are minted only to fund accounts.
contract TinyDepthCloseVpiTest is OrderRouterPythTestBase {
    address internal keeper = address(0x4EE9);
    address internal carol = address(0xCA201); // long, paid on the fall
    address internal dave = address(0xDA7E); // large short winner
    address internal erin = address(0xE41); // large long, loser at 1.90
    address internal frank = address(0xF4A2); // victim: small short winner
    address internal gina = address(0x61A); // second victim: small short winner

    uint256 internal constant T0 = SETUP_TIMESTAMP + 10 hours;
    uint256 internal now_;
    int64 internal px;
    IPositionProtectionActions internal book;

    // ------------------------------------------------------------------ fixture helpers
    function _release() internal {
        IHousePool.PoolConfig memory pc = _currentPoolConfig();
        pc.maxSeniorExposureAssets = 40_000_000e6;
        pc.maxSeniorShareBps = 8_000;
        pc.seniorRateBps = 800;
        pool.proposePoolConfig(pc);
        vm.warp(pool.poolConfigActivationTime());
        pool.finalizePoolConfig();
        ICfdEngineAdminHost.EngineRiskConfig memory config;
        config.riskParams = CfdTypes.RiskParams({
            vpiFactor: 0.01e18,
            maxSkewRatio: 0.4e18,
            maintMarginBps: 10,
            initMarginBps: 20,
            fadMarginBps: 300,
            baseCarryBps: 500,
            minBountyAssets: 1e6,
            bountyBps: 10,
            keeperShareBps: 5_000,
            protocolShareBps: 0
        });
        config.executionFeeBps = 4;
        config.frozenCloseSpreadBps = 50;
        config.settlementBufferBps = 25;
        engineAdmin.proposeRiskConfig(config);
        vm.warp(vm.getBlockTimestamp() + 72 hours + 1);
        engineAdmin.finalizeRiskConfig();
    }

    function _blob(int64 price, uint256 t, uint256 tPrev) internal pure returns (bytes[] memory d) {
        MockPyth.FeedUpdate[] memory u = new MockPyth.FeedUpdate[](2);
        u[0] = MockPyth.FeedUpdate(FEED_A, MockPyth.MockPrice(price, 0, int32(-8), t, tPrev));
        u[1] = MockPyth.FeedUpdate(FEED_B, MockPyth.MockPrice(price, 0, int32(-8), t, tPrev));
        d = new bytes[](1);
        d[0] = abi.encode(u);
    }

    function _tick(uint256 dt) internal {
        now_ += dt;
        vm.warp(now_);
        vm.roll(vm.getBlockNumber() + 1);
    }

    function _mark() internal {
        _tick(2);
        bytes[] memory b = _blob(px, now_ - 1, now_ - 2);
        vm.prank(keeper);
        router.updateMarkPrice(b);
    }

    function _setPx(int64 p) internal {
        px = p;
        _mark();
    }

    function _fund(address who, uint256 amt) internal {
        settlementToken.mint(who, amt);
        vm.startPrank(who);
        settlementToken.approve(address(clearinghouse), type(uint256).max);
        clearinghouse.deposit(who, amt);
        vm.stopPrank();
    }

    function _request(CfdTypes.Side side, uint256 size, uint256 margin, bool isClose, uint256 maxCharge)
        internal
        view
        returns (OrderV3Types.OrderRequest memory req)
    {
        req = OrderV3Types.OrderRequest({
            clientOrderId: keccak256(abi.encode(now_, size, margin, isClose, gasleft())),
            side: side,
            sizeDelta: size,
            marginDelta: margin,
            targetPrice: (side == CfdTypes.Side.LONG) == isClose ? type(uint256).max : 1,
            isClose: isClose,
            bounds: OrderV3Types.ExecutionBounds({
                submitBy: uint64(block.timestamp) + uint64(router.maxExecutionWindowSeconds()),
                executionWindowSeconds: uint32(router.maxExecutionWindowSeconds()),
                allowedExecutionModes: 7,
                expectedConfigHash: router.lifecycleBook().currentExecutionConfigHash(),
                maxExecutionBountyAssets: type(uint256).max,
                maxExecutionNotionalAssets: type(uint256).max,
                maxGrossAccountDebitAssets: type(uint256).max,
                maxActionChargeAssets: maxCharge,
                maxExplicitFeesAssets: type(uint256).max,
                maxPostPositionSize: type(uint256).max,
                minPostSettlementBalanceAssets: 0,
                minPostPositionEquityAssets: 0,
                maxPostLeverageBps: type(uint32).max
            })
        });
    }

    /// Commit through the production V3 entrypoint and self-execute one block later at the current price.
    function _trade(address a, CfdTypes.Side side, uint256 size, uint256 margin, bool isClose, uint256 maxCharge)
        internal
        returns (OrderV3Types.ExecutionResult memory r)
    {
        if (engine.lastMarkTime() + 40 < now_) _mark();
        _tick(1);
        OrderV3Types.OrderRequest memory req = _request(side, size, margin, isClose, maxCharge);
        vm.prank(a);
        uint64 id = router.commitOrder(req);
        _tick(2);
        bytes[] memory b = _blob(px, now_ - 1, now_ - 2);
        vm.prank(a);
        r = router.executeOrder(id, b);
    }

    function _must(address a, CfdTypes.Side side, uint256 size, uint256 margin, bool isClose) internal {
        OrderV3Types.ExecutionResult memory r = _trade(a, side, size, margin, isClose, type(uint256).max);
        require(r.status == OrderV3Types.LifecycleStatus.Executed, "trade not executed");
    }

    function _size(address a) internal view returns (uint256 s) {
        (s,,,,,,) = engine.positions(a);
    }

    function _cash(address a) internal view returns (int256) {
        return int256(settlementToken.balanceOf(a) + clearinghouse.balanceAssets(a));
    }

    function _claim(address a) internal view returns (int256) {
        return int256(engine.traderClaimBalanceAssets(a));
    }

    function _depth() internal view returns (int256) {
        return int256(po

The original report as published on Immunefi, by v4rvl. 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 price-impact charge is skipped only at exactly zero depth while the curve has no upper bound as depth approaches zero, and the charge is collected from the account's entire free settlement balance.

Impact

A victim's close can lose its whole clearinghouse balance including free settlement, or with a bounded order be refused and frozen for at least 7 days until another party raises the depth.

What the attacker needed

Public calls only; pool close to exhausted; attacker sets depth first

The fix

The zero-depth exemption should be replaced by a depth floor or a bounded charge so a close at tiny positive depth cannot cost many times its notional.

How it was found

  1. Set up the book at price 1.00 with several long and short positions and a junior LP depositor.
  2. Redeem the junior LP shares up to the maximum withdrawable amount.
  3. Mark the price to 0.50 so one side closes in profit and is paid in cash.
  4. Mark the price to 1.90.
  5. Have a trader close enough lots to leave the pool depth one lot above zero.
  6. Have the victim close its whole position with an ordinary close order.

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 pool charges a fee for moving the price, and that fee is meant to be small. The fee is calculated by dividing by the pool's spare depth, so when that depth is almost zero the fee becomes enormous. Because the fee is taken from the trader's whole account balance, not just the trade, a close at that moment can wipe out money the trader never risked.

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 v4rvl

View all

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