DEX v5 Order Lifecycle - ATCE Integration
Complete process flow for trade orders through the DEX v5 3-service stack, including ATCE compliance gating, batch auction clearing, and settlement.
DEX v5 is a 3-microservice trading stack deployed across DevNet and all 20 mainnet validators.
market-state :8561
Market state machine tracking volatility, oracle deviation, utilization, and settlement failures. Four states with hysteresis thresholds prevent oscillation. Depends on PostgreSQL, Redis.
execution-router :8562
Routes incoming trade intents to Retail Lane or RFQ Lane based on a 7-rule precedence engine. Queries market-state for current conditions before routing. Depends on market-state, compliance-api, PostgreSQL.
retail-lane-engine :8563
Batch auction clearing engine. Collects intents in 3-second windows, applies VRF shuffle and iterative price discovery, then executes matched trades. Depends on ledger-service, PostgreSQL, Kafka.
market-state → execution-router → retail-lane-engine. The execution-router fetches market state via HTTP with a 2-second timeout and fails open to NORMAL if unreachable. All services are Express/TypeScript, following existing service patterns.
4-state machine with hysteresis thresholds preventing rapid oscillation.
Service: market-state (:8561). Endpoints: GET /v1/market/state, POST /v1/market/signals, POST /v1/market/governance/halt, POST /v1/market/governance/resume, GET /v1/market/history. DB Tables: market_state_current (singleton), market_state_transitions (history).
NORMAL
Full AMM + RFQ. Standard batch sizes.
ELEVATED
Wider spreads. Dwell: 5 min.
STRESSED
RFQ-first routing. Dwell: 10 min.
HALTED
No new trades. Dwell: 30 min.
Hysteresis: The state machine can escalate multiple levels upward in a single evaluation cycle, but must step down only one level at a time. Dwell times enforce minimum duration in each state before de-escalation. HALTED can only be entered or exited via governance action (multi-sig required).
Deterministic routing decision tree evaluated top-to-bottom. First match wins.
Service: execution-router (:8562). Endpoints: POST /v1/router/preview (no DB write), POST /v1/router/execute (records intent). DB Tables: router_intents, router_config. Pre-seeded pairs: JIL/USDC, JIL/ETH, jBTC/jUSDC, jETH/jUSDC.
HALTEDBLOCKED (ATCE freeze or compliance hold)RFQ_MIN threshold for pairSTRESSED (RFQ-first routing)HEAVY (toxic flow detection)RFQ_PRIORITY flag setDEFAULT - all other ordersBefore routing, the execution-router runs 4 ATCE compliance checks. Any failure blocks the trade.
Service: compliance-api (:8100). Called by: execution-router (:8562). Enforcement: Pre-routing gate - runs before rule 1 of the decision tree.
Trust Level Classification
Enforcement policy: Blocked accounts are permanently rejected (rule 2 in the routing tree). HighRisk accounts are subject to reduced daily caps (5% instead of 10%) and mandatory RFQ routing. MediumRisk and below follow standard rules. Trusted accounts can access higher batch limits.
3-second batch windows with VRF-shuffled fair clearing.
Service: retail-lane-engine (:8563). Batch window: BATCH_WINDOW_MS=3000. Endpoints: POST /v1/retail/intent/submit, GET /v1/retail/batch/:batchId, GET /v1/retail/intent/:intentId, POST /v1/retail/batch/trigger, GET /v1/retail/pools. DB Tables: retail_pools (4 pre-seeded), retail_batches, retail_intents.
VRF Shuffle
Deterministic Fisher-Yates shuffle using a SHA-256 chain seeded from the batch VRF output. Ensures no participant can predict or influence execution order. Algorithm ported from Rust crates/ammv5-core/src/batch.rs.
Oracle Band Clamping
Clearing price is clamped to the oracle band boundaries. Prevents batch execution at prices that deviate beyond the configured oracle deviation tolerance. Protects against stale or manipulated oracle feeds.
Iterative Price Discovery
Runs 8 iterations with 1% step adjustments. Converges on a clearing price that maximizes volume by iteratively testing price levels against the order book. Deterministic output given identical inputs.
Execute Intents
Executes matched intents at the discovered clearing price. Each intent is checked against its slippage tolerance and limit price. Intents that fail these checks are returned unfilled with a SLIPPAGE_EXCEEDED or LIMIT_NOT_MET reason.
Fee Split
Collected fees are distributed: 50% LP providers, 40% Operations, 10% Humanitarian fund. Fee split is applied per-trade at execution time. LP shares are proportional to liquidity contribution.
Uses setTimeout recursion (not setInterval) to prevent timer drift and race conditions. The rotate-first pattern ensures the current batch map is snapshotted before new intents can be submitted to the next window. Fixed in PR #338: Map iterator infinite loop bug resolved with Array.from() snapshot.
All fees are denominated in basis points (bps). 1 bps = 0.01%.
Fee Distribution
LP share is distributed proportional to each provider's liquidity contribution in the pool at the time of trade execution. The humanitarian fund allocation is a protocol-level commitment; it cannot be redirected without a governance vote.
Complete vertical flow from user submitting a trade order through settlement and confirmation.
Phase 1: Order Submission
User selects pair, amount, slippage tolerance in Web Wallet (:3003). Trade forwarded to wallet-api (:8002) via POST /wallet/trade.
Phase 2: ATCE Compliance Gate
execution-router (:8562) forwards to compliance-api (:8100). Four sequential checks: freeze, zone, cap, kyb. Queries compliance state from PostgreSQL.
Phase 3: Market State + Routing
execution-router queries market-state (:8561) with 2s timeout (fail-open to NORMAL). Records routing decision (Retail or RFQ) in router_intents table.
Phase 4: Retail Lane Clearing
retail-lane-engine (:8563) collects intent in 3s batch window. Clears via VRF shuffle, oracle clamp, price discovery (8 iter), execute, fee split.
Phase 5: Ledger Settlement
ledger-service (:8001) processes PaymentTx for balance updates on L1. settlement-consumer (:8051) confirms finality. TRADE_SETTLED published to Kafka.
Phase 6: User Confirmation
Web wallet (:3003) displays updated balances and trade receipt to the user. Complete flow takes ~3 seconds from submission to confirmation.
Horizontal dependency map across the DEX v5 trade pipeline.
DEX v5 Core
market-state :8561 (volatility tracking, 4-state hysteresis) → execution-router :8562 (7-rule precedence, RFQ vs Retail) → retail-lane-engine :8563 (3s batch auctions, VRF shuffle)
Supporting Services
wallet-api :8002 (trade entry point) → compliance-api :8100 (ATCE gate) → ledger-service :8001 (balance + settlement) → settlement-consumer :8051 (Kafka consumer)
Infrastructure Layer
PostgreSQL 16 (all DEX tables: market_state_*, router_*, retail_*), Redis (state cache, rate limits), Kafka/RedPanda (TRADE_SETTLED, BATCH_COMPLETED, STATE_CHANGED topics)
All DEX v5 tables reside in the shared PostgreSQL 16 instance.
market_state_current
Singleton row: id (INT PK DEFAULT 1), state (TEXT - NORMAL/ELEVATED/STRESSED/HALTED), volatility_bps (INT), oracle_deviation (NUMERIC), utilization (NUMERIC), settlement_failures (INT), entered_at (TIMESTAMPTZ), updated_at (TIMESTAMPTZ).
market_state_transitions
History log: id (UUID PK), from_state (TEXT), to_state (TEXT), trigger (TEXT - signal/governance/timeout), trigger_data (JSONB), transitioned_at (TIMESTAMPTZ).
router_intents
id (UUID PK), account_id (TEXT), pair (TEXT), side (BUY/SELL), amount (NUMERIC), price_limit (NUMERIC), slippage_bps (INT), routed_to (RETAIL/RFQ/REJECTED), routing_rule (INT 1-7), market_state (TEXT), status (pending/filled/partial/rejected), created_at (TIMESTAMPTZ).
router_config
pair (TEXT PK), rfq_min_amount (NUMERIC), enabled (BOOLEAN), dex_fee_bps (INT DEFAULT 200), settlement_fee_bps (INT DEFAULT 4), rfq_fee_bps (INT DEFAULT 10), updated_at (TIMESTAMPTZ).
retail_pools
pair (TEXT PK), base_asset (TEXT), quote_asset (TEXT), base_reserve (NUMERIC), quote_reserve (NUMERIC), oracle_price (NUMERIC), lp_total_shares (NUMERIC), status (active/paused/deprecated), updated_at (TIMESTAMPTZ). 4 pre-seeded pairs.
retail_batches
id (UUID PK), pair (TEXT), batch_number (BIGINT), vrf_seed (TEXT), clearing_price (NUMERIC), total_buy/sell_volume (NUMERIC), matched_volume (NUMERIC), intent_count (INT), filled_count (INT), total_fees (NUMERIC), status (collecting/clearing/settled/failed), window_start/end (TIMESTAMPTZ), settled_at (TIMESTAMPTZ).
All endpoints across the DEX v5 stack and supporting services.
| Service | Endpoint | Method | Purpose |
|---|---|---|---|
| market-state :8561 | /v1/market/state | GET | Returns current market state |
| market-state :8561 | /v1/market/signals | POST | Submit volatility/oracle/utilization signals |
| market-state :8561 | /v1/market/governance/halt | POST | Emergency governance halt (multi-sig) |
| market-state :8561 | /v1/market/governance/resume | POST | Resume from HALTED state (multi-sig) |
| market-state :8561 | /v1/market/history | GET | State transition history with trigger data |
| execution-router :8562 | /v1/router/preview | POST | Preview routing decision (no DB write) |
| execution-router :8562 | /v1/router/execute | POST | Execute routing: ATCE, state query, record, forward |
| retail-lane-engine :8563 | /v1/retail/intent/submit | POST | Submit intent to current batch window |
| retail-lane-engine :8563 | /v1/retail/batch/:batchId | GET | Get batch result and fill statistics |
| retail-lane-engine :8563 | /v1/retail/intent/:intentId | GET | Get individual intent status and fill details |
| retail-lane-engine :8563 | /v1/retail/batch/trigger | POST | Manually trigger batch clearing |
| retail-lane-engine :8563 | /v1/retail/pools | GET | List all retail liquidity pools |
| wallet-api :8002 | /wallet/trade | POST | User-facing trade entry point |
| ledger-service :8001 | /state/accounts/:id/balances | GET | Query account balances after settlement |
| settlement-consumer :8051 | /v1/settlement/status/:txId | GET | Check settlement status for transaction |
| compliance-api :8100 | /v1/compliance/check | POST | Run ATCE compliance checks |
Institutional-grade DEX with built-in compliance at every step.
JIL Sovereign's DEX v5 combines batch auction fairness, 4-state market protection, and ATCE compliance gating - all in a 3-service microservice architecture deployed across 20 mainnet validators.