Skip to content
Business logic Audit finding Advanced

Atomic Protection Retry in PositionProtectionBook Lets Callers Grief Owner Recovery

Any address can atomically execute a failing protection close and immediately retry it, which returns the protection to the Triggered state and blocks the owner's standalone limit amendment and ordinary close. By repeating this cycle the caller can keep the owner's position open and its PnL pledge reserved for as long as they keep winning the execution race.

zer0luck_xint Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#99228 [SC-High] Atomic Protection Retry in PositionProtectionBook Lets Callers Grief Owner Recovery

Submitted on Nov 12th 2026 at 13:41:02 UTC by @zer0luck_xint for Audit Competition | Plether

Description

Brief/Intro

PositionProtectionBook permits any address to retry a failed protection close. When a close fails its retained financial limits, a caller can execute the attempt and retry in one transaction, returning the protection to Triggered before the owner can make a standalone amendment.

Repeating that cycle forces the owner to win a child-execution race before amending the limits. Until the owner does, a standalone amendment and ordinary close revert while the position remains open and exposed to price movement.

Vulnerability Details

Close limits and the owner's recovery. By design, each position protection retains the owner's close financial limits (execution notional, gross account debit, action charges and explicit fees) and applies them to every triggered or retried close attempt (CANONICAL_ENTRYPOINTS.md:121-126). Triggered means one live close attempt, and Latched means the trigger remains active with no live attempt and may be retried permissionlessly. The recovery sequence gives the owner the interval after a failed attempt relatches and before a fresh retry to amend the retained limits. A live child keeps its original request (IPositionProtectionActions.sol:32-33). The conservative keeper procedure investigates persistent planner or constraint failures before retry and avoids continuous requeueing of the same failing attempt (DEPLOYMENT.md:420-421). When each close continues to exceed the owner's retained financial limits, amendment is an owner-controlled remedy for the repeated close failures.

amendLatchedPositionProtectionCloseLimits checks both conditions:

https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src/PositionProtectionBook.sol#L315-L327

Solidity
        StoredProtection storage protection = _ownedActiveProtection(protectionId, msg.sender);
        if (protection.status != PositionProtectionTypes.PositionProtectionStatus.Latched) {
            revert OrderRouter__ProtectionNotLatched();
        }
        if (IPositionProtectionRouterHost(ROUTER).pendingOrderCounts(msg.sender) != 0) {
            revert OrderRouter__PendingOrdersExist();
        }

Retry restores the blocking state. retryPositionProtectionClose loads the protection without an owner check (_activeProtection instead of _ownedActiveProtection, PositionProtectionBook.sol:983-1000). It requires the same Latched status and empty account queue, commits a new close attempt for the protected account, and records it as the live attempt, which returns the protection to Triggered (PositionProtectionBook.sol:564-578):

https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src/PositionProtectionBook.sol#L382-L405

Solidity
        StoredProtection storage protection = _activeProtection(protectionId);
        if (protection.status != PositionProtectionTypes.PositionProtectionStatus.Latched) {
            revert OrderRouter__ProtectionNotLatched();
        }
        _requireMatchingPosition(protection);

        IPositionProtectionRouterHost router = IPositionProtectionRouterHost(ROUTER);
        if (router.pendingOrderCounts(protection.account) != 0) {
            revert OrderRouter__PendingOrdersExist();
        }

The execute-and-retry cycle. Order execution is also permissionless. In one transaction, a caller executes the live close attempt through OrderRouter.executeOrder; the retained gross-debit limit makes it fail, and the lifecycle callback relatches the protection (PositionProtectionBook.sol:637-668) and removes the failed attempt from the account queue. Before the transaction ends, the same caller calls retryPositionProtectionClose, which finds Latched status and an empty queue and commits the next attempt. The caller's transaction leaves Triggered with one pending attempt, in which a standalone amendment reverts. If the owner or another keeper executes the live child first, it leaves Latched until a retry. The owner can amend during that interval, including by executing the child and amending in one smart-account transaction. During a frozen-market window, the Router skips the SameBlock and MevBoundary timing checks (OrderRouterExecutionSidecar.sol:445-451); a same-block batch can execute a fresh child if the remaining execution conditions hold.

Ordinary close is rejected while the protection remains active. The protection lock rejects the owner's ordinary open and close orders while any protection is active:

https://github.com/immunefi-team/audit-comp-plether/blob/a82d4fefb02768e5b3bddcc97dee371eee24fea8/packages/perps/src/router/OrderLiquidationBatchLogic.sol#L313-L314

Cancellation accepts only PendingOpen or Armed protection, and cancel-and-close accepts only Armed protection (PositionProtectionBook.sol:414-419, :345-347). Queued intents have no manual cancellation (SECURITY.md:1345). The position's PnL pledge remains reserved while the position is open. If the owner or another keeper executes the failing child before the caller, the protection relatches and the owner can amend before the next retry.

Caller authority. The caller needs no role. It uses only OrderRouter.executeOrder and PositionProtectionBook.retryPositionProtectionClose with valid price updates, once in each attempt's execution window.

The retained close limits and the owner amendment were added in commit eadc5c58 (Plether-Fi/plether-core#124) so that the trader's financial ceilings stay effective in triggered and retried attempts. They remain effective in every retry, and a ceiling that prevents execution is recoverable through the owner amendment after relatch. The defect reported here is introduced by that change: the amendment requires Latched, which the permissionless retry can consume and replace with Triggered atomically before the owner changes the ceilings.

Impact Details

Severity: Medium, Griefing (e.g. no profit motive for an attacker, but damage to the users or the protocol).

A caller who executes a failing stop-loss child and retries it in one transaction makes the owner's standalone amendment and ordinary close revert. Repeating the cycle forces a child to be executed before the caller's next retry, followed by the owner's amendment, or requires the owner to combine execution and amendment in a smart-account transaction. Until recovery, the position remains open, its PnL pledge stays reserved, and the owner remains exposed to price movement.

In the release deployment fixture with release parameters, the honest sequence and the attack start from the same state: a leveraged 200,000-unit LONG with a stop-loss at 1.22 and a gross account debit limit, and a gap to 1.25 at which the close attempt fails that limit (parameters in the Proof of Concept). In the honest sequence the owner amends the limits after the failed attempt and exits at once. In the attack sequence, an address with no role executes each child first and retries it once per minute, with no competing order execution.

Honest sequence Attack
Attacker-first execute-and-retry cycling 0 s 86,400 s (1,440 cycles)
Standalone amendment and ordinary close after a child fails owner amends and exits revert after attacker cycles
PnL pledge locked at the end 0.000000 19,376.000576
Maximum immediate withdrawal 29,803.596530 19,999.600000
Additional USDG unavailable for immediate withdrawal 0.000000 9,803.996530
Owner balance after exiting at the unchanged price 29,803.596530 29,796.932862 (6.663668 less)
USDG gained by the caller at the unchanged price N/A 0.00

At the end of this attacker-first sequence, 9,803.996530 USDG is additionally unavailable for immediate withdrawal. The 19,376.000576 USDG PnL pledge is the gross reserved amount, not the incremental amount denied by the attack; 19,999.600000 USDG remains withdrawable. At an unchanged price, the eventual balance difference is 6.663668 USDG from carry and other time-dependent settlement.

The following additional losses require an adverse basket movement during the lock. From the same starting state, the honest sequence exits at 1.25:

Basket during the 24-hour lock Owner's final USDG, honest sequence Owner's final USDG, attack Difference
Unchanged at 1.25 29,803.60 29,796.93 6.66
Moves 1% to 1.2625 29,803.60 27,295.93 2,507.66
Reaches the position's liquidation price at the start of the lock, 1.29558441; the caller then liquidates the position and receives the 120.00 USDG liquidation bounty 29,803.60 20,252.10 9,551.50

The pending close attempt does not prevent liquidation. The position's equity at liquidation is 252.45 USDG, above the 240.00 USDG liquidation charge, so the liquidation leaves no bad debt.

Prerequisites:

  • A protection whose close attempt exceeds its retained limits. This occurs when the price moves past the trigger by more than the owner's limits allow, for example in a gap through a stop-loss. Repeated failure requires the price to stay beyond those limits; a retrace may permit the next child to close.
  • In the measured sequence, the caller executes each close attempt before the owner or another keeper and retries in the same transaction. Each attempt is executed near the end of its 60-second execution window, so for most of each window the owner or an ordinary keeper can execute it first. An owner that executes the live child and amends before the next retry ends the cycle, atomically from a smart account or with back-to-back transactions that win that race. Against an acting owner, the caller must execute each child as soon as it becomes executable, which does not require observing the owner's transaction. The test does not measure the cost or probability of maintaining attacker-first ordering against an acting owner.
  • Adding margin prevents the liquidation shown above but does not by itself make a standalone amendment succeed after the next attacker cycle. Adding margin and opening an opposite 200,000-unit SHORT from a second account in the first 2 minutes reduces the difference in the drift to the liquidation price to 852.37 USDG.
  • One cycle uses an average of 1,237,626 gas with warm storage in the 24-hour test and 1,543,695 gas in Forge isolated-transaction mode. The latter is not an Arbitrum One fee measurement: the PoC's MockPyth accepts one empty update blob and returns a zero fee, while deployed execution requires signed updates for all 6 feeds and pays transaction and data fees. The test runs 1,440 cycles at one cycle per minute. The oracle accepts a publication only after the attempt's commit time (PletherOracle.sol:610), but that condition does not guarantee a complete new signed basket at any fixed cadence. At an unchanged price the caller gains no USDG.
  • No privileged role, incorrect oracle value or unusual configuration is involved. Every call in the cycle is public; the fixture supplies coherent 6-feed MockPyth prices. Live execution requires authenticated signed updates as described above.

Recommendation

The owner's recovery requires a state that the permissionless retry removes within the same transaction. Allow the owner to amend the retained close limits while the protection is Triggered, leaving the request of the already pending close attempt unchanged, so that the next retry copies the amended limits, and keep the existing empty-queue requirement for amendments in Latched status. Permissionless retry then remains available, and the owner's recovery no longer depends on winning an execution race.

References

Proof of Concept

Proof of Concept

The tests deploy the release contracts with script/DeployPerpsArbitrumSepolia.s.sol inside Forge through ReleaseFixture.sol (source at the end of this section). In-scope contracts are unmodified. Only out-of-scope components are mocked:

  • Pyth: the repository's test/mocks/MockPyth.sol, etched at the release Pyth address.
  • USDG: the release MockUSDG.
  • The ArbSys block-number precompile.

The PoC consists of 2 test files. Steps in test_attack_retry_loop_locks_owner_24h (ProtectionRetryLock24h.t.sol), all through public entry points:

  1. A Junior LP provides liquidity. Alice opens a 200,000-unit LONG with 20,000 USDG margin and a stop-loss at 1.22. The protection limits gross account debit to 5,000 USDG.
  2. The basket moves to 1.25. The close attempt fails the retained limit and relatches (lifecycle status 3 is Failed, terminal reason 8 is ConstraintViolation).
  3. An address with no role uses a helper contract that, in one transaction, executes the live close attempt with executeOrder and calls retryPositionProtectionClose after the attempt fails.
  4. The cycle repeats 1,440 times, once in each attempt's execution window, with the caller always first and no competing keeper execution. At checkpoints and after the final cycle, the test checks that standalone owner amendment, cancellation, cancel-and-close and ordinary close calls revert.
  5. After 86,400 seconds, the test checks that the full position is still open, the protection is still Triggered, those standalone owner calls still revert and the full balance cannot be withdrawn, and logs the PnL pledge. A separate counter-check executes the live child from an owner wallet and escapes after winning one execution race.

test_control_vs_attack_same_snapshot runs the honest sequence and the attack from one snapshot and compares the owner's maximum immediate withdrawal and final balance. The same file contains counter-checks: the owner's amendment succeeds after an honest execution leaves the protection Latched, separate owner transactions sent after an atomic cycle revert, and an owner that batches execution and amendment escapes by winning one execution race. test_execute_and_retry_cycle_gas, run with --isolate, measures the gas of one cycle as its own transaction, with cold account and storage access and its intrinsic cost.

The owner-batch counter-check runs in the live-market execution state. The tests do not exercise an owner batch in a frozen-market window or establish that the remaining execution conditions always hold there.

ProtectionRetryLockLiquidation.t.sol uses the same setup, with a fresh address performing the cycle (1,440 cycles in the drift and hedge tests), and compares the owner's final USDG with an immediate amendment and exit taken from the same snapshot and measured at the same final time:

  1. The basket moves linearly from 1.25 to the position's liquidation price, 1.29558441, over the 1,440 cycles. Two blocks (4 seconds) after the last cycle, the same address calls executeLiquidation for Alice. The pending close attempt ends Failed with terminal reason AccountLiquidated, and the address withdraws its liquidation bounty.
  2. The basket moves linearly from 1.25 to 1.2625 (1%) over the 1,440 cycles. The caller then stops, the last attempt fails, and Alice amends and exits at 1.2625.
  3. During the lock, a new protection, an ordinary open and a full withdrawal revert. addMargin succeeds and raises the liquidation price; liquidation at the former liquidation price then reverts with CfdEngine__PositionIsSolvent, and the next cycle still locks the owner out. A further test opens an opposite hedge from a second account during the lock.

On a fresh clone of the audit commit, run git submodule update --init --recursive. Create test/poc/ at the repository root, place ReleaseFixture.sol, ProtectionRetryLock24h.t.sol and ProtectionRetryLockLiquidation.t.sol (sources at the end of this section) in it, then run from the repository root with Forge 1.5.1:

Bash
forge test --match-path test/poc/ProtectionRetryLock24h.t.sol --gas-limit 30000000000 -vv
forge test --isolate --match-path test/poc/ProtectionRetryLock24h.t.sol --match-test test_execute_and_retry_cycle_gas -vv
forge test --match-path test/poc/ProtectionRetryLockLiquidation.t.sol --gas-limit 30000000000 -vv

Excerpt from the output of the first command for test_attack_retry_loop_locks_owner_24h and test_control_vs_attack_same_snapshot (the release deployment script's 56 log lines after Logs: omitted):

[PASS] test_attack_retry_loop_locks_owner_24h() (gas: 1482171116)
Logs:
  cycle 0: child status / terminalReason 3 8
  attack: attacker-first sequence elapsed seconds 86400
  attack: cycles / avg gas / max gas 1440 1237626 1243394
  attack: alice clearinghouse balance before/after 24 h 39615600576 39615600576
  attack: alice pnl pledge (locked)  19376000576
  attacker wallet / keeper USDG gained 0 0
[PASS] test_control_vs_attack_same_snapshot() (gas: 1494968995)
Logs:
  same-snapshot: locked settlement / total locked / free 39615600576 19616000576 19999600000
  same-snapshot: locked maximum withdraw / immediate control exit 19999600000 29803596530
  same-snapshot: immediate control exit minus locked maximum withdraw 9803996530
  same-snapshot: alice balance at latch 39615600576
  same-snapshot: control exit balance / exit time 29803596530 1709535652
  same-snapshot: attack exit balance / lock seconds 29796932862 86400
  same-snapshot: extra cost to alice from the lock (carry etc.), atoms 6663668
  same-snapshot: attacker USDG gained 0

Excerpt from the output of the second command (deployment lines omitted):

[PASS] test_execute_and_retry_cycle_gas() (gas: 21866172)
Logs:
  execute-and-retry cycle gas: cycles / min / max 8 1543695 1543695

Excerpt from the output of the third command for the drift to the liquidation price, the 1% drift and the hedge (deployment lines omitted):

[PASS] test_drift_to_liquidation_while_protection_close_pending() (gas: 1490742357)
Logs:
  position margin (PnL pledge) / trader claim / entry cost atoms 19376000576 0 240000000000
  liquidation price: closed form without pending carry / canonical lens predicate 129558442 129558441
  liquidation price after 24 h (canonical lens predicate) 129555112
  Alice before liquidation: settlement / PnL pledge / liquidation reserve 39615600576 19376000576 240000000
  Alice before liquidation: free settlement 19999600000
  liquidation preview: equity / liquidation charge / keeper bounty 252451978 240000000 120000000
  liquidation preview: LP liquidation fee / settlement retained / immediate payout 120000000 20252051978 0
  immediate-exit control: exit time / balance 1709535652 29803596530
  locked sequence: cycles / total gas / liquidation gas 1440 1782032499 682742
  locked sequence: liquidation time / price 1709622040 129558441
  Alice final USDG: immediate-exit control / locked then liquidated 29803596530 20252095978
  Alice realized loss from the lock 9551500552
  HousePool totalAssets: control / locked 1010102003470 1019533504022
  retry caller USDG before / after (keeper bounty) 0 120000000
[PASS] test_mild_drift_realized_loss() (gas: 1485904682)
Logs:
  mild drift: start / end basket price 125000000 126250000
  mild drift: cycles / total gas / lock seconds 1440 1782030045 86409
  Alice final USDG: immediate-exit control / locked then exit 29803596530 27295932862
  Alice realized loss from the lock 2507663668
  HousePool totalAssets: control / locked 1010102003470 1012609667138
[PASS] test_owner_hedge_bounds_loss() (gas: 1491058097)
Logs:
  hedge: Alice LONG account / hedge account final USDG 20053878173 13897344415
  hedge: combined net of hedge deposit / immediate-exit control 28951222588 29803596530
  hedge: residual loss against control 852373942

Source files

ReleaseFixture.sol

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

// Deploys the release contracts with script/DeployPerpsArbitrumSepolia.s.sol inside Forge.
// Pyth, USDG and ArbSys are replaced by local test components; in-scope contracts are unmodified.

import {DeployPerpsArbitrumSepolia} from "../../script/DeployPerpsArbitrumSepolia.s.sol";
import {MockPyth} from "../mocks/MockPyth.sol";
import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.sol";
import {PletherOracle} from "@plether/perps/PletherOracle.sol";
import {TrancheVault} from "@plether/perps/TrancheVault.sol";
import {Test, console2} from "forge-std/Test.sol";

/// @dev Mirrors the Arbitrum precompile's block-number view inside the local test EVM.
contract ReleaseFixtureArbSys {

  function arbBlockNumber() external view returns (uint256) {
    return block.number;
  }

}

abstract contract ReleaseFixture is Test {

  address internal constant RELEASE_PYTH = 0x0B73614636C855Bf23F342F307FB981A3e47f42B;
  uint256 internal constant DEPLOYER_KEY = 0xA11CE;
  uint256 internal constant MONDAY_MORNING = 1_709_532_000; // Mon 2024-03-04 06:00 UTC (live market)
  uint256 internal constant BASKET_1_20 = 120_000_000; // normalized basket mark 1.20 (8 decimals)
  uint8 internal constant MODE_LIVE = 1;
  uint8 internal constant MODE_FAD = 2;
  uint8 internal constant MODE_FROZEN = 4;
  uint8 internal constant MODE_ANY = 7;

  DeployPerpsArbitrumSepolia.DeployedContracts internal d;
  address internal owner;
  address internal keeper = makeAddr("keeper");
  uint256 internal clientNonce;

  function setUp() public virtual {
    vm.chainId(421_614);
    vm.warp(MONDAY_MORNING);
    ReleaseFixtureArbSys arbSys = new ReleaseFixtureArbSys();
    vm.etch(address(100), address(arbSys).code);
    MockPyth pyth = new MockPyth();
    vm.etch(RELEASE_PYTH, address(pyth).code);
    vm.setEnv("TEST_PRIVATE_KEY", vm.toString(DEPLOYER_KEY));
    d = DeployPerpsArbitrumSepolia(deployCode("DeployPerpsArbitrumSepolia.s.sol:DeployPerpsArbitrumSepolia")).run();
    owner = vm.addr(DEPLOYER_KEY);

    // Permanent 1 USDG seeds per tranche (release values), then activation.
    d.settlementToken.mint(owner, 2e6);
    vm.startPrank(owner);
    d.settlementToken.approve(address(d.housePool), 2e6);
    d.housePool.initializeSeedPosition(false, 1e6, owner);
    d.housePool.initializeSeedPosition(true, 1e6, owner);
    d.housePool.activateTrading();
    vm.stopPrank();

    _setBasketPrices(BASKET_1_20);
    d.router.updateMarkPrice(_updateData());
  }


  function _oracle() internal view returns (PletherOracle) {
    return PletherOracle(d.pletherOracle);
  }

  /// @dev Sets all six feeds so the normalized basket equals `basketPrice`, published at the current block time.
  function _setBasketPrices(
    uint256 basketPrice
  ) internal {
    _setBasketPricesAt(basketPrice, vm.getBlockTimestamp());
  }

  function _setBasketPricesAt(
    uint256 basketPrice,
    uint256 publishTime
  ) internal {
    for (uint256 i; i < 6; ++i) {
      _setFeed(i, basketPrice, publishTime);
    }
  }

  /// @dev Sets one component so that it alone would give normalized basket `basketPrice`, at `publishTime`.
  function _setFeed(
    uint256 i,
    uint256 basketPrice,
    uint256 publishTime
  ) internal {
    PletherOracle oracle = _oracle();
    uint256 normalizedPrice = oracle.basePrices(i) * basketPrice / 1e8;
    uint256 feedPrice = oracle.inversions(i) ? 1e16 / normalizedPrice : normalizedPrice;
    MockPyth(RELEASE_PYTH).setPrice(oracle.pythFeedIds(i), int64(uint64(feedPrice)), int32(-8), publishTime);
  }

  /// @dev Same as _setFeed with an explicit confidence (in feed units).
  function _setFeedWithConf(
    uint256 i,
    uint256 basketPrice,
    uint64 conf,
    uint256 publishTime
  ) internal {
    PletherOracle oracle = _oracle();
    uint256 normalizedPrice = oracle.basePrices(i) * basketPrice / 1e8;
    uint256 feedPrice = oracle.inversions(i) ? 1e16 / normalizedPrice : normalizedPrice;
    MockPyth(RELEASE_PYTH).setPrice(oracle.pythFeedIds(i), int64(uint64(feedPrice)), conf, int32(-8), publishTime);
  }

  /// @dev A non-encoded payload makes the MockPyth double use the configured per-feed prices.
  function _updateData() internal pure returns (bytes[] memory data) {
    data = new bytes[](1);
    data[0] = "";
  }

  function _refreshMark(
    uint256 basketPrice
  ) internal {
    _setBasketPrices(basketPrice);
    vm.prank(keeper);
    d.router.updateMarkPrice(_updateData());
  }


  function _warp(
    uint256 dt
  ) internal {
    vm.warp(vm.getBlockTimestamp() + dt);
    vm.roll(vm.getBlockNumber() + 1 + dt / 4);
  }

  function _warpTo(
    uint256 t
  ) internal {
    uint256 nowTs = vm.getBlockTimestamp();
    require(t >= nowTs, "warp back");
    vm.roll(vm.getBlockNumber() + 1 + (t - nowTs) / 4);
    vm.warp(t);
  }


  function _mint(
    address to,
    uint256 amount
  ) internal {
    d.settlementToken.mint(to, amount);
  }

  function _vault(
    bool senior
  ) internal view returns (TrancheVault) {
    return senior ? d.seniorVault : d.juniorVault;
  }

  function _requestDeposit(
    bool senior,
    address lp,
    uint256 assets
  ) internal returns (uint256 requestId) {
    TrancheVault v = _vault(senior);
    _mint(lp, assets);
    vm.startPrank(lp);
    d.settlementToken.approve(address(v), assets);
    requestId = v.requestDeposit(assets, lp, lp);
    vm.stopPrank();
  }

  /// @dev Warps to the request's epoch start (if not past) and settles through the Router's atomic oracle route.
  function _settleEpoch(
    uint256 requestId,
    uint256 basketPrice
  ) internal {
    uint256 start = d.housePool.lpEpochStart(requestId);
    if (vm.getBlockTimestamp() < start) {
      _warpTo(start);
    }
    _setBasketPrices(basketPrice);
    vm.prank(keeper);
    d.router.settleLpEpoch(_updateData());
  }

  function _claimDeposit(
    bool senior,
    address lp,
    uint256 requestId
  ) internal returns (uint256 shares) {
    TrancheVault v = _vault(senior);
    uint256 claimable = v.claimableDepositRequest(requestId, lp);
    vm.prank(lp);
    shares = v.claimDeposit(requestId, claimable, lp, lp);
  }

  /// @dev Request, settle at `basketPrice`, claim. Returns shares.
  function _lpDeposit(
    bool senior,
    address lp,
    uint256 assets,
    uint256 basketPrice
  ) internal returns (uint256 shares) {
    uint256 requestId = _requestDeposit(senior, lp, assets);
    _settleEpoch(requestId, basketPrice);
    shares = _claimDeposit(senior, lp, requestId);
  }

  function _requestRedeem(
    bool senior,
    address lp,
    uint256 shares
  ) internal returns (uint256 requestId) {
    vm.prank(lp);
    requestId = _vault(senior).requestRedeem(shares, lp, lp);
  }

  function _claimRedeem(
    bool senior,
    address lp,
    uint256 requestId
  ) internal returns (uint256 assets) {
    TrancheVault v = _vault(senior);
    uint256 shares = v.claimableRedeemRequest(requestId, lp);
    vm.prank(lp);
    assets = v.claimRedeem(requestId, shares, lp, lp);
  }


  function _fundTrader(
    address trader,
    uint256 assets
  ) internal {
    _mint(trader, assets);
    vm.startPrank(trader);
    d.settlementToken.approve(address(d.clearinghouse), assets);
    d.clearinghouse.depositMargin(assets);
    vm.stopPrank();
  }

  /// @dev Permissive bounds: no practical ceilings (zero means zero, so ceilings use max values).
  function _bounds(
    uint8 modes
  ) internal view returns (OrderV3Types.ExecutionBounds memory b) {
    b.submitBy = uint64(vm.getBlockTimestamp() + 60);
    b.executionWindowSeconds = 60;
    b.allowedExecutionModes = modes;
    b.expectedConfigHash = d.lifecycleBook.currentExecutionConfigHash();
    b.maxExecutionBountyAssets = type(uint256).max;
    b.maxExecutionNotionalAssets = type(uint256).max;
    b.maxGrossAccountDebitAssets = type(uint256).max;
    b.maxActionChargeAssets = type(uint256).max;
    b.maxExplicitFeesAssets = type(uint256).max;
    b.maxPostPositionSize = type(uint256).max;
    b.minPostSettlementBalanceAssets = 0;
    b.minPostPositionEquityAssets = 0;
    b.maxPostLeverageBps = type(uint32).max;
  }

  function _nextClientId() internal returns (bytes32) {
    return bytes32(uint256(keccak256(abi.encode("poc", ++clientNonce))));
  }

  /// @param size synthetic size in 1e18 units; must be a multiple of 100e18 (positionSizeQuantum 1e20).
  function _openReq(
    CfdTypes.Side side,
    uint256 size,
    uint256 margin,
    uint256 targetPrice
  ) internal returns (OrderV3Types.OrderRequest memory r) {
    r.clientOrderId = _nextClientId();
    r.side = side;
    r.sizeDelta = size;
    r.marginDelta = margin;
    r.targetPrice = targetP

The original report as published on Immunefi, by zer0luck_xint. 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 owner amendment requires the Latched status, but the permissionless retry can consume that status and replace it with Triggered within the same transaction, so the recovery window can be closed before the owner acts.

Impact

The owner's position could stay open with its PnL pledge reserved and the owner exposed to price movement, with measured losses of about 6.66 USDG at an unchanged price, 2,507.66 USDG on a 1% adverse move and 9,551.50 USDG if the position is liquidated, though the caller gains nothing and an owner who executes the child first can still amend.

What the attacker needed

A protection whose close attempt exceeds its limits; price stays beyond those limits; caller executes each child before the owner; no privileged role needed

The fix

The owner should be allowed to amend the retained close limits while the protection is Triggered, leaving the pending attempt's request unchanged so the next retry copies the amended limits.

How it was found

  1. A liquidity provider seeds the pool and the owner opens a leveraged long with a stop-loss and a gross account debit limit.
  2. The basket price gaps past the trigger so the close attempt exceeds the retained limit and the protection relatches as failed.
  3. An address with no role executes the live close attempt and calls the retry function in the same transaction, returning the protection to Triggered.
  4. The cycle is repeated once per execution window while the caller always executes first.
  5. The test confirms that standalone owner amendment, cancellation, cancel-and-close and ordinary close all revert while the position stays open.

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 trader sets a stop-loss with spending limits, and when a close attempt breaks those limits it fails and waits in a paused state so the trader can raise the limits. The retry function is open to anyone, so an attacker can run the failing close and the retry back to back, putting the protection straight back into the busy state where the trader's fix is refused. The trader then has to beat the attacker to the next execution before they can adjust anything.

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 zer0luck_xint

View all

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