SC-L1 fix incomplete: every later settlement re-applies the unbacked residual recapitalization, moving Senior LP principal to Junior LPs
The SC-L1 fix that caps pending recapitalization buckets against the whole distributable amount is checked against funds that already back principal from a previous pass, so each later settlement re-applies the unbacked residual. A Junior holder can trigger a permissionless settlement and move Senior LP principal to Junior holders, who then withdraw it as USDG.
- Disclosed after under an hour
#99504 [SC-High] SC-L1 fix incomplete: every later settlement re-applies the unbacked residual recapitalization, moving Senior LP principal to Junior LPs
Submitted on Nov 13th 2026 at 22:42:40 UTC by @Lester for Audit Competition | Plether
- Report ID: #99504
- Report Type: Smart Contract
- Report severity: High
- Target: https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src/HousePool.sol
- Impacts:
- Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield
Description
Brief/Intro
After a terminal-deficit wipe, the owner's documented CfdEngine.recapitalizePool restores Senior LPs through a pending bucket. The SC-L1 fix caps that bucket to what is "actually settleable" and leaves the rest pending until it is backed. The cap is checked against the whole distributable, and part of that already backs the principal the previous pass created. So every later reconciliation applies the unbacked residual again. Any Junior holder can trigger this with a full-balance requestRedeem followed by the permissionless settleLpEpoch. No value arrives and no price moves, yet Senior principal moves to Junior and Junior holders can withdraw it.
- Impact: Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield
- Severity: Critical (also met: Theft of unclaimed yield, High; floor: Contract fails to deliver promised returns, Low)
- Actor needs: no role; Junior shares bought before the wipe, any size for the queue item; one permissionless call. State: a pool after a terminal-deficit wipe whose owner recapitalization is not fully settled at the next settlement.
- Funds at risk: Senior principal restored by the owner. In the project's own mixed-inflow test, one settlement takes Senior from 25,000 to 15,000 at once, and a 10,000 Senior LP loses 9,090.90. An entity holding Junior realises +9,017.75 USDG in the next epoch with no new backing; on the code with the one-line fix it gets 0. If the trader-claim liability ends after its settlement, it gets +22,518.02, and +44,535.80 in the project's SC-L1 test state.
- Reproduce:
FOUNDRY_SPARSE_MODE=true forge test --root packages/perps --match-path 'test/ResidualRecapReapplied.t.sol' -vv(file in the PoC, pinned a82d4fefb02768e5b3bddcc97dee371eee24fea8; 11 tests pass)
Vulnerability Details
Spec vs code
| What the project says | What happens (PoC, pinned a82d4fef) |
|---|---|
| SC-L1 response (Fixed in #29): "Anything that can't be settled yet stays pending, stays reserved everywhere, and gets applied later once it's backed." | One settlement with no new backing applies the residual: pending recap 15,000 -> 0 (mixed test), 50,040 -> 80 (SC-L1 test). |
| PR #122 invariant: "Partial settlement retains residual buckets and their reserves; repeated reconciliation cannot double-count inflows." MED-12 context there: "Reconciliation batching could change the resulting ownership." | One extra reconciliation changes the final ownership: Senior 15,000 vs 40,000 (mixed), 50,040 vs 100,000 (SC-L1). |
HousePoolWaterfall.t.sol:201 "Residual recap should preserve senior's recovery target" (seniorHighWaterMark == 100,000) |
Fails after one ordinary settlement with "50040000000 != 100000000000" (the PoC catches the project's own assertion). |
HousePoolWaterfall.t.sol:217 "Residual recap should settle once backing becomes available" (seniorPrincipal == 100,000) |
Fails: Senior 50,040, Junior 49,880, unassigned 80. |
HousePoolSnapshotParity.t.sol:155-169 test_PartialMixedInflowsPreserveFullIntentAndSettleResidualLater: 25,000 / 0 after one pass, 40,000 / 15,000 after the release |
One settlement in between: 15,000 / 10,000 at once, 15,000 / 40,000 after the release. |
ACCOUNTING_SPEC.md:337 "Losses do not reduce the Senior high-water mark"; :340 "Reserving them in step 2 prevents counting the same inflow twice." |
No value changes, yet the mark falls 100,000 -> 50,040; the same cash is reserved for the bucket and also backs the principal. |
HousePoolPendingPreviewLib.sol:107 "recapitalization never accrues to junior principal"; Cecuro MED-12 comment: "partial-settlement residuals stay reserved" |
49,880 (SC-L1 test) and 30,000 (exact-gap test) of the owner's recapitalization end as Junior principal. |
Root cause
packages/perps/src/HousePool.sol:1829-1834 (added by the SC-L1 fix, 31a38bb7):
function _settleablePendingClaimantBuckets(
HousePoolAccountingLib.ReconcileSnapshot memory reconcileSnapshot,
HousePoolPendingPreviewLib.ClaimantPendingBuckets memory claimantBuckets
) internal pure returns (HousePoolPendingPreviewLib.ClaimantPendingBuckets memory settleableClaimantBuckets) {
return HousePoolPendingPreviewLib.capClaimantBuckets(claimantBuckets, reconcileSnapshot.distributable);
}
The cap is the whole distributable. On the first pass that is correct: both principals are zero, so all of it is free. On every later pass, part of distributable already backs seniorPrincipal + juniorPrincipal from the previous pass. HousePoolReconcilePlanLib.planReconcile (:68-71) then subtracts the settleable amount from distributable ("Settleable pending claimant assets already represented in snapshot.distributable and therefore reserved", :41-42). It finds the principal unbacked, and absorbLoss charges it. _applyPendingClaimantBucketsLive (HousePool.sol:1759-1776) credits the amount again and decrements the bucket. When the loss took both principals to zero, applyClaimantRecapitalizationIntent (HousePoolPendingPreviewLib.sol:117-122) takes the empty-bootstrap branch and sets seniorHighWaterMark = max(remaining bucket, amount). Settleable revenue then goes to Junior, because the new mark leaves no Senior gap.
Project numbers (SC-L1 test), second pass, no value change (pool cash 100,000, trader claim 50,040, distributable 49,960):
| step | Senior principal | high-water mark | pending recap |
|---|---|---|---|
| after the project's first reconcile | 49,960 | 100,000 | 50,040 |
| cap: min(50,040, 49,960) = 49,960 reserved; plan sees 0 for 49,960 of principal -> loss | 0 | 100,000 | 50,040 |
| empty bootstrap: principal += 49,960, mark = max(50,040, 49,960) | 49,960 | 50,040 | 80 |
Trigger (ordinary calls only)
HousePool.reconcile()isonlyVault, and no vault function calls it. The production path issettleLpEpoch.HousePool.settleLpEpochis permissionless with no open positions or a frozen oracle (HousePool.sol:794-820). With open positions it is reached throughOrderRouter.settleLpEpoch(bytes[]), "Permissionless and available while the router admin is paused".- A settlement must advance a queue item; with nothing queued it reverts
HousePool__NoLpEpochProgress(asserted). A Junior holder's full-balancerequestRedeemhas no minimum size. At zero Junior principal it is refunded (HousePool.sol:960-985), and that counts as progress (juniorProcessedEpochs == 1in the PoC). So a Junior holder can trigger a settlement whenever it likes. Keepers that settle every epoch trigger it anyway. - The state comes from the owner's documented recovery action.
SCOPE.mdtrusted roles: "recapitalize the pool".SECURITY.md: "Owner-funded recapitalization". Runbook: "4. Recapitalize or clear positions. 5. Clear degraded mode only after raw solvencyE >= Lis genuinely restored". Revenue is queued in this state by design:recordClaimantInflowNatSpec says "revenue is explicitly queued when both stored tranche principals are zero".
Impact Details
Immediate form and actor profit (lead)
Base: the project's mixed test (wipe, 40,000 owner recapitalization + 15,000 revenue, 30,000 trader claim, one reconcile: Senior 25,000, mark 40,000, residual 15,000). Holders: a 10,000 Senior LP, a passive 10,000 Junior LP, and one entity with two Junior accounts (100,000 and 1,000). The entity bought them by ordinary deposits before the wipe. After the wipe, Junior deposits revert (asserted), as documented: "a wiped tranche cannot be silently revived by an ordinary asynchronous deposit" (ACCOUNTING_SPEC.md:326).
| test | what happens | result (USDG) |
|---|---|---|
test_EntityProfit_MixedState |
T1: the small account requests its full balance and the entity itself calls settleLpEpoch. T2 (next epoch): the large account redeems. No new backing. |
At T1: Senior 25,000 -> 15,000, residual 15,000 -> 0, Senior LP -9,090.90, entity value 0 -> 9,017.87. At T2 the entity realises 9,017.750652. Nobody settling: 0. Fixed code, same calls: 0 (both requests refunded). |
| same test, liability ends after T1 | The project's own release step (trader claim to 0, no new cash) comes after the entity's T1 settlement. | Entity realises 36,044.83 vs 13,526.81 without the T1 settlement: +22,518.017728. The latter equals the project's expected final state and the fixed code. Senior -24,999.86; Senior LP -22,727.13. |
test_EntityProfit_ProjectState |
Same calls on the project's SC-L1 test state | Without backing nothing is realisable in any arm (Junior stays 0). Liability ends after the entity's settlement: +44,535.797448 vs 0; Senior -49,960; Senior LP -45,418.14. |
test_MixedInflows_oneOrdinarySettlement_movesSeniorToJunior |
Mixed test + one settlement triggered by the Junior LP's full-balance request, any address calling | At once: Senior 25,000 -> 15,000; Junior LP paid 9,090.999660 USDG out of pool cash in the same transaction; Senior LP -9,090.901544. After the release: Senior 15,000 / Junior 40,000 vs the project's 40,000 / 15,000. |
Pool cash plus USDG paid out is conserved in every arm. The party values add up to principals plus payouts. The entity puts no USDG in after the wipe, and its pre-wipe deposits are lost in every arm alike.
Baseline, stated plainly: every ordinary settlement in that window moves the residual. Against an arm where the entity's own later redemption settlement runs anyway, the extra call changes its result by -0.12. An entity holding Junior gains by making sure one settlement happens, measured against nobody settling and against the code with the one-line fix. Value is conserved: what Senior holders lose, Junior holders gain.
Recovery target (high-water mark) decline
| test | result |
|---|---|
test_ProjectTest_withOneOrdinarySettlement (SC-L1 test + one settlement) |
Pool cash 100,000, trader claim 50,040 and Senior 49,960 are unchanged, yet the mark goes 100,000 -> 50,040 and pending 50,040 -> 80. The project's assertions at :201 and :217 fail with their exact messages. Final: Senior 50,040, Junior 49,880, unassigned 80. |
test_Control_noSettlement_projectAssertionsHold |
Same clock, no added call: the project's assertions hold (Senior 100,000, Junior 0). |
test_RunMinusControl_perParty |
Senior -49,960 (Senior LP -45,418.144113); Junior +49,880 (Junior LP +45,345.906306); unassigned +80; pool cash equal. |
test_ExactGapRecap_routineSettlements_vs_none |
The owner recapitalizes exactly the 50,000 deficit and the backing arrives in ten steps. Routine settlements after steps 1-4: mark 50,000 -> 20,000; final Senior 20,000 / Junior 30,000 vs 50,000 / 0. |
Whole state from transactions
ResidualRecapFromTransactionsTest builds the wipe from trades and mark pushes (no vm.store, no stdstore, no prank as a protocol contract). The owner calls only recapitalizePool and clearDegradedMode, and degradedMode is asserted after every step. Each extra keeper settlement moves 94.347204 (the revenue bucket) out of Senior's recovery. With 59 extra settlements over 120 epochs, a 50,000 Senior LP ends with 1,644.14 instead of 7,101.40: Senior holders -5,566.55, Junior holders +11,133.03.
Owner-procedure step: the trigger works only after clearDegradedMode. Before it, every settlement reverts HousePool__DegradedMode, and the clear reverts CfdEngine__StillInsolvent until the whole gap is paid. After an exact-gap recapitalization and the clear, the recapitalization is still entirely unsettled, so the state exists. The immediate 25,000 -> 15,000 form is not reproduced from transactions; it uses the project's own test construction.
Severity (program rules)
- Row. Senior LP principal, backed by pool cash, moves to Junior holders, who withdraw it as USDG (9,090.999660 in the same transaction). No price moves and no value arrives. That is user funds taken, so it is the Critical row. The Senior recovery owed from later backing also goes to Junior (High "Theft of unclaimed yield", tests above). With the fix the same calls leave Senior intact.
- Actor profit (
SCOPE.md:239). The griefing rule applies "where the attacker gains no profit". Here the triggering entity realises +9,017.75 USDG in the next epoch for the cost of gas, against nobody settling and against the fixed code. It realises +22,518.02 or +44,535.80 when the liability ends after its settlement. The baseline is stated above: an ordinary settlement by anyone in that window would also move the residual. - Financial risk (
:235). The actor puts nothing at risk after the wipe beyond gas. Its Junior shares are worth 0 in every arm until a settlement moves the residual. - Feasibility (
:336). The trigger has no obstacle: no minimum request size, a permissionless call, any epoch. The rare part is the state, given as a fact below. - Role (
:196,:251). The owner performs only its documented recovery:recapitalizePool, thenclearDegradedModeonceE >= L. That is "a legitimate, documented action by a trusted role that triggers a bug", and "an in-scope impact arises from a logic error that a privileged address can trigger, which remains valid". The harmful call is not privileged. - Keeper (
:200). "Keepers are not trusted ... harm caused by any caller acting as a keeper is in scope." The trigger is a keeper call anyone can make. - Rare state, as a fact. It needs a terminal-deficit wipe (both tranches at zero with shares outstanding) and an owner recapitalization not fully settled when the next settlement runs. In a trade-built wipe, settlements stay blocked until the owner clears degraded mode; after the clear the recapitalization is still unsettled (test above). The mixed form needs a revenue bucket too, which this state queues by design. Each pass moves at most the part of the bucket that
distributableappears to back.
Relationship to published known issues
- SC-L1 (pre-audit, Fixed in #29). Same code, same numbers (100,000 / 49,960). The exercised line,
HousePool.sol:1833, is the fix's own cap (31a38bb7). The fix holds for one reconcile and fails on the next. The program counts "the fix at commit a82d4fef is incomplete" as valid. - Cecuro MED-12 (Addressed by PR #122). Its fix kept "partial-settlement limits" unchanged and states "partial-settlement residuals stay reserved". The immediate form is its own mixed case with one settlement added.
- Not claimed: the FIRST reconcile's reset of the high-water mark to the recapitalization amount. It is documented ("With senior owners and zero claimed principal ... sets the high-water mark to
max(recapitalizationTargetAssets, amount)"; test "Explicit recapitalization should reset the HWM"). Every test here keeps the project's values for that first pass and starts after it. This is not an entry by deposit at near-zero NAV after a wipe: there is no deposit and no price move. Also not claimed: settlement work spent on zero-payout epochs (MED-24,SECURITY.mdKnown Limitations), and multi-pass rounding of redemption funding (SECURITY.md:1411). - AI scan, collaborative audit, Cantina: no item on pending claimant buckets or a second reconciliation.
Recommended fix
Cap the settleable buckets by the value that does not already back claimed principal, at both call sites (HousePool.sol:1566 live, :1619 preview):
uint256 claimed = seniorPrincipal + juniorPrincipal;
uint256 free = reconcileSnapshot.distributable > claimed ? reconcileSnapshot.distributable - claimed : 0;
settleableClaimantBuckets = HousePoolPendingPreviewLib.capClaimantBuckets(claimantBuckets, free);
With this change applied to a copy, all eight bug tests in the PoC fail on their first bug assertion: Senior stays at 25,000, the mark stays at 100,000 or 50,000, and the high-water mark is equal in RUN and CONTROL in the transactions-only test. The control, the deposit/queue check and the owner-procedure gates still pass. A regression test: run the project's two partial-settlement tests with one settleLpEpoch between the first reconcile and the release.
References
- Root cause: https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src/HousePool.sol#L1829-L1834
- Plan reserve: https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src/libraries/HousePoolReconcilePlanLib.sol#L68-L71
- Empty bootstrap: https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src/libraries/HousePoolPendingPreviewLib.sol#L103-L135
- Live bucket step: https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src/HousePool.sol#L1759-L1776
- Permissionless settlement: https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src/HousePool.sol#L794-L820
- Project tests: https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/test/perps/accounting/waterfall/HousePoolWaterfall.t.sol#L177-L220 and https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/test/perps/differential/HousePoolSnapshotParity.t.sol#L155-L169
- Spec: https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/ACCOUNTING_SPEC.md#L326-L340
- SC-L1 and its response:
audits/plether-pre-audit-report.pdf(SC-L1, "Fixed in Plether-Fi/plether-core#29"); PR #122: https://github.com/Plether-Fi/plether-core/pull/122
Proof of Concept
Proof of Concept
One Foundry file, pinned commit a82d4fefb02768e5b3bddcc97dee371eee24fea8, with two contracts on the project's own test bases. The full file is at the end.
Run
git clone https://github.com/immunefi-team/audit-comp-plether.git && cd audit-comp-plether
git checkout a82d4fefb02768e5b3bddcc97dee371eee24fea8 && git submodule update --init --recursive
# save the file below as packages/perps/test/ResidualRecapReapplied.t.sol
FOUNDRY_SPARSE_MODE=true forge test --root packages/perps --match-path 'test/ResidualRecapReapplied.t.sol' -vv
Checked on a clean copy of the pinned tree, cold build (forge 1.5.1-stable, solc 0.8.35): 11 passed, 0 failed; also with --isolate. Each bug test asserts the observed values next to the project's expected values, so it passes while the bug is present.
What is built how
ResidualRecapReappliedTest(HousePoolTestBase): the states are the project's two tests of a partial settlement (HousePoolSnapshotParity.t.sol:155-169,HousePoolWaterfall.t.sol:177-220), built as they build them: cash burned to wipe both tranches, trader-claim liability set withstdstore, revenue recorded as the engine. One change: the recapitalization goes through the owner'sCfdEngine.recapitalizePool. Every added step is ordinary calls only: a Junior holder's full-balancerequestRedeemand a permissionlesssettleLpEpoch. RUN and CONTROL arms share one snapshot and one clock.degradedModeis asserted false around every settlement.ResidualRecapFromTransactionsTest(BasePerpTest): the whole state from transactions. Wallets are funded once at setUp; LP deposits go throughrequestDeposit/ keeper settlement /claimDeposit; trades go throughOrderRouterwith keeper execution and MockPyth prices; the owner calls onlyrecapitalizePoolandclearDegradedMode. Novm.store, nostdstore, no prank as a protocol contract.degradedModeis asserted after every step, and every refused call by its selector.
Tests
test_EntityProfit_MixedState: one entity (100,000 + 1,000 Junior, bought before the wipe). Its small account requests its full balance, the entity settles itself, and its large account redeems next epoch. T1: Senior 25,000 -> 15,000, Senior LP -9,090.901544, entity value 9,017.874062. T2: the entity realises 9,017.750652 USDG with no backing; nobody settling: 0; against an arm in which its own T2 settlement runs anyway: -0.123410. Liability ends after its T1 settlement: 36,044.828822 vs 13,526.811094 (project expectation), +22,518.017728; Senior LP -22,727.129327. Conservation asserted in every arm.test_EntityProfit_ProjectState: same on the SC-L1 test state. No backing: 0 in every arm, mark 100,000 -> 50,040. Liability ends after its settlement: +44,535.797448 vs 0; Senior -49,960.test_MixedInflows_oneOrdinarySettlement_movesSeniorToJunior: the project's mixed test + one settlement (Junior LP's request, any address settles), no value arriving. Senior 25,000 -> 15,000, residual 15,000 -> 0, Junior LP paid 9,090.999660 USDG out of pool cash, Senior LP -9,090.901544. After the release: 15,000 / 40,000 vs the project's 40,000 / 15,000.test_ProjectTest_withOneOrdinarySettlement: pool cash, claim and Senior unchanged; mark 100,000 -> 50,040, pending 50,040 -> 80. The project's own assertion helpers fail with "Residual recap should preserve senior's recovery target: 50040000000 != 100000000000" and "Residual recap should settle once backing becomes available: 50040000000 != 100000000000". Final 50,040 / 49,880 / unassigned 80.test_Control_noSettlement_projectAssertionsHold: same clock, no call; the project's assertions hold.test_RunMinusControl_perParty: Senior -49,960 (Senior LP -45,418.144113), Junior +49,880 (Junior LP +45,345.906306), unassigned +80, pool cash equal.test_ExactGapRecap_routineSettlements_vs_none: exact 50,000 recapitalization, backing in ten steps, settlements after steps 1-4: mark 50,000 -> 20,000; final 20,000 / 30,000 vs 50,000 / 0 (preview checked against a real settlement).test_NoDepositEntry_and_settlementNeedsAQueuedRequest: JuniorrequestDepositreverts after the wipe (TerminallyWiped) and after the recapitalization; a settlement with nothing queued revertsHousePool__NoLpEpochProgress.test_FromTransactions_ownerProcedureGates: wipe by trades (degradedModelatches at a 0.985 close; a SHORT closes at the 2.00 cap). Settlements revertHousePool__DegradedModebefore any owner action, after half the gap and after the full gap;clearDegradedModerevertsCfdEngine__StillInsolventuntil the gap (7,243.528343) is paid. After the clear, the first settlement succeeds with both principals 0 and the whole recapitalization still pending; a trader's margin deposit queues a 94.347204 revenue bucket.test_FromTransactions_oneExtraSettlement(n = 2) and 11.test_FromTransactions_59ExtraSettlements(n = 60, 120 epochs): RUN settles at the cap until n settlements succeed, CONTROL settles once, same epochs and holder calls; then the same unwind and full redemption. Each extra settlement lowers the Senior mark, the pending recapitalization and unassigned by one bucket (asserted). n = 60: Senior LP 7,101.403002 -> 1,644.138024, Senior holders -5,566.545883, Junior holders +11,133.030918 (trigger +3,336.556720); traders, keeper, treasury unchanged; every USDG at a listed address; party sum equal within 2 atoms.
Test-quality control: with the fix proposed in the description applied to a copy (two lines, HousePool.sol:1566 and :1619), tests 1-4, 6, 7, 10 and 11 fail on their first bug assertion (for example "T1: senior principal 25,000 -> 15,000 in the entity's settlement: 25000000000 != 15000000000"; "Senior HWM falls one bucket per extra settlement: 0 != 5566485036"). Tests 5, 8 and 9 pass. The source was restored and diff -r against the pinned tree is clean.
Output excerpt (-vv)
[PASS] test_EntityProfit_MixedState()
ENTITY USDG RUN - nobody settles = + 9017750652
ENTITY USDG RUN - CONTROL = - 123410
ENTITY USDG RUN-hold - CONTROL-hold = + 22518017728
[PASS] test_FromTransactions_59ExtraSettlements()
cap: Senior HWM RUN / CONTROL 1677043307 7243528343
SEN_A (Senior LP) | 1644138024 | 7101403002 | -5457264978
JUN_B (Junior LP, trigger) | 238808053393 | 235471496673 | +3336556720
Senior holders RUN - CONTROL -5566545883
Junior holders RUN - CONTROL +11133030918
Suite result: ok. 8 passed; 0 failed; 0 skipped
Suite result: ok. 3 passed; 0 failed; 0 skipped
File: packages/perps/test/ResidualRecapReapplied.t.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.35;
// A residual pending recapitalization is applied again by every later reconciliation: the settleable cap is the whole
// distributable (HousePool._settleablePendingClaimantBuckets, HousePool.sol:1829-1834), part of which already backs the
// principal the previous pass created.
// Pinned source: immunefi-team/audit-comp-plether a82d4fefb02768e5b3bddcc97dee371eee24fea8.
// Save as packages/perps/test/ResidualRecapReapplied.t.sol; from the repository root:
// FOUNDRY_SPARSE_MODE=true forge test --root packages/perps --match-path 'test/ResidualRecapReapplied.t.sol' -vv
//
// Contract 1 (project's HousePoolTestBase): the states are the project's own two tests of a partial pending-bucket
// settlement (HousePoolSnapshotParity.t.sol:155-169, HousePoolWaterfall.t.sol:177-220), built as they build them (cash
// burned to wipe both tranches, trader-claim liability written with stdstore, revenue recorded as the engine); the
// recapitalization goes through the owner's CfdEngine.recapitalizePool. Every added step is ordinary calls only:
// requestRedeem of a Junior balance and the permissionless HousePool.settleLpEpoch (no open positions; with open
// positions the same call is OrderRouter.settleLpEpoch). Tests assert the observed values next to the project's.
// Contract 2 (project's BasePerpTest): the whole state from transactions, degradedMode asserted after every step.
import {BasePerpTest} from "./perps/BasePerpTest.sol";
import {HousePoolTestBase} from "./perps/shared/HousePoolTestBase.sol";
import {console} from "forge-std/console.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 {ICfdEngineTypes} from "@plether/perps/interfaces/ICfdEngineTypes.sol";
import {MockPyth} from "@plether/test-utils/MockPyth.sol";
contract ResidualRecapReappliedTest is HousePoolTestBase {
address internal constant SEN_LP = address(0x5E01); // ordinary Senior LP (10,000)
address internal constant JUN_LP = address(0x1E01); // ordinary Junior LP (10,000)
address internal constant ANYONE = address(0xBEEF); // any address acting as keeper
address internal constant E_MAIN = address(0xE1); // one entity: large Junior holder (100,000), calls the settlement
address internal constant E_SMALL = address(0xE2); // same entity: small Junior holder (1,000), the queue item
uint256 internal constant PENDING = 100_000e6; // the project's numbers, HousePoolWaterfall.t.sol:182-184
uint256 internal constant CLAIM = 50_040e6;
uint256 internal constant SETTLEABLE = PENDING - CLAIM; // 49,960
struct Book {
uint256 seniorPrincipal;
uint256 juniorPrincipal;
uint256 hwm;
uint256 pendingRecap;
uint256 unassigned;
uint256 poolRaw;
// party value = pro-rata principal of shares held (incl. shares in a pending request) + USDG received
uint256 senLp;
uint256 senSeed;
uint256 junLp;
uint256 junSeed;
uint256 junLpUsdg;
uint256 eMain;
uint256 eSmall;
uint256 eUsdg; // USDG received by the entity (E_MAIN + E_SMALL)
}
uint256 internal reqJun;
uint256 internal reqSmall;
uint256 internal reqMain;
function setUp() public override {
super.setUp();
_fundSenior(SEN_LP, 10_000e6);
_fundJunior(JUN_LP, 10_000e6);
}
// ------------------------------------------------------------------------------------------------ helpers
/// @dev Both entity accounts buy Junior by ordinary deposits BEFORE the wipe (after it Junior deposits revert).
function _fundEntity() internal {
_fundJunior(E_MAIN, 100_000e6);
_fundJunior(E_SMALL, 1_000e6);
}
function _noDegraded() internal view {
assertFalse(engine.degradedMode(), "degradedMode false");
}
/// @dev The engine owner's documented recovery call (owner = this test contract, as in the project's base).
function _ownerRecapitalizes(
uint256 amount
) internal {
settlementToken.mint(address(this), amount);
settlementToken.approve(address(engine), amount);
engine.recapitalizePool(amount);
assertEq(pool.pendingRecapitalizationAssets(), amount, "recapitalization queued for normal reconciliation");
}
function _wipe() internal {
settlementToken.burn(address(pool), pool.totalAssets());
vm.prank(address(juniorVault));
pool.reconcile();
assertEq(pool.seniorPrincipal() + pool.juniorPrincipal(), 0, "both tranches wiped");
assertGt(juniorVault.totalSupply(), 0, "Junior shares outstanding");
_noDegraded();
}
/// @dev The project's partial
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
The settleable-bucket cap uses the whole distributable figure, which already backs principal created by the previous pass, so the plan treats that principal as unbacked and re-applies the residual recapitalization.
Impact
Senior LP principal backed by pool cash can move to Junior holders who withdraw it, and the Senior recovery target falls, though the trigger needs a rare post-wipe state and the immediate form was not reproduced from transactions.
What the attacker needed
Terminal-deficit wipe with shares outstanding; owner recapitalization not fully settled; Junior shares bought before the wipe; one permissionless settleLpEpoch call
The fix
The settleable buckets should be capped by the distributable amount minus the principal already claimed, at both call sites.
How it was found
- Reach a state after a terminal-deficit wipe where the owner's recapitalization is not fully settled.
- A Junior holder submits a full-balance redeem request to advance the queue.
- Anyone calls the permissionless settleLpEpoch to run the settlement.
- The cap reserves part of distributable that already backs principal, the plan sees it as unbacked, and the residual recapitalization is applied again.
- Senior principal drops and Junior holders can redeem the moved value as 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 has two groups of depositors, Senior and Junior, and after a big loss the owner puts money back in to restore the Senior side. The fix that was meant to hold that money back until it is truly covered checks it against a total that already includes money promised to Senior depositors, so the same amount gets counted twice. A Junior depositor can then trigger a routine settlement and end up owning Senior money that they can withdraw.
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.