Skip to content
Business logic Audit finding Advanced

The MED-28 fix makes stop-loss/take-profit arming revert after any order execution, so any account can block every trader's protection at no cost

After the fix for a prior finding, the protection-arming functions validate trigger prices against the accepted oracle basket, which reverts whenever an ordinary order execution has advanced the Engine mark past that basket. Any account can deliberately trigger this state at no asset cost, blocking every trader's ability to create, replace or open with stop-loss/take-profit protection until someone pays for a refresh.

argo_the_hacker Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#99889 [SC-Low] The MED-28 fix makes stop-loss/take-profit arming revert after any order execution, so any account can block every trader's protection at no cost

Submitted on Nov 15th 2026 at 16:33:27 UTC by @argo_the_hacker for Audit Competition | Plether

Description

Severity: Medium. Impact selected from the program's list: "Griefing (e.g. no profit motive for an attacker, but damage to the users or the protocol)".

Target: immunefi-team/audit-comp-plether @ a82d4fefb02768e5b3bddcc97dee371eee24fea8, packages/perps/src/PositionProtectionBook.sol (_freshProtectionObservation, lines 862-886), reaching packages/perps/src/PletherOracle.sol (_snapshotFromBasket, lines 892-896).

Relation to prior findings: a new bug introduced by the fix for Cecuro MED-28 (the program's known-issues rule makes a report on a fixed root valid when it shows the fix "is incomplete or introduces a new bug"). It is not MED-28, MED-17, LOW-73 or the SECURITY.md keeper limitation; the section "Relation to prior findings" explains each.

Summary

To fix Cecuro MED-28, createPositionProtection, replacePositionProtection and commitOpenOrderWithProtection now validate the trader's trigger prices against "the current accepted oracle observation". They do this by calling oracle.getLatestPrice(PriceMode.MarkRefresh) (PositionProtectionBook.sol:880). That view enforces publish order: it reverts PletherOracle__PriceOutOfOrder whenever the accepted live basket is older than the Engine mark (PletherOracle.sol:892-896).

Ordinary order execution puts the system in exactly that state. A keeper's executeOrder pushes the order's historical Pyth tick into the Engine mark (OrderRouterExecutionSidecar.sol:979, :1053-1061) but never writes the accepted basket. From then until someone pays for a fresh updateMarkPrice, every trader's protection create, replace and open-with-protection reverts, even though the oracle is live, the Engine mark is fresh, and the MED-28 comment and the Book's own predicate _acceptedMarkInstalled() (PositionProtectionBook.sol:888-895) both accept this state. The other arming path in the same contract, the one that arms protection when a protected open fills (PositionProtectionBook.sol:598-602), accepts the state and arms from ENGINE.lastMarkTime().

Anyone can cause the state on purpose and at no asset cost. An account with no position commits an order whose slippage bound cannot be met and executes it itself. The order fails on slippage, but its tick has already advanced the Engine mark (the oracle step runs before settlement), and the execution bounty comes back to the same account as executor. The PoC repeats this after each of five refreshes by the victim and every arm attempt is refused, at zero settlement-asset cost to the account causing it.

The damage is to traders who rely on the protection. In the PoC, a trader whose one attempt to arm a 1.10 stop-loss is refused is liquidated at 1.19 instead of being stopped out at 1.10, and ends 905.400002 USDC worse off than the same trader in the same market whose arm was accepted. The LP pool ends 905.000002 USDC better off.

The same call also produces a second symptom: for up to 15 seconds after each refresh, arming reverts PletherOracle__StalePrice while the Engine mark is still fresh (section "Second symptom").

The limits are stated plainly in the Impact section: the refusal is a visible revert, one refresh in the same second clears it, and closing a position is never blocked.

Relation to prior findings

Cecuro MED-28 (Acknowledged, "Addressed"), "Trader can arm a new protection from a stale engine mark after oracle state already crossed it". The maintainers' comment on the fix: "New protection, replacement and [open-with-protection] staging validate trigger geometry against the current accepted oracle observation, rather than only the cached Engine mark. … The integrated synchronization guard also rejects arming when the accepted oracle mark is ahead of, or inconsistent with, the Engine mark." MED-28 was the case where the oracle is ahead of a stale Engine mark. This report is the opposite state, where the Engine mark is ahead of the accepted basket. The fix's own policy allows that state, and the fix itself causes the revert:

  1. The getLatestPrice(MarkRefresh) call at PositionProtectionBook.sol:880 is the MED-28 remediation (MED-28 p. 66: "read pletherOracle.getLatestPrice(PriceMode.MarkRefresh) … during protection creation and replacement"). It arrived with the protection hardening commit eadc5c58 (#124), after the audited code.
  2. _acceptedMarkInstalled() (PositionProtectionBook.sol:888-895), the synchronization predicate the MED-28 comment refers to (commit 81919218, #120), returns true for acceptedTime < markTime. On create/replace that branch can never be reached, because the line before it has already reverted. The open-with-protection fill path (:598-602) does reach it on every fill.
  3. The repository documents only the reverse failure. WORKING_WITH_AI_AGENTS.md:270-272 says protection fails "If the accepted live basket is newer than the Engine mark or disagrees at the same timestamp". No maintainer test expects PriceOutOfOrder from the protection Book; the OracleMarkAhead tests in PositionProtection.t.sol cover only the oracle-ahead case.
  4. SECURITY.md:563-564 states the property this breaks: "Existing-position protection creation remains available in degraded mode because it adds no exposure. Router pause, frozen-oracle policy, freshness, position/queue checks, and post-lock collateral admission still apply." Publish order relative to the Engine mark is not in that list.

Other nearby items, and why they are different:

  • MED-17 (trigger publish time versus the armedAt wall clock) says creation and replacement "use the accepted current oracle observation". It does not describe or accept a refusal.
  • LOW-73 (create reverted while the old degradedMode latch was set) has the same user-facing symptom but a different root (the latch, since removed).
  • MED-18 (the cached mark rewritten at the same timestamp) has no protection-arming consequence.
  • MED-30 (known issue: no automatic stop-loss trigger while the oracle is frozen) needs a frozen market. This report needs a live market and concerns create/replace, not the trigger. In a frozen market _freshProtectionObservation reverts ConditionalTriggerFrozen before reaching the oracle call.
  • SECURITY.md:1341 ("execution remains dependent on fresh keeper infrastructure and oracle publication outside frozen windows") is about execution. Arming is not execution, and the refusal happens while the accepted basket is inside its staleness limit and the Engine mark is fresher still.
  • ORACLE_SYNCHRONIZATION.md:149-151 acknowledges the state ("historical execution may advance the Engine without advancing the accepted live basket") but never says that create/replace are refused in it.
  • AI-scan info item "Later mark refresh can make live historical-price orders permanently out of order" runs the other way (a refresh blocks a historical order). Here a historical execution blocks protection arming.

Vulnerability details

The refused state

_freshProtectionObservation() (PositionProtectionBook.sol:862-886):

Solidity
        uint64 markTime = ENGINE.lastMarkTime();
        cachedMarkPrice = ENGINE.lastMarkPrice();
        if (
            cachedMarkPrice == 0 || markTime == 0
                || OracleFreshnessPolicyLib.isStale(markTime, policy.maxStaleness, block.timestamp)
        ) {
            revert OrderRouter__ProtectionMarkTooStale();
        }
        IPletherOracle.PriceSnapshot memory current = oracle.getLatestPrice(IPletherOracle.PriceMode.MarkRefresh);
        currentMarkPrice = current.markPrice;
        currentPublishTime = current.publishTime;
        if (!_acceptedMarkInstalled()) {
            revert PositionProtectionBook__OracleMarkAhead();
        }

getLatestPrice(MarkRefresh) builds the snapshot from the stored accepted basket (_acceptedLiveBasket, PletherOracle.sol:706-727) and calls _snapshotFromBasket(basket, policy, true) (PletherOracle.sol:578). With enforcePublishOrder = true (PletherOracle.sol:892-896):

Solidity
        if (enforcePublishOrder) {
            uint64 markTime = engine.lastMarkTime();
            if (snapshot.publishTime < markTime) {
                revert PletherOracle__PriceOutOfOrder(snapshot.publishTime, markTime);
            }

The predicate checked one line later says this state is fine (PositionProtectionBook.sol:888-895):

Solidity
    function _acceptedMarkInstalled() private view returns (bool) {
        (bool accepted, uint256 acceptedPrice, uint64 acceptedTime) = _activeOracle().getAcceptedBasketMark();
        if (!accepted) {
            return true;
        }
        uint64 markTime = ENGINE.lastMarkTime();
        return acceptedTime < markTime || (acceptedTime == markTime && acceptedPrice == ENGINE.lastMarkPrice());
    }

How ordinary execution reaches it

executeOrder → _prepareSingleOracle validates the order's historical tick (the first Pyth update after the order's commit time) and then calls _updateEngineMark (OrderRouterExecutionSidecar.sol:979), which writes it into the Engine whenever it is newer (:1053-1061):

Solidity
    function _updateEngineMark(
        IOrderRouterExecutionHost host,
        OracleResult memory result
    ) private {
        ICfdEngineCore engine_ = ICfdEngineCore(host.engine());
        if (result.publishTime > engine_.lastMarkTime()) {
            engine_.updateMarkPrice(result.neutralMarkPrice, result.publishTime);
        }
    }

The accepted basket is written only by a live updateMarkPrice intake, so after any executed (or failed) order whose tick is newer than the last refresh, acceptedBasket.publishTime < engine.lastMarkTime(), and protection arming reverts for every account. Because executeOrder has no executor allow-list (the executor is msg.sender, OrderRouterExecutionSidecar.sol:129-139), any address can create this state. The slippage check runs after the oracle step (OrderRouterExecutionSidecar.sol:467-473), so even an order that fails on its own slippage bound moves the Engine mark.

Second symptom (same call): StalePrice while the mark is fresh

The same getLatestPrice(MarkRefresh) call also checks every basket component against the 60 s MarkRefresh staleness limit (PletherOracle.sol:720-722), while the Book's own freshness check tests only the Engine mark time (PositionProtectionBook.sol:874-879), which is the newest component. Live intake allows components to differ by up to LIVE_TICK_LOOKBACK = 15 s (PletherOracle.sol:29, :762-764). So after each refresh there is a window of up to 15 s (oldest component + 60 s < now ≤ newest component + 60 s) in which create/replace/open-with-protection revert PletherOracle__StalePrice although the mark check passes. The PoC shows a 12 s window with ordinary skew. It is the same line and the same fix as above, so it is reported here as a second symptom, not as a separate finding.

Impact

Who: any address. No role, no position and no market exposure are needed. Ordinary keeper execution of other traders' orders also reaches the state without anyone intending it.

What breaks: createPositionProtection, replacePositionProtection and commitOpenOrderWithProtection revert for every trader while the oracle is live and the Engine mark is fresh. The PoC shows a trader cannot arm a stop on an open position, cannot tighten an existing stop, and cannot open with protection.

Cost to the account causing it: zero settlement assets per cycle. A self-executed order that fails on slippage pays its execution bounty back to the same account (asserted in the PoC; gas only).

Damage to users (measured): in the PoC market (10,000-notional LONG, 2,000 USDC margin), a trader who tries once to arm a 1.10 stop-loss, is refused, and does not retry is liquidated at 1.19 and ends 905.400002 USDC worse off than the same trader whose arm was accepted. The LP pool ends 905.000002 USDC better off in the same comparison. Two more cases in the second test file, each blocked by an account with no position: a stop at 1.05 that could not be armed before a fast move to 1.20 (the trader is 1,386.36 USDC worse off than with the stop), and a refused tightening of an existing 1.10 stop to 1.05 (the trader is stopped out at the old level, 400.16 USDC worse off).

This matches the program's Medium impact "Griefing (e.g. no profit motive for an attacker, but damage to the users or the protocol)": the account causing it gains nothing, and the damage lands on traders who rely on the protection the protocol says stays available (SECURITY.md:563-564).

Limits, stated plainly:

  • The refusal is a visible revert, not a silent failure. A trader who notices it can retry.
  • One updateMarkPrice with a current Pyth update clears it. A refresh and an arm in the same second cannot be split by another account: the only tick that account can use is the first one after its own commit, and if that is not newer than the refresh, the Engine mark does not move (PoC test_A_Control_SameSecondRefreshThenArmCannotBeInterleaved). Repeated blocking therefore works against a victim whose refresh and arm land in different seconds, for example two ordinary transactions from an EOA.
  • Exits are never blocked. A plain close commits and executes in the blocked state, and already-armed protection still triggers.
  • The loss figures are counterfactuals: they assume the trader does not retry, refresh or close by hand while the price moves against them (19% in the 905.40 USDC case).

Recommendation

Make create/replace/open-with-protection accept exactly the state the MED-28 policy and _acceptedMarkInstalled() accept. When the accepted basket is older than, or equal to (same price), the Engine mark, the freshness-checked Engine mark is the newest accepted observation. Use it, as the open-with-protection fill path already does (PositionProtectionBook.sol:598-602 arms from ENGINE.lastMarkTime() once _acceptedMarkInstalled() passes), and keep the MED-28 refusal when the accepted basket is ahead or disagrees:

Solidity
    function _freshProtectionObservation()
        private
        view
        returns (uint256 cachedMarkPrice, uint256 currentMarkPrice, uint64 currentPublishTime)
    {
        IPletherOracle oracle = _activeOracle();
        IPletherOracle.PolicySnapshot memory policy = oracle.getOrderExecutionPolicy(true);
        if (policy.oracleFrozen) {
            revert OrderRouter__ConditionalTriggerFrozen();
        }
        uint64 markTime = ENGINE.lastMarkTime();
        cachedMarkPrice = ENGINE.lastMarkPrice();
        if (
            cachedMarkPrice == 0 || markTime == 0
                || OracleFreshnessPolicyLib.isStale(markTime, policy.maxStaleness, block.timestamp)
        ) {
            revert OrderRouter__ProtectionMarkTooStale();
        }
        (bool accepted, uint256 acceptedPrice, uint64 acceptedTime) = oracle.getAcceptedBasketMark();
        if (!accepted) {
            revert IPletherOracle.PletherOracle__NoAcceptedBasket(); // unchanged outcome before the first intake
        }
        // MED-28: refuse when the accepted oracle mark is ahead of, or inconsistent with, the Engine mark.
        if (acceptedTime > markTime || (acceptedTime == markTime && acceptedPrice != cachedMarkPrice)) {
            revert PositionProtectionBook__OracleMarkAhead();
        }
        // Accepted basket older than (historical execution advanced the Engine) or equal to the Engine mark:
        // the freshness-checked Engine mark is the current accepted observation.
        currentMarkPrice = cachedMarkPrice;
        currentPublishTime = markTime;
    }

This removes the getLatestPrice(MarkRefresh) call, so it fixes both symptoms: the publish-order revert, and the per-component StalePrice revert while the mark itself is fresh. The trigger path is unchanged and still ingests and validates a fresh Pyth update when the protection fires (triggerPositionProtection dispatches updateMarkPrice, PositionProtectionBook.sol:375-378, which reaches oracle.updatePrice(…, MarkRefresh) in router/OrderLiquidationBatchLogic.sol:607-609).

If the maintainers want to keep the component-level re-validation at arming, the narrower alternative is to call getLatestPrice(MarkRefresh) only when acceptedTime == markTime, and to use the Engine mark when acceptedTime < markTime. That fixes the main symptom but not the second one.

Either way, a regression test like test_Property_RouterPath_TraderCanArmProtectionAfterKeeperExecution above (arming after another trader's keeper execution) would catch this case; the current suite only tests the oracle-ahead direction.

Link to Proof of Concept

https://gist.github.com/Richter2552/76e3fa5cae573b6902104c8669d89aaf

Proof of Concept

Proof of Concept

The program requires PoCs to run in the repository's Foundry test suite at the commit in scope without modifying the contracts in scope. The three test files below extend the maintainers' PositionProtectionTest fixture and use only public entry points from unprivileged accounts after the fixture's setUp: production OrderRouter.commitOrder(OrderRequest), router.executeOrder from an address with no role, the permissionless router.updateMarkPrice, HousePool.settleLpEpoch, TrancheVault request/claim, createPositionProtection, replacePositionProtection, triggerPositionProtection and executeLiquidationBatch. Pyth is the maintainers' MockPyth (Pyth is outside the scope). No protocol contract is pranked and no storage is written. The fixture's junior deposit helper is switched off (_initialJuniorDeposit() = 0) because it impersonates the router; the junior LP deposits through the public vault flow instead. Because of that override, the tests inherited from PositionProtectionTest are not meant to run in these contracts; run only the tests named below.

Each property test states the behaviour the code should have and fails on the pinned code with the named error. Each characterize/control test passes and pins the exact revert, the cost, the remedy and the measured value.

Run instructions (from a checkout of immunefi-team/audit-comp-plether at a82d4fefb02768e5b3bddcc97dee371eee24fea8 with submodules; solc 0.8.35 via the repository's packages/perps/foundry.toml):

Bash
cp Card1351S2RouterPathProtectionBlocked.t.sol Card1351S2PersistenceCostValue.t.sol \
   Card1351S2ValueAndStaleWindow.t.sol packages/perps/test/perps/spec/trader/
cd packages/perps

forge test --match-contract '^Card1351S2RouterPathProtectionBlockedTest$' --match-test '^test_Property_RouterPath_' -vv
forge test --match-contract '^Card1351S2RouterPathProtectionBlockedTest$' --match-test '^test_(Control|Characterize)_RouterPath_' -vv

forge test --match-contract '^Card1351S2PersistenceCostValueTest$' --match-test '^test_((A|B|C)_|ReadDown_)' -vv

forge test --match-contract '^Card1351S2ValueAndStaleWindowTest$' --match-test '^test_(Value_|Recovery_|StaleWindow_Characterize_|StaleWindow_RemedyWithMaxSkew)' -vv
forge test --match-contract '^Card1351S2ValueAndStaleWindowTest$' --match-test '^test_StaleWindow_Property_' -vv

PoC output (pinned code, unmodified contracts)

Run on a fresh tree from git archive a82d4fef with the three files installed as above (forge 1.8.1, solc 0.8.35, the repository's packages/perps/foundry.toml). The result: 12 characterize/control tests pass, and the 3 property tests fail with the named errors. Excerpt (forge -vv logs):

CONSOLE
[FAIL: PletherOracle__PriceOutOfOrder(1709535618 [1.709e9], 1709535629 [1.709e9])] test_Property_RouterPath_TraderCanArmProtectionAfterKeeperExecution() (gas: 9375298)
[FAIL: PletherOracle__PriceOutOfOrder(1709535610 [1.709e9], 1709535612 [1.709e9])] test_Property_RouterPath_TraderCanArmProtectionAfterOwnOpen() (gas: 5662967)
[PASS] test_Characterize_RouterPath_RevertAndRemedy() (gas: 10108091)
Logs:
  accepted basket publishTime 1709535618
  engine lastMarkTime         1709535629
[PASS] test_Control_RouterPath_ArmSucceedsWhenAcceptedBasketCurrent() (gas: 6060569)

[PASS] test_A_FailedSelfExecutedOrderBlocksArmingAtZeroAssetCost() (gas: 8013255)
Logs:
  MALLORY settlement delta per cycle (USDC 1e6): 0
  gas: commit 1370878
  gas: execute 654070
[PASS] test_A_GriefLoop_ReblocksEveryRefreshThenArmAcrossSeconds() (gas: 19524625)
Logs:
  rounds, all arm attempts refused: 5
  victim refresh gas total: 1160944
  griefer gas total: 10124936
  griefer settlement delta total: 0
[PASS] test_A_Control_SameSecondRefreshThenArmCannotBeInterleaved() (gas: 8523669)
[PASS] test_B_FastMarket_BlockedStopLossDifferential() (gas: 13927739)
Logs:
  ALICE settlement, control (stop at 1.05, filled 1.06): 19391360000
  ALICE settlement, griefed (no stop, closed 1.20):      18005000000
  difference (USDC 1e6): 1386360000
[PASS] test_C_TighteningExistingStopIsBlocked_Differential() (gas: 13930521)
Logs:
  ALICE settlement, control (tightened to 1.05): 19391360000
  ALICE settlement, griefed (old 1.10 stop):     18991199999
  difference (USDC 1e6): 400160001
[PASS] test_ReadDown_VictimCanExitOrSelfClear() (gas: 11011837)

[PASS] test_Value_RefusedStopLossCostsTheTrader() (gas: 40578379)
Logs:
  world control (stop armed)
    ALICE armed / stop fired / liquidated true true false
    liquidation price (1e8) 119000000
    ALICE balance (USDC 1e6) 18991199996
    CAROL balance (USDC 1e6) 18085799994
    pool totalAssets (USDC 1e6) 1004905000010
  world refused (arm reverted, no retry)
    ALICE armed / stop fired / liquidated false false true
    liquidation price (1e8) 119000000
    ALICE balance (USDC 1e6) 18085799994
    CAROL balance (USDC 1e6) 18085799994
    pool totalAssets (USDC 1e6) 1005810000012
  ALICE loss vs control (USDC 1e6) 905400002
  pool gain vs control (USDC 1e6) 905000002
[PASS] test_Recovery_RefreshThenArm() (gas: 15639642)
[PASS] test_StaleWindow_Characterize_WindowAndRemedy() (gas: 11058835)
Logs:
  stale-component window seconds 12
[PASS] test_StaleWindow_RemedyWithMaxSkewStillArms() (gas: 13021389)
[FAIL: PletherOracle__StalePrice(1, 0x0000000000000000000000000000000000000000000000000000000000000001, 1709535629 [1.709e9], 60, 1709535690 [1.709e9])] test_StaleWindow_Property_ArmWhileMarkFresh() (gas: 9504169)

Expected output on a fixed contract: the three property tests pass. The characterize tests that pin the revert (test_Characterize_RouterPath_RevertAndRemedy, test_A_*, test_StaleWindow_Characterize_*) then fail at their expectRevert, because the revert they pin no longer happens.

What the tests show

step test result on the pinned code
ALICE opens through commitOrder + keeper executeOrder; BOB's ordinary order is then keeper-executed with the next Pyth tick; ALICE tries to arm a take-profit test_Property_RouterPath_TraderCanArmProtectionAfterKeeperExecution FAILS: PletherOracle__PriceOutOfOrder(accepted, mark)
ALICE tries to arm right after her own open is keeper-executed test_Property_RouterPath_TraderCanArmProtectionAfterOwnOpen FAILS: PletherOracle__PriceOutOfOrder
exact revert, no bounty held, one public refresh clears it test_Characterize_RouterPath_RevertAndRemedy passes
with the accepted basket current, the same create succeeds test_Control_RouterPath_ArmSucceedsWhenAcceptedBasketCurrent passes
an account with no position self-executes an order that fails on slippage; the Engine mark moves; arming is refused; the account's settlement balance is unchanged test_A_FailedSelfExecutedOrderBlocksArmingAtZeroAssetCost passes
the same after each of five refreshes by the victim; all five arm attempts refused; zero settlement-asset cost test_A_GriefLoop_ReblocksEveryRefreshThenArmAcrossSeconds passes
limit: a refresh and an arm in the same second cannot be split test_A_Control_SameSecondRefreshThenArmCannotBeInterleaved passes
a refused stop in a fast market, and a refused tightening of an existing stop, compared with the accepted case test_B_FastMarket_BlockedStopLossDifferential, test_C_TighteningExistingStopIsBlocked_Differential passes (control balance > refused balance)
limit: in the blocked state a manual close works, and a self-refresh clears it test_ReadDown_VictimCanExitOrSelfClear passes
control world vs refused world, same market: ALICE ends 905.400002 USDC worse, the pool 905.000002 USDC better, CAROL identical test_Value_RefusedStopLossCostsTheTrader passes
one public refresh lets ALICE arm, and her stop then fires at 1.10 test_Recovery_RefreshThenArm passes
second symptom: mark 49 s old (fresh), oldest component 61 s old; ALICE arms test_StaleWindow_Property_ArmWhileMarkFresh FAILS: PletherOracle__StalePrice
second symptom: arm works at +60 s, refused at +61 s, a refresh clears it test_StaleWindow_Characterize_WindowAndRemedy passes
the remedy refresh for the main symptom, at the widest skew intake allows, still lets ALICE arm at once test_StaleWindow_RemedyWithMaxSkewStillArms passes

Test file 1 of 3: packages/perps/test/perps/spec/trader/Card1351S2RouterPathProtectionBlocked.t.sol (minimal reproduction)

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

import {PositionProtectionTest} from "./PositionProtection.t.sol";
import {CfdTypes} from "@plether/perps/CfdTypes.sol";
import {OrderRouter} from "@plether/perps/OrderRouter.sol";
import {OrderV3Types} from "@plether/perps/OrderV3Types.sol";
import {IOrderRouterAccounting} from "@plether/perps/interfaces/IOrderRouterAccounting.sol";
import {IPletherOracle} from "@plether/perps/interfaces/IPletherOracle.sol";
import {MockPyth} from "@plether/test-utils/MockPyth.sol";
import {console2} from "forge-std/console2.sol";

/// @title Protection arming is refused after an ordinary keeper execution (public entry points, unprivileged accounts)
/// @notice Pinned commit a82d4fefb02768e5b3bddcc97dee371eee24fea8. Install next to PositionProtection.t.sol in
///         packages/perps/test/perps/spec/trader/ and run with the repository's own foundry.toml.
/// @dev `BasePerpTest._open` pranks the router into `engine.processOrderTyped`, and the fixture's junior LP funding
///      pranks the router to install a mark. This file uses neither:
///      - Deployment and owner configuration come from the maintainers' fixture (BasePerpTest.setUp). Both seeds and
///        `pool.activateTrading()` run there; the test asserts `isTradingActive()` and `canIncreaseRisk()`.
///      - `_initialJuniorDeposit()` is 0, so setUp makes no router-impersonated call. The junior LP deposits through
///        `TrancheVault.requestDeposit`, a public `router.updateMarkPrice`, the permissionless
///        `HousePool.settleLpEpoch(0, 0)` (no open positions, HousePool.sol:809-819), and `claimDeposit`.
///      - Every trade is a production V3 `OrderRouter.commitOrder(OrderRequest)` from the trader's own account. The
///        harness's scalar `commitOrder` overload is not used.
///      - Every execution is `router.executeOrder` from KEEPER, an address with no role. The executor is
///        `msg.sender` with no allow-list (OrderRouterExecutionSidecar.sol:129-139).
///      - Every mark refresh is the permissionless `router.updateMarkPrice` (OrderRouter.sol:424-434).
///      - Pyth is the maintainers' MockPyth. A keeper's update is the first tick after commitTime: the
///        `parsePriceFeedUpdatesUnique` window is [commitTime+1, ...] (PletherOracle.sol:608-614), with
///        `previousPublishTime = commitTime`. No prank, no stdstore write, and no `vm.store` touches protocol state.
contract Card1351S2RouterPathProtectionBlockedTest is PositionProtectionTest {

    address internal constant LP = address(0x1B1B);
    address internal constant KEEPER = address(0x5EE5); // no role anywhere; any EOA
    address internal constant REFRESHER = address(0x4EF4); // any EOA
    uint256 internal constant JUNIOR_LP_ASSETS = 1_000_000e6;

    uint256 private _clientNonce;

    /// No junior deposit in the fixture setUp: its helper pranks the router into `engine.updateMarkPrice`.
    function _initialJuniorDeposit() internal pure override returns (uint256) {
        return 0;
    }

    // ---------------------------------------------------------------------------------------------------------------
    // Public-entry-point helpers
    // ---------------------------------------------------------------------------------------------------------------

    /// A live Pyth tick at the current block time, chained to the last engine mark time.
    function _tickNow(
        uint256 price
    ) private view returns (bytes[] memory updateData) {
        bytes32[] memory ids = _basePythFeedIds();
        MockPyth.FeedUpdate[] memory ticks = new MockPyth.FeedUpdate[](ids.length);
        uint256 previous = engine.lastMarkTime();
        uint256 nowTs = vm.getBlockTimestamp();
        for (uint256 i; i < ids.length; ++i) {
            ticks[i] = MockPyth.FeedUpdate(ids[i], MockPyth.MockPrice(int64(uint64(price)), 0, -8, nowTs, previous));
        }
        updateData = ne

The original report as published on Immunefi, by argo_the_hacker. 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 MED-28 fix calls a price view that enforces publish order against the Engine mark, so it reverts in the state where a historical execution has advanced the Engine mark beyond the accepted basket, a state the contract's own synchronisation predicate treats as valid.

Impact

Traders cannot arm or tighten protection while the oracle is live, and in the PoC a trader who does not retry is liquidated at 1.19 instead of being stopped out at 1.10, ending about 905 USDC worse off; the refusal is a visible revert, one refresh clears it, and closing a position is never blocked.

What the attacker needed

No role or position needed; attacker pays gas only; victim does not retry or refresh

The fix

The report recommends making create, replace and open-with-protection accept the state the synchronisation predicate already accepts, using the freshness-checked Engine mark when the accepted basket is older, and keeping the refusal only when the accepted basket is ahead or disagrees.

How it was found

  1. An account with no position commits an order whose slippage bound cannot be met.
  2. The same account executes the order itself; it fails on slippage but its price tick has already advanced the Engine mark.
  3. The execution bounty returns to the same account, so the cycle costs no settlement assets.
  4. Every trader's attempt to create, replace or open with protection now reverts until a fresh mark price update is paid for.
  5. The account repeats this after each refresh, so arm attempts keep being refused.

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 stop-loss is an automatic instruction to close a trade if the price moves too far against you. This protocol checks the price against two records that can drift apart: one updated by normal trade execution and one updated by a separate price refresh. When the first is newer, the check refuses to let anyone set up a stop-loss, and anyone can make that happen on purpose for free.

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 argo_the_hacker

View all

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