Skip to content
Smart contracts Audit finding Advanced

Close VPI is uncapped when economic depth is tiny but non-zero, so a closing trader (or its keeper-triggered stop-loss) forfeits its whole settlement, which an attacker holding Senior shares then redeems

The close-side VPI charge formula divides by the pool's economic depth, and only an exact-zero depth is exempted, so when depth is tiny but non-zero the charge becomes enormous. A trader closing in the skew-increasing direction then forfeits its entire settlement, and an attacker holding Senior shares can redeem the confiscated value.

redbaron Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#98202 [SC-High] Close VPI is uncapped when economic depth is tiny but non-zero, so a closing trader (or its keeper-triggered stop-loss) forfeits its whole settlement, which an attacker holding Senior shares then redeems

Submitted on Nov 5th 2026 at 22:44:12 UTC by @redbaron for Audit Competition | Plether

Description

Brief/Intro

The close-side VPI charge is k·(post² − pre²) / (2·D), where D is the pool's economic depth, pool.totalAssets() − totalTraderClaims. Only one case is guarded: D == 0 creates no fresh charge (CloseAccountingLib.sol:107), and the docs state that rule for zero depth only. Nothing covers D between 1 atom and a few USDG, where the same formula yields charges of millions of USDG on an ordinary close.

That depth is reachable with public calls once the pool is in its documented claims regime (degraded mode, trader claims ≈ pool cash). A losing trader sizes a partial close so that its realized loss leaves D at a few USDG. From then on, every close that increases skew collects the closer's whole settlement:

  • its realized profit;
  • its position margin;
  • free settlement that was never pledged to the position.

The shortfall is written off. A keeper-triggered stop-loss does the same to a trader who takes no action. The confiscated cash becomes LP equity and flows to the Senior tranche.

The PoC uses release parameters. An attacker holds the Senior shares and controls the depth-sizing trader, and pays 3.17 USDG in fees. It redeems 237,478.12 USDG instead of 125,196.08 USDG in the identical timeline without the bug, a gain of +112,282.04 USDG. The victim ends with 0 instead of 112,505.47 USDG.

Vulnerability Details

Line numbers refer to immunefi-team/audit-comp-plether at a82d4fe. The in-scope code is identical to the Arbitrum Sepolia v2.0.0 release.

1. The only guard is the exact-zero exemption

Solidity
// packages/perps/src/libraries/CloseAccountingLib.sol:105-117
// 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
    );
}
// Clamp so lifetime VPI (accrued + delta) never goes negative. ...
if (state.proportionalAccrualAssets + state.vpiDeltaAssets < 0) {
    state.vpiDeltaAssets = -state.proportionalAccrualAssets;
}

CfdMath.calculateVPI (CfdMath.sol:150-161) is k·(post² − pre²)/(2·depth) with no cap. The clamp that follows bounds only rebates; it never bounds charges. The router supplies poolDepthAssets as the net depth pool.totalAssets() − totalTraderClaims: OrderRouterExecutionSidecar.sol:933/953 reads it and CfdEnginePlanLib.sol:448-487 nets it.

The zero-depth rule was added in 6d6622f ("use net risk depth"). Its stated purpose is to "keep protective exits live" at exhausted depth. One atom above zero the exit is still live, but it confiscates the closer's funds.

2. The charge is collected from everything the account owns

The charge is an action charge. MarginClearinghouse.sol:955-959 collects min(charge, eligible), where eligible covers the spendable action reserve, free buying power and committed order margin, in addition to the closed position's pledge. CfdEngineSettlementSidecar.sol:674 (ActionChargeSettled) records the rest as waived. The close executes and nothing reverts. The victim's realized profit is withheld against the charge, and its unrelated free settlement is taken.

3. Depth can be steered to a few USDG with public calls

In the claims regime, a winner's unpaid profit is booked as a trader claim, so D = assets − claims sits at 0. Any losing trader can choose D by closing part of its position: the realized loss enters pool assets. One coarse partial close gives D ≈ 64 USDG; two give D ≈ 2.2 USDG. The attacker's fees are 3.17 USDG. The attacker's trading loss is the same with or without the attack, as the control timeline shows.

4. The confiscated value becomes redeemable Senior equity

With claims fully covered, the victim's seized cash is free pool equity. Junior is first-loss and was already wiped in the regime, so the value restores impaired Senior principal. When the remaining positions close, the owner's documented recovery action clearDegradedMode() becomes possible: it requires cash ≥ max liability (CfdEngine.sol:658-665). WHITEPAPER.md §7.5 (lines 1335-1339) describes it as the protocol's recovery path: "After genuine restoration to A_eff ≥ L_max, the owner may clear the latch through the explicit recovery path". After it, the normal LP epoch settlement funds Senior redemptions, and the attacker's Senior shares redeem the victim's value.

settleLpEpoch reverts HousePool__DegradedMode until that point in both timelines. The owner action is therefore the protocol's ordinary exit path for every LP, not something the attack needs from a malicious owner. The program puts this case in scope: "a legitimate, documented action by a trusted role that triggers a bug harming users or the protocol".

5. The victim has no defense

  • Unbounded close: the 5-argument commitOrder has no charge bound, so the victim's whole settlement goes.
  • Stop-loss: the victim's stop-loss protection is triggered and executed by a public keeper. The program says "harm caused by any caller acting as a keeper is in scope". The result is the same total loss with no further action by the victim.
  • Bounded close: a close with maxActionChargeAssets reverts ConstraintViolation. Withdrawals of positioned accounts revert CfdEngine__DegradedMode (CfdEngineSettlementSidecar.sol:274). The account cannot be liquidated, because it is solvent. Stored depth does not move by itself: 48 h later the charge is still 218,333 USDG, 8.4× the account's balance. The only exit costs everything.

Impact Details

Direct theft of user funds (Critical). The PoC executes the theft end to end: the attacker realizes the victim's funds as USDG in its own wallet.

Timeline (same snapshot) Victim V closes V ends with Attacker's Senior redemption
Attack: V closes at D = 2.18 USDG charge 2,819,144.31 USDG on a 100k close 0 237,478.12 USDG
Control: V closes after depth is restored rebate 4.18 USDG 112,505.47 USDG 125,196.08 USDG
Difference −112,505.47 +112,282.04

The attacker controls two accounts: the Senior LP and the depth-sizing trader L. The test asserts that L's trading account ends the same in both timelines (60,718.17 USDG, within 42 atoms of rounding), so the attacker's net gain across both accounts is +112,282.04 USDG. The third-party claimant W ends with exactly the same balance in both timelines. The taken value comes from the victim alone.

Cost to the attacker: 3.17 USDG in fees, about 1 : 35,000 against the amount taken. With the fix applied, the same test gives a net gain of 669.99 USDG instead of 112,282.04.

Every trader who closes in the skew-increasing direction while D is small loses the same way. Voluntary closes and keeper-triggered stop-losses are both affected. The attacker keeps D small because nothing else moves it in a degraded pool, where opens are blocked.

Other measured cases:

Scenario D before the close Close charge Victim settlement before → after
Control, before the claims regime 1,011,121.71 −27.22 (rebate) 25,926.62 → 112,528.51
One sized partial close 63.90 96,884.59 25,926.62 → 15,616.92 (86,580 profit also forfeited)
Two sized partial closes 2.18 2,819,144.31 (2,706,637.69 waived) 25,926.62 → 0
Stop-loss triggered by a keeper 2.19 3,110,424.46 25,926.61 → 0
Bounded close (max charge 1,000) 2.19 ConstraintViolation no close, no withdraw, not liquidatable; charge 218,333 at t+48 h

If the redemption step is not accepted as theft, the bounded-close case meets the High impact "Temporary freezing of funds for at least 24 hours". The total-loss cases are not griefing under the program's ratio rule: 3 USDG causing more than 100k USDG of damage.

Precondition and feasibility (stated openly)

The pool must already be in the claims regime: trader claims ≈ pool cash, with degraded mode latched. Opens must leave assets ≥ max liability plus a settlement buffer (CfdEnginePlanLib.sol:421 → SolvencyAccountingLib.sol:93-104), and LP redemptions reserve max liability plus claims (HousePoolAccountingLib.sol:50-51). So the regime needs one side's profit to be paid out and then the other side to win close to its maximum. In the PoC this is a 1.0 → 1.5 → 0.2 basket path with large positions on both sides.

The state is documented protocol behavior: degraded mode, trader claims and the zero-depth close rule. No trusted role and no oracle trust is needed. Under the program's Feasibility Limitations, "Impact is calculated first, separately from feasibility. Feasibility limitations do not change the impact or severity of a finding, only the amount paid for it." The capital involved is well below the USD 100M threshold.

Not a known issue

  • Documentation: the docs state the zero-depth rule for zero depth only: ACCOUNTING_SPEC.md:665-669 ("A zero-depth close creates no fresh VPI charge or rebate"), SECURITY.md:1439-1440 and WHITEPAPER.md:866-867. SECURITY.md:1434-1445 lists the VPI limitations (zero depth, lifetime clamp, partial-close approximation, liquidation); small positive depth is not among them.
  • AI scan Info items: "Temporary pool liquidity can reduce a skew-increasing close charge" and "... can amplify a skew-reducing close rebate" describe a trader moving totalAssets with its own liquidity to lower its own charge or raise its own rebate. This report is the opposite direction, with a different victim, a different defect and a different fix. The scan's remedy (commit-time or time-weighted depth) does not remove it: the depth here is genuinely tiny at both times.
  • Not "lack of liquidity": the loss is not a delayed or unpaid payout. A formula singularity takes the trader's own collateral, unrelated to pool cash, and an attacker then redeems it.

Recommendation

Treat depth below a floor as zero for the fresh close-side charge, or cap the fresh positive charge at a share of the closed slice's notional. The gist's fix.diff uses 5% of the closed notional. With it applied, the cliff tests fail and the repo's 178 close/VPI tests pass. Evaluating the VPI delta with max(D, D_min) is an equivalent option.

Link to Proof of Concept

https://gist.github.com/the-red-ace/4395a2418911c1e0be32d484b6fa2c71

Proof of Concept

Proof of Concept

Gist: https://gist.github.com/the-red-ace/4395a2418911c1e0be32d484b6fa2c71. It contains X2Cliff.t.sol, X2GridBase.sol, X2ErrNames.sol, fix.diff and a README.

The tests run in the repo's own Foundry suite at a82d4fe with release risk parameters. They do not modify any in-scope contract. The only mocks are MockPyth price updates and mock USDG, both allowed by the program. All state changes go through commitOrder, executeOrder, updateMarkPrice, createPositionProtection and triggerPositionProtection, plus the owner's clearDegradedMode() recovery action before LP redemption. There is no vm.store, deal or mockCall.

Bash
git checkout a82d4fefb02768e5b3bddcc97dee371eee24fea8 && git submodule update --init --recursive
mkdir -p packages/perps/test/perps/x2 && cp X2GridBase.sol X2ErrNames.sol X2Cliff.t.sol packages/perps/test/perps/x2/
forge test --root packages/perps --match-path test/perps/x2/X2Cliff.t.sol -vv
Test What it asserts
test_X2C_Control_LargeDepth At normal depth the same close is an ordinary rebate, and V keeps 112,528.51.
test_X2C_Cliff One sized partial close (D = 63.9): V ends below its pre-close settlement on a winning close.
test_X2C_A_FineDepth_WholeSettlementConsumed D = 2.18: settlement goes to 0, the remainder is waived, nothing reverts.
test_X2C_B_BoundedCloseFrozen ConstraintViolation, withdraw reverts DegradedMode, not liquidatable, depth unchanged after 48 h.
test_X2C_C_AttackerIsJuniorLP Junior (first-loss, wiped) captures nothing; the Senior tranche rises by the victim's loss.
test_X2C_D_ProtectionTriggeredCliff A keeper-executed stop-loss at D = 2.19 takes V's settlement to 0.
test_X2C_E_SeniorAttackerRealizesVictimLoss Attack and control timelines from the same snapshot. The attacker's Senior redemption is 112,282.04 USDG higher and the victim 112,505.47 USDG poorer. The attacker's trading account and the third-party claimant end the same in both, so the net theft is 112,282.04 USDG.
test_X2C_Escape_Liquidation_And_Wait V is not liquidatable, and seven days of waiting leave D unchanged.

Expected output:

Suite result: ok. 8 passed; 0 failed; 0 skipped
test_X2C_E: attacker (Senior LP) redeems 237478122767 (attack) vs 125196083224 (control): +112282039543
            victim ends 0 (attack) vs 112505465699 (control); attacker's tuning fees 3169087
            attacker NET gain across both accounts: 112282039501
test_X2C_A: D before close 2178986 | vpiDelta 2819144309459 | V settlement 25926617619 -> 0
test_X2C_D: D at trigger 2186806 | charge 3110424456565 | V settlement 25926609799 -> 0

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

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 14 min read.

Context

Plether is a perps protocol whose in-scope code lives in the packages/perps/src tree of the immunefi-team/audit-comp-plether repository, at commit [redacted]. The report notes that this in-scope code is identical to the Arbitrum Sepolia v2.0.0 release. The finding was submitted to the Plether audit competition on Immunefi as report #98202, severity High, by @redbaron.

The feature at the centre of the report is the VPI (virtual price impact) charge applied when a trader closes a position. On the close side the charge is computed as k·(post² − pre²) / (2·D), where D is the pool's economic depth, defined as pool.totalAssets() − totalTraderClaims. When a close increases skew, the formula produces a positive charge that is taken from the closing account. When a close reduces skew, it produces a rebate. The protocol documents a special rule for zero depth: a close at exactly zero depth creates no fresh VPI charge or rebate, so that protective exits stay live when depth is exhausted.

The pool also has a documented claims regime (degraded mode) in which trader claims are approximately equal to pool cash. In that regime opens are blocked, Junior is first-loss and already wiped, and the owner has a documented recovery action, clearDegradedMode(), which becomes possible once cash is at least the maximum liability.

Setup

The proof of concept runs in the repository's own Foundry suite at the pinned commit, with release risk parameters. It does not modify any in-scope contract. The only mocks are MockPyth price updates and mock USDG, both allowed by the program. All state changes go through the protocol's own entry points: commitOrder, executeOrder, updateMarkPrice, createPositionProtection and triggerPositionProtection, plus the owner's clearDegradedMode() recovery action before LP redemption. There is no vm.store, deal or mockCall.

The attacker controls two accounts: a Senior LP and a depth-sizing trader, referred to as L. A third-party claimant, W, is present in the scenario and is used to show that its balance is unaffected. The victim, V, holds a position and a stop-loss protection.

The precondition, stated openly in the report, is that the pool must already be in the claims regime: trader claims approximately equal to pool cash, with degraded mode latched. Reaching that state requires one side's profit to be paid out and then the other side to win close to its maximum. In the PoC this is a 1.0 → 1.5 → 0.2 basket path with large positions on both sides. The report stresses that this state is documented protocol behaviour (degraded mode, trader claims, the zero-depth close rule) and needs no trusted role and no oracle trust.

Finding it

The researcher started from the only guard around the close-side charge. In CloseAccountingLib.sol:105-117 the fresh charge is skipped only when depth is exactly zero:

Solidity
// packages/perps/src/libraries/CloseAccountingLib.sol:105-117
// 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
    );
}
// Clamp so lifetime VPI (accrued + delta) never goes negative. ...
if (state.proportionalAccrualAssets + state.vpiDeltaAssets < 0) {
    state.vpiDeltaAssets = -state.proportionalAccrualAssets;
}

CfdMath.calculateVPI (CfdMath.sol:150-161) is k·(post² − pre²)/(2·depth) with no cap. The clamp that follows bounds only rebates; it never bounds charges. The router supplies poolDepthAssets as the net depth pool.totalAssets() − totalTraderClaims: OrderRouterExecutionSidecar.sol:933/953 reads it and CfdEnginePlanLib.sol:448-487 nets it.

The zero-depth rule was added in commit 6d6622f ("use net risk depth") with the stated purpose of keeping protective exits live at exhausted depth. The researcher's observation is that one atom above zero the exit is still live, but the same formula now confiscates the closer's funds. Nothing covers D between 1 atom and a few USDG, where the formula yields charges of millions of USDG on an ordinary close.

The documentation confirms the gap. ACCOUNTING_SPEC.md:665-669 says "A zero-depth close creates no fresh VPI charge or rebate", and SECURITY.md:1439-1440 and WHITEPAPER.md:866-867 carry the same rule. SECURITY.md:1434-1445 lists the VPI limitations (zero depth, lifetime clamp, partial-close approximation, liquidation); small positive depth is not among them.

Exploitation

Step 1: reach the claims regime and steer depth to a few USDG

In the claims regime a winner's unpaid profit is booked as a trader claim, so D = assets − claims sits at 0. Any losing trader can then choose D by closing part of its position, because the realised loss enters pool assets. One coarse partial close gives D ≈ 64 USDG; two give D ≈ 2.2 USDG. The attacker's fees are 3.17 USDG, and its trading loss is the same with or without the attack, as the control timeline shows.

Step 2: the victim closes into the tiny depth

The victim's close increases skew, so the uncapped formula applies. The charge is an action charge, and MarginClearinghouse.sol:955-959 collects min(charge, eligible), where eligible covers the spendable action reserve, free buying power and committed order margin, in addition to the closed position's pledge. CfdEngineSettlementSidecar.sol:674 (ActionChargeSettled) records the rest as waived. The close executes and nothing reverts. The victim's realised profit is withheld against the charge, and its unrelated free settlement is taken too.

At D = 2.18 USDG the charge on a 100k close is 2,819,144.31 USDG. The victim's settlement goes to 0 and the remainder is waived.

Step 3: the same happens through a keeper-triggered stop-loss

The victim's stop-loss protection is triggered and executed by a public keeper. At D = 2.19 the charge is 3,110,424.46 USDG and the victim's settlement goes to 0 with no further action by the victim. The program states that "harm caused by any caller acting as a keeper is in scope".

Step 4: the victim's alternatives all fail

  • A close with maxActionChargeAssets reverts ConstraintViolation.
  • Withdrawals of positioned accounts revert CfdEngine__DegradedMode (CfdEngineSettlementSidecar.sol:274).
  • The account cannot be liquidated, because it is solvent.
  • Stored depth does not move by itself: 48 h later the charge is still 218,333 USDG, 8.4× the account's balance.

The only exit costs everything.

Step 5: the confiscated value becomes redeemable Senior equity

With claims fully covered, the victim's seized cash is free pool equity. Junior is first-loss and was already wiped in the regime, so the value restores impaired Senior principal. When the remaining positions close, the owner's documented recovery action clearDegradedMode() becomes possible: it requires cash ≥ max liability (CfdEngine.sol:658-665). WHITEPAPER.md §7.5 (lines 1335-1339) describes it as the protocol's recovery path: "After genuine restoration to A_eff ≥ L_max, the owner may clear the latch through the explicit recovery path". After it, the normal LP epoch settlement funds Senior redemptions, and the attacker's Senior shares redeem the victim's value.

settleLpEpoch reverts HousePool__DegradedMode until that point in both timelines, so the owner action is the protocol's ordinary exit path for every LP, not something the attack needs from a malicious owner. The program puts this case in scope: "a legitimate, documented action by a trusted role that triggers a bug harming users or the protocol".

Step 6: run the PoC

The gist at https://gist.github.com/the-red-ace/[redacted] contains X2Cliff.t.sol, X2GridBase.sol, X2ErrNames.sol, fix.diff and a README. The tests are run as follows:

Bash
git checkout [redacted] && git submodule update --init --recursive
mkdir -p packages/perps/test/perps/x2 && cp X2GridBase.sol X2ErrNames.sol X2Cliff.t.sol packages/perps/test/perps/x2/
forge test --root packages/perps --match-path test/perps/x2/X2Cliff.t.sol -vv

The suite asserts the following:

Test What it asserts
test_X2C_Control_LargeDepth At normal depth the same close is an ordinary rebate, and V keeps 112,528.51.
test_X2C_Cliff One sized partial close (D = 63.9): V ends below its pre-close settlement on a winning close.
[redacted] D = 2.18: settlement goes to 0, the remainder is waived, nothing reverts.
test_X2C_B_BoundedCloseFrozen ConstraintViolation, withdraw reverts DegradedMode, not liquidatable, depth unchanged after 48 h.
test_X2C_C_AttackerIsJuniorLP Junior (first-loss, wiped) captures nothing; the Senior tranche rises by the victim's loss.
[redacted] A keeper-executed stop-loss at D = 2.19 takes V's settlement to 0.
[redacted] Attack and control timelines from the same snapshot. The attacker's Senior redemption is 112,282.04 USDG higher and the victim 112,505.47 USDG poorer. The attacker's trading account and the third-party claimant end the same in both, so the net theft is 112,282.04 USDG.
[redacted] V is not liquidatable, and seven days of waiting leave D unchanged.

The expected output is:

Text
Suite result: ok. 8 passed; 0 failed; 0 skipped
test_X2C_E: attacker (Senior LP) redeems 237478122767 (attack) vs 125196083224 (control): [redacted]
            victim ends 0 (attack) vs 112505465699 (control); attacker's tuning fees 3169087
            attacker NET gain across both accounts: 112282039501
test_X2C_A: D before close 2178986 | vpiDelta 2819144309459 | V settlement 25926617619 -> 0
test_X2C_D: D at trigger 2186806 | charge 3110424456565 | V settlement 25926609799 -> 0

Root cause

The defect is the exact-zero exemption. The close-side charge is uncapped, and the only case that is guarded is D == 0. The clamp that follows the calculation bounds only rebates, never charges. Between 1 atom and a few USDG the formula's division by a tiny depth produces charges far larger than the account's entire settlement, and the action-charge collection logic then takes everything the account owns: the realised profit, the position margin, and free settlement that was never pledged to the position. The shortfall is written off rather than reverting, so the close succeeds.

Existing defences do not stop it. The bounded-close path (maxActionChargeAssets) reverts, but that only freezes the account rather than protecting it. Withdrawals revert in degraded mode. Liquidation is impossible because the account is solvent. Depth does not drift on its own in a degraded pool where opens are blocked, so waiting does not help. The zero-depth rule is documented for zero depth only, and small positive depth is not among the listed VPI limitations.

Impact

The report classifies this as direct theft of user funds (Critical impact), with the PoC executing the theft end to end: the attacker realises the victim's funds as USDG in its own wallet.

Timeline (same snapshot) Victim V closes V ends with Attacker's Senior redemption
Attack: V closes at D = 2.18 USDG charge 2,819,144.31 USDG on a 100k close 0 237,478.12 USDG
Control: V closes after depth is restored rebate 4.18 USDG 112,505.47 USDG 125,196.08 USDG
Difference −112,505.47 +112,282.04

The attacker controls two accounts: the Senior LP and the depth-sizing trader L. The test asserts that L's trading account ends the same in both timelines (60,718.17 USDG, within 42 atoms of rounding), so the attacker's net gain across both accounts is +112,282.04 USDG. The third-party claimant W ends with exactly the same balance in both timelines. The taken value comes from the victim alone.

Cost to the attacker: 3.17 USDG in fees, about 1 : 35,000 against the amount taken. With the fix applied, the same test gives a net gain of 669.99 USDG instead of 112,282.04.

Every trader who closes in the skew-increasing direction while D is small loses the same way. Voluntary closes and keeper-triggered stop-losses are both affected. The attacker keeps D small because nothing else moves it in a degraded pool, where opens are blocked.

Other measured cases:

Scenario D before the close Close charge Victim settlement before → after
Control, before the claims regime 1,011,121.71 −27.22 (rebate) 25,926.62 → 112,528.51
One sized partial close 63.90 96,884.59 25,926.62 → 15,616.92 (86,580 profit also forfeited)
Two sized partial closes 2.18 2,819,144.31 (2,706,637.69 waived) 25,926.62 → 0
Stop-loss triggered by a keeper 2.19 3,110,424.46 25,926.61 → 0
Bounded close (max charge 1,000) 2.19 ConstraintViolation no close, no withdraw, not liquidatable; charge 218,333 at t+48 h

If the redemption step is not accepted as theft, the bounded-close case meets the High impact "Temporary freezing of funds for at least 24 hours". The total-loss cases are not griefing under the program's ratio rule: 3 USDG causing more than 100k USDG of damage.

On feasibility, the report is explicit that the pool must already be in the claims regime. Opens must leave assets ≥ max liability plus a settlement buffer (CfdEnginePlanLib.sol:421 → SolvencyAccountingLib.sol:93-104), and LP redemptions reserve max liability plus claims (HousePoolAccountingLib.sol:50-51). Under the program's Feasibility Limitations, "Impact is calculated first, separately from feasibility. Feasibility limitations do not change the impact or severity of a finding, only the amount paid for it." The capital involved is well below the USD 100M threshold.

The report also distinguishes this from known issues. The AI scan's Info items ("Temporary pool liquidity can reduce a skew-increasing close charge" and "... can amplify a skew-reducing close rebate") describe a trader moving totalAssets with its own liquidity to lower its own charge or raise its own rebate. This report is the opposite direction, with a different victim, a different defect and a different fix. The scan's remedy (commit-time or time-weighted depth) does not remove it, because the depth here is genuinely tiny at both times. It is also not "lack of liquidity": the loss is not a delayed or unpaid payout. A formula singularity takes the trader's own collateral, unrelated to pool cash, and an attacker then redeems it.

Fix

The recommendation is to treat depth below a floor as zero for the fresh close-side charge, or to cap the fresh positive charge at a share of the closed slice's notional. The gist's fix.diff uses 5% of the closed notional. With it applied, the cliff tests fail and the repository's 178 close/VPI tests pass. Evaluating the VPI delta with max(D, D_min) is an equivalent option.

Variants to test

  • Other formulas with a division by a state variable. Look for any charge or rebate computed as a function divided by a pool or account quantity, and check whether the guard is an exact-zero check. A positive result is a value that is tiny but non-zero producing a charge larger than the account's balance.
  • Action-charge collection across multiple balances. Where a charge is collected from min(charge, eligible) and the remainder is waived rather than reverting, check whether the eligible set includes funds unrelated to the action. A positive result is a close or action that succeeds while taking free settlement or committed order margin.
  • Keeper-triggered paths. Check whether a protection or stop-loss executed by a public keeper reaches the same charge logic as a voluntary close. A positive result is a keeper-triggered exit that zeroes a solvent trader's settlement.
  • Degraded or claims regimes. Look for modes where opens are blocked and depth is set by a losing trader's partial close. A positive result is a depth that can be steered to a few USDG with public calls and stays there over time.
  • Bounded-action escape hatches. Check whether a maxActionChargeAssets-style bound reverts while withdrawals and liquidation are also blocked. A positive result is an account that is frozen, solvent and not liquidatable, with the charge unchanged after 48 h.
  • Tranche accounting after a write-off. Check where a waived shortfall lands in the LP accounting. A positive result is a first-loss tranche that is already wiped and a senior tranche that rises by the victim's loss and can be redeemed after the documented recovery action.

Hunting notes

This kind of bug tends to hide at the boundary of a documented special case. The zero-depth rule was written for exactly zero, and the documentation repeats it for zero only, which is a strong signal that the interval just above zero was never analysed. When a formula divides by a state variable, the interesting question is not whether zero is handled but what happens at one atom.

During recon, the signals that point to it are: a charge formula with a division by pool depth; a guard written as != 0; a clamp that bounds only one sign of the result; an action-charge collector that takes min(charge, eligible) and waives the rest instead of reverting; and a documented degraded mode in which opens are blocked and depth is set by trader losses. A protocol with a documented recovery action that becomes possible once cash covers max liability is also worth reading closely, because it tells you how confiscated value eventually becomes redeemable.

The researcher built a control timeline from the same snapshot to measure the difference. The attacker's trading account and an uninvolved third-party claimant end the same in both timelines, which isolates the gain to the victim's loss. The PoC runs in the repository's own Foundry suite with release parameters, uses only the protocol's public entry points and the owner's documented recovery action, and avoids vm.store, deal and mockCall. The report also states the precondition openly, addresses the program's feasibility rule, and separates the finding from the AI scan's Info items and from a generic lack of liquidity, so the impact argument stands on its own.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 28 min read.

What happened, in plain words

Plether is a trading platform for "perps", short for perpetual futures. A perpetual future is a bet on the price of something (here, a basket of assets) that never expires: you put down some money as a guarantee, called margin, and you win or lose as the price moves. The code that runs this platform is public on GitHub, in a folder called packages/perps/src inside the repository immunefi-team/audit-comp-plether, at a specific saved version (a "commit") named [redacted]. A commit is like a numbered snapshot of the code, so anyone can download exactly the same files the researcher looked at. The report says this code is identical to the version released on Arbitrum Sepolia, a test network for the Arbitrum blockchain.

The report was sent to a bug bounty competition run by Immunefi, a company that pays security researchers for finding flaws in software. This particular competition is an "audit competition": many researchers examine the same code and submit reports, and the best ones win prizes. The report is number #98202, rated High severity, and written by a researcher using the name @redbaron.

The feature at the centre of the report is a fee called VPI, short for "virtual price impact". When many traders bet in the same direction, the platform's book of open bets becomes lopsided, which is called "skew". VPI is a charge designed to discourage traders from making the skew worse, and to reward those who make it better. When a trader closes a position (ends the bet), the platform calculates a charge with this formula:

k·(post² − pre²) / (2·D)

Here k is a fixed multiplier, pre and post are the skew before and after the close, and D is the pool's "economic depth", defined as pool.totalAssets() − totalTraderClaims. In plain words, depth is the pool's cash minus everything it already owes to traders. If a close makes the skew worse, the formula gives a positive number, a charge taken from the closing trader. If the close makes the skew better, it gives a negative number, a rebate paid to the trader.

The protocol has a written rule for one special case: when depth is exactly zero, a close creates no fresh VPI charge or rebate. The idea is that when the pool has no spare cash, traders should still be able to close positions to protect themselves, without being charged extra. The report's core observation is that this rule only covers exactly zero. Just above zero, the same formula divides by a tiny number, and dividing by a tiny number gives a huge result. So a close at a depth of a couple of dollars can produce a charge of millions of dollars, and the platform takes the trader's entire settlement.

The pool also has a documented state called "degraded mode" or the "claims regime". In this state, the money the pool owes to traders is roughly equal to the cash it holds. New positions are blocked, and the pool's two investor groups, called tranches, are affected: the Junior tranche absorbs losses first and has already been wiped out, while the Senior tranche is the safer one that gets paid first. The owner of the protocol has a documented recovery action, clearDegradedMode(), which becomes possible once the pool's cash is at least the maximum it could owe.

The attack works like this. An attacker holds Senior shares, meaning a claim on the Senior tranche. The attacker also controls a second trading account. Once the pool is in degraded mode, the attacker uses that second account to make small losing trades, which pushes the depth down to a few dollars. Then an ordinary trader, the victim, closes a position. Because the depth is tiny, the VPI formula charges the victim millions, far more than the victim owns. The platform takes everything the victim has, writes off the rest, and the close still succeeds. The confiscated money becomes pool equity, which restores the Senior tranche, and the attacker then redeems its Senior shares for the victim's money. The victim is left with zero.

Context

The in-scope code, meaning the code the competition allows researchers to examine, lives in the packages/perps/src tree of the immunefi-team/audit-comp-plether repository at commit [redacted]. The report notes that this code is identical to the Arbitrum Sepolia v2.0.0 release. The finding was submitted to the Plether audit competition on Immunefi as report #98202, severity High, by @redbaron.

The feature at the centre of the report is the VPI (virtual price impact) charge applied when a trader closes a position. On the close side the charge is computed as k·(post² − pre²) / (2·D), where D is the pool's economic depth, defined as pool.totalAssets() − totalTraderClaims. When a close increases skew, the formula produces a positive charge that is taken from the closing account. When a close reduces skew, it produces a rebate. The protocol documents a special rule for zero depth: a close at exactly zero depth creates no fresh VPI charge or rebate, so that protective exits stay live when depth is exhausted.

The pool also has a documented claims regime (degraded mode) in which trader claims are approximately equal to pool cash. In that regime opens are blocked, Junior is first-loss and already wiped, and the owner has a documented recovery action, clearDegradedMode(), which becomes possible once cash is at least the maximum liability.

Setup

The proof of concept, or PoC, is a small program that demonstrates the attack. It runs in the repository's own Foundry suite at the pinned commit, with release risk parameters. Foundry is a toolkit for writing and running tests against blockchain code; a test suite is a collection of automated checks that run the code and compare the results with what is expected. "Release risk parameters" means the settings used are the ones the protocol actually ships with, not made-up values. The PoC does not modify any in-scope contract. A contract is a program that lives on a blockchain and runs automatically. The only mocks are MockPyth price updates and mock USDG, both allowed by the program. A mock is a stand-in that behaves like a real component so a test can run without the real thing; Pyth is a service that publishes price data, and USDG is a stablecoin, a digital token designed to stay worth about one US dollar. All state changes go through the protocol's own entry points: commitOrder, executeOrder, updateMarkPrice, createPositionProtection and triggerPositionProtection, plus the owner's clearDegradedMode() recovery action before LP redemption. An entry point is a function the protocol exposes for anyone to call. "LP redemption" means an investor in the pool, a liquidity provider, cashing out its shares. There is no vm.store, deal or mockCall: these are Foundry shortcuts that let a test rewrite storage directly, hand out free tokens, or fake a call to another contract. Avoiding them means the test only does what a real user could do on the live network.

The attacker controls two accounts: a Senior LP and a depth-sizing trader, referred to as L. A third-party claimant, W, is present in the scenario and is used to show that its balance is unaffected. The victim, V, holds a position and a stop-loss protection. A stop-loss is an automatic instruction: if the position loses enough, close it. The protection here is executed by a keeper, a public role that anyone can play, which watches for conditions and triggers actions on behalf of users.

The precondition, stated openly in the report, is that the pool must already be in the claims regime: trader claims approximately equal to pool cash, with degraded mode latched. "Latched" means the state stays on until something explicitly turns it off. Reaching that state requires one side's profit to be paid out and then the other side to win close to its maximum. In the PoC this is a 1.0 → 1.5 → 0.2 basket path with large positions on both sides: the basket price moves from 1.0 to 1.5, then down to 0.2, and large bets on both sides of the market are open along the way. The report stresses that this state is documented protocol behaviour (degraded mode, trader claims, the zero-depth close rule) and needs no trusted role and no oracle trust. An oracle is the outside service that feeds prices into the blockchain; "no oracle trust" means the attack does not depend on the price feed being wrong or manipulated.

Finding it

The researcher started from the only guard around the close-side charge. A guard is a check in the code that stops something from happening. In CloseAccountingLib.sol:105-117 the fresh charge is skipped only when depth is exactly zero:

Solidity
// packages/perps/src/libraries/CloseAccountingLib.sol:105-117
// 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
    );
}
// Clamp so lifetime VPI (accrued + delta) never goes negative. ...
if (state.proportionalAccrualAssets + state.vpiDeltaAssets < 0) {
    state.vpiDeltaAssets = -state.proportionalAccrualAssets;
}

Line by line, in plain words:

  1. The first two lines are comments, notes for humans that the computer ignores. They explain the intent: when there is no economic depth, keep protective exits working without creating a fresh charge or rebate. The second comment says the clamp below still recovers any negative VPI the trader received earlier.
  2. if (inputs.poolDepthAssets != 0) { is the guard. It says: only do the following if the depth is not equal to zero. The != symbol means "not equal to". So when depth is exactly zero, the block is skipped entirely and no charge is calculated.
  3. Inside the block, state.vpiDeltaAssets = CfdMath.calculateVPI(...) calls a maths function and stores the result. CfdMath is a library, a reusable bundle of functions. The function receives the skew before the close, the skew after the close, the depth, and a factor k. The result is the VPI charge or rebate for this close.
  4. The next comment explains the clamp: it makes sure the lifetime VPI, the running total of charges and rebates, never goes negative.
  5. if (state.proportionalAccrualAssets + state.vpiDeltaAssets < 0) { checks whether the running total plus this close's delta is below zero. If so, the next line sets the delta to exactly cancel the running total, bringing it to zero. This protects the trader from being owed more rebate than it has accrued.

The key point: this clamp only limits rebates, the negative side. It never limits charges, the positive side. A charge can be as large as the formula says.

CfdMath.calculateVPI (CfdMath.sol:150-161) is k·(post² − pre²)/(2·depth) with no cap. The clamp that follows bounds only rebates; it never bounds charges. The router supplies poolDepthAssets as the net depth pool.totalAssets() − totalTraderClaims: OrderRouterExecutionSidecar.sol:933/953 reads it and CfdEnginePlanLib.sol:448-487 nets it. A router is the part of the system that takes a user's order and works out what to do with it.

The zero-depth rule was added in commit 6d6622f ("use net risk depth") with the stated purpose of keeping protective exits live at exhausted depth. The researcher's observation is that one atom above zero the exit is still live, but the same formula now confiscates the closer's funds. An atom is the smallest possible unit of a token, like a cent is to a dollar; blockchain tokens are often divisible to many decimal places. Nothing covers D between 1 atom and a few USDG, where the formula yields charges of millions of USDG on an ordinary close.

The documentation confirms the gap. ACCOUNTING_SPEC.md:665-669 says "A zero-depth close creates no fresh VPI charge or rebate", and SECURITY.md:1439-1440 and WHITEPAPER.md:866-867 carry the same rule. SECURITY.md:1434-1445 lists the VPI limitations (zero depth, lifetime clamp, partial-close approximation, liquidation); small positive depth is not among them. In other words, the protocol's own documents describe the special case for zero only, which suggests nobody analysed what happens just above zero.

Exploitation

Step 1: reach the claims regime and steer depth to a few USDG

In the claims regime a winner's unpaid profit is booked as a trader claim, so D = assets − claims sits at 0. Any losing trader can then choose D by closing part of its position, because the realised loss enters pool assets. One coarse partial close gives D ≈ 64 USDG; two give D ≈ 2.2 USDG. The attacker's fees are 3.17 USDG, and its trading loss is the same with or without the attack, as the control timeline shows. A "control timeline" is the same scenario run without the attack, used as a comparison so the difference can be measured.

Why this step matters: the attacker needs the depth to be tiny but not zero. Closing a losing position moves money from the trader into the pool, which raises the pool's assets and therefore raises the depth. By choosing how much of its position to close, the attacker chooses the depth. Two small closes land it at about 2.2 USDG, just above the zero threshold where the guard would kick in.

Step 2: the victim closes into the tiny depth

The victim's close increases skew, so the uncapped formula applies. The charge is an action charge, and MarginClearinghouse.sol:955-959 collects min(charge, eligible), where eligible covers the spendable action reserve, free buying power and committed order margin, in addition to the closed position's pledge. An action charge is a fee taken for performing an action. min(charge, eligible) means the platform takes the smaller of the two numbers: the charge, or everything the account is allowed to pay. The "eligible" set is broader than the position itself: it includes the action reserve (money set aside for fees), free buying power (unused balance), and committed order margin (money locked for other orders), plus the pledge (the margin backing the closed position). CfdEngineSettlementSidecar.sol:674 (ActionChargeSettled) records the rest as waived. Waived means written off: the platform does not collect it and does not revert. To revert is to cancel the whole transaction and undo it, as if it never happened. The close executes and nothing reverts. The victim's realised profit is withheld against the charge, and its unrelated free settlement is taken too.

At D = 2.18 USDG the charge on a 100k close is 2,819,144.31 USDG. The victim's settlement goes to 0 and the remainder is waived.

Why this matters: the victim never agreed to pay millions. The charge is calculated automatically, the platform takes everything it can reach, and the transaction still succeeds. The charge is calculated automatically and the transaction still succeeds.

Step 3: the same happens through a keeper-triggered stop-loss

The victim's stop-loss protection is triggered and executed by a public keeper. At D = 2.19 the charge is 3,110,424.46 USDG and the victim's settlement goes to 0 with no further action by the victim. The program states that "harm caused by any caller acting as a keeper is in scope". In scope means the competition rules accept it as a valid finding.

Why this matters: even a trader who does nothing can lose everything. The stop-loss is supposed to protect the trader, but here it becomes the mechanism that takes the whole settlement.

Step 4: the victim's alternatives all fail

  • A close with maxActionChargeAssets reverts ConstraintViolation.
  • Withdrawals of positioned accounts revert CfdEngine__DegradedMode (CfdEngineSettlementSidecar.sol:274).
  • The account cannot be liquidated, because it is solvent.
  • Stored depth does not move by itself: 48 h later the charge is still 218,333 USDG, 8.4× the account's balance.

The only exit costs everything.

In plain words: maxActionChargeAssets is an optional limit a trader can set on a close, saying "do not charge me more than this". If the calculated charge exceeds the limit, the transaction reverts with ConstraintViolation, meaning it is cancelled. That sounds protective, but it leaves the trader stuck: the position cannot be closed. Withdrawing money also fails, because the pool is in degraded mode. Liquidation, the forced closing of an unhealthy position, cannot happen because the account is solvent, meaning it has enough money to cover what it owes. And the depth does not change on its own, so waiting does not help: two days later the charge is still 218,333 USDG, 8.4 times the account's balance. Every route out either costs everything or is blocked.

Step 5: the confiscated value becomes redeemable Senior equity

With claims fully covered, the victim's seized cash is free pool equity. Junior is first-loss and was already wiped in the regime, so the value restores impaired Senior principal. When the remaining positions close, the owner's documented recovery action clearDegradedMode() becomes possible: it requires cash ≥ max liability (CfdEngine.sol:658-665). WHITEPAPER.md §7.5 (lines 1335-1339) describes it as the protocol's recovery path: "After genuine restoration to A_eff ≥ L_max, the owner may clear the latch through the explicit recovery path". After it, the normal LP epoch settlement funds Senior redemptions, and the attacker's Senior shares redeem the victim's value.

settleLpEpoch reverts HousePool__DegradedMode until that point in both timelines, so the owner action is the protocol's ordinary exit path for every LP, not something the attack needs from a malicious owner. The program puts this case in scope: "a legitimate, documented action by a trusted role that triggers a bug harming users or the protocol".

In plain words: equity here means the pool's own money, the part not owed to traders. The victim's seized cash increases that equity. The Junior tranche, which absorbs losses first, is already empty, so the increase goes to the Senior tranche, the safer one. The attacker holds Senior shares, so it now owns a bigger slice of the pool. To cash out, the pool must leave degraded mode, which the owner does with clearDegradedMode() once the pool's cash covers its maximum possible liability. That is a normal, documented step that the protocol needs anyway, not something the attacker forces a malicious owner to do. After that, the normal settlement process pays out Senior redemptions, and the attacker's shares turn into the victim's money.

Step 6: run the PoC

The gist at https://gist.github.com/the-red-ace/[redacted] contains X2Cliff.t.sol, X2GridBase.sol, X2ErrNames.sol, fix.diff and a README. A gist is a simple way to share files online. The tests are run as follows:

Bash
git checkout [redacted] && git submodule update --init --recursive
mkdir -p packages/perps/test/perps/x2 && cp X2GridBase.sol X2ErrNames.sol X2Cliff.t.sol packages/perps/test/perps/x2/
forge test --root packages/perps --match-path test/perps/x2/X2Cliff.t.sol -vv

Line by line:

  1. git checkout [redacted] && git submodule update --init --recursive switches the local copy of the repository to the exact commit the report refers to, then downloads any submodules. A submodule is a separate repository that this one depends on, like a library kept in its own folder. The && means run the second command only if the first succeeds.
  2. mkdir -p packages/perps/test/perps/x2 && cp X2GridBase.sol X2ErrNames.sol X2Cliff.t.sol packages/perps/test/perps/x2/ creates a folder for the new tests and copies the three test files from the gist into it. mkdir -p creates the folder and any missing parents; cp copies files.
  3. forge test --root packages/perps --match-path test/perps/x2/X2Cliff.t.sol -vv runs the tests with Forge, the Foundry test runner. --root says where the project lives, --match-path selects only this test file, and -vv asks for more detailed output so the numbers can be read.

The suite asserts the following:

Test What it asserts
test_X2C_Control_LargeDepth At normal depth the same close is an ordinary rebate, and V keeps 112,528.51.
test_X2C_Cliff One sized partial close (D = 63.9): V ends below its pre-close settlement on a winning close.
[redacted] D = 2.18: settlement goes to 0, the remainder is waived, nothing reverts.
test_X2C_B_BoundedCloseFrozen ConstraintViolation, withdraw reverts DegradedMode, not liquidatable, depth unchanged after 48 h.
test_X2C_C_AttackerIsJuniorLP Junior (first-loss, wiped) captures nothing; the Senior tranche rises by the victim's loss.
[redacted] A keeper-executed stop-loss at D = 2.19 takes V's settlement to 0.
[redacted] Attack and control timelines from the same snapshot. The attacker's Senior redemption is 112,282.04 USDG higher and the victim 112,505.47 USDG poorer. The attacker's trading account and the third-party claimant end the same in both, so the net theft is 112,282.04 USDG.
[redacted] V is not liquidatable, and seven days of waiting leave D unchanged.

Each test name describes one check. The control test shows the same close at normal depth is a normal rebate. The cliff test shows the first drop in depth already hurts the victim. The fine-depth test shows the whole settlement disappearing. The bounded-close test shows the escape hatch freezing the account. The Junior test shows the first-loss tranche gets nothing. The protection test shows a keeper-triggered stop-loss doing the same damage. The Senior test shows the attacker cashing out the victim's loss. The escape test shows waiting does not help.

The expected output is:

Text
Suite result: ok. 8 passed; 0 failed; 0 skipped
test_X2C_E: attacker (Senior LP) redeems 237478122767 (attack) vs 125196083224 (control): [redacted]
            victim ends 0 (attack) vs 112505465699 (control); attacker's tuning fees 3169087
            attacker NET gain across both accounts: 112282039501
test_X2C_A: D before close 2178986 | vpiDelta 2819144309459 | V settlement 25926617619 -> 0
test_X2C_D: D at trigger 2186806 | charge 3110424456565 | V settlement 25926609799 -> 0

Reading the output: the suite result line says all eight tests passed. The test_X2C_E lines show the attacker's Senior redemption in the attack timeline versus the control timeline, the difference, the victim's ending balance in both, the fees paid, and the attacker's net gain across both accounts. The test_X2C_A line shows the depth before the close, the VPI delta, and the victim's settlement going from a positive number to zero. The test_X2C_D line shows the same for the keeper-triggered stop-loss. The numbers are in the token's smallest unit, so they look large; the report converts them to USDG in its tables.

Root cause

The defect is the exact-zero exemption. The close-side charge is uncapped, and the only case that is guarded is D == 0. The clamp that follows the calculation bounds only rebates, never charges. Between 1 atom and a few USDG the formula's division by a tiny depth produces charges far larger than the account's entire settlement, and the action-charge collection logic then takes everything the account owns: the realised profit, the position margin, and free settlement that was never pledged to the position. The shortfall is written off rather than reverting, so the close succeeds and the trader has no signal that anything went wrong.

Existing defences do not stop it. The bounded-close path (maxActionChargeAssets) reverts, but that only freezes the account rather than protecting it. Withdrawals revert in degraded mode. Liquidation is impossible because the account is solvent. Depth does not drift on its own in a degraded pool where opens are blocked, so waiting does not help. The zero-depth rule is documented for zero depth only, and small positive depth is not among the listed VPI limitations.

In everyday terms: imagine a shop that says "if the shelf is completely empty, you can take an item for free". Nobody thought about a shelf with one crumb on it. The rule as written treats one crumb as a full shelf, and the pricing formula, which divides by how full the shelf is, produces an absurd price. The shop then takes everything in the customer's wallet, and the till still records the sale as successful.

Impact

The report classifies this as direct theft of user funds (Critical impact), with the PoC executing the theft end to end: the attacker realises the victim's funds as USDG in its own wallet.

Timeline (same snapshot) Victim V closes V ends with Attacker's Senior redemption
Attack: V closes at D = 2.18 USDG charge 2,819,144.31 USDG on a 100k close 0 237,478.12 USDG
Control: V closes after depth is restored rebate 4.18 USDG 112,505.47 USDG 125,196.08 USDG
Difference −112,505.47 +112,282.04

The attacker controls two accounts: the Senior LP and the depth-sizing trader L. The test asserts that L's trading account ends the same in both timelines (60,718.17 USDG, within 42 atoms of rounding), so the attacker's net gain across both accounts is +112,282.04 USDG. The third-party claimant W ends with exactly the same balance in both timelines. The taken value comes from the victim alone.

Cost to the attacker: 3.17 USDG in fees, about 1 : 35,000 against the amount taken. With the fix applied, the same test gives a net gain of 669.99 USDG instead of 112,282.04.

Every trader who closes in the skew-increasing direction while D is small loses the same way. Voluntary closes and keeper-triggered stop-losses are both affected. The attacker keeps D small because nothing else moves it in a degraded pool, where opens are blocked.

Other measured cases:

Scenario D before the close Close charge Victim settlement before → after
Control, before the claims regime 1,011,121.71 −27.22 (rebate) 25,926.62 → 112,528.51
One sized partial close 63.90 96,884.59 25,926.62 → 15,616.92 (86,580 profit also forfeited)
Two sized partial closes 2.18 2,819,144.31 (2,706,637.69 waived) 25,926.62 → 0
Stop-loss triggered by a keeper 2.19 3,110,424.46 25,926.61 → 0
Bounded close (max charge 1,000) 2.19 ConstraintViolation no close, no withdraw, not liquidatable; charge 218,333 at t+48 h

If the redemption step is not accepted as theft, the bounded-close case meets the High impact "Temporary freezing of funds for at least 24 hours". The total-loss cases are not griefing under the program's ratio rule: 3 USDG causing more than 100k USDG of damage. Griefing means causing harm for no personal gain; the ratio rule compares the cost to the attacker with the damage caused.

On feasibility, the report is explicit that the pool must already be in the claims regime. Feasibility means how hard the attack is to carry out. Opens must leave assets ≥ max liability plus a settlement buffer (CfdEnginePlanLib.sol:421 → SolvencyAccountingLib.sol:93-104), and LP redemptions reserve max liability plus claims (HousePoolAccountingLib.sol:50-51). Under the program's Feasibility Limitations, "Impact is calculated first, separately from feasibility. Feasibility limitations do not change the impact or severity of a finding, only the amount paid for it." The capital involved is well below the USD 100M threshold.

The report also distinguishes this from known issues. The AI scan's Info items ("Temporary pool liquidity can reduce a skew-increasing close charge" and "... can amplify a skew-reducing close rebate") describe a trader moving totalAssets with its own liquidity to lower its own charge or raise its own rebate. This report is the opposite direction, with a different victim, a different defect and a different fix. The scan's remedy (commit-time or time-weighted depth) does not remove it, because the depth here is genuinely tiny at both times. It is also not "lack of liquidity": the loss is not a delayed or unpaid payout. A formula singularity takes the trader's own collateral, unrelated to pool cash, and an attacker then redeems it. A singularity is a point where a formula blows up, here because it divides by a number close to zero.

Fix

The recommendation is to treat depth below a floor as zero for the fresh close-side charge, or to cap the fresh positive charge at a share of the closed slice's notional. The gist's fix.diff uses 5% of the closed notional. With it applied, the cliff tests fail and the repository's 178 close/VPI tests pass. Evaluating the VPI delta with max(D, D_min) is an equivalent option.

In plain words: either treat any depth below a small minimum as zero, so the existing exemption applies, or put a ceiling on the charge, for example 5% of the size of the position being closed. The suggested patch uses the 5% ceiling. The tests that demonstrate the cliff then fail, which is expected because the bug is gone, while the repository's existing 178 tests about closes and VPI still pass, showing the fix does not break normal behaviour. Using the larger of the actual depth and a minimum depth in the formula is another way to get the same result.

Variants to test

  • Other formulas with a division by a state variable. Look for any charge or rebate computed as a function divided by a pool or account quantity, and check whether the guard is an exact-zero check. A positive result is a value that is tiny but non-zero producing a charge larger than the account's balance.
  • Action-charge collection across multiple balances. Where a charge is collected from min(charge, eligible) and the remainder is waived rather than reverting, check whether the eligible set includes funds unrelated to the action. A positive result is a close or action that succeeds while taking free settlement or committed order margin.
  • Keeper-triggered paths. Check whether a protection or stop-loss executed by a public keeper reaches the same charge logic as a voluntary close. A positive result is a keeper-triggered exit that zeroes a solvent trader's settlement.
  • Degraded or claims regimes. Look for modes where opens are blocked and depth is set by a losing trader's partial close. A positive result is a depth that can be steered to a few USDG with public calls and stays there over time.
  • Bounded-action escape hatches. Check whether a maxActionChargeAssets-style bound reverts while withdrawals and liquidation are also blocked. A positive result is an account that is frozen, solvent and not liquidatable, with the charge unchanged after 48 h.
  • Tranche accounting after a write-off. Check where a waived shortfall lands in the LP accounting. A positive result is a first-loss tranche that is already wiped and a senior tranche that rises by the victim's loss and can be redeemed after the documented recovery action.

Hunting notes

This kind of bug tends to hide at the boundary of a documented special case. The zero-depth rule was written for exactly zero, and the documentation repeats it for zero only, which is a strong signal that the interval just above zero was never analysed. When a formula divides by a state variable, the interesting question is not whether zero is handled but what happens at one atom.

During recon, the signals that point to it are: a charge formula with a division by pool depth; a guard written as != 0; a clamp that bounds only one sign of the result; an action-charge collector that takes min(charge, eligible) and waives the rest instead of reverting; and a documented degraded mode in which opens are blocked and depth is set by trader losses. A protocol with a documented recovery action that becomes possible once cash covers max liability is also worth reading closely, because it tells you how confiscated value eventually becomes redeemable. Recon means the early exploration phase, reading code and documentation before testing anything.

The researcher built a control timeline from the same snapshot to measure the difference. The attacker's trading account and an uninvolved third-party claimant end the same in both timelines, which isolates the gain to the victim's loss. The PoC runs in the repository's own Foundry suite with release parameters, uses only the protocol's public entry points and the owner's documented recovery action, and avoids vm.store, deal and mockCall. The report also states the precondition openly, addresses the program's feasibility rule, and separates the finding from the AI scan's Info items and from a generic lack of liquidity, so the impact argument stands on its own.

Glossary

  • Perps (perpetual futures): a bet on a price that never expires, backed by margin.
  • Margin: money a trader puts down as a guarantee for a position.
  • Commit: a saved snapshot of a code repository, identified by a long hash.
  • Repository: a folder of code tracked by a version control system such as git.
  • Bug bounty competition / audit competition: an event where researchers find flaws in code and are paid for valid reports.
  • Immunefi: the platform hosting the competition.
  • Severity: a rating of how serious a finding is, such as High or Critical.
  • VPI (virtual price impact): a charge or rebate applied when a trader closes a position, based on how the close changes the market's skew.
  • Skew: how lopsided the open bets are, for example more money on one side than the other.
  • Economic depth (D): the pool's cash minus what it owes traders, pool.totalAssets() − totalTraderClaims.
  • Atom: the smallest unit of a token.
  • USDG: a stablecoin designed to be worth about one US dollar.
  • Rebate: a payment back to a trader, the negative side of a charge.
  • Charge: a fee taken from a trader.
  • Clamp: a check that limits a value to a range, here only on the negative side.
  • Guard: a check in code that prevents something from happening.
  • Degraded mode / claims regime: a documented pool state where trader claims roughly equal pool cash, opens are blocked and a recovery action is needed.
  • Latch: a state that stays on until explicitly cleared.
  • Tranche: one of two investor groups in the pool; Junior absorbs losses first, Senior is paid first.
  • Junior tranche: the first-loss group, already wiped in this scenario.
  • Senior tranche: the safer group whose shares the attacker holds.
  • Equity: the pool's own money, not owed to traders.
  • LP (liquidity provider): an investor who puts money into the pool and holds shares in it.
  • Redemption: cashing out pool shares for money.
  • clearDegradedMode(): the owner's documented recovery action that leaves degraded mode once cash covers maximum liability.
  • Maximum liability: the most the pool could owe.
  • Keeper: a public role that anyone can play, watching for conditions and triggering actions such as stop-losses.
  • Stop-loss: an automatic instruction to close a position if it loses enough.
  • Oracle: an outside service that feeds prices into the blockchain.
  • Proof of concept (PoC): a program that demonstrates a vulnerability in practice.
  • Foundry: a toolkit for writing and running tests against blockchain code.
  • Forge: the Foundry test runner.
  • Test suite: a collection of automated checks.
  • Mock: a stand-in component used in tests.
  • Pyth: a price feed service.
  • Entry point: a function the protocol exposes for anyone to call.
  • Router: the part of the system that processes a user's order.
  • Action charge: a fee taken for performing an action.
  • min(charge, eligible): take the smaller of the charge and what the account can pay.
  • Eligible: the set of balances a charge can be collected from.
  • Action reserve: money set aside for fees.
  • Buying power: unused balance available to trade.
  • Committed order margin: money locked for open orders.
  • Pledge: the margin backing a specific position.
  • Waived: written off, not collected.
  • Revert: cancel a transaction and undo it.
  • ConstraintViolation: the error when a close exceeds a trader's maximum charge limit.
  • CfdEngine__DegradedMode: the error when an action is blocked because the pool is in degraded mode.
  • Liquidation: forced closing of an unhealthy position.
  • Solvent: having enough money to cover what is owed.
  • maxActionChargeAssets: an optional limit a trader can set on a close's charge.
  • settleLpEpoch: the normal settlement process that funds LP redemptions.
  • Gist: a simple way to share files online.
  • Submodule: a separate repository that another repository depends on.
  • Control timeline: the same scenario run without the attack, used for comparison.
  • Griefing: causing harm for no personal gain.
  • Feasibility: how hard an attack is to carry out.
  • Singularity: a point where a formula blows up, here from dividing by a number close to zero.
  • Recon: the early exploration phase of reading code and documentation.
  • vm.store, deal, mockCall: Foundry shortcuts that rewrite storage, hand out free tokens, or fake calls; avoided here so the test only does what a real user could do.
  • Notional: the size of a position used as the base for a percentage cap.
  • fix.diff: a file containing the suggested code change.

More by redbaron

View all

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

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.