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
- Pathfinding: Dijkstra algorithm for optimal routing (AMM + orderbook, up to 3 hops)
- Quote generation: Deterministic quotes with QuoteHash (blake2b-256)
- Fee injection: Transparent routing fee (20 bps default) included in hash
- Circuit breakers: Price deviation detection with automatic rejection
- Security: Namespace isolation, memory limits, audit logging
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
)
- 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)
- Namespace isolation: quotes, rate_limits, circuit_breaker
- Memory limits: 512MB cap with LRU eviction
- TTL support: Automatic expiration
- Concurrent safety: Tested with 200+ goroutines
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:
- Quote requests (success/rejected)
- Circuit breaker triggers
- Validation errors
- No PII: Amounts hashed, no IP addresses
- 90-day retention
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
- Nodes: Assets (XRP, USD.issuer, BTC.issuer, etc.)
- Edges: AMM pools (bidirectional) + orderbook offers (unidirectional)
- Weights: Fee multipliers (1 - fee_bps/10000)
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)
- Default: 20 bps (0.2%)
- Included in QuoteHash: Tamper-evident
- Transparent: Shown in quote response
Trading Fees
- AMM pools: Set by pool creator (typically 30 bps)
- Orderbook: None (taker pays quality/price only)
Test Coverage
| Router Components | 92.1% |
| KV Store | 92.5% |
| Database Layer | 26.0% (mocked) |
| Race Detector | 0 races |
Security Test Suite
- Memory exhaustion protection
- Concurrent access safety (200 goroutines)
- Namespace isolation
- Input validation bypass attempts
- Quote replay prevention
- SQL injection prevention
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
- 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):
- Initial production release
- Pathfinding with Dijkstra algorithm
- Deterministic QuoteHash (blake2b-256)
- Circuit breaker with caution mode
- KV store with namespace isolation
- Comprehensive test coverage (92.1%)
- Zero technical debt