Home
Learn

How It Works

Tokenomics

Roadmap

Humanitarian Impact Fund

FAQ

Products

Wallet

DEX

LaunchPad

Token Factory

Vaults

Company

About

Contact

Buy JIL
Process Flow

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.

3 Services market-state, execution-router, retail-lane-engine
4 States Hysteresis Market Machine
7 Rules Precedence Routing
3s Batch Windows
Overview

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.

Dependency chain:

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.

Market State Machine

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.

enter: <300bps

ELEVATED

Wider spreads. Dwell: 5 min.

enter: 500bps / exit: 300bps

STRESSED

RFQ-first routing. Dwell: 10 min.

enter: 1000bps / exit: 700bps

HALTED

No new trades. Dwell: 30 min.

governance action only

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

Execution Router - 7-Rule Precedence

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.

1
Market state is HALTED
REJECT
2
Account is BLOCKED (ATCE freeze or compliance hold)
REJECT
3
Order size ≥ RFQ_MIN threshold for pair
RFQ LANE
4
Market state is STRESSED (RFQ-first routing)
RFQ LANE
5
Order flagged as HEAVY (toxic flow detection)
RFQ LANE
6
Account has RFQ_PRIORITY flag set
RFQ LANE
7
DEFAULT - all other orders
RETAIL LANE
ATCE Compliance Gate

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

1
freeze_check(from_address)
Checks if the sender address is frozen by governance or compliance action. Frozen accounts cannot initiate any trade. Zero gas cost (cached in-memory).
REJECT if frozen
2
zone_gate(from_zone, to_zone)
Validates zone transfer policy. Transfers from a protected zone to an unprotected zone are blocked. Prevents assets from leaving the protected perimeter without authorization.
REJECT if blocked
3
cap_check(account, amount)
Anti-dump mechanism: enforces a 10% daily sell limit based on the account's holdings at the start of the UTC day. Prevents large liquidation events.
REJECT if >10%
4
kyb_status(issuer)
KYB (Know Your Business) verification check for token issuers. Ensures the traded token's issuer has passed institutional verification before allowing trades.
REJECT if unverified

Trust Level Classification

Blocked
High Risk
Medium Risk
Low Risk
Trusted

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.

Retail Lane - Batch Auction

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.

1

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.

2

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.

3

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.

4

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.

5

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.

Batch timer:

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.

Fee Structure

All fees are denominated in basis points (bps). 1 bps = 0.01%.

200bps
DEX Trading Fee
1% buyer side + 1% seller side
4bps
Settlement Fee
Applied on ledger settlement
10bps
RFQ Routing Fee
Additional fee for RFQ lane only

Fee Distribution

50% LP Providers
40% Operations
10% Humanitarian

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.

End-to-End Order Flow

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.

Services Architecture

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)

Database Tables

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

Key Endpoints

All endpoints across the DEX v5 stack and supporting services.

Service Endpoint Method Purpose
market-state :8561/v1/market/stateGETReturns current market state
market-state :8561/v1/market/signalsPOSTSubmit volatility/oracle/utilization signals
market-state :8561/v1/market/governance/haltPOSTEmergency governance halt (multi-sig)
market-state :8561/v1/market/governance/resumePOSTResume from HALTED state (multi-sig)
market-state :8561/v1/market/historyGETState transition history with trigger data
execution-router :8562/v1/router/previewPOSTPreview routing decision (no DB write)
execution-router :8562/v1/router/executePOSTExecute routing: ATCE, state query, record, forward
retail-lane-engine :8563/v1/retail/intent/submitPOSTSubmit intent to current batch window
retail-lane-engine :8563/v1/retail/batch/:batchIdGETGet batch result and fill statistics
retail-lane-engine :8563/v1/retail/intent/:intentIdGETGet individual intent status and fill details
retail-lane-engine :8563/v1/retail/batch/triggerPOSTManually trigger batch clearing
retail-lane-engine :8563/v1/retail/poolsGETList all retail liquidity pools
wallet-api :8002/wallet/tradePOSTUser-facing trade entry point
ledger-service :8001/state/accounts/:id/balancesGETQuery account balances after settlement
settlement-consumer :8051/v1/settlement/status/:txIdGETCheck settlement status for transaction
compliance-api :8100/v1/compliance/checkPOSTRun ATCE compliance checks
Compliant Trading Infrastructure

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.