Liquidity Risk Engine
Coordinated risk controls for institutional DeFi liquidity. Real-time pool health monitoring, concentration risk detection, impermanent loss mitigation, and adaptive circuit breakers for AMM v5 operations.
Liquidity is discontinuous, reflexive, and frequently adversarial. Every trading platform without a dedicated risk engine is one flash crash away from catastrophic failure.
Traditional DEX designs assume liquidity is always available and rational. Reality is harsher: liquidity is discontinuous, reflexive, and frequently adversarial. The 2022-2023 DeFi crises demonstrated that liquidity can evaporate within minutes, cascading across protocols and causing billions in losses. Without a dedicated risk engine, every trading platform is one flash crash away from catastrophic failure.
| Risk Category | Description | Real-World Impact |
|---|---|---|
| Concentration Risk | Small number of LP positions or wallets dominate pool depth | Single LP exit can cause 80%+ slippage spike in seconds |
| Liquidity Flight | LPs withdraw when volatility rises, causing sudden slippage cliffs | Reflexive: volatility causes withdrawals, which cause more volatility |
| Toxic Flow | MEV bots, arbitrage dominance, and informed flow extract value from uninformed traders | Estimated $1.2B+ extracted annually from DEX users via sandwich attacks |
| Route Fragility | Single-venue execution fails when pools are stressed or fragmented | Users face reverts, partial fills, and excessive slippage during stress events |
| Oracle Manipulation | Price feed attacks distort risk calculations and enable extraction | Manipulated oracles caused $200M+ in DeFi exploits in 2023 alone |
| Governance Capture | Single entity or jurisdiction controls risk parameters | Centralized admin keys exploited in multiple protocol compromises |
Liquidity risk is adversarial as often as it is natural. A risk engine must defend against intentional exploitation (MEV, oracle gaming, pool drain attacks) and natural market dynamics (volatility-driven LP flight, correlated stress events) simultaneously. JIL's engine addresses both through policy-bound controls and distributed governance.
Explicitly modular. No single component has unilateral authority over execution decisions.
JIL's trading stack delivers liquidity risk as coordinated services and contracts, with each component serving a distinct role in the risk control chain.
| Component | Port | Role in Liquidity Risk Control |
|---|---|---|
| liquidity-risk | 8898 | Concentration assessment, pool health scoring, threshold alerts |
| liquidity-analytics | 8903 | Real-time depth calculation, utilization rates, regime classification |
| settlement-router | 8081 | Multi-venue routing and execution orchestration |
| rfq-service | 8091 | Institutional OTC quotes when DEX execution is unsafe |
| ammv5-core | (crate) | AMM V5 execution features: batch auctions, TWAMM, slippage tolerance |
| oracle | (contracts) | Chainlink/Pyth price normalization for risk measures and USD conversions |
| corridor-governance | (policy) | Defines allowed venues, throttles, and fees per corridor |
Data Flow Architecture
Circuit Breaker Design
The engine implements a four-state machine that governs the entire trading stack. Transitions are triggered by measurable on-chain conditions, not human judgment. Each state progressively restricts execution to protect users during stress.
| State | AMM | RFQ | Batches | Withdrawals | Trigger |
|---|---|---|---|---|---|
| NORMAL | Full | Full | Standard | Instant | Baseline operations |
| ELEVATED | Wider spreads | Full | Reduced caps | Instant | Volatility above 2-sigma |
| STRESSED | Throttled | First priority | Minimal | Queued | Depth below 30% of normal |
| HALTED | Disabled | Disabled | None | Governance required | 14-of-20 validator consensus |
NORMAL -> ELEVATED -> STRESSED -> HALTED. Resume follows the reverse path with graduated controls. The HALTED state can only be entered or exited via multi-sig governance action from the 14-of-20 validator set.
Liquidity risk is not a single number. The engine maintains a real-time scorecard combining pool structure, market regime, and flow quality.
Each metric feeds into the regime classification system and determines whether the current execution environment is safe.
| Metric | Description | Update Frequency |
|---|---|---|
| Depth and Slope | Effective liquidity at multiple price bands (+/- 1%, 2%, 5%, 10%) | Per block (1.5s) |
| Concentration Score | Share of liquidity controlled by top LP positions; the "exit risk" metric | Per block (1.5s) |
| Utilization Rate | Swap volume vs available depth; how rapidly liquidity is being consumed | Rolling 5-minute window |
| Slippage Analytics | Observed vs expected slippage per trade; symptom of poor depth and toxic flow | Per transaction |
| Volatility Regime | Normal vs stressed classification using realized volatility bands | Rolling 1-hour window |
| Withdrawal Velocity | Rate of LP position removal; early warning signal for liquidity flight | Rolling 15-minute window |
| Risk Envelopes | Conservative bounds under tail moves used for gates and throttles | Recalculated hourly |
Concentration Scoring
Concentration risk explains most sudden liquidity collapses. When a small number of LPs can withdraw, the pool's slippage surface changes abruptly and nonlinearly. The engine treats this as a measurable hazard and routes or throttles flow before the hazard expresses itself as user harm.
Herfindahl-Hirschman Index (HHI)
Sum of squared LP share percentages. HHI above 2500 triggers ELEVATED state and alerts for concentrated pools.
Top-N Exit Impact
Simulates the slippage impact if the top 3 or top 5 LPs withdraw simultaneously. Exceeding 15% impact triggers RFQ-first routing.
LP Tenure Weighting
Recently added liquidity is weighted higher in risk scoring since new LPs are statistically more likely to withdraw during stress.
Cross-Pool Correlation
Detects when the same LP addresses dominate multiple pools, indicating correlated withdrawal risk across the protocol.
Depth Profiling
The engine calculates effective depth at multiple price bands rather than relying on total value locked (TVL), which masks the distribution of liquidity across the price curve. A pool with $100M TVL concentrated in a narrow range is far more fragile than one with $50M distributed evenly.
Three authority levels. Increasing human involvement, decreasing response speed.
This layered model ensures that common conditions are handled instantly while extraordinary situations receive appropriate governance scrutiny.
Autonomous Controls (On-Ledger)
These controls execute automatically based on on-chain conditions. No human action is required and no human can prevent them from executing when conditions are met.
Oracle Band Enforcement
Trades are rejected if the execution price deviates beyond configurable bands from oracle-reported prices. Prevents stale oracle exploitation.
Batch Cap Limits
Maximum trade size per batch is automatically reduced as depth decreases. Prevents any single trade from consuming disproportionate depth.
Slippage Protection
Per-swap slippage tolerance enforced at the contract level. Users cannot be impacted beyond their stated tolerance regardless of market conditions.
State Transitions
Automatic escalation from NORMAL to ELEVATED to STRESSED based on real-time metric thresholds. No admin intervention needed.
Risk Engine Adaptive Controls
Signed, time-limited decisions from the risk engine that adapt to changing conditions. These controls have bounded authority and produce auditable decision records.
| Control | Authority | Duration | Audit Trail |
|---|---|---|---|
| Spread Widening | Risk engine auto-sign | Max 4 hours | On-chain epoch record |
| Venue Throttling | Risk engine auto-sign | Max 2 hours | On-chain epoch record |
| RFQ-First Routing | Risk engine auto-sign | Max 8 hours | On-chain epoch record |
| Batch Size Reduction | Risk engine auto-sign | Max 1 hour | On-chain epoch record |
Human Governance Controls (Emergency)
Multi-signature actions requiring validator consensus. Used for extraordinary situations that cannot be handled by autonomous or adaptive controls.
HALT / Resume
14-of-20 multi-sig
Key Rotation
Guardian ceremony
Parameter Update
24-hour timelock
Corridor Change
Validator consensus
Controls MUST NOT confiscate user funds, retroactively reprice settled trades, censor transactions without producing auditable receipts, or exercise unbounded discretion. All emergency actions are time-bounded and require multi-jurisdictional validator approval.
Four categories of threats: extraction, griefing, Sybil attacks, and natural stress scenarios.
Liquidity risk is adversarial as often as it is natural. The engine must defend against intentional exploitation and natural market dynamics simultaneously.
Extraction Attacks
| Attack | Technique | JIL Mitigation | Result |
|---|---|---|---|
| Batch Stuffing | Fill batch auction slots to exclude legitimate trades | VRF-randomized ordering within batches; priority fee auction for slot access | MITIGATED |
| Oracle Gaming | Manipulate price feeds to distort risk calculations | Multi-oracle aggregation (Chainlink + Pyth); confidence weighting; staleness rejection | MITIGATED |
| Toxic Flow | MEV extraction via sandwich attacks and frontrunning | Batch auctions eliminate ordering advantage; commit-reveal for transaction privacy | MITIGATED |
| Inventory Skew | Force AMM into extreme price ranges to exploit rebalancing | Concentration detection triggers TWAMM routing; maximum position limits per address | MITIGATED |
Griefing Attacks
| Attack | Technique | JIL Mitigation |
|---|---|---|
| RFQ Spraying | Send thousands of quote requests with no intent to execute | Rate limiting per BPoH identity; reputation scoring for market makers |
| Order/Cancel Storms | Rapidly place and cancel orders to consume system resources | Minimum order TTL; cancellation fee above threshold frequency |
| Settlement Failures | Intentionally fail settlement to disrupt counterparties | Escrow-first execution; settlement bonds; failure penalty escalation |
| Circuit Breaker Abuse | Deliberately trigger STRESSED state to halt trading | Multi-metric triggers (no single vector can force state change); hysteresis on transitions |
Sybil and Stress Scenarios
Sybil Cluster Detection
Related wallets identified through on-chain graph analysis are treated as a single entity for concentration scoring. Prevents LP fragmentation from gaming the HHI metric.
Withdrawal Stampedes
When withdrawal velocity exceeds 3-sigma of normal, the engine activates queued withdrawals with proportional allocation to prevent first-mover advantage.
Pool Drain Dynamics
Concentration assessment detects when a small LP set can remove most depth quickly. Automatic corridor containment activates before the drain completes.
Contagion Prevention
Failures in one venue or pool are isolated. The routing and corridor containment layers prevent cascading failures across the protocol.
Mechanisms specifically aligned with stress resilience and execution integrity.
Each AMM V5 feature directly reduces a class of risk that the engine monitors and controls.
| Feature | Mechanism | Risk Reduction |
|---|---|---|
| Constant Product (x*y=k) | Predictable base curve for depth and impact modeling | Enables precise slippage prediction and risk envelope calculation |
| Batch Auctions | VRF-randomized ordering within auction windows | Eliminates MEV extraction during congested or volatile periods |
| TWAMM | Time-weighted average market maker for large orders | Reduces instantaneous impact; spreads execution across multiple blocks |
| ERC-4626 Vaults | Standardized LP accounting with share-based positions | Cleaner analytics, attribution, and reporting for risk decisions |
| Per-Swap Slippage Protection | Hard revert if price impact exceeds user-specified tolerance | Absolute user protection against pathological price impact events |
Batch Auction Risk Properties
Batch auctions are the primary defense against MEV extraction. By collecting trades within a time window and executing them at a uniform clearing price with VRF-randomized ordering, the engine eliminates the ordering advantage that enables sandwich attacks, frontrunning, and backrunning.
Each batch auction uses a Verifiable Random Function to determine execution order within the batch. This means no participant, including validators, can predict or manipulate the ordering of trades within a batch. Combined with commit-reveal transaction submission, this provides strong MEV resistance.
TWAMM for Institutional Orders
Time-Weighted Average Market Maker execution splits large orders across multiple blocks, reducing the instantaneous price impact that makes large trades targets for extraction. The settlement router automatically routes institutional-size orders to TWAMM when the risk engine determines that single-block execution would create damaging impact.
ERC-4626 Vault Accounting
Standardized vault accounting enables the risk engine to monitor LP positions with precision. Share-based accounting eliminates the complexity of tracking individual LP ranges and provides clean inputs for concentration scoring, withdrawal velocity tracking, and exit impact simulation.
Execution rules for the entire trading stack. Risk posture cannot be silently weakened.
Each corridor specifies allowed venues, fee structures, throttle limits, and escalation conditions. Corridor changes follow a ceremony flow with validator consensus and a timelock.
| Corridor | Venues Allowed | Fee | Throttle | Use Case |
|---|---|---|---|---|
| default | DEX + RFQ | 2 bps | 6,000/min | Normal operations, all users |
| protected | RFQ only | 5 bps | 3,000/min | Protected zone accounts (KYC verified) |
| unprotected | DEX only | 2 bps | 6,000/min | Permissionless retail |
| containment | Lifeline only | 25 bps | 60/min | Emergency mode, settlement only |
Governance Ceremony Flow
Any change to corridor policies must traverse a multi-step ceremony that prevents unilateral modification of risk parameters.
Distributed Governance
| Governance Aspect | Value |
|---|---|
| Validator Count | 20 |
| Jurisdictions | 13 (CH, ADGM, SG, USA, EU, UK, CA, JP, AU, LATAM, BR, HK, NL) |
| Consensus Threshold | 14-of-20 (70% BFT) |
| Corridor Changes | Require validator consensus + 24-hour timelock |
| Emergency Actions | Multi-sig with geographic distribution |
| Timelock Duration | 24 hours for policy changes, immediate for HALT only |
Distributing the validator set across 13 jurisdictions means no single regulator, government, or corporate entity can compel a corridor change. The 14-of-20 threshold (70% BFT) ensures that even if 6 validators in coordinated jurisdictions are compromised or coerced, the remaining 14 maintain governance integrity.
The execution interface that incorporates risk signals before committing trades.
The Settlement Router operates as the enforcement point for all risk engine decisions, corridor policies, and venue steering logic.
API Surface
Risk-Aware Routing Capabilities
Venue Selection
Prefer venue with best risk-adjusted execution: lowest impact per unit size, factoring in depth, concentration, and current regime state.
Order Splitting
Split orders using TWAMM or batch auctions when size would create damaging market impact. Splitting parameters are determined by real-time depth analysis.
RFQ Escalation
Route institutional-size orders to RFQ when pool depth is unsafe or concentrated. Market makers provide firm quotes with execution guarantees.
Trade Rejection
Reject or delay trades that violate corridor throttles, slippage tolerances, or would push the pool into an unsafe state. Provides clear reason codes.
Failure Modes
| Failure Mode | Detection | Response |
|---|---|---|
| Venue Unreachable | Health check timeout (>500ms) | Automatic failover to next venue in corridor priority list |
| Insufficient Depth | Simulated impact exceeds tolerance | Route to RFQ or queue for TWAMM execution |
| Oracle Stale | Price feed age exceeds 60 seconds | Reject new trades; allow withdrawals at last known price |
| Settlement Timeout | No confirmation within 30 seconds | Automatic retry with exponential backoff; DLQ after 3 failures |
| Corridor Exhausted | Throttle limit reached | Queue with priority ordering; clear reason code to user |
Multi-Venue Execution
The router maintains live connections to all venues authorized within the active corridor. Venue health is monitored continuously, and the routing table updates in real time based on depth availability, concentration scores, and latency measurements. This ensures that no single venue failure can disrupt execution for the entire protocol.
Each validator node processes settlements for its authorized compliance zones via RedPanda message queues. Zone-specific topics (e.g., jil.settlement.DE_BAFIN, jil.settlement.SG_MAS) ensure that settlement messages are consumed only by validators authorized for that jurisdiction, maintaining regulatory compliance at the infrastructure level.
From foundation to production hardening in four phases.
Phase 1 - Foundation (Months 1-3)
Deploy liquidity-analytics and liquidity-risk services. Implement depth profiling, concentration scoring, and basic regime classification. Integrate with AMM V5 batch auctions. TestNet validation across 5 Hetzner nodes.
Phase 2 - Venue Steering (Months 4-6)
Settlement router integration with risk-aware routing. RFQ escalation logic. Corridor policy enforcement. TWAMM routing for institutional orders. Multi-oracle aggregation with confidence weighting.
Phase 3 - Governance Layer (Months 7-9)
14-of-20 validator governance for corridor changes. 24-hour timelock ceremony flow. Emergency HALT/resume with geographic distribution. Audit trail with on-chain epoch records.
Phase 4 - Production Hardening (Months 10-12)
MainNet deployment across 20 validators in 13 jurisdictions. Sybil cluster detection. Cross-pool correlation monitoring. Withdrawal stampede protection. Full P2P settlement via RedPanda zone topics.
Key Milestones
- Complete liquidity-risk service deployment with concentration scoring, HHI calculation, and top-N exit impact simulation across all active pools.
- Integrate settlement router with risk engine for real-time venue steering based on depth, concentration, and regime classification signals.
- Deploy corridor governance ceremony with 14-of-20 validator consensus, 24-hour timelock, and on-chain epoch binding.
- Validate circuit breaker state machine through chaos engineering across TestNet, including simulated flash crashes, LP withdrawal stampedes, and oracle failures.
- Achieve MainNet readiness with 20 validators across 13 jurisdictions processing zone-authorized settlements via P2P RedPanda architecture.
Coordinated risk controls for institutional-grade liquidity.
JIL Sovereign's Liquidity Risk Engine delivers real-time pool health monitoring, adaptive circuit breakers, and distributed governance across 13 jurisdictions - purpose-built for institutional AMM operations.