Skip to content
Business logic Audit finding Advanced

Ordinary LP settlements erase Senior's principal-recovery target after a terminal-deficit recapitalization, so a Junior holder redeems the USDG that restores Senior principal

After a terminal LP deficit, the owner's documented recapitalization leaves a residual pending amount, but each ordinary LP settlement re-caps that residual against equity that already backs Senior principal, booking a phantom loss that lowers Senior's high-water mark. A Junior holder can then redeem revenue that should have restored Senior principal, taking USDG that belongs to the Senior LP.

emanueldlvg Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#98751 [SC-High] Ordinary LP settlements erase Senior's principal-recovery target after a terminal-deficit recapitalization, so a Junior holder redeems the USDG that restores Senior principal

Submitted on Nov 10th 2026 at 01:39:42 UTC by @emanueldlvg for Audit Competition | Plether

Description

Affected contracts (in-scope commit a82d4fef; identical runtime code live on Arbitrum Sepolia v2.0.0)

The program states that the v2.0.0 Arbitrum Sepolia release is built from a commit whose packages/perps/src is identical to a82d4fef. The proof of concept runs in the repository's Foundry suite at the in-scope commit, with the release parameters and Pyth mocked. No in-scope contract is modified.

Contract Arbitrum Sepolia v2.0.0 address Role in the issue
HousePool (HousePoolReconcilePlanLib, HousePoolPendingPreviewLib, HousePoolWaterfallAccountingLib) 0xeb5604c393843b2f3c347ec24fa9ddad6ab2131e Root cause. _reconcile re-caps the full residual pending recapitalization against the full distributable equity on every pass, reserves it again, books the double reservation as a Senior loss, then re-bootstraps Senior with a lower high-water mark
CfdEngine 0xca18a6783d7542f9d2f28f4f259772b74c4d6baa recapitalizePool (owner, documented recovery) records the recapitalization; clearDegradedMode
TrancheVault (Senior) 0x5dc42ba5a1e8dd3e1b6868d10f66a9bf8fb5b83d Holds the Senior LP shares whose principal-recovery target is erased; pays the Senior LP less USDG on redemption
TrancheVault (Junior) 0x4a8b67184a1e3224c11a191cc69f22c50eef734e A Junior holder's exit request triggers the re-reservation; the Junior holder later redeems the Senior principal restoration as USDG
OrderRouter 0x918663d6da8cb33b325a04c4a5e8c51d42f3b444 Public trading path used to reach the terminal-deficit state in the proof

Release parameters used (packages/perps/DEPLOYMENT.md and the program page):

  • risk: vpiFactor 0.01e18, maxSkewRatio 0.4e18, maintenance 10 bps, initial 20 bps, frozen-market 300 bps, baseCarryBps 500, liquidation bountyBps 10;
  • execution fee 4 bps, LP epoch 1 hour;
  • Senior cap 40,000,000 USDG and 80% of the pool, set through the 72-hour timelock;
  • Senior and Junior seeds of 1 USDG each.

Brief/Intro

After a terminal LP deficit d, the documented recovery is that the owner recapitalizes the pool and then clears degraded mode (SECURITY.md, "Explicit terminal-deficit cascade"). CfdEngine.recapitalizePool(X) gives Senior a principal of X. The part that equity backs, X − d, is credited to Senior principal at once. The rest, d, stays pending "until it is backed". Senior's high-water mark is set to X. That high-water mark is Senior's principal-recovery target. In the specification's words, it is "the unimpaired senior entitlement that future revenue must restore", and "Revenue restores impaired senior principal to its high-water mark before junior participates." The d gap between Senior principal and its high-water mark is impaired Senior principal. It is not yield.

HousePool does not record that the residual has already been capped. On every later reconcile it caps the whole residual against the whole distributable equity again, although that equity already backs the Senior principal the first pass credited. With no new backing, the double reservation is booked as a loss that zeroes Senior principal. Senior is then re-bootstrapped at the same principal but with a lower high-water mark. Senior's principal-recovery claim disappears without a trade, a price move or a loss. The revenue that should restore Senior principal is then credited to Junior, and Junior holders redeem it as USDG.

Any LP's ordinary exit settlement triggers it. A Junior holder can do it on purpose: request an exit from a second wallet so that one settlement runs before backing arrives, then redeem after the revenue arrives. In the proof of concept the setup uses release parameters and public calls, and the owner recapitalizes at the repository's own fixture ratio X = 1.9984 d. From one EVM snapshot:

  • the Junior holder redeems 45,530.035820 USDG in the attack branch and 0.000000 USDG in the control branch;
  • the Senior LP redeems 56,901.293994 USDG instead of 103,451.451131 USDG, a loss of 46,550.157137 USDG;
  • Senior ends 46,551.351822 USDG below its principal-restoration entitlement.

Vulnerability Details

What the Senior high-water mark represents

ACCOUNTING_SPEC.md lines 331–338:

seniorPrincipal and juniorPrincipal are the current NAV attributed to the two tranches, not immutable records of historical deposits. seniorHighWaterMark records the Senior entitlement that future revenue must restore after a loss. … 3. Charge a shortfall to Junior first, then Senior. Losses do not reduce the Senior high-water mark. 4. Route surplus first to restore Senior principal to its high-water mark, then to Junior.

WHITEPAPER.md lines 628–629: "the senior high-water mark: the unimpaired senior entitlement that future revenue must restore before junior receives residual value." Lines 772–773: "Revenue restores impaired senior principal to its high-water mark before junior participates."

After the recapitalization the high-water mark is X, the Senior principal the owner's recapitalization creates. Senior principal is X − d only because d of that recapitalization is not yet backed. The gap HWM − S = d is therefore impaired Senior principal. The revenue that closes it is, by the specification's own words, the restoration of Senior principal. It is not a coupon or other yield: the Senior coupon is a separate transfer (step 1 of the same list), and Junior holds no claim on revenue until Senior principal is back at its high-water mark.

The repository's own fixture, and what it does not exercise

test/perps/accounting/waterfall/HousePoolWaterfall.t.sol lines 177–220, test_PendingRecapitalization_CapsAgainstTraderClaimLiabilitiesAndCarriesResidual:

  • recapitalizes pendingAmount = 100_000e6 while trader claims are 50_040e6;
  • reconciles once and asserts seniorHighWaterMark == pendingAmount: "Residual recap should preserve senior's recovery target" (line 201);
  • removes the liability and reconciles again;
  • asserts "Residual recap should settle once backing becomes available" (line 217) and "Settled recap should keep senior restoration out of unassigned assets" (line 219).

The test never runs an ordinary reconcile between the first pass and the arrival of backing. On the live protocol that happens on the next hourly LP epoch with any matured request. Inserting one such settlement breaks all three assertions (see the Proof of Concept).

Root cause: the residual is re-capped against equity that already backs Senior

HousePool._reconcile (HousePool.sol lines 1555–1599) computes the settleable buckets from the full outstanding pending buckets and the full terminal distributable equity:

Solidity
HousePoolPendingPreviewLib.ClaimantPendingBuckets memory claimantBuckets = _getPendingClaimantBuckets();
HousePoolPendingPreviewLib.ClaimantPendingBuckets memory settleableClaimantBuckets =
    _settleablePendingClaimantBuckets(reconcileSnapshot, claimantBuckets);
...
HousePoolReconcilePlanLib.ReconcilePlan memory plan = HousePoolReconcilePlanLib.planReconcile(
    _currentPendingAccountingState(), reconcileSnapshot,
    _pendingClaimantBucketAssets(settleableClaimantBuckets), poolConfig.seniorRateBps, couponElapsed, markFresh
);
...
_setWaterfallState(plan.state.waterfall);
...
_applyPendingClaimantBucketsLive(settleableClaimantBuckets, claimantBuckets, allowRevenueContinuation);

_settleablePendingClaimantBuckets (lines 1829–1834) is a plain cap against the current distributable:

Solidity
return HousePoolPendingPreviewLib.capClaimantBuckets(claimantBuckets, reconcileSnapshot.distributable);

HousePoolReconcilePlanLib.planReconcile then reserves the settleable amount out of distributable before it reconciles the waterfall (HousePoolReconcilePlanLib.sol lines 68–71), and books any shortfall against current principal as a loss (lines 84–105):

Solidity
if (pendingBucketAssets > 0) {
    snapshot.distributable =
        snapshot.distributable > pendingBucketAssets ? snapshot.distributable - pendingBucketAssets : 0;
}
...
HousePoolWaterfallAccountingLib.ReconcilePlan memory waterfallPlan = HousePoolWaterfallAccountingLib.planReconcile(
    plan.state.waterfall.seniorPrincipal, plan.state.waterfall.juniorPrincipal, distributableToClaims
);
...
if (plan.deltaAssets > 0) {
    plan.state.waterfall = HousePoolWaterfallAccountingLib.absorbLoss(plan.state.waterfall, plan.deltaAssets);

Step by step, after the first pass:

  • Senior principal is S = X − d, and it equals the whole distributable equity D = X − d.
  • The residual d is still pending.
  • The next reconcile reserves min(d, D) from D again.
  • For X ≤ 2d, the reserve is all of D, so the waterfall sees distributable 0 against principal X − d.
  • absorbLoss (HousePoolWaterfallAccountingLib.sol lines 167–184) zeroes Senior and leaves the high-water mark unchanged.

_applyPendingClaimantBucketsLive then applies the settleable recapitalization to a waterfall with S = J = 0. That reaches the bootstrap branch of HousePoolPendingPreviewLib.applyClaimantRecapitalizationIntent (HousePoolPendingPreviewLib.sol lines 118–122):

Solidity
if (state.waterfall.seniorPrincipal == 0 && state.waterfall.juniorPrincipal == 0) {
    state.waterfall.seniorPrincipal += remaining;
    state.waterfall.seniorHighWaterMark =
        recapitalizationTargetAssets > remaining ? recapitalizationTargetAssets : remaining;
    remaining = 0;
}

Senior principal is restored to the same X − d, but the high-water mark is overwritten with max(remaining pending, settleable), which is max(d, X − d) < X. The pending bucket shrinks although no backing arrived. Each further pass repeats this until the target reaches the backed principal. At X = 1.9984 d one pass takes the target from X to d. At X = 1.5 d two passes take it from X to d and then to X − d.

From then on, distributeRevenue sees no Senior impairment, and revenue is credited to Junior.

The same double reservation has a second ordering, which follows from the code and is not exercised by the proof of concept below. If backing of at least d arrives before any extra settlement (X > 2d, or a lump of revenue), the waterfall sees only R − d of revenue. It fills the Senior gap first, and the residual recapitalization then finds no gap and is routed to unassignedAssets (lines 124–136). Junior loses d to an owner-only bucket. The fix below covers both orderings.

Not the designed explicit-recapitalization reset.

The repository deliberately lets an explicit owner recapitalization of a genuinely wiped pool set a fresh high-water mark (test/perps/accounting/waterfall/TrancheRecoveryBehavior.t.sol lines 24–55, "Explicit recapitalization should reset the HWM"). That is a decision the owner makes with each recapitalizePool call. Here the owner made one recapitalization with target X, which the first reconcile records as the recovery target. The target is then lowered by ordinary LP settlements, with no new owner decision and no new loss. It also contradicts the residual-recapitalization test above (line 201).

The trigger: the documented recovery, then any LP's ordinary settlement

SECURITY.md lines 1499–1511 ("Explicit terminal-deficit cascade"): "4. Recapitalize or clear positions. 5. Clear degraded mode only after raw solvency E >= L is genuinely restored". EMERGENCY_RESPONSE_GUIDE.md line 228 repeats that criterion. No document sizes X:

  • With the deficit held as trader claims and no open positions, L = 0. The smallest runbook-compliant X is therefore just above d.
  • The drain occurs for every X ∈ (d, 2d], and the repository's own fixture ratio, 1.9984 d, is in that band.

The owner's action is the documented recovery procedure. The bug is triggered afterwards by any LP's ordinary settlement, which needs only one matured LP request and a permissionless settleLpEpoch call. A Senior holder cannot defend: a Senior exit request queued after the first settlement freezes all LP settlement while free cash is 0, and the first settlement that lands still drains (test_ReactiveSeniorExitDoesNotDefend). New deposits cannot dilute the attacker in this state, because HousePool._canAcceptTrancheDeposits rejects them while Junior principal is zero, a recapitalization is pending or Senior is below its high-water mark (HousePool.sol lines 480–502, 1120–1137). The program: "In scope: a legitimate, documented action by a trusted role that triggers a bug harming users or the protocol."

Published items: an incomplete SC-L1 fix, and what the documentation says

The pre-audit report (SC Audit Studio, audits/plether-pre-audit-report.pdf) lists SC-L1, "Permissionless zero-value senior withdraw can persist overstated HousePool tranche principal". It found that _reconcile() applied pending claimant buckets "without capping the credit against the liability-adjusted distributable amount". The project's response: "Fixed in Plether-Fi/plether-core#29. Pending recap/revenue is now capped to what's actually settleable after MTM/deferred liabilities. Anything that can't be settled yet stays pending, stays reserved everywhere, and gets applied later once it's backed."

The fix caps the pending bucket on every pass but forgets that the equity it caps against already backs the principal the previous pass credited. In the proof, the residual is applied without any backing: pending falls from 56,900.44 to 91.04 USDG while LP equity is unchanged. That contradicts the fix statement. The program's known-issue rule makes this eligible: "a report on the same root cause is valid only if it shows that the fix at commit a82d4fef ... is incomplete or introduces a new bug."

The Cecuro item MED-12 ("Mixed recovery inflows can strand LP revenue in ownerless pool assets") concerns the revenue-continuation flag in a same-batch recapitalization plus revenue. That is a different root cause.

None of the listed SECURITY.md known-limitation sections mentions residual recapitalization or the high-water mark. The specification states the opposite of the observed behaviour:

  • "Losses do not reduce the Senior high-water mark" (ACCOUNTING_SPEC.md line 337);
  • "Reserving them in step 2 prevents counting the same inflow twice" (lines 339–340);
  • "Revenue restores impaired senior principal to its high-water mark before junior participates" (WHITEPAPER.md line 772).

Exploitation

The proof of concept uses the repository's BasePerpTest stack with the release risk parameters, the release Router configuration, 1 USDG seeds and the 40M / 80% Senior caps (asserted). All LP capital enters through public requests:

  • a Senior LP with 300,000 USDG;
  • a Junior holder (the attacker) with 980,000 USDG, plus a second wallet with 5,000 USDG;
  • three other Junior holders with 5,000 USDG each.

Every trade uses the public V3 commitOrder / executeOrder, and every price is a MockPyth tick through OrderRouter.updateMarkPrice. The owner's only actions are the documented recapitalizePool and clearDegradedMode. There is no vm.store, deal, etch or mockCall on in-scope contracts.

The terminal-deficit state and the documented recovery, identical in every test:

  1. Traders open a hedge at 1.00 inside the 40% skew cap: three 430,000 USDG SHORTs and two 400,000 USDG LONGs. Each margin covers its endpoint maximum profit, so every carry borrow base is 0, and the test asserts this.
  2. The basket rises 60% in Pyth marks of at most 1% per trading day, weekends skipped: 48 marks over 66 calendar days. A 300,000-token LONG opens at the top, and the SHORTs close in profit. That latches degraded mode.
  3. The basket falls 61.25% in marks of at most 1% per trading day: 95 marks over 133 calendar days. The LONGs close, and the payout above pool cash becomes a trader claim. The terminal LP deficit is d = 56,900.444682 USDG.
  4. The owner follows the documented recovery: recapitalizePool(X) with X = 1.9984 d = 113,709.848652 USDG, then clearDegradedMode().
  5. One ordinary Junior exit is settled by a keeper. This gives the repository-intended state: Senior principal 56,809.403970, high-water mark 113,709.848652, pending recapitalization 56,900.444682.

Attack (test_Attack_JuniorHolderSettlesBeforeBackingThenRedeems, test_AttackVersusControl_RedeemableUsdg): 6. The Junior holder requests an exit from its second wallet, and the matured epoch is settled. There is no trade, no price move and no loss. The Senior high-water mark falls from 113,709.848652 to 56,900.444682. Pending recapitalization falls from 56,900.444682 to 91.040712 although no backing arrived. Senior principal is unchanged at 56,809.403970. 7. Ordinary losing trades bring R = 46,642.392534 USDG of LP revenue, and one more ordinary settlement runs. LP equity is 103,451.796504 USDG, so Senior is entitled to min(X, equity) = 103,451.796504. Senior holds 56,900.444682, and Junior got 46,460.311110. 8. The Junior holder and the Senior LP each request their full balance, and one settlement funds both in full. The Junior holder receives 45,530.035820 USDG and the Senior LP 56,901.293994 USDG.

Control (test_Control_NoSettlementBeforeBackingThenRedeem, and the control branch of test_AttackVersusControl_RedeemableUsdg):

  • Step 6 is skipped, and everything else is the same.
  • After the same backing, Senior holds its full entitlement of 103,451.796504 with the high-water mark at 113,709.848652, and Junior principal is 0.
  • The Senior LP redeems 103,451.451131 USDG, and the Junior holder redeems 0.000000 USDG.

test_RepoRatio_OneOrdinarySettlementHalvesSeniorTarget runs the same sequence with step 6 done by an unrelated Junior holder. The result is identical: Senior shortfall 46,551.351822 USDG, and Senior LP share value 56,900.254720 USDG.

test_ReactiveSeniorExitDoesNotDefend uses X = 1.5 d = 85,350.667023. The Senior LP queues a 10% exit after the first settlement. Every settlement then reverts NoLpEpochProgress while free cash is 0. The first settlement that lands, after two small losing trades, still lowers the high-water mark from 85,350.667023 to 52,937.410496, with 2,053.011752 USDG of the Senior exit funded.

Impact Details

Critical — Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield.

  • What is taken. The Senior LP's principal-restoration claim, which the specification defines as the unimpaired Senior entitlement that revenue must restore to impaired Senior principal before Junior participates.
  • Who takes it. After the drain, that restoration is credited to Junior principal. A Junior holder who triggered the drain withdraws it as USDG.
  • Measured from one EVM snapshot:
    • the Junior holder gains 45,530.035820 USDG (attack minus control);
    • the Senior LP redeems 46,550.157137 USDG less;
    • the remaining 1,020.121317 USDG stays with the other Junior shares and with unassigned assets.
  • The Senior LP has no recovery.
    • A later recapitalization, with Senior principal above zero, fills only HWM − S = 0 and goes to unassignedAssets.
    • assignUnassignedAssets mints to a single receiver.
    • A Senior exit does not defend (test_ReactiveSeniorExitDoesNotDefend).

The setup, stated factually:

  • The terminal-deficit state that the documented recovery procedure exists for. The proof reaches it through public calls with marks of at most 1% per trading day: a +60% leg over 66 calendar days and a −61.25% leg over 133.
  • The owner's documented recapitalization at the repository's own fixture ratio, followed by clearDegradedMode() once E >= L.
  • One ordinary LP settlement before backing arrives.

The program's feasibility rule: "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." On trusted-role scope: recapitalization is the documented recovery procedure, and the bug is triggered by any LP's ordinary settlement afterwards ("In scope: a legitimate, documented action by a trusted role that triggers a bug harming users or the protocol").

Recommendation

Do not re-cap a residual that a previous pass already capped against the same equity.

  • Option 1. Cap pending recapitalization only against the distributable equity that is not already claimed by tranche principal: settleable = min(pending, max(distributable − (seniorPrincipal + juniorPrincipal + unassignedAssets), 0)). With no new backing, the residual then stays pending and reserved, as the SC-L1 fix statement promises, instead of being re-reserved out of equity that already backs Senior.
  • Option 2. Apply the residual before the waterfall routes any surplus, so that new backing fills the residual recapitalization first. Revenue then reaches Junior only after the recapitalization is settled.

Either option also removes the second ordering described in the root cause. Add a regression test that inserts one ordinary reconcile between the first pass and the arrival of backing in test_PendingRecapitalization_CapsAgainstTraderClaimLiabilitiesAndCarriesResidual, and asserts the existing lines 201, 217 and 219.

Proof of Concept

Save the test below as packages/perps/test/perps/poc/ResidualRecapPrincipalTheft.t.sol and run from the repository root:

Bash
forge test --root packages/perps --match-contract ResidualRecapPrincipalTheftPoC -vv

The file contains five tests:

  • test_RepoRatio_OneOrdinarySettlementHalvesSeniorTarget: the repository's ratio X = 1.9984 d; one extra ordinary settlement before backing;
  • test_Attack_JuniorHolderSettlesBeforeBackingThenRedeems: the Junior holder's extra settlement, the backing, then both redemptions;
  • test_Control_NoSettlementBeforeBackingThenRedeem: the same without the extra settlement;
  • test_AttackVersusControl_RedeemableUsdg: attack and control from one EVM snapshot, asserting the Junior holder's USDG gain and the Senior LP's USDG loss;
  • test_ReactiveSeniorExitDoesNotDefend: the Senior LP's own exit request does not prevent the drain.

The suite's Router is the repository's test harness, which only adds a legacy scalar commitOrder overload. The proof uses the production V3 commitOrder(OrderRequest), executeOrder, updateMarkPrice and settleLpEpoch entry points.

Complete test:

<details> <summary>Complete test </summary>
Solidity
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.35;

import {BasePerpTest} from "../BasePerpTest.sol";
import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.sol";
import {TrancheVault} from "@plether/perps/TrancheVault.sol";
import {IHousePool} from "@plether/perps/interfaces/IHousePool.sol";
import {IOrderRouterAdminHost} from "@plether/perps/interfaces/IOrderRouterAdminHost.sol";
import {MockPyth} from "@plether/test-utils/MockPyth.sol";

/// @notice After a terminal LP deficit `d`, the owner's documented recovery `CfdEngine.recapitalizePool(X)` leaves a
///         residual pending recapitalization (the part not yet backed). Every later ordinary LP settlement re-caps that
///         SAME residual against the SAME distributable equity that the first settlement already credited to Senior
///         principal, books the double reservation as a loss that zeroes Senior, and re-bootstraps Senior with a lower
///         high-water mark. Senior's principal-recovery target falls with no economic event, and later revenue that the
///         waterfall owes to Senior's principal restoration is credited to Junior, which a Junior holder then redeems.
///
///         The terminal deficit is reached through public calls only, at release parameters, with one <=1% Pyth mark per
///         trading day (weekends skipped) and fully margined positions (carry borrow base asserted 0). The owner's only
///         actions are the documented recapitalizePool and clearDegradedMode. Pyth (MockPyth) and USDG (mock token) are
///         the only mocks; no vm.store / deal / etch / mockCall on in-scope contracts.
contract ResidualRecapPrincipalTheftPoC is BasePerpTest {

    // --- actors ---
    address internal constant SHORT_ACCOUNT = address(0xA770C2);
    address internal constant LONG_A = address(0xA770A1); // longs opened at 1.00
    address internal constant LONG_B = address(0xA770B1); // longs opened at the top
    address internal constant REV_TRADER = address(0x5EE0A1); // ordinary losing trader (backing revenue)
    address internal constant SENIOR_LP = address(0x5E1105);
    address internal constant JUNIOR_LP = address(0x1D1105); // main Junior holder
    address internal constant LP_EXIT_A = address(0x1D2001); // ordinary Junior holders who exit after the crisis
    address internal constant LP_EXIT_B = address(0x1D2002);
    address internal constant LP_EXIT_C = address(0x1D2003);
    address internal constant LP_EXIT_D = address(0x1D2004);
    address internal constant KEEPER = address(0xE0EC);

    // --- scenario constants ---
    uint256 internal constant ENTRY_PRICE = 1e8;
    uint256 internal constant TOP_PRICE = 160_000_000; // +60% in 1% daily marks
    uint256 internal constant BOTTOM_PRICE = 62_000_000; // -61.25% in 1% daily marks
    uint256 internal constant TICK_INTERVAL = 2 minutes; // backing round trips only
    uint256 internal constant JUNIOR_MAIN = 980_000e6;
    uint256 internal constant EXIT_WALLET_DEPOSIT = 5_000e6;
    uint256 internal constant SENIOR_DEPOSIT = 300_000e6;
    uint256 internal constant REPO_RATIO_BPS = 19_984; // HousePoolWaterfall.t.sol:182-183 uses 100,000 vs 50,040
    uint256 internal constant HALF_BAND_BPS = 15_000; // 1.5 d

    uint256 internal curPrice;
    uint256 internal orderNonce;

    struct Snap {
        uint256 s;
        uint256 h;
        uint256 j;
        uint256 u;
        uint256 pending;
    }

    // ------------------------------------------------------------------ configuration (release values)

    function _riskParams() internal pure override returns (CfdTypes.RiskParams memory) {
        return CfdTypes.RiskParams({
            vpiFactor: 0.01e18,
            maxSkewRatio: 0.4e18,
            maintMarginBps: 10,
            initMarginBps: 20,
            fadMarginBps: 300,
            baseCarryBps: 500,
            minBountyAssets: 1e6,
            bountyBps: 10,
            keeperShareBps: 5000,
            protocolShareBps: 0
        });
    }

    function _initialJuniorDeposit() internal pure override returns (uint256) {
        return 0; // all LP capital enters through the public request/settle/claim path
    }

    function _initialJuniorSeedDeposit() internal pure override returns (uint256) {
        return 1e6;
    }

    function _initialSeniorSeedDeposit() internal pure override returns (uint256) {
        return 1e6;
    }

    function setUp() public override {
        super.setUp();
        _applyReleaseRouterConfig(); // 72 h timelock
        _setSeniorCapacity(40_000_000e6, 8_000); // 72 h timelock
        assertEq(pool.maxSeniorShareBps(), 8_000, "release Senior share cap");
        assertEq(pool.maxSeniorExposureAssets(), 40_000_000e6, "release Senior exposure cap");
        assertEq(engine.executionFeeBps(), 4, "release execution fee");
        vm.warp(SETUP_TIMESTAMP + 7 days); // Monday 10:00 UTC, live market
        curPrice = ENTRY_PRICE;
        _refreshMark(curPrice);

        uint256 jr = _requestDeposit(juniorVault, JUNIOR_LP, JUNIOR_MAIN);
        uint256 e1 = _requestDeposit(juniorVault, LP_EXIT_A, EXIT_WALLET_DEPOSIT);
        uint256 e2 = _requestDeposit(juniorVault, LP_EXIT_B, EXIT_WALLET_DEPOSIT);
        uint256 e3 = _requestDeposit(juniorVault, LP_EXIT_C, EXIT_WALLET_DEPOSIT);
        uint256 e4 = _requestDeposit(juniorVault, LP_EXIT_D, EXIT_WALLET_DEPOSIT);
        _warpTo(juniorVault.depositEpochStart(jr));
        _refreshMark(curPrice);
        pool.settleLpEpoch(0, 0); // no open positions: permissionless
        _claimDeposit(juniorVault, JUNIOR_LP, jr);
        _claimDeposit(juniorVault, LP_EXIT_A, e1);
        _claimDeposit(juniorVault, LP_EXIT_B, e2);
        _claimDeposit(juniorVault, LP_EXIT_C, e3);
        _claimDeposit(juniorVault, LP_EXIT_D, e4);
        uint256 sr = _requestDeposit(seniorVault, SENIOR_LP, SENIOR_DEPOSIT);
        _warpTo(seniorVault.depositEpochStart(sr));
        _refreshMark(curPrice);
        pool.settleLpEpoch(0, 0);
        _claimDeposit(seniorVault, SENIOR_LP, sr);
        _refreshMark(curPrice);
    }

    // ------------------------------------------------------------------ tests

    /// @notice Headline: the repository's own residual-recapitalization ratio, X = 1.9984 d, no attacker.
    function test_RepoRatio_OneOrdinarySettlementHalvesSeniorTarget() external {
        (uint256 x, uint256 d) = _crisisAndRunbook(REPO_RATIO_BPS);
        _ordinaryExit(LP_EXIT_A); // first ordinary settlement after the recapitalization
        Snap memory a = _snap("after the first ordinary settlement (repository-intended state)");
        assertEq(a.h, x, "HWM must be the recapit

The original report as published on Immunefi, by emanueldlvg. 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 reconcile step re-caps the full residual pending recapitalization against the full distributable equity on every pass, even though that equity already backs the Senior principal credited by the first pass, so the double reservation is booked as a loss and Senior is re-bootstrapped with a lower high-water mark.

Impact

A Junior holder could take roughly 45,530 USDG of revenue that should have restored Senior principal, leaving the Senior LP about 46,550 USDG short, and a Senior exit request does not prevent the drain.

What the attacker needed

Terminal LP deficit reached; owner recapitalizes at X in (d, 2d]; one matured LP exit request; permissionless settleLpEpoch call

The fix

The residual should only be capped against distributable equity not already claimed by tranche principal, or applied before the waterfall routes surplus, with a regression test inserting an ordinary reconcile before backing arrives.

How it was found

  1. Reach a terminal LP deficit through public trades and price marks, then have the owner call recapitalizePool and clearDegradedMode.
  2. Settle one ordinary Junior exit so Senior principal sits below its high-water mark with a residual pending recapitalization.
  3. Have a Junior holder request an exit from a second wallet and settle the matured epoch, which lowers the Senior high-water mark without any new backing.
  4. Let ordinary losing trades generate LP revenue and run another settlement, which credits the revenue to Junior.
  5. Have the Junior holder and the Senior LP request their full balances and settle, so the Junior holder redeems the USDG.

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 pool splits money between a cautious 'Senior' group that gets paid back first and a riskier 'Junior' group. After a big loss the owner tops the pool up, and the rules say future earnings must first pay Senior back to its original target before Junior gets anything. A bookkeeping mistake makes the pool forget that target whenever anyone withdraws normally, so later earnings go to Junior instead, and a Junior user can cash them out.

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 emanueldlvg

View all

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