Diffusal

Backend Operations

Off-chain validation, keeper coordination, and server operations

Backend operations complement the on-chain protocol with off-chain validation, data indexing, and keeper coordination.

Architecture Overview

The backend consists of multiple specialized servers:

ServerPurposePublic
API ServerREST API for market data and account infoYes
WebSocket ServerReal-time market data streamsYes
RFQ ServerRequest-for-quote handlingYes (with auth)
Operator ServerTransaction relay and matchingNo
Keeper ServerAutomated liquidations and settlementsNo

See Backend Architecture for detailed server descriptions.

Pre-Trade Margin Validation

Before any trade is submitted on-chain, the backend validates:

  1. Portfolio Health Check: Verify post-trade equity ≥ initial margin
  2. Stress Test: Ensure portfolio survives 4-corner stress scenarios
  3. Deposit Sufficiency: Confirm sufficient deposit for premium obligations

Validation Flow

User → Submit Order → Backend Validation → On-Chain Submission

                    [Check Failed]

                    Return Error (No Gas Spent)

This prevents users from spending gas on transactions that would revert.

Margin Check Endpoint

// POST /helpers/validate-trade
{
  "portfolioId": "123",
  "trade": {
    "seriesId": "...",
    "size": "1000000000000000000",
    "isBuy": true
  }
}

Response includes:

  • preTradeHealth: Current portfolio state
  • postTradeHealth: Projected state after trade
  • isValid: Whether trade passes validation
  • errors: Specific validation failures

Settlement Readiness Checks

The backend continuously monitors portfolios for settlement readiness:

  1. Identify Expiring Positions: Find positions within 24 hours of expiry
  2. Calculate Obligations: Determine worst-case settlement obligations
  3. Check Cash Coverage: Verify deposited cash ≥ obligations
  4. Trigger Liquidation: Alert keepers if liquidation is needed

Liquidation Alerts

When a portfolio fails settlement readiness:

// Alert payload
{
  "portfolioId": "123",
  "reason": "INSUFFICIENT_CASH",
  "obligation": "8000000000",  // $80,000 in USDC decimals
  "cash": "2000000000",        // $20,000 in USDC decimals
  "expiry": "1736409600",
  "recommendedAction": "LIQUIDATE_TO_TARGET"
}

Keeper Coordination

The backend coordinates keeper operations without controlling them:

  • Price Monitoring: Track oracle prices and identify snapshot opportunities
  • Liquidation Opportunities: Broadcast liquidatable portfolios to registered keepers
  • Settlement Triggers: Monitor expiry times and alert keepers

Keeper Registration

Keepers register with the backend to receive:

  • Real-time liquidation opportunities
  • Settlement timing alerts
  • Gas price recommendations

Data Indexing

The indexer (Ponder) provides:

  • Portfolio State: Current positions, balances, and health
  • Historical Data: Past trades, settlements, and liquidations
  • Market Data: Orderbook state, recent trades, oracle prices

Query Patterns

Common indexed queries:

# Get portfolio positions
query {
  portfolio(id: "123") {
    positions {
      series {
        symbol
        expiry
        strike
      }
      optionBalance
      entryMark
    }
    collateral
    health
  }
}

Error Handling

Backend validation errors prevent on-chain reverts:

Error CodeCauseResolution
INSUFFICIENT_MARGINPost-trade equity < IMDeposit more collateral or reduce position size
STRESS_TEST_FAILED4-corner scenario loss exceeds thresholdReduce position concentration
INSUFFICIENT_DEPOSITDeposit < premium obligationDeposit more USDC
INVALID_SERIESSeries does not existCheck series ID
EXPIRED_SERIESSeries already expiredCannot trade expired options

On this page