Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

OrderRouter

Git Source

Inherits: IPerpsKeeper, IPerpsTraderActions, IOrderRouterAdminHost, OrderExecutionOrchestrator

Title: OrderRouter (The MEV Shield)

Manages Commit-Reveal, MEV protection, and the un-brickable FIFO queue.

Holds only non-trader-owned keeper execution reserves. Trader collateral remains in MarginClearinghouse.

Note: security-contact: contact@plether.com

Constants

admin

address public immutable admin;

DEFAULT_MAX_ORDER_AGE

uint256 internal constant DEFAULT_MAX_ORDER_AGE = 60;

State Variables

nextCommitId

uint64 public nextCommitId = 1;

nextExecuteId

uint64 public nextExecuteId = 1;

maxOrderAge

uint256 public maxOrderAge;

minOpenNotionalUsdc

uint256 public minOpenNotionalUsdc;

openOrderExecutionBountyBps

uint256 public openOrderExecutionBountyBps;

minOpenOrderExecutionBountyUsdc

uint256 public minOpenOrderExecutionBountyUsdc;

maxOpenOrderExecutionBountyUsdc

uint256 public maxOpenOrderExecutionBountyUsdc;

closeOrderExecutionBountyUsdc

uint256 public closeOrderExecutionBountyUsdc;

maxPendingOrders

uint256 public maxPendingOrders;

globalTailOrderId

uint64 public globalTailOrderId;

Functions

_onlyEngine

function _onlyEngine() internal view;

_onlyAdmin

function _onlyAdmin() internal view;

constructor

constructor(
    address _engine,
    address _engineLens,
    address _vault,
    address _pyth,
    bytes32[] memory _feedIds,
    uint256[] memory _quantities,
    uint256[] memory _basePrices,
    bool[] memory _inversions
) OrderOracleExecution(_engine, _engineLens, _vault, _pyth, _feedIds, _quantities, _basePrices, _inversions);

Parameters

NameTypeDescription
_engineaddressCfdEngine that processes trades and liquidations
_engineLensaddress
_vaultaddressCfdVault used for vault depth queries and liquidation bounty payouts
_pythaddressPyth oracle contract (address(0) enables mock mode on Anvil)
_feedIdsbytes32[]Pyth price feed IDs for each basket component
_quantitiesuint256[]Weight of each component (must sum to 1e18)
_basePricesuint256[]Base price per component for normalization (8 decimals)
_inversionsbool[]Whether to invert each feed (e.g. USD/JPY -> JPY/USD)

_revertZeroAddress

function _revertZeroAddress() internal pure override;

_revertOracleValidation

function _revertOracleValidation(
    uint8 code
) internal pure;

_revertQueueState

function _revertQueueState(
    uint8 code
) internal pure;

_revertCommitValidation

function _revertCommitValidation(
    uint8 code
) internal pure;

_revertEmptyFeeds

function _revertEmptyFeeds() internal pure override;

_revertLengthMismatch

function _revertLengthMismatch() internal pure override;

_revertInvalidBasePrice

function _revertInvalidBasePrice() internal pure override;

_revertInvalidWeights

function _revertInvalidWeights() internal pure override;

_revertMissingPythUpdateData

function _revertMissingPythUpdateData() internal pure override;

_revertInsufficientPythFee

function _revertInsufficientPythFee() internal pure override;

_revertMockModeDisabled

function _revertMockModeDisabled() internal pure override;

_revertOraclePriceTooStale

function _revertOraclePriceTooStale() internal pure override;

_revertOracleConfidenceTooWide

function _revertOracleConfidenceTooWide() internal pure override;

_revertOraclePublishTimeOutOfOrder

function _revertOraclePublishTimeOutOfOrder() internal pure override;

_revertMevOraclePriceTooStale

function _revertMevOraclePriceTooStale() internal pure override;

_revertOraclePriceNegative

function _revertOraclePriceNegative() internal pure override;

commitOrder

Submits a trade intent to the FIFO queue. Margin and the order’s execution bounty are reserved immediately.

function commitOrder(
    CfdTypes.Side side,
    uint256 sizeDelta,
    uint256 marginDelta,
    uint256 targetPrice,
    bool isClose
) external;

Parameters

NameTypeDescription
sideCfdTypes.SideBULL or BEAR
sizeDeltauint256Position size change (18 decimals)
marginDeltauint256Margin to add or remove (6 decimals, USDC)
targetPriceuint256Slippage limit price (8 decimals, 0 = market order)
isCloseboolTrue to allow execution even when paused or in FAD close-only mode

syncMarginQueue

Returns the total queued escrow state for an account across all pending orders.

function syncMarginQueue(
    bytes32 accountId
) external;

getPendingOrderView

function getPendingOrderView(
    uint64 orderId
) external view returns (IOrderRouterAccounting.PendingOrderView memory pending, uint64 nextAccountOrderId);

executeOrder

Keeper executes the current global queue head.

Validates oracle freshness, publish-time ordering, and slippage, then delegates to the engine. Invalid, expired, or out-of-slippage orders are finalized from router-custodied execution bounty escrow; the router does not maintain a retry/requeue lane.

function executeOrder(
    uint64 orderId,
    bytes[] calldata pythUpdateData
) external payable;

Parameters

NameTypeDescription
orderIduint64Must equal the current global queue head (expired orders are auto-skipped)
pythUpdateDatabytes[]Pyth price update blobs; attach ETH to cover the Pyth fee

executeOrderBatch

Executes queued pending orders against a single Pyth price tick. Updates Pyth once, then loops through the FIFO queue. Aggregates reserved USDC execution bounties across processed orders and refunds excess ETH in a single transfer.

function executeOrderBatch(
    uint64 maxOrderId,
    bytes[] calldata pythUpdateData
) external payable;

Parameters

NameTypeDescription
maxOrderIduint64Inclusive upper bound on committed order ids the batch may begin processing from
pythUpdateDatabytes[]Pyth price update blobs; attach ETH to cover the Pyth fee

_queueHeadOrderId

function _queueHeadOrderId() internal view override returns (uint64);

_setQueueHeadOrderId

function _setQueueHeadOrderId(
    uint64 orderId
) internal override;

_queueTailOrderId

function _queueTailOrderId() internal view override returns (uint64);

_setQueueTailOrderId

function _setQueueTailOrderId(
    uint64 orderId
) internal override;

_revertOrderNotPending

function _revertOrderNotPending() internal pure override;

_maxOrderAge

function _maxOrderAge() internal view override returns (uint256);

_revertNoOrdersToExecute

function _revertNoOrdersToExecute() internal pure override;

_revertInsufficientGas

function _revertInsufficientGas() internal pure override;

_revertMevDetected

function _revertMevDetected() internal pure override;

_revertCloseOnlyMode

function _revertCloseOnlyMode() internal pure override;

_sendEth

function _sendEth(
    address to,
    uint256 amount
) internal override;

_creditOrDeferLiquidationBounty

Liquidation keeper value follows the same default custody path as other keeper flows: credit the beneficiary’s clearinghouse account when cash is available, otherwise defer the claim for later clearinghouse settlement.

function _creditOrDeferLiquidationBounty(
    uint256 liquidationBountyUsdc,
    uint256 executionPrice,
    uint64 oraclePublishTime
) internal;

_forfeitEscrowedOrderBountiesOnLiquidation

function _forfeitEscrowedOrderBountiesOnLiquidation(
    bytes32 accountId
) internal;

_clearLiquidatedAccountOrders

function _clearLiquidatedAccountOrders(
    bytes32 accountId
) internal;

_quoteOpenOrderExecutionBountyUsdc

function _quoteOpenOrderExecutionBountyUsdc(
    uint256 sizeDelta,
    uint256 price
) internal view returns (uint256);

_reserveCloseExecutionBounty

function _reserveCloseExecutionBounty(
    bytes32 accountId,
    uint256 sizeDelta,
    uint256 executionBountyUsdc
) internal override;

_hasFreshCarryCheckpointMark

function _hasFreshCarryCheckpointMark() internal view returns (bool);

_deleteOrder

function _deleteOrder(
    uint64 orderId,
    IOrderRouterAccounting.OrderStatus terminalStatus
) internal override;

applyRouterConfig

function applyRouterConfig(
    IOrderRouterAdminHost.RouterConfig calldata config
) external;

applyOracleConfig

function applyOracleConfig(
    IOrderRouterAdminHost.OracleConfig calldata config
) external;

_nextCommitId

function _nextCommitId() internal view override returns (uint64);

_releaseCommittedMarginForExecution

function _releaseCommittedMarginForExecution(
    uint64 orderId
) internal override;

updateMarkPrice

Push a fresh mark price to the engine without processing an order. Required before LP deposits/withdrawals when mark is stale.

function updateMarkPrice(
    bytes[] calldata pythUpdateData
) external payable;

Parameters

NameTypeDescription
pythUpdateDatabytes[]Pyth price update blobs; attach ETH to cover the Pyth fee

executeLiquidation

Keeper-triggered liquidation using the canonical live-market staleness policy. Forfeits any queued-order execution escrow to the vault instead of crediting it back to trader settlement, then credits the liquidation keeper through the clearinghouse when cash is available.

function executeLiquidation(
    bytes32 accountId,
    bytes[] calldata pythUpdateData
) external payable;

Parameters

NameTypeDescription
accountIdbytes32The account to liquidate (bytes32-encoded address)
pythUpdateDatabytes[]Pyth price update blobs; attach ETH to cover the Pyth fee

_revertInsufficientFreeEquity

function _revertInsufficientFreeEquity() internal pure override;

_revertMarginOrderLinkCorrupted

function _revertMarginOrderLinkCorrupted() internal pure override;

_revertPendingOrderLinkCorrupted

function _revertPendingOrderLinkCorrupted() internal pure override;

Events

OrderCommitted

event OrderCommitted(uint64 indexed orderId, bytes32 indexed accountId, CfdTypes.Side side);

Errors

OrderRouter__ZeroSize

error OrderRouter__ZeroSize();

OrderRouter__OracleValidation

error OrderRouter__OracleValidation(uint8 code);

OrderRouter__QueueState

error OrderRouter__QueueState(uint8 code);

OrderRouter__CommitValidation

error OrderRouter__CommitValidation(uint8 code);

OrderRouter__InsufficientGas

error OrderRouter__InsufficientGas();

OrderRouter__PredictableOpenInvalid

error OrderRouter__PredictableOpenInvalid(uint8 code);