Skip to content
Business logic Audit finding Advanced

An exit authorized before pool depth falls near zero can transfer the trader's whole account to the pool because close-time VPI has no upper bound

Close-time virtual price impact divides by net pool depth with no upper bound, so when depth is just above zero a minority-side close is charged many times the account's value. A trader whose exit was authorised earlier with unlimited limits can lose their entire custody to the pool, while a trader with finite limits cannot exit at all.

Nyksx Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#99567 [SC-High] An exit authorized before pool depth falls near zero can transfer the trader's whole account to the pool because close-time VPI has no upper bound

Submitted on Nov 14th 2026 at 09:06:57 UTC by @Nyksx for Audit Competition | Plether

Description

Summary

Close-time virtual price impact (VPI) divides by net pool depth, is skipped only when that depth is exactly zero, and has no upper bound. After a terminal trader-claim deficit, net depth returns to at or just above zero through the owner's documented recapitalizePool() or, with no owner action, through a trader's loss payment that exceeds the shortfall by a small amount, and a minority-side exit that the trader authorized earlier is then assessed a charge many times the account's value: in the proof of concept a stop-loss armed in a normal market with the unlimited limits, and an ordinary close committed while every preview showed a 128.13 USDG charge, each take the account's whole custody of 50,063.79 USDG on an 80,000 USDG close, and the pool gains about 50,032 USDG.

Finding Description

Close VPI is 0.5 * k * (S_post^2 - S_pre^2) / D, where S is the absolute directional skew and D is net economic depth (pool assets minus outstanding trader claims, floored at zero). When a close increases skew (the closing position is on the minority side), the charge is positive and scales with 1 / D. The close path skips the fresh charge only when D == 0 and applies a lifetime clamp that limits rebates only. No guard relates the charge to the notional being closed, and closes are not subject to the skew-to-depth cap that applies to opens.

With the release parameters (vpiFactor = 0.01e18) and an 80,000 USDG minority SHORT closing against a 160,000 USDG LONG, k * (S_post^2 - S_pre^2) / 2 is 96,000,000 USDG², so the charge is about 96,000,000 / D USDG. It exceeds a 1,600 USDG allowance (2% of the closed notional) below about 60,000 USDG of net depth, and it exceeds the account's whole custody (about 50,064 USDG) below about 1,900 USDG of net depth.

The zero-depth skip does not protect an exit after a recapitalization of exactly the shortfall. The views then show D = 0, but the close first realizes the closing account's own unpaid carry into the pool and prices VPI on depth that includes it. An order cannot execute in the second of its commit, so at least one second of carry is always realized. In the proof of concept that carry is 0.000174 USDG to 0.243642 USDG, and the charge assessed on it is between 384 million and 551 billion USDG.

1. The fresh charge is skipped only at exactly zero depth, and the clamp only limits rebates.

Solidity
// packages/perps/src/libraries/CloseAccountingLib.sol:105-118 (a82d4fef)
// 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) { // any D > 0, however small, prices the full curve
    state.vpiDeltaAssets = CfdMath.calculateVPI(
        inputs.preSkewAssets, inputs.postSkewAssets, inputs.poolDepthAssets, inputs.vpiFactor
    );
}
// Clamp so lifetime VPI (accrued + delta) never goes negative. ...
if (state.proportionalAccrualAssets + state.vpiDeltaAssets < 0) {
    state.vpiDeltaAssets = -state.proportionalAccrualAssets; // lower bound only; positive charges are not capped
}
Solidity
// packages/perps/src/CfdMath.sol:123-139 (a82d4fef), tryGetSkewCost()
if (depthAssets == 0 || skewAssets == 0) {
    return (true, 0);
}
// ...
uint256 sqSkewOverDepthWad = (skewWad * skewWad) / depthWad; // S^2 / D: grows without limit as D -> 0+
// ...
uint256 costWad = (vpiFactorWad * sqSkewOverDepthWad) / WAD / 2;
return (true, costWad / 1e12);

2. The depth used is net of trader claims, and the close adds the account's own carry to it before pricing.

Solidity
// packages/perps/src/libraries/CfdEnginePlanLib.sol:814-815 (a82d4fef), planClose()
delta.pendingCarryAssets = _pendingCarryAssets(snap);
delta.realizedCarryAssets = _applyPendingCarryRealizationToSnapshot(snap, delta.pendingCarryAssets);

// packages/perps/src/libraries/CfdEnginePlanLib.sol:638 (a82d4fef), _applyPendingCarryRealizationToSnapshot()
snap.poolAssets += realizedCarryAssets; // the closing account's carry enters the depth used below

// packages/perps/src/libraries/CfdEnginePlanLib.sol:1339-1341 (a82d4fef), _buildCloseState()
poolDepthAssets: PositionRiskAccountingLib.computeNetPoolDepthAssets(
    snap.poolAssets, snap.totalTraderClaimBalanceAssets // D = poolAssets - claims, floored at 0
),

3. An order executes at least one second after its commit. Some carry is therefore realized at every live execution:

Solidity
// packages/perps/src/PletherOracle.sol:610 (a82d4fef)
uint64 minPublishTime = request.commitTime + 1; // the execution tick is later than the commit

// packages/perps/src/OrderRouterExecutionSidecar.sol:447-452 (a82d4fef)
if (!request.oracleFrozen && ExecutionBlockNumberLib.current() == order.commitBlock) {
    return _pendingResult(order.orderId, OrderV3Types.PendingReason.SameBlock);
}
if (!request.oracleFrozen && request.oraclePublishTime <= order.commitTime) {
    return _pendingResult(order.orderId, OrderV3Types.PendingReason.MevBoundary);
}

4. Opens are guarded against low depth; closes are not. Opens reject at zero depth and must keep post-trade skew within maxSkewRatio of depth:

Solidity
// packages/perps/src/libraries/CfdEnginePlanLib.sol:448-452 and :473 (a82d4fef), _planOpenState()
uint256 netDepthAssets =
    PositionRiskAccountingLib.computeNetPoolDepthAssets(snap.poolAssets, snap.totalTraderClaimBalanceAssets);
if (netDepthAssets == 0) {
    delta.revertCode = CfdEnginePlanTypes.OpenRevertCode.SOLVENCY_EXCEEDED;
    return;
// ...
uint256 maxSkewAssets = Math.mulDiv(netDepthAssets, snap.riskParams.maxSkewRatio, CfdMath.WAD); // opens only

5. A full close collects the charge from the account's reachable buckets and waives the rest; the trader's limits are the only bound. The charge is taken from the action reserve, free settlement, released margin and, for a full close, committed order margin. The account's free settlement balance is therefore taken as well as the position margin:

Solidity
// packages/perps/src/libraries/CfdEnginePlanLib.sol:1130-1133 (a82d4fef), _planCloseCashSources()
delta.actionChargeCollectedAssets = delta.vpiRebateReserveConsumedAssets + delta.actionReserveConsumedAssets
    + freeConsumedAssets + delta.actionChargeFromReleasedMarginAssets
    + delta.actionCommittedMarginConsumedAssets;
delta.actionChargeWaivedAssets = delta.actionChargeToCollectAssets - delta.actionChargeCollectedAssets;
Solidity
// packages/perps/src/CfdOrderPolicyEvaluatorBase.sol:509-513 (a82d4fef), _enforceBounds()
_requireMaximum(
    OrderV3Types.ConstraintKind.ActionCharge,
    assessment.actionChargeAssessedAssets, // includes the fresh close VPI
    bounds.maxActionChargeAssets
);

The limits are set when the exit is authorized, not when it executes. For a protection they are stored at creation and reused by every later trigger and retry, and the documents name the unlimited value as a supported choice:

Solidity
// packages/perps/src/interfaces/PositionProtectionTypes.sol:44-46 (a82d4fef)
/// @notice Trader-authorized financial ceilings for every close generated by this protection.
/// @dev Values use 6-decimal settlement token. Zero is a real zero allowance; `type(uint256).max` is an explicit
///      unlimited allowance. The Book retains these limits across trigger and permissionless retries.

6. In degraded mode an account with an open position cannot withdraw, and an account with an active protection cannot commit an ordinary close.

Solidity
// packages/perps/src/CfdEngineSettlementSidecar.sol:274-276 (a82d4fef), validateWithdraw()
if (engine.degradedMode()) { // reached only when the account still has an open position
    revert ICfdEngineTypes.CfdEngine__DegradedMode();
}

// packages/perps/src/router/OrderLiquidationBatchLogic.sol:313-315 (a82d4fef)
if (enforceProtectionLock && host.positionProtectionBook().activePositionProtectionId(account) != 0) {
    revert OrderRouter__ProtectionActive();
}

Sequence measured in the proof of concept.

  1. In a normal market (net depth 1,000,034.01 USDG) a trader holds an 80,000 USDG SHORT on the minority side with 50,063.79 USDG of custody. The trader arms a stop-loss with all four close limits set to type(uint256).max. The lens quotes 95.99 USDG of VPI for the close.
  2. A two-sided basket move leaves a terminal trader-claim deficit: trader claims exceed pool assets, and the engine latches degraded mode. Net depth is 0. A close in this state still costs the normal amount, because the fresh charge is skipped.
  3. The owner follows the documented recovery and calls recapitalizePool() with exactly the shortfall read from the views. The views still show a net depth of 0.
  4. The mark crosses the stop-loss price. A keeper triggers the protection and executes its close one second later. The execution realizes 0.243642 USDG of the account's carry, prices VPI on that depth, and assesses an action charge of 384,231,814.54 USDG. It collects 49,063.59 USDG, which is everything the account has left after the 1,000.00 USDG price loss and the 0.20 USDG trigger bounty, and waives the rest. The account's custody goes from 50,063.79 USDG to 0, and pool assets rise by 50,031.99 USDG. The same stop-loss at normal depth, and the same stop-loss after the deficit without a recapitalization, leave the account 48,935.99 USDG and 48,935.76 USDG.

The same outcome occurs in the other measured arrangements. A recapitalization of the shortfall plus 1 USDG gives a charge of 75,274,909.98 USDG and the same loss. A stop-loss armed during degraded mode at D = 0 also ends with a custody of 0. An ordinary close with an unlimited action-charge bound, committed at D = 0 while previewClose() showed a 128.13 USDG action charge, is executed one second later, after the owner's recapitalization landed inside its 60-second execution window: it is assessed 551,724,137,963.03 USDG, the whole custody of 50,063.79 USDG is collected, and the pool gains 50,031.65 USDG. In this arrangement the lens still quotes 95.99 USDG after the recapitalization, because the views show D = 0; the depth that the execution prices on is 0.000174 USDG of carry realized in the same call. Without the recapitalization the same order leaves the account 49,935.66 USDG.

When the trader's limits are finite, the close fails instead. With an action-charge ceiling of 1,600 USDG the stop-loss attempt ends with ConstraintViolation(ActionCharge), and the protection becomes Latched. While it is latched, an ordinary close reverts with OrderRouter__ProtectionActive, cancelPositionProtection() reverts with OrderRouter__ProtectionNotArmed, and a withdrawal of the account's 39,967.60 USDG of free settlement reverts with CfdEngine__DegradedMode.

Sequence without an owner action. The same state is reached when the owner does nothing. In a second arrangement of the deficit, a third-party SHORT of 150,000 units that opened at the 2.00 cap is still open when the basket is back at 0.80, with a mark loss of 180,000 USDG, and trader claims exceed pool assets by 96,419.86 USDG. When that third party closes part of its position, its realized loss is paid into the pool, and net depth becomes the amount by which the payment exceeds the shortfall. The third party's remaining SHORT reduces the skew term, so the charge at a given depth is lower than in the first arrangement.

Conditions. Net depth uses the same formula as the solvency cash E (pool assets net of trader claims, packages/perps/src/CfdEngine.sol:865-871), so D < L is raw insolvency. Near-zero depth with open positions follows trader payouts and claims that reach pool assets, which on the real paths are recorded by _payOrRecordTraderClaim() as a terminal trader-claim deficit once cash cannot cover them (packages/perps/src/CfdEngine.sol:849-855); the close or liquidation that leaves E < L latches degraded mode through _enterDegradedModeIfInsolvent() (packages/perps/src/CfdEngine.sol:1351-1368). recapitalizePool() does not clear degraded mode (packages/perps/SECURITY.md:161), and clearDegradedMode() requires E >= L (packages/perps/src/CfdEngine.sol:658-667). While claims exceed pool assets by more than the carry a close realizes, D stays zero at pricing, and exits cost the normal amount. The behaviour therefore starts when pool assets rise to just above trader claims. Two measured ways lead there: the owner's recapitalization of about the shortfall, and a payment of a trader's realized loss that exceeds the shortfall, after which D equals the excess. An account that closes part of a losing position chooses the size of that payment in steps of one position quantum (100 units, which is 120 USDG of realized loss per step in the proof of concept). Other inflows to pool assets of a similar size were not measured. The behaviour applies to minority-side closes until depth recovers or the majority side reduces skew. New LP deposits do not restore depth in this state, because _entryStatusBlocked() treats degraded mode as a blocked-entry state

Impact Explanation

An account whose exit was authorized with the documented unlimited limits loses its whole custody to the pool when that exit executes while net depth is just above zero, after a recapitalization or after a third party's loss payment: 50,063.79 USDG on an 80,000 USDG close in the proof of concept, of which 48,935.99 USDG is in excess of what the same stop-loss costs at normal depth, and the loss includes the account's free settlement balance as well as the position margin. At a net depth of 4,740.14 USDG the same exit costs 11,002.66 USDG more than its control. The amount is booked as pool revenue, so it accrues to LPs and backs outstanding trader claims. The trader takes no action in the low-depth state, and in the committed-order case the lens preview does not show the charge even after the recapitalization. An account with finite limits does not lose funds but cannot exit.

Recommendation

Consider bounding the depth used to price a skew-increasing close from below, so that the fresh charge stays proportional to the skew it creates.

Proof of Concept

Proof of Concept

The test deploys the production contracts from BasePerpTest with the release risk parameters, the release Router configuration, release senior capacity and 1 USDG seeds. Only Pyth (MockPyth) and USDG (MockSettlementToken) are mocked. The junior LP deposits through the public ERC-7540 vault functions. Every trade is a production V3 router.commitOrder(OrderRequest) by the trader, executed by a third-party keeper with router.executeOrder(); protections use createPositionProtection(), the keeper's triggerPositionProtection() and retryPositionProtectionClose(). The owner calls only recapitalizePool(), and in the tests of item 5 the owner calls nothing. The test writes no storage, mocks no call and impersonates no protocol contract. The basket price is 0.80 (0.79 at the stop-loss). The deficit is reached on real paths: a third-party SHORT opens at 0.80, the basket reaches the 2.00 cap, a third-party LONG opens there, the SHORT closes and is paid in cash, the basket returns to 0.80, and the LONG closes with a profit above the remaining pool cash, which the engine records as a trader claim. The tests of item 5 use a second arrangement of the same basket move, with a smaller winning SHORT and one more third-party SHORT that opens at the cap and is still open at 0.80.

  1. test_Control_ArmedBeforeDeficit_NoRecapitalization() is the control: the stop-loss is armed in the normal market and executes after the deficit with no recapitalization. The account keeps 48,935.76 USDG.
  2. test_ArmedBeforeDeficit_ExactShortfallRecapitalization() is the same sequence with the owner's recapitalization of exactly the shortfall: custody goes to 0.
  3. test_CommittedAtZeroDepth_ExactShortfallLandsBeforeExecution() commits an ordinary close at D = 0, where the preview shows a 128.13 USDG charge, and executes it one second later, after the recapitalization: custody goes to 0.
  4. test_CarefulLimits_ArmedBeforeDeficit_ExactShortfallRecapitalization() uses a 1,600 USDG action-charge ceiling: the close fails, the protection latches, the account cannot close, cancel or withdraw, and a retry 25 hours later fails again.
  5. test_Control_NoOwnerAction_ThirdPartyDoesNotClose(), test_NoOwnerAction_ThirdPartyPartialCloseLeavesSixtyUsdgDepth() and test_NoOwnerAction_ThirdPartyPartialCloseLeavesFiveThousandUsdgDepth() involve no owner action: a third party closes part of a losing SHORT after the deficit and its realized loss lifts pool assets above trader claims. The account keeps 48,935.78 USDG in the control, 0 at a net depth of 60.14 USDG and 37,933.12 USDG at a net depth of 4,740.14 USDG.

Command (from the repository root, forge 1.9.0, run against unmodified a82d4fef sources):

forge test --root packages/perps --match-path test/Submission_C08.t.sol -vv

Output (test results and logs; compiler warnings omitted; amounts in USDG):

Ran 7 tests for test/Submission_C08.t.sol:ArmedExitNearZeroDepthTest
[PASS] test_ArmedBeforeDeficit_ExactShortfallRecapitalization() (gas: 23294170)
Logs:
  case: armed before the deficit, recapitalization = exact shortfall
    net depth when the exit was authorized: 1000034.012222
    lens VPI quote when the exit was authorized: 95.987522
    net depth just before the exit: 0.000000
    lens VPI quote just before the exit: 384507962.064674
    status (2 = Executed, 3 = Failed): 2
    receipt: VPI charged: 384231782.697564
    receipt: action charge collected: 49063.587503
    receipt: action charge waived: 384182750.953703
    receipt: failed action-charge check, assessed: 0.000000
    minority custody before: 50063.787503
    minority custody after: 0.000000
    pool assets gained at execution: 50031.987503

[PASS] test_CarefulLimits_ArmedBeforeDeficit_ExactShortfallRecapitalization() (gas: 26460957)
Logs:
  case: careful limits, armed before the deficit, recapitalization = exact shortfall
    net depth when the exit was authorized: 1000034.012222
    lens VPI quote when the exit was authorized: 95.987522
    net depth just before the exit: 0.000000
    lens VPI quote just before the exit: 384507962.064674
    status (2 = Executed, 3 = Failed): 3
    receipt: VPI charged: 0.000000
    receipt: action charge collected: 0.000000
    receipt: action charge waived: 0.000000
    receipt: failed action-charge check, assessed: 384231814.541206
    minority custody before: 50063.787503
    minority custody after: 50063.587503
    pool assets gained at execution: 0.000000
    retry 25 hours later: status (3 = Failed): 3
    retry 25 hours later: assessed action charge: 5868745.565738
    minority custody after the retry: 50063.587503
    minority free settlement (not withdrawable): 39967.600000

[PASS] test_CommittedAtZeroDepth_ExactShortfallLandsBeforeExecution() (gas: 22599500)
Logs:
  case: ordinary close committed at D == 0, recapitalization = exact shortfall
    net depth when the exit was authorized: 0.000000
    lens VPI quote when the exit was authorized: 95.987522
    net depth just before the exit: 0.000000
    lens VPI quote just before the exit: 95.987522
    status (2 = Executed, 3 = Failed): 2
    receipt: VPI charged: 551724137931.034483
    receipt: action charge collected: 50063.787522
    receipt: action charge waived: 551724087899.385884
    receipt: failed action-charge check, assessed: 0.000000
    minority custody before: 50063.787522
    minority custody after: 0.000000
    pool assets gained at execution: 50031.648773
    CfdClosePreview at commit: action charge: 128.126271

[PASS] test_Control_ArmedBeforeDeficit_NoRecapitalization() (gas: 22994632)
Logs:
  case: control: armed before the deficit, no recapitalization
    net depth when the exit was authorized: 1000034.012222
    lens VPI quote when the exit was authorized: 95.987522
    net depth just before the exit: 0.000000
    lens VPI quote just before the exit: 95.987522
    status (2 = Executed, 3 = Failed): 2
    receipt: VPI charged: 95.987522
    receipt: action charge collected: 127.831164
    receipt: action charge waived: 0.000000
    receipt: failed action-charge check, assessed: 0.000000
    minority custody before: 50063.787503
    minority custody after: 48935.756339
    pool assets gained at execution: 1096.231164

[PASS] test_Control_NoOwnerAction_ThirdPartyDoesNotClose() (gas: 26841881)
Logs:
  case: control: no owner action, the third party does not close
    net depth when the exit was authorized: 1000034.012222
    lens VPI quote when the exit was authorized: 95.987522
    net depth just before the exit: 0.000000
    lens VPI quote just before the exit: 95.987522
    status (2 = Executed, 3 = Failed): 2
    receipt: VPI charged: 95.987522
    receipt: action charge collected: 127.806532
    receipt: action charge waived: 0.000000
    receipt: failed action-charge check, assessed: 0.000000
    minority custody before: 50063.787503
    minority custody after: 48935.780971
    pool assets gained at execution: 1096.206532
    shortfall after the deficit (claims - pool assets): 96419.855144
    pool assets gained from the third party's close: 0.000000
    third party's SHORT still open (units): 150000.000000000000000000

[PASS] test_NoOwnerAction_ThirdPartyPartialCloseLeavesFiveThousandUsdgDepth() (gas: 30545258)
Logs:
  case: no owner action, the third party closes 84,300 units
    net depth when the exit was authorized: 1000034.012222
    lens VPI quote when the exit was authorized: 95.987522
    net depth just before the exit: 4740.144856
    lens VPI quote just before the exit: 11098.648013
    status (2 = Executed, 3 = Failed): 2
    receipt: VPI charged: 11098.647605
    receipt: action charge collected: 11130.466789
    receipt: action charge waived: 0.000000
    receipt: failed action-charge check, assessed: 0.000000
    minority custody before: 50063.787503
    minority custody after: 37933.120714
    pool assets gained at execution: 12098.866789
    shortfall after the deficit (claims - pool assets): 96419.855144
    pool assets gained from the third party's close: 101160.000000
    third party's SHORT still open (units): 65700.000000000000000000

[PASS] test_NoOwnerAction_ThirdPartyPartialCloseLeavesSixtyUsdgDepth() (gas: 30571530)
Logs:
  case: no owner action, the third party closes 80,400 units
    net depth when the exit was authorized: 1000034.012222
    lens VPI quote when the exit was authorized: 95.987522
    net depth just before the exit: 60.144856
    lens VPI quote just before the exit: 831252.922071
    status (2 = Executed, 3 = Failed): 2
    receipt: VPI charged: 831250.525975
    receipt: action charge collected: 49063.587503
    receipt: action charge waived: 782218.757656
    receipt: failed action-charge check, assessed: 0.000000
    minority custody before: 50063.787503
    minority custody after: 0.000000
    pool assets gained at execution: 50031.987503
    shortfall after the deficit (claims - pool assets): 96419.855144
    pool assets gained from the third party's close: 96480.000000
    third party's SHORT still open (units): 69600.000000000000000000

Suite result: ok. 7 passed; 0 failed; 0 skipped

Test file packages/perps/test/Submission_C08.t.sol:

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

import {BasePerpTest} from "./perps/BasePerpTest.sol";
import {CfdClosePreview} from "@plether/perps/CfdClosePreview.sol";
import {CfdEnginePlanTypes} from "@plether/perps/CfdEnginePlanTypes.sol";
import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.sol";
import {ICfdEngineTypes} from "@plether/perps/interfaces/ICfdEngineTypes.sol";
import {ICfdOrderPolicyEvaluator} from "@plether/perps/interfaces/ICfdOrderPolicyEvaluator.sol";
import {IMarginClearinghouse} from "@plether/perps/interfaces/IMarginClearinghouse.sol";
import {IOrderLifecycleBook} from "@plether/perps/interfaces/IOrderLifecycleBook.sol";
import {IOrderRouterAdminHost} from "@plether/perps/interfaces/IOrderRouterAdminHost.sol";
import {IOrderRouterErrors} from "@plether/perps/interfaces/IOrderRouterErrors.sol";
import {IPositionProtectionActions} from "@plether/perps/interfaces/IPositionProtectionActions.sol";
import {IPositionProtectionViews} from "@plether/perps/interfaces/IPositionProtectionViews.sol";
import {PositionProtectionTypes} from "@plether/perps/interfaces/PositionProtectionTypes.sol";
import {MockPyth} from "@plether/test-utils/MockPyth.sol";

/// @notice Exits authorized before net depth became small. Close-time VPI is `0.5 * k * (S_post^2 - S_pre^2) / D`
///         with D = pool assets minus trader claims; `CloseAccountingLib.buildCloseState()` skips the fresh charge
///         only when D == 0. The tests measure the minority SHORT's exit (a stop-loss armed at normal depth, or an
///         ordinary close committed at D == 0) when D is just above zero at execution. Two ways lead there after a
///         trader-claim deficit: the owner's documented `engine.recapitalizePool()` of exactly the shortfall (tests
///         2 to 4), and, with no owner action, a third party that closes a losing position and pays its realized
///         loss into the pool (tests 6 and 7). Tests 1 and 5 are the controls. Keepers act at once and honestly.
/// @dev    Release risk parameters, release Router configuration, release senior capacity and 1 USDG seeds
///         (DEPLOYMENT.md). Only Pyth (MockPyth) and USDG (MockSettlementToken) are mocked. The junior LP deposits
///         through the public ERC-7540 vault functions and a third-party keeper settles the epoch with
///         `router.settleLpEpoch()`. Every trade is a production V3 `router.commitOrder(OrderRequest)` by the trader,
///         executed by a third-party keeper with `router.executeOrder()`; between orders a keeper publishes marks
///         with `router.updateMarkPrice()`. Protections use the public `PositionProtectionBook` actions
///         (`createPositionProtection`, keeper `triggerPositionProtection`, permissionless
///         `retryPositionProtectionClose`). `CfdClosePreview` is the stateless pre-commit preview from src. Router:
///         `LegacyOrderRouterHarness`, a subclass of `OrderRouter` whose only addition (a scalar commit helper) is not
///         used here. No storage write, call mock or impersonated protocol contract.
///         Real-path deficit (`_arrangeDeficit()`, Tuesday 2024-03-12 08:10-08:30 UTC): the majority LONG and the
///         minority SHORT are open at 0.80; a third-party SHORT opens at 0.80; the basket reaches the 2.00 cap and
///         a second third party opens a LONG; the SHORT closes at 2.00 and is paid in cash, which latches degraded
///         mode; the basket returns to 0.80 and the LONG's profit is recorded as a trader claim above pool assets
///         (D == 0).
contract ArmedExitNearZeroDepthTest is BasePerpTest {

    /// @dev Measurements for one exit, from the moment it was authorized to its execution.
    struct Exit {
        uint64 protectionId;
        uint64 orderId;
        uint256 depthAtAuthorization;
        int256 quoteAtAuthorization;
        int256 vpiAccruedAtAuthorization;
        uint256 depthBeforeExit;
        int256 quoteBeforeExit;
        uint256 custodyBefore;
        uint256 custodyAfter;
        uint256 poolBefore;
        uint256 poolAfter;
        uint64 executionDeadline;
        uint64 executedAt;
        OrderV3Types.ExecutionResult result;
        OrderV3Types.OrderReceipt receipt;
    }

    address internal constant MAJORITY = address(0xA001);
    address internal constant MINORITY = address(0xA002);
    address internal constant CLAIMANT = address(0xA003); // LONG whose profit at 0.80 becomes the trader claim
    address internal constant WINNER = address(0xA004); // SHORT paid in cash at the cap
    address internal constant LOSER = address(0xA005); // no-owner tests: SHORT opened at the cap, losing at 0.80
    address internal constant JUNIOR_LP = address(0x1A18);
    address internal constant KEEPER = address(0x4EE718);

    uint256 internal constant LOT = 1e20; // positionSizeQuantum
    uint256 internal constant PRICE = 0.8e8; // basket != $1.00
    uint256 internal constant HIGH = CAP_PRICE; // 2.00
    uint256 internal constant STOP_LOSS = 0.79e8; // the minority SHORT's stop-loss (a SHORT loses as the basket falls)
    uint256 internal constant MAJ_SIZE = 200_000e18; // 160,000 USDG LONG notional
    uint256 internal constant MIN_SIZE = 100_000e18; // 80,000 USDG SHORT notional (minority side)
    uint256 internal constant WINNER_SIZE = 600_000e18; // largest SHORT the skew cap admits at 0.80
    uint256 internal constant CLAIMANT_SIZE = 416_800e18; // largest LONG the solvency buffer admits at 2.00
    uint256 internal constant SMALLER_WINNER_SIZE = 500_000e18; // no-owner tests: 400,000 USDG SHORT notional at 0.80
    uint256 internal constant LOSER_SIZE = 150_000e18; // no-owner tests: 300,000 USDG SHORT notional at 2.00
    uint256 internal constant MAJ_FUNDING = 300_000e6;
    uint256 internal constant MIN_FUNDING = 50_000e6;
    uin

The original report as published on Immunefi, by Nyksx. 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 close path prices skew-increasing VPI on net pool depth without any lower bound on that depth or any cap relative to the notional being closed, and skips the charge only at exactly zero depth.

Impact

An account whose exit was authorised with unlimited limits loses its whole custody to the pool, including free settlement, while an account with finite limits cannot close, cancel or withdraw.

What the attacker needed

Open minority-side position; exit authorised with unlimited limits; pool depth near zero after deficit; keeper triggers the close

The fix

The depth used to price a skew-increasing close should be bounded from below so the fresh charge stays proportional to the skew it creates.

How it was found

  1. Arm a stop-loss on a minority-side position with all close limits set to unlimited in a normal market.
  2. Reach a terminal trader-claim deficit so net depth is zero and degraded mode latches.
  3. The owner recapitalises the pool with exactly the shortfall, leaving views showing zero depth.
  4. The mark crosses the stop-loss price and a keeper triggers the close one second later.
  5. The execution realises a tiny carry, prices VPI on that depth, and collects the account's whole custody.

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 perps pool charges a fee when you close a trade that pushes the pool further out of balance, and that fee grows as the pool's spare cash shrinks. Here the fee formula divides by the spare cash, so when that cash is almost nothing the fee becomes enormous. A trader who set no spending cap on their stop-loss then has their whole balance taken by the pool.

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 Nyksx

View all

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