Skip to content
Business logic Audit finding Advanced

Atomic expire-and-retry lets any outsider consume the owner-only Latched repair window

A permissionless retry function could be called atomically right after an order expiry, consuming the owner-only Latched repair state before the owner could amend the close limits. An outsider could therefore repeatedly deny the owner's only documented post-trigger ceiling-repair action, at the cost of gas only.

FestiveSRT Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#98849 [SC-High] Atomic expire-and-retry lets any outsider consume the owner-only Latched repair window

Submitted on Nov 10th 2026 at 14:57:10 UTC by @FestiveSRT for Audit Competition | Plether

Description

Summary

Cecuro MED-9 reported that permissionless position-protection retries lacked trader-selected financial ceilings. The frozen repair preserves four close ceilings across attempts and lets only the position owner amend them while the protection is Latched. Retry remains permissionless.

The two sides of that repair do not compose safely. A naturally expired close attempt changes the protection from Triggered to Latched, but any caller may immediately call retryPositionProtectionClose. An outsider contract can therefore call expireOrder(child) and retryPositionProtectionClose(protection) back-to-back in one transaction. The first call creates the owner-only repair state; the second consumes it and queues a new child before any owner transaction can be ordered between them. The replacement keeps the retained ceilings and restores Triggered, so the owner's documented amendment action reverts.

The attached local-fork proof demonstrates this composition against the exact Arbitrum Sepolia v2.0.0 deployed comparator. The outsider has no owner, guardian, governance, oracle, or victim privilege; supplies no false oracle data; and starts and ends with zero settlement tokens. Its trigger is an ordinary child reaching its configured deadline. A matched one-hunk control that restricts retry to the owner rejects the identical outsider transaction and rolls back all state, after which the owner can expire and retry normally.

This report uses the competition's explicit incomplete-fix exception: a report on a fixed or Acknowledged audit root remains valid when the frozen fix is incomplete or introduces a new bug. I am not claiming that permissionless retry, retained limits, or the MED-9 family was previously unknown. The narrow claim is that the repair introduced an owner-only Latched action without making that state externally actionable before a foreign caller can consume it atomically.

Root cause

When a close attempt terminates for a permitted non-liquidation failure and the exact protected position still exists, PositionProtectionBook.handleFailedProtectionAttempt deletes the old child mapping and performs:

Solidity
retained = _positionMatches(protection);
if (retained) {
    protection.status = PositionProtectionTypes.PositionProtectionStatus.Latched;
    return true;
}

The MED-9 repair action is owner-only through _ownedActiveProtection and is available only in that state with no pending Router order:

Solidity
function amendLatchedPositionProtectionCloseLimits(
    uint64 protectionId,
    PositionProtectionTypes.CloseFinancialLimits calldata limits
) external nonReentrant {
    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();
    }
    _setCloseLimits(protection, limits);
}

In contrast, retry loads the record through _activeProtection, not _ownedActiveProtection, and contains no caller check or priority interval:

Solidity
function retryPositionProtectionClose(
    uint64 protectionId
) external nonReentrant returns (uint64 linkedOrderId) {
    StoredProtection storage protection = _activeProtection(protectionId);
    if (protection.status != PositionProtectionTypes.PositionProtectionStatus.Latched) {
        revert OrderRouter__ProtectionNotLatched();
    }
    _requireMatchingPosition(protection);
    // ... no-pending and linked-child checks ...
    linkedOrderId = IPositionProtectionCloseAttemptHost(ROUTER)
        .commitProtectionCloseAttempt(
            protectionId, protection.account, protection.side, protection.size
        );
    _recordCloseAttempt(protection, linkedOrderId);
}

expireOrder is also public. Solidity transaction atomicity therefore lets a foreign helper create Latched and consume it in the same transaction. The ordinary cancellation and atomic cancel-and-close routes accept only pre-trigger states; a Triggered or Latched protection remains binding.

Executed trigger and impact

The proof binds source commit a82d4fefb02768e5b3bddcc97dee371eee24fea8, tree d88b5f9fca750cd69197b33e99a5189d3f1eccf2, chain 421614, and block 325561334. At target entry it checks all 30 v2.0.0 release runtime hashes. After control installation it rechecks all 30, allowing exactly one disclosed Book-runtime exception. Local code replacement in the vulnerable branch is limited to Pyth and ArbSys adapters.

All numerical execution values in this section are MEASURED in the exact clean-extracted r02 archive run. No intended-mainnet economic value or damage ratio is derived from them.

In the vulnerable branch:

  1. distinct victim, keeper, and outsider actors open a real protected position through the deployed stack;
  2. child 33 naturally reaches its deadline and expiration returns protection 6 to Latched;
  3. the owner successfully amends the retained ceilings from a 1,000,000-atom notional ceiling to [2,000,000; 25,000,000,000; 25,000,000,000; 25,000,000,000];
  4. the outsider permissionlessly retries to child 34;
  5. after child 34 naturally reaches its deadline, one outsider transaction expires 34 and retries protection 6, installing child 35; and
  6. the owner's immediate attempt to change all four ceilings to 25,000,000,000 atoms reverts with exact OrderRouter__ProtectionNotLatched() selector 0x5b54e624.

The failed owner transaction consumes 33,103 local gas. The full candidate- state SHA-256 is byte-for-byte equal before and after its revert:

Text
4354a60a6f9bd19756066d2353a71955f424168d05838a2e7381e34945f99338

At that point protection 6 is Triggered, child 35 is the sole pending linked order and retains the prior 2,000,000-atom notional ceiling. Position, victim settlement balance, action reserve, and outsider settlement-token balance are unchanged. The outsider starts and ends with zero settlement tokens. The vulnerable branch uses 15 local transactions.

In the matched control, the only in-scope logic change is this check at the start of retry:

Solidity
if (msg.sender != protection.account) {
    revert OrderRouter__Unauthorized();
}

The identical outsider expire-plus-retry call reverts with exact selector 0xb02f6f95; the complete state hash before and after is:

Text
6db3776d729d0fefb88b92f28710d327761c468e6b9cadcc7aea06c026c7e263

Child 34 remains the sole pending child. The owner then expires it and successfully retries to child 35. The control uses 17 local transactions. This isolates permissionless consumption of Latched as the cause; owner-only retry is diagnostic, not the only proposed remedy.

Impact and severity

The directly demonstrated damage is denial of the owner's only documented post-trigger ceiling-repair action. A successful outsider transaction renews the pending protection attempt with the old limits, keeps the protection binding, makes the immediate owner repair transaction revert, and costs the outsider only native gas. The same structural opportunity returns when a later child naturally reaches its deadline. The outsider must win ordering at each renewal; the proof does not assume control of the oracle, keeper, owner, or sequencer.

I select Medium — Griefing (e.g. no profit motive for an attacker, but damage to the users or the protocol). I do not claim attacker profit, principal theft, permanent freezing, or a distinct victim-owned amount inaccessible for one hour. A close attempt may execute, liquidation or position mutation may terminalize the protection, a privileged containment action may intervene, or the owner may win a later deadline race. Those recovery paths bound the claim but do not remove the executed outsider-caused denial and gas damage.

Preconditions and feasibility

  • A protection has triggered and its current zero-bounty close attempt reaches its legitimate deadline while the exact protected position remains.
  • The outsider monitors the public deadline and pays native gas for one public atomic transaction. No settlement-token capital is required.
  • The outsider's transaction wins ordering over any competing owner/keeper action at that deadline.
  • To renew the obstruction, each replacement child must again remain pending until its deadline and the outsider must win again.

These are natural/environmental conditions and public composition, not malicious-oracle or trusted-role assumptions. The proof establishes exact frozen-release mechanics, not a current intended-mainnet victim population, real-USDG liquidity, production gas costs, or monetary value at risk.

Knownness and strongest accepted-design objection

The overlap is material:

  • Cecuro MED-9 disclosed permissionless retries without trader-selected ceilings. The acknowledged repair retained close limits and added the owner-only Latched amendment.
  • SCAN-10 disclosed the early trigger-bounty/zero-bounty retry flow, noncancellable Triggered/Latched protection, and the resulting open-position loss/liquidation channel.
  • Frozen documentation says retry is permissionless, says the owner may amend after a failure becomes Latched, and instructs keeper infrastructure to process the terminal attempt, observe Latched, then submit a separate retry transaction.
  • The out-of-scope AA-client README says the owner can amend limits "before a permissionless retry." Public development history introduced retry races among keepers and later added amendment-before-retry coverage.

The strongest closure is therefore that the repair intentionally leaves a public race and the quoted phrase already accepts that another caller may win. That objection is substantial. The distinguishing evidence is that the documented keeper sequence and test assume a separately observable Latched state, whereas the public expiry and retry entrypoints can be composed by one foreign helper so no owner transaction can occupy the interval. No current public audit item, known-issue entry, source comment, documentation passage, test, issue, or commit message found in the 10 November public refresh states that exact atomic composition or says the owner-only repair state may be made externally unreachable in this way.

Independently re-verified against the full public history, not merely the current tree: retryPositionProtectionClose was introduced in Plether-Fi/plether-core PR #78 ("feat(perps): add latched SL/TP close retries") calling the unchecked _activeProtection(protectionId) from its original introduction. PR #124 ("fix(perps): harden trader protection, liquidation pricing, and manual exits") later added the sibling amendLatchedPositionProtectionCloseLimits correctly owner-checked via _ownedActiveProtection(protectionId, msg.sender), but never touches retryPositionProtectionClose's own definition — the asymmetry has existed unexamined across both PRs. The retained PositionProtection.t.sol calls retryPositionProtectionClose from a non-owner address (CAROL) extensively and as passing, intended behavior, but in every one of those call sites the expiry and the retry are two separate statements (a keeper expires, then a later, distinct vm.prank/call retries) — none of them compose the two into one atomic transaction the way this proof's expireAndRetry helper does. No test exercises the atomic composition itself. A full-history GitHub PR/issue search for PositionProtectionBook, amendLatchedPositionProtectionCloseLimits, and retryPositionProtectionClose across all states returned ten PRs and zero issues; none discusses this atomic-composition race. The repository's own audits/scan-plether-fi-plether-core-d4541b49.md static-scan references PositionProtectionBook.sol extensively by line but never cites either of these two functions or this authorization asymmetry.

This is deliberately presented as an incomplete MED-9 repair, not broad novelty. Formal CVQC and the filing-time knownness check must still decide whether the public wording makes the ordering behavior accepted design or the same publicly disclosed root.

Cross-finding leakage census: the candidate fields and upload archive contain only this atomic expiry-plus-retry mechanism, its diagnostic control, and the MED-9/SCAN-10 material necessary to disclose public knownness. They contain no trigger, exploit path, impact, or remediation for a separate unsubmitted finding.

Recommended remediation

Preserve permissionless liveness while guaranteeing that the owner-only repair operation is usable. Possible designs include:

  • an owner-priority block/time interval after relatching before a foreign retry;
  • an owner-native atomic expire-and-amend operation;
  • allowing the owner to stage limits that the next retry must consume even while the current attempt is Triggered; or
  • requiring owner authorization for retry, as in the diagnostic control.

Add an integration regression in which a foreign contract atomically calls expiry and retry at the natural deadline, and prove either that owner-staged limits reach the replacement child or that the foreign retry cannot consume the repair state before the defined priority boundary.

References

Link to Proof of Concept

https://gist.github.com/AFestive/77b261572c5a99f460fb8fc0d322f54f

Proof of Concept

Proof of Concept

Run per the attached README.md's ./run.sh invocation. Vulnerable: child 35 installed, owner amend reverts 0x5b54e624. Control: same call reverts 0xb02f6f95, rollback.

Inline files (byte-identical)

<!--run_af011_local_target.py-->
Python
#!/usr/bin/env python3
"""One AF-011 R10 deterministic-time attempt against a loopback Anvil fork.

This target has no upstream endpoint, credential lookup, proxy orchestration, or
public-node path. It uses only ordinary unlocked local-Anvil EOAs and production
external functions after the launcher's pinned state hydration.
"""

from __future__ import annotations

import argparse
import datetime
import hashlib
import json
import os
import pathlib
import re
import subprocess
import time
import urllib.error
import urllib.request


PINNED_COMMIT = "a82d4fefb02768e5b3bddcc97dee371eee24fea8"
FORK_BLOCK = 325_561_334
CHAIN_ID = 421_614
LOCAL_URLS = {
    "vulnerable": "http://127.0.0.1:29811",
    "control": "http://127.0.0.1:29821",
}

TOKEN = "0x3d051dbbf5ff427a4ae8ad09746902666af8fb9d"
CLEARINGHOUSE = "0xb5b851f627d6df3cf3f096e23e20a58884d7b89a"
ENGINE = "0xca18a6783d7542f9d2f28f4f259772b74c4d6baa"
ROUTER = "0x918663d6da8cb33b325a04c4a5e8c51d42f3b444"
BOOK = "0x81e3b03cf29865b6c0f85925839567e2bc61073d"
PYTH = "0x0b73614636c855bf23f342f307fb981a3e47f42b"
ARB_SYS = "0x0000000000000000000000000000000000000064"

MARK_PRICE = 100_000_000
TRIGGER_PRICE = 90_000_000
POSITION_SIZE = 10_000 * 10**18
POSITION_MARGIN = 5_000 * 10**6
TRADER_FUNDS = 50_000 * 10**6
INITIAL_NOTIONAL_LIMIT = 1 * 10**6
AMENDED_NOTIONAL_LIMIT = 2 * 10**6
OTHER_LIMIT = 25_000 * 10**6
MAX_TX_GAS = 100_000_000
STATUS_ARMED = 2
STATUS_TRIGGERED = 3
STATUS_LATCHED = 8
LIFECYCLE_PENDING = 1
PROTECTION_BOUNTY_KIND = 1

FEED_IDS = (
    "0xa995d00bb36a63cef7fd2c287dc105fc8f3d93779f062f09551b0af3e81ec30b",
    "0xef2c98c804ba503c6a707e38be4dfbb16683775f195b091252bf24693042fd52",
    "0x84c2dde9633d93d1bcad84e7dc41c9d56578b7ec52fabedc1f335d673df0a7c1",
    "0x3112b03a41c910ed446852aacf67118cb1bec67b2cd0b9a214c58cc0eaa2ecca",
    "0x8ccb376aa871517e807358d4e3cf0bc7fe4950474dbe6c9ffc21ef64e43fc676",
    "0x0b1e3297e69f162877b577b0d6a47a0d63b2392bc8499e6540da4187a63e28f8",
)

_local_url = ""
_run_handle = None
_tx_count = 0


class RpcFailure(RuntimeError):
    def __init__(self, method: str, item: object):
        super().__init__(f"{method}: local JSON-RPC error")
        self.method = method
        self.item = item


def output(*argv: str, cwd: pathlib.Path) -> str:
    return subprocess.check_output(list(argv), cwd=cwd, text=True).strip()


def record(step: str, status: str, **details) -> None:
    if _run_handle is None:
        raise RuntimeError("run log is not open")
    row = {"time": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "step": step, "status": status, **details}
    _run_handle.write(json.dumps(row, sort_keys=True) + "\n")
    _run_handle.flush()
    os.fsync(_run_handle.fileno())
    print(f"{step}: {status}", flush=True)


def rpc(method: str, params: list):
    payload = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode()
    request = urllib.request.Request(_local_url, data=payload, headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(request, timeout=120) as response:
            body = json.loads(response.read())
    except urllib.error.HTTPError as error:
        raw = error.read()
        try:
            body = json.loads(raw)
        except json.JSONDecodeError as decode_error:
            raise RpcFailure(
                method,
                {"http": error.code, "kind": "non-json", "complete_raw_response_hex": "0x" + raw.hex()},
            ) from decode_error
    if "error" in body:
        raise RpcFailure(method, body["error"])
    return body["result"]


def cast(args: argparse.Namespace, *values: str) -> str:
    return output(str(args.cast), *values, cwd=args.lane)


def cast_argument(value: object) -> str:
    if isinstance(value, bool):
        return "true" if value else "false"
    return str(value)


def calldata(args: argparse.Namespace, signature: str, *values) -> str:
    return cast(args, "calldata", signature, *(cast_argument(value) for value in values))


def selector(args: argparse.Namespace, signature: str) -> str:
    return cast(args, "sig", signature).lower()


def keccak_hex(args: argparse.Namespace, value: str) -> str:
    return cast(args, "keccak", value).lower()


def artifact(args: argparse.Namespace, source: str, contract: str) -> dict:
    path = args.scratch / "build/out" / source / f"{contract}.json"
    with path.open(encoding="utf-8") as handle:
        return json.load(handle)


def object_hex(value: str) -> str:
    return value if value.startswith("0x") else "0x" + value


def words(raw: str) -> list[int]:
    payload = raw[2:]
    if len(payload) % 64:
        raise AssertionError("non-word-aligned ABI response")
    return [int(payload[index : index + 64], 16) for index in range(0, len(payload), 64)]


def call_data_raw(to: str, data: str, *, sender: str | None = None, value: int = 0) -> str:
    transaction = {"to": to, "data": data, "value": hex(value)}
    if sender is not None:
        transaction["from"] = sender
    return rpc("eth_call", [transaction, "latest"])


def call_raw(args: argparse.Namespace, to: str, signature: str, *values, sender: str | None = None) -> str:
    return call_data_raw(to, calldata(args, signature, *values), sender=sender)


def signed_word(value: int, bits: int) -> int:
    masked = value & ((1 << bits) - 1)
    sign = 1 << (bits - 1)
    return masked - (1 << bits) if masked & sign else masked


def dynamic_uints(raw: str) -> list[int]:
    decoded = words(raw)
    if len(decoded) < 2 or decoded[0] != 32:
        raise AssertionError("unexpected dynamic uint-array encoding")
    length = decoded[1]
    if len(decoded) != length + 2:
        raise AssertionError("dynamic uint-array length mismatch")
    return decoded[2:]


def canonical_sha256(value: object) -> str:
    encoded = json.dumps(value, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(encoded).hexdigest()


def write_json_exclusive(path: pathlib.Path, value: object) -> None:
    with path.open("x", encoding="utf-8") as handle:
        json.dump(value, handle, indent=2, sort_keys=True)
        handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())
    descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
    try:
        os.fsync(descriptor)
    finally:
        os.close(descriptor)


def uint_call(args: argparse.Namespace, to: str, signature: str, *values) -> int:
    values_out = words(call_raw(args, to, signature, *values))
    if len(values_out) != 1:
        raise AssertionError(f"{signature}: expected one return word")
    return values_out[0]


def address_call(args: argparse.Namespace, to: str, signature: str, *values) -> str:
    raw = call_raw(args, to, signature, *values)
    if len(raw) != 66:
        raise AssertionError(f"{signature}: invalid address response")
    return "0x" + raw[-40:].lower()


def assert_equal(label: str, observed, expected) -> None:
    ok = observed == expected
    record(label, "PASS" if ok else "FAIL", observed=observed, expected=expected)
    if not ok:
        raise AssertionError(f"{label}: observed {observed!r}, expected {expected!r}")


def assert_gt(label: str, observed: int, boundary: int) -> None:
    ok = observed > boundary
    record(label, "PASS" if ok else "FAIL", observed=observed, boundary=boundary)
    if not ok:
        raise AssertionError(f"{label}: {observed} is not greater than {boundary}")


def wait_receipt(tx_hash: str) -> dict:
    deadline = time.monotonic() + 120
    while time.monotonic() < deadline:
        receipt = rpc("eth_getTransactionReceipt", [tx_hash])
        if receipt is not None:
            return receipt
        time.sleep(0.05)
    raise RuntimeError("local receipt timeout")


def send_data(
    sender: str,
    to: str | None,
    data: str,
    label: str,
    *,
    expected_status: int = 1,
) -> dict:
    global _tx_count
    transaction = {"from": sender, "data": data, "gas": hex(MAX_TX_GAS), "value": "0x0"}
    if to is not None:
        transaction["to"] = to
    receipt = wait_receipt(rpc("eth_sendTransaction", [transaction]))
    observed = int(receipt["status"], 16)
    _tx_count += 1
    ok = observed == expected_status
    record(
        label,
        "PASS" if ok else "FAIL",
        observed_status=observed,
        expected_status=expected_status,
        gas_used=int(receipt["gasUsed"], 16),
        transaction_hash=receipt["transactionHash"],
        block_number=int(receipt["blockNumber"], 16),
        complete_receipt=receipt,
    )
    if not ok:
        raise AssertionError(f"{label}: status {observed}, expected {expected_status}")
    transaction_details = rpc("eth_getTransactionByHash", [receipt["transactionHash"]])
    if transaction_details is None:
        raise AssertionError(f"{label}: missing mined transaction details")
    record(f"{label}-transaction", "PASS", complete_transaction=transaction_details)
    return receipt


def send(
    args: argparse.Namespace,
    sender: str,
    to: str,
    signature: str,
    values: tuple,
    label: str,
    *,
    expected_status: int = 1,
) -> dict:
    return send_data(sender, to, calldata(args, signature, *values), label, expected_status=expected_status)


def deploy(args: argparse.Namespace, sender: str, source: str, contract: str, label: str, constructor: str = "") -> str:
    build = artifact(args, source, contract)
    creation = object_hex(build["bytecode"]["object"]) + constructor
    receipt = send_data(sender, None, creation, label)
    address = receipt.get("contractAddress")
    if not address:
        raise AssertionError(f"{label}: missing contract address")
    return address.lower()


def current_timestamp() -> int:
    return int(rpc("eth_getBlockByNumber", ["latest", False])["timestamp"], 16)


def advance_to(timestamp: int, label: str) -> None:
    before = current_timestamp()
    if timestamp > before:
        rpc("evm_setNextBlockTimestamp", [timestamp])
    rpc("evm_mine", [])
    observed = current_timestamp()
    ok = observed >= timestamp
    record(label, "PASS" if ok else "FAIL", before=before, requested=timestamp, observed=observed)
    if not ok:
        raise AssertionError(f"{label}: timestamp boundary not reached")


def advance_seconds(seconds: int, label: str) -> None:
    rpc("evm_increaseTime", [seconds])
    rpc("evm_mine", [])
    rpc("evm_mine", [])
    record(label, "PASS", seconds=seconds, timestamp=current_timestamp())


def next_monday_six_utc(timestamp: int) -> int:
    current = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
    days = (7 - current.weekday()) % 7
    candidate_date = (current + datetime.timedelta(days=days)).date()
    candidate = datetime.datetime.combine(candidate_date, datetime.time(6, 0), tzinfo=datetime.timezone.utc)
    if candidate.timestamp() <= timestamp:
        candidate += datetime.timedelta(days=7)
    return int(candidate.timestamp())


def find_hex(value: object) -> list[str]:
    found: list[str] = []
    if isinstance(value, str):
        found.extend(item.lower() for item in re.findall(r"0x[0-9a-fA-F]{8,}", value))
    elif isinstance(value, dict):
        for item in value.values():
            found.extend(find_hex(item))
    elif isinstance(value, list):
        for item in value:
            found.extend(find_hex(item))
    return found


def expect_revert_selector(
    args: argparse.Namespace,
    sender: str,
    to: str,
    signature: str,
    values: tuple,
    expected_selector: str,
    label: str,
) -> None:
    try:
        call_raw(args, to, signature, *values, sender=sender)
    except RpcFailure as error:
        matches = [item for item in find_hex(error.item) if item.startswith(expected_selector)]
        ok = bool(matches)
        record(label, "PASS" if ok else "FAIL", expected_selector=expected_selector, selector_matched=ok)
        if not ok:
            raise AssertionError(f"{label}: expected selector absent") from error
        return
    record(label, "FAIL", expected_selector=expected_selector, reason="local-call-succeeded")
    raise AssertionError(f"{label}: local call unexpectedly succeeded")


def manifest_runtime_check(args: argparse.Namespace) -> dict:
    with args.manifest.open(encoding="utf-8") as handle:
        release = json.load(handle)
    contracts = release.get("contracts", {})
    assert_equal("release-runtime-count", len(contracts), 30)
    rows = []
    for name, item in contracts.items():
        address = item["address"].lower()
        actual = keccak_hex(args, rpc("eth_getCode", [address, "latest"]))
        expected = item["runtimeCodeHash"].lower()
        rows.append({"name": name, "address": address, "actual": actual, "expected": expected})
        if actual != expected:
            record("runtime-hashes", "FAIL", rows=rows)
            raise AssertionError(f"runtime mismatch: {name}")
    record("runtime-hashes", "PASS", count=len(rows), rows=rows)
    return release


def install_adapter(args: argparse.Namespace, address: str, source: str, contract: str, label: str) -> None:
    build = artifact(args, source, contract)
    runtime = object_hex(build["deployedBytecode"]["object"])
    rpc("anvil_setCode", [address, runtime])
    observed = rpc("eth_getCode", [address, "latest"])
    assert_equal(label, keccak_hex(args, observed), keccak_hex(args, runtime))


def install_control(args: argparse.Namespace, deployer: str) -> None:
    original = rpc("eth_getCode", [BOOK, "latest"])
    constructor = ROUTER[2:].rjust(64, "0") + ENGINE[2:].rjust(64, "0")
    deployed = deploy(
        args,
        deployer,
        "PositionProtectionBook.sol",
        "PositionProtectionBook",
        "deploy-control-position-protection-book",
        constructor,
    )
    runtime = rpc("eth_getCode", [deployed, "latest"])
    assert_gt("control-runtime-nonempty", len(runtime), 2)
    assert_equal("control-runtime-differs", keccak_hex(args, runtime) == keccak_hex(args, original), False)
    assert_equal("control-router-immutable", address_call(args, deployed, "ROUTER()"), ROUTER)
    assert_equal("control-engine-immutable", address_call(args, deployed, "ENGINE()"), ENGINE)
    rpc("anvil_setCode", [BOOK, runtime])
    control_runtime_hash = keccak_hex(args, runtime)
    assert_equal("control-runtime-installed", keccak_hex(args, rpc("eth_getCode", [BOOK, "latest"])), control_runtime_hash)
    assert_equal("router-book-binding", address_call(args, ROUTER, "positionProtectionBook()"), BOOK)
    assert_equal("installed-control-router", address_call(args, BOOK, "ROUTER()"), ROUTER)
    assert_equal("installed-control-engine", address_call(args, BOOK, "ENGINE()"), ENGINE)

    # Re-verify the full release runtime set after the one preregistered Book exception.
    with args.manifest.open(encoding="utf-8") as handle:
        release = json.load(handle)
    rows = []
    book_exceptions = 0
    for name, item in release.get("contracts", {}).items():
        address = item["address"].lower()
        actual = keccak_hex(args, rpc("eth_getCode", [address, "latest"]))
        expected = item["runtimeCodeHash"].lower()
        if address == BOOK:
            book_exc

The original report as published on Immunefi, by FestiveSRT. 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 retry function loads the protection through an unchecked lookup rather than the owner-checked one, so a public caller can consume the owner-only Latched state atomically with a public expiry.

Impact

The owner's only documented post-trigger ceiling-repair action is denied and their transaction reverts, costing the outsider only gas; the outsider must win ordering at each renewal and recovery paths such as a later deadline race remain.

What the attacker needed

A triggered protection whose close attempt expires; outsider wins ordering at the deadline; no settlement-token capital needed

The fix

The report recommends preserving permissionless liveness while guaranteeing the owner-only repair is usable, for example via an owner-priority interval, an owner-native atomic expire-and-amend, owner-staged limits, or requiring owner authorisation for retry.

How it was found

  1. A protected position is opened and its close attempt reaches its deadline, returning the protection to Latched.
  2. The owner amends the retained ceilings successfully.
  3. An outsider permissionlessly retries, creating a new child order.
  4. After that child reaches its deadline, one outsider transaction expires it and retries, installing another child.
  5. The owner's immediate attempt to change the ceilings reverts with ProtectionNotLatched.

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's protective close order can fail and enter a special 'Latched' state where only the trader is meant to adjust the safety limits. Because the function that retries the order does not check who is calling, anyone can trigger the expiry and the retry in a single transaction, so the trader never gets a chance to make their change. The result is that the trader's repair transaction fails, though no funds are stolen.

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 FestiveSRT

View all

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