Router Technical Documentation

Deterministic quote generation with pathfinding, fee injection, and circuit breakers. Security-hardened, zero-trust architecture.

Overview

The LucenDEX router generates deterministic quotes for token swaps by finding optimal paths through AMM pools and orderbook offers, with comprehensive security controls and tamper-evident QuoteHash binding.

Core Capabilities

Quote Generation Flow

1. Validate input (amount bounds, asset format, XRPL address)
2. Find best route via Dijkstra pathfinding
3. Calculate total fees (AMM trading fees + routing fee)
4. Compute price and price impact
5. Check circuit breaker (reject if price anomaly)
6. Generate QuoteHash (blake2b-256, tamper-evident)
7. Cache quote in KV store (30s TTL)
8. Return QuoteResponse

QuoteHash (Tamper-Evident Binding)

Every quote includes a deterministic hash that binds all parameters:

QuoteHash = blake2b-256(
  in_asset + out_asset + amount +
  router_bps + trading_fees + est_out_fee +
  ledger_index + ttl
)
✓ Security Properties
  • Same inputs always produce same hash (deterministic)
  • Fee tampering changes hash (tamper-evident)
  • Reproduced from any indexer snapshot (verifiable)
  • Embedded in XRPL transaction memo (binding)

Circuit Breaker Protection

Automatic price anomaly detection prevents execution of extreme trades:

Price Deviation Check

threshold = 5% (default)
deviation = |price - avg_recent| / avg_recent

if deviation > threshold:
  failures++
  if failures >= 5:
    state = OPEN (reject all trades)

States

CLOSED Normal operation, all trades allowed
OPEN Blocking mode, rejects all trades (30s timeout)
HALF-OPEN Testing mode after timeout, first valid trade closes breaker

Caution Mode

On startup, router enters caution mode for 60 seconds with 50% stricter thresholds to prevent execution during state rebuilding.

Security Architecture

KV Store (In-Memory Cache)

Quote Replay Prevention

Every used quote is tracked in metering.used_quotes to ensure single-use only:

CREATE TABLE metering.used_quotes (
  quote_hash BYTEA PRIMARY KEY,
  ledger_index BIGINT NOT NULL,
  used_at TIMESTAMPTZ DEFAULT now(),
  partner_id UUID,
  tx_hash TEXT
);

Rate Limit Persistence

Dual-layer architecture: PostgreSQL as source of truth, KV as cache. Rate limits survive restarts.

Audit Logging

All router operations logged to metering.router_audit for compliance:

Performance Targets

Quote Latency (p95) <200ms
Database Query (p95) <50ms
Cache Hit Rate >80%
Circuit Breaker Eval <10ms
KV Get Operation <1µs
KV Set Operation <10µs

Pathfinding Algorithm

Dijkstra's algorithm with fee-aware edge weights finds optimal routes through liquidity sources:

Graph Construction

Multi-Hop Routing

Example: XRP → BTC → USD
Hop 1: AMM pool (XRP/BTC)
Hop 2: Orderbook (BTC/USD)
Max hops: 3

AMM Constant Product Formula

amount_out = (amount_in * (1 - fee) * reserve_out) / 
             (reserve_in + amount_in * (1 - fee))

Fee Structure

Router Fee (Lucendex)

Trading Fees

Test Coverage

Router Components 92.1%
KV Store 92.5%
Database Layer 26.0% (mocked)
Race Detector 0 races

Security Test Suite

Prometheus Metrics

# Quote generation
lucendex_quotes_total{outcome="success|rejected"}
lucendex_quote_latency_ms{outcome}

# Circuit breaker
lucendex_circuit_breaker_state{pair}

# Cache performance
lucendex_cache_hits_total
lucendex_cache_misses_total
lucendex_kv_memory_bytes

Security Guarantees

✓ Zero-Trust Architecture
  • Namespace isolation prevents cross-contamination
  • Memory limits (512MB) prevent DoS
  • Input validation prevents bypass attacks
  • QuoteHash prevents fee tampering
  • Audit logs provide compliance trail (no PII)
  • Circuit breakers prevent anomalous trades

Version History

v1.0.0 (2025-11-11):