LPsLux Proposals
Markets & DeFi
LP-9000

DEX - Core Trading Protocol Specification

Final

Core specification for the Lux DEX trading protocols, including AMM and order book implementations

Category
LRC
Created
2025-12-11

Normative topology + fee model: LP-0130. D-Chain (LP-9000) is the canonical DEX chain in the 10-chain roster. User funds enter D via ImportTx from X-Chain, trade inside D, and withdraw via ExportTx back to X (LP-0130 §2, §4). D-Chain does NOT hold canonical UTXO asset supply — X remains the settlement ledger. Order-book / CLOB matching semantics moved here from LP-1100 (X-Chain exchange-scope retired 2026-07-03).

Documentation: dex.lux.network

Source: github.com/luxfi/dex

Discussions: GitHub Discussions

Abstract

LP-9000 specifies the Lux DEX (Decentralized Exchange) core trading protocols, encompassing both the order book — the D-Chain dexvm, which matches at block Verify — and the AMM — C-Chain smart contracts. This LP serves as the foundation for all DeFi trading standards on Lux Network.

Asset model — asset identity and permissionless admission are specified in LP-9026. Wire transport — the CCXT public surface and the dex_* ZAP wire are specified in LP-9027.

Motivation

A comprehensive DEX specification provides:

  1. Unified Trading: Consistent trading interface across protocols
  2. Liquidity: Standards for liquidity provision
  3. Interoperability: Cross-chain trading capabilities
  4. Performance: High-throughput trading infrastructure

Specification

DEX Architecture

┌─────────────────────────────────────────────────────────────────┐
│                     Lux DEX Architecture                        │
├──────────────────────┬──────────────────────────────────────────┤
│   D-Chain (dexvm)    │            C-Chain (EVM)                 │
├──────────────────────┼──────────────────────────────────────────┤
│ • Order Book CLOB    │ • AMM Pools (concentrated liquidity)     │
│ • Matcher at Verify  │ • Smart Contract Settlement              │
│ • zapdb State        │ • ERC-20 Compatible                      │
└──────────────────────┴──────────────────────────────────────────┘
                              │
              ┌───────────────┴───────────────┐
              │     Cross-Chain Bridge        │
              │  (B-Chain + Atomic Swaps)     │
              └───────────────────────────────┘

EVM settlement is via the 0x9999 receipt-settlement precompile (LP-9999): D matches (D-Chain dexvm CLOB, BLS-signed DFillReceipt) · C settles (C-Chain 0x9999 verifies the certificate inline and debits/credits balances under Block-STM). The precompile is not a matcher.

Implementation

Repositories:

  • github.com/luxfi/dex - DEX implementation (D-Chain dexvm)
  • github.com/luxfi/standard - AMM contracts (C-Chain)

Order Book (D-Chain dexvm)

The order book is the D-Chain dexvm. There is no separate matching service: the match runs inside block Verify. Verify re-executes the block's orders against a versiondb overlay, derives the fills and book rows, and checks the proposer's claimed execution root; every validator runs the same match, so a lying proposer is rejected (dex/pkg/dchain/block.go). Accept commits the overlay to zapdb; Reject returns the orders to the mempool.

Order Types

TypeDescription
LimitFixed price order
MarketBest available price
StopTriggered at price level
Stop-LimitStop with limit price
Post-OnlyMaker only, rejects if would take
IOCImmediate or cancel
FOKFill or kill
GTCGood till cancelled

Order Structure

type Order struct {
    ID          ids.ID
    Trader      Address
    Pair        TradingPair
    Side        OrderSide    // Buy, Sell
    Type        OrderType
    Price       uint64       // 18 decimals
    Amount      uint64
    Remaining   uint64
    Timestamp   uint64
    Expiration  uint64
    Flags       OrderFlags   // PostOnly, IOC, FOK
}

type TradingPair struct {
    BaseAsset   ids.ID
    QuoteAsset  ids.ID
}

Matching Engine

type MatchingEngine interface {
    AddOrder(order *Order) ([]*Trade, error)
    CancelOrder(orderID ids.ID) error
    GetOrderBook(pair TradingPair, depth int) (*OrderBook, error)
    GetBestBid(pair TradingPair) (*PriceLevel, error)
    GetBestAsk(pair TradingPair) (*PriceLevel, error)
}

Matching Rules:

  • Price-time priority (FIFO)
  • Pro-rata for large orders (optional)
  • Self-trade prevention
  • Partial fills allowed

AMM Pools (C-Chain)

Pool Interface

interface ILuxPool {
    struct Pool {
        address token0;
        address token1;
        uint128 liquidity;
        uint160 sqrtPriceX96;
        int24 tick;
        uint24 fee;
    }

    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);
}

Concentrated Liquidity

struct Position {
    uint128 liquidity;
    uint256 feeGrowthInside0LastX128;
    uint256 feeGrowthInside1LastX128;
    uint128 tokensOwed0;
    uint128 tokensOwed1;
}

Fee Tiers:

  • 0.01% (1 bps) - Stablecoin pairs
  • 0.05% (5 bps) - Standard pairs
  • 0.30% (30 bps) - Exotic pairs
  • 1.00% (100 bps) - High volatility

Liquidity Mining

interface ILiquidityMining {
    struct RewardInfo {
        address rewardToken;
        uint256 rewardRate;
        uint256 periodFinish;
        uint256 rewardPerTokenStored;
    }

    function stake(uint256 tokenId) external;
    function withdraw(uint256 tokenId) external;
    function getReward() external;
    function earned(address account) external view returns (uint256);
}

Cross-Chain Trading

Atomic Swaps

type AtomicSwap struct {
    InitiatorChain  ids.ID
    ResponderChain  ids.ID
    HashLock        [32]byte
    TimeLock        uint64
    InitiatorAsset  Asset
    ResponderAsset  Asset
    Status          SwapStatus
}

Bridge Trading

interface ICrossChainSwap {
    function initiateSwap(
        uint256 sourceChainId,
        uint256 destChainId,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient
    ) external returns (bytes32 swapId);

    function completeSwap(
        bytes32 swapId,
        bytes calldata bridgeProof
    ) external;
}

Fee Structure

OperationFeeDistribution
Maker0.00% - 0.05%Protocol
Taker0.05% - 0.30%LP + Protocol
Bridge0.10%Validators
WithdrawalGas onlyNetwork

API Endpoints

Order Book API

MethodDescription
dex.createOrderCreate new order
dex.cancelOrderCancel order
dex.getOrderBookGet order book
dex.getOrdersGet user orders
dex.getTradesGet trade history
dex.getTickerGet market ticker

AMM API

MethodDescription
pool.swapExecute swap
pool.addLiquidityAdd liquidity
pool.removeLiquidityRemove liquidity
pool.getQuoteGet swap quote
pool.getPositionGet LP position

REST Endpoints

# Order Book (D-Chain dexvm)
POST /v1/bc/D/dex/orders
DELETE /v1/bc/D/dex/orders/{orderId}
GET /v1/bc/D/dex/orderbook/{pair}
GET /v1/bc/D/dex/trades/{pair}
GET /v1/bc/D/dex/ticker/{pair}

# AMM (C-Chain)
POST /v1/bc/C/dex/swap
POST /v1/bc/C/dex/liquidity/add
POST /v1/bc/C/dex/liquidity/remove
GET /v1/bc/C/dex/pools
GET /v1/bc/C/dex/quote/{pair}

WebSocket Feeds

# Real-time feeds
ws://node/v1/bc/D/dex/ws

# Subscribe to:
- orderbook:{pair}     # Order book updates
- trades:{pair}        # Trade stream
- ticker:{pair}        # Price ticker
- user:{address}       # User orders/trades

Configuration

{
  "dex": {
    "orderBook": {
      "maxOrdersPerUser": 1000,
      "maxOrderLifetime": "30d",
      "minOrderSize": "0.0001",
      "tickSize": "0.00000001"
    },
    "amm": {
      "defaultFee": 3000,
      "tickSpacing": 60,
      "maxLiquidityPerTick": "10000000000000000000000000"
    },
    "crossChain": {
      "bridgeFee": 10,
      "minConfirmations": 1,
      "maxSwapTime": "1h"
    }
  }
}

Performance

MetricOrder BookAMM
Throughput100,000+ orders/sec4,500 TPS
Latency<1ms matching~2s finality
Finality~2s~2s
Gas CostN/A (UTXO)~150k gas/swap

Rationale

Design decisions for DEX:

  1. Dual Model: Order book for professional trading, AMM for simplicity
  2. Matcher at Verify: the order book is consensus state; every validator re-runs the match, so the book needs no trusted operator
  3. Cross-Chain: Seamless trading across chains
  4. Concentrated Liquidity: Capital efficiency for LPs

Backwards Compatibility

LP-9000 is a new standard. Existing DEX implementations should align with this specification.

Test Cases

# Order book tests
cd dex && go test ./pkg/lx/... -v

# AMM contract tests
cd standard && forge test --match-contract PoolTest

# Integration tests
go test ./integration/dex/... -v

Reference Implementation

Repositories:

  • github.com/luxfi/dex — D-Chain dexvm (pkg/dchain), matcher at Verify
  • github.com/luxfi/standard — C-Chain AMM contracts

Security Considerations

  1. Front-Running: Time priority and private mempools
  2. Flash Loans: Reentrancy protection
  3. Oracle Manipulation: TWAP oracles
  4. Sandwich Attacks: Slippage protection
LPTitleRelationship
LP-9026AssetsAsset identity and admission
LP-9027WireCCXT surface and dex_* transport
LP-9100Order MatchingSub-specification
LP-9200Liquidity PoolsSub-specification
LP-9300DerivativesSub-specification
LP-9400Lending/BorrowingSub-specification
LP-9500Yield ProtocolsSub-specification

Copyright and related rights waived via CC0.