Order Gateway

Overview

The order gateway has two contracts

  • DelayedOrderGateway

  • orderGatewayV2 (used by front end and API)

DelayedOrderGateway is covered here; orderGatewayV2 is limited to use by the Perp v3 frontend and API (no external functions for direct contract interaction).

The order gateways have two key roles:

  1. Route orders to the optimal liquidity source

  2. Prevent trades from front-running the oracle using a 3 second delay

Workflow

  1. Call createOrder() to generate an order, including createdAt and executableAt timestamps

  2. Wait for executableAt() timestamp

  3. Call executeOrder() with orderId to execute a trade

  4. Call cancelOrder() with orderID to cancel an unexecuted order

Contract

struct DelayedOrder {
    DelayedOrderType orderType; // Types: OpenPosition or ClosePosition
    address sender; // Sender address
    uint256 ; // See annotation
    uint256 createdAt; // block.timestamp
    uint256 executableAt; // block.timestamp + orderDelaySeconds
    bytes data;
}
/// @notice Create an order (but do not execute)
function createOrder(
    DelayedOrderType orderType, 
    bytes calldata data
) 

emit OrderCreated(
    orderId, 
    delayedOrder.sender, 
    marketId, 
    abi.encode(delayedOrder)
);
/// @notice Execute an order (probably first call createOrder)
function executeOrder(
        uint256 orderId,
        bytes calldata makerData
)

returns (
        int256 base, 
        int256 quote
);
/// @notice Cancel unexecuted order
function cancelOrder(
    uint256 orderId
)

emit OrderCanceled(
    orderId
);
/// @notice There are many public view functions available
function getCurrentNonce() public view returns (uint256) {
        return _getOrderGatewayStorage().nonce;
}

function getOrdersCount() public view returns (uint256) {
    return _getOrderGatewayStorage().orderIds.length();
}

function getOrderIds(uint256 start, uint256 end) public view returns (uint256[] memory) {
    return _getOrderGatewayStorage().orderIds.valuesAt(start, end);
}

function getUserOrdersCount(address taker) public view returns (uint256) {
    return _getOrderGatewayStorage().userOrderIdsMap[taker].length();
}

function getUserOrderIds(address taker, uint256 start, uint256 end) public view returns (uint256[] memory) {
    return _getOrderGatewayStorage().userOrderIdsMap[taker].valuesAt(start, end);
}

function getOrder(uint256 orderId) public view returns (DelayedOrder memory) {
    return _getOrderGatewayStorage().ordersMap[orderId];
}

Last updated