Architecture Deep Dive

A detailed look at the internal architecture powering GRID's delta-managed liquidity strategy.


System Overview

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     Grid Liquidity Bot                        β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                  β”‚
β”‚  β”‚ GridCoordinator│◄────►│PositionActors  β”‚                  β”‚
β”‚  β”‚  (orchestrator)β”‚      β”‚(per position)  β”‚                  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚
β”‚          β”‚                        β”‚                           β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”                  β”‚
β”‚  β”‚LiquidityManagerβ”‚    β”‚  BalanceActor    β”‚                  β”‚
β”‚  β”‚(Orca operations)β”‚   β”‚  (monitoring)    β”‚                  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚
β”‚           β”‚                                                   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                  β”‚
β”‚  β”‚  Volatility     β”‚   β”‚   Registry       β”‚                  β”‚
β”‚  β”‚  Regime         β”‚   β”‚  (persistence)   β”‚                  β”‚
β”‚  β”‚  Detector       β”‚   β”‚                  β”‚                  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚
                     β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
                     β”‚  API Server β”‚ (HTTP REST)
                     β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
                            β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   Hedge Engine (TypeScript)                   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚Delta Monitor │───►│Position Manager│◄──│Drift Protocolβ”‚   β”‚
β”‚  β”‚(calculates)  β”‚    β”‚(executes hedges)β”‚  β”‚  (perpetuals)β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Actor System (Rust)

The LP engine uses an actor-based architecture for concurrent position management. Each actor operates independently with message-passing for coordination.

GridCoordinator

The central orchestrator managing all position actors:

Message Routing

Routes messages between actors using priority queues. Priorities: Critical β†’ High β†’ Normal β†’ Low. Critical operations (position opening, emergency shutdowns) always execute first.

Balance Coordination

Handles balance requests from position actors via BalanceActor. Requests have 5-second timeout with correlation IDs for response matching.

Supervisor Pattern

Runs health checks every 30 seconds. Automatically restarts failed actors. Circuit breaker opens after consecutive failures to prevent cascading issues.

PositionActor

One actor per liquidity position, handling complete lifecycle:

State Machine:

NotCreated β†’ Pending β†’ Active ⇄ OutOfRange β†’ Rebalancing β†’ Active β†’ Closed
                ↓
           Error (recoverable/non-recoverable)

Key Operations:

  • Initialize: Crash recovery checks for orphaned on-chain positions
  • Health Check: Monitors range boundaries, fee accumulation
  • Rebalance: Closes position, calculates new range, opens with fresh parameters
  • Close: Removes liquidity, harvests fees, burns position NFT

BalanceActor

Dedicated actor for wallet balance monitoring:

  • Caching: Balance data cached with configurable TTL to reduce RPC load
  • On-chain Fetch: Direct RPC calls for accurate position data when needed
  • Circuit Breaker: Tracks failures, opens after threshold, half-opens for tests

Liquidity Management

LiquidityManager

Primary interface for all Orca Whirlpool operations:

MethodDescription
open_strategic_position()Opens position with volatility-calculated range
close_position()Closes position, returns liquidity to wallet
harvest_fees()Collects accumulated trading fees
increase_liquidity()Adds more liquidity to existing position
decrease_liquidity()Removes liquidity from position

Position Opening Flow

  1. Duplicate Check: Verify position doesn't already exist on-chain
  2. Volatility Fetch: Get 24h historical prices from Pyth
  3. Range Calculation: EWMA-smoothed volatility β†’ tick range
  4. Wallet Rebalance: Swap tokens to achieve required ratio
  5. Liquidity Calculation: Exact token amounts for price range
  6. Transaction Build: Priority fees + optional Jito bundle
  7. Submission: Exponential backoff confirmation polling
  8. Registry Update: Persist NFT mint, ticks, metadata

WalletRebalancer

Ensures correct token ratios before position operations:

Current Balances β†’ Target Calculation β†’ Tolerance Check β†’ Swap Execution β†’ Verification

Features:

  • WebSocket balance monitoring (optional, with polling fallback)
  • Swap execution through Orca with slippage protection
  • Exponential backoff on balance verification

Volatility Analysis

VolatilityConfig

Default parameters for volatility calculation:

ParameterDefaultDescription
Lookback Hours24Historical price window
Interval Mins60Price sampling interval
Min Observations20Required data points
Max Threshold110%Volatility cap
Min Threshold5%Volatility floor

Volatility Regime Detector

Monitors for significant volatility changes:

RegimeVolatilityStrategyCapital Factor
Crab< 3% dailyAggressive (tight ranges)1.2x
Normal3-8% dailyBalanced1.0x
Blast> 8% dailyConservative (wide ranges)0.7x

Regime Change Handling:

  • Rate limited to prevent excessive rebalancing
  • Minimum interval between rebalances enforced
  • Emergency threshold for immediate action

Hedge Engine Architecture

Component Overview

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                      Hedge Engine                            β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                  β”‚
β”‚  β”‚ RustBotClient   β”‚  β”‚  DriftClient     β”‚                  β”‚
β”‚  β”‚ (delta fetch)   β”‚  β”‚  (perp trading)  β”‚                  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚
β”‚           β”‚                    β”‚                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”                  β”‚
β”‚  β”‚         HedgeEngine / DynamicHedge    β”‚                  β”‚
β”‚  β”‚  β€’ Delta calculation                   β”‚                  β”‚
β”‚  β”‚  β€’ Hedge decision logic                β”‚                  β”‚
β”‚  β”‚  β€’ Trade execution                     β”‚                  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚
β”‚                       β”‚                                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                  β”‚
β”‚  β”‚         ExecutionController           β”‚                  β”‚
β”‚  β”‚  β€’ Deadband filter                     β”‚                  β”‚
β”‚  β”‚  β€’ Proportional sizing                 β”‚                  β”‚
β”‚  β”‚  β€’ Market condition adjustments        β”‚                  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚
β”‚                       β”‚                                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                  β”‚
β”‚  β”‚         CollateralManager             β”‚                  β”‚
β”‚  β”‚  β€’ Auto deposit/withdraw               β”‚                  β”‚
β”‚  β”‚  β€’ Ratio maintenance                   β”‚                  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

MA-Adaptive Policy

Moving average-based hedge ratio adjustment:

regime = price > MA + band ? 'up'
       : price < MA - band ? 'down'
       : 'neutral';

hedgeRatio = regime === 'up'      ? uptrendRatio    // e.g., 40%
           : regime === 'down'    ? downtrendRatio  // e.g., 100%
           : neutralRatio;                          // e.g., 70%

Optional Tilts:

  • Funding Sensitivity: Reduce hedging when funding is expensive
  • Volatility Sensitivity: Adjust based on ATR percentage

Execution Controller Logic

deltaError = targetShort - currentShort

if (|deltaError| < deadband) β†’ skip
if (timeSinceLastTrade < cooldown) β†’ skip

intensity = proportionalGain
intensity *= fundingPenalty      // reduce if funding expensive
intensity *= spreadPenalty       // reduce if spread wide
intensity *= liquidityScore      // reduce in poor liquidity

orderSize = clamp(intensity Γ— deltaError, minTrade, maxTrade)

Transaction Management

TransactionManager

Handles all blockchain transaction lifecycle:

Priority Tiers:

TierUse CaseFee Multiplier
LOWNon-urgent operations1x
MEDIUMNormal operations1.5x
HIGHTime-sensitive trades2x
TURBOCritical operations5x

Features:

  • Dynamic compute unit estimation
  • Jito bundle integration for MEV protection
  • Exponential backoff retry logic
  • Fresh blockhash on expiration errors

Error Recovery

Error TypeRecovery Strategy
TokenMinSubceededIncrement slippage tolerance, retry
Blockhash ExpiredFetch new blockhash, retry
Simulation FailedLog details, abort transaction
TimeoutExponential backoff, up to max retries
RPC ErrorCircuit breaker, fallback endpoint

Resource Management

ResourceManager

Global resource pooling for efficiency:

RPC Client Pool

Reuses RPC clients instead of creating new connections. Max 10 clients in pool. Automatic failover to backup endpoints on failure.

Token Decimals Cache

Token decimals cached permanently (no TTL). Eliminates redundant RPC calls for commonly used tokens.

Whirlpool State Cache

Pool state cached with 5-second TTL. Balances freshness with RPC efficiency for frequently accessed data.


Data Persistence

PositionsRegistry

Thread-safe state management for positions:

Storage Format: TOML files

  • positions_config.toml: Static configuration
  • positions_registry.toml: Runtime state (NFTs, liquidity, metrics)

Features:

  • Atomic writes prevent corruption
  • On-chain sync reconciles local vs blockchain state
  • Tracks: fees earned, rebalance count, APR, PnL

Communication Flow

LP Engine β†’ Hedge Engine

GET /api/delta
Response: {
  delta: number,          // LP delta in USD
  lpNotional: number,     // Total position value
  confidence: number,     // Calculation confidence
  timestamp: string
}

The hedge engine polls this endpoint, calculates required hedge adjustment, and executes trades on Drift Protocol to maintain target delta.


Was this page helpful?