DeFi Risk Engine

Technical documentation for the defi-risk-engine repository.

Whitepaper | Quantir UI Walkthrough | Use Cases | DeFi Risk Engine | Roadmap

This page is part of the externalized documentation layer that sits beside the main Quantir whitepaper. The whitepaper should stay focused on narrative, methodology, validation framing, and buyer logic, while the deeper runtime and service-level description of the system can live here.

What This System Is

defi-risk-engine is a monitoring and risk-explanation platform for DeFi protocols. It consists of several independent runtime services that together do the following:

Main Runtime Parts

Service Path Role
API service api/ Auth, dashboard/bootstrap API, watchlist, alerts, websocket token issuance
On-chain engine src/onchain_data/ Main ingestion runtime, snapshots, tx events, charts, audit hydration
Explain service src/explain_service/ Durable explain jobs and provider ensemble
Alert system src/alert_system/ Router/worker delivery pipeline via Redis Streams
Forecast system src/forecast_system/ Chronos-based short-horizon forecasting
Risk model src/risk_model/ Rust scoring service for base risk
Off-chain news worker src/offchain_data/ RSS/Atom ingestion for protocol_news

System Architecture

System Architecture
System architecture diagram of the DeFi risk engine and its main service interactions.

Main Data Flow

  1. src/onchain_data/index.js starts the engine, connects to MongoDB, and syncs the protocol catalog.
  2. Collectors gather TVL, whale, tx behavior, token health, candles, and historical bootstrap data.
  3. The engine computes derived metrics and calls the Rust risk model.
  4. The engine obtains forecasts from the forecast service and stores precomputed chart artifacts.
  5. The engine writes protocolsnapshots, tx_risk_events, protocolchartpayloads, and marketcandles.
  6. The engine sends explain requests to src/explain_service/ when needed.
  7. The off-chain news worker writes protocol_news.
  8. The alert router/worker reads events, routes delivery jobs, and writes user notifications.
  9. api/ reads MongoDB and serves user-scoped payloads to risk-ui.
  10. The frontend gets a websocket token through POST /api/ws/token and connects to the alert socket.

Repository Landscape

Layer Path Role
Core runtime src/onchain_data/ Main engine runtime
Core runtime src/explain_service/ Explain jobs, provider orchestration, and fusion
Core runtime src/alert_system/ Router and worker alerts pipeline
Core runtime src/forecast_system/ Node orchestration for Chronos forecasting
Core runtime src/risk_model/ Rust scoring service
Core runtime src/offchain_data/ Off-chain protocol news ingestion
Shared contracts and persistence src/db/ Mongo connection, schemas, and repositories
Shared contracts and persistence src/bootstrap/ Startup helpers and initial catalog sync
Shared contracts and persistence src/strategies/ Transaction-driven risk adjustment
Shared contracts and persistence src/config_builder/ Generator for src/onchain_data/config/protocols.json
User-facing delivery api/ Authenticated backend for the dashboard
User-facing delivery risk-ui/ Frontend application
Historical / legacy layers src/routers/ Express-era routers
Historical / legacy layers src/services/ Express-era service helpers
Historical / legacy layers src/modules/ Shared domain helpers between the legacy layer and the newer api/src/modules/

On-Chain Engine

Purpose

src/onchain_data/ is the central runtime of the entire platform. It is responsible for:

Bootstrap Sequence

src/onchain_data/index.js starts the engine in this order:

  1. connect to MongoDB
  2. sync protocol metadata from config/protocols.json
  3. hydrate stored ABI and contract-audit intelligence
  4. start the alerts websocket API
  5. bootstrap missing snapshots
  6. bootstrap scheduled explain requests
  7. start transaction monitoring
  8. start the model explanation loop
  9. start periodic collector loops
  10. asynchronously refresh contract audits

Main Responsibilities

Key Components

TVLCollector, WhaleCollector, TxBehaviourCollector, TokenRiskProfileCollector, CandleCollector, HistoricalBootstrapCollector

explain rule matching, context construction, dispatch

precomputed payload generation for dashboard charts

contract capability audit and ABI hydration

collector base abstractions and websocket helpers

Strategy-Adjusted Risk

After the base model score, the system adds a transaction-driven contribution.

Formula used by the strategy layer:

R_total = clamp01(R_base + Delta_tx)

Where:

Illustration:

Risk Scoring Dynamics
Risk Scoring Dynamics

Explain Service

What It Does

src/explain_service/ does not calculate risk itself. It turns already-normalized risk context into durable explanation jobs:

Main Use Cases

Providers

The current implementation uses a practical provider ensemble:

Runtime Architecture

cooldown handling, duplicate active jobs, duplicate event_id

creates durable explain job payloads and reconstructs context for manual requests

runs enabled providers in parallel and writes job state transitions

fuses successful provider outputs into judge_result, final_summary, and confidence

Explain Service Diagrams

Conceptual Architecture

Explain Service Architecture
Explain Service Architecture

Agent Weighting Reference

Explain Service Agent Weighting
Explain Service Agent Weighting

Example Hypothesis Distribution

Explain Service Hypothesis Distribution
Explain Service Hypothesis Distribution

Model Explanation Loop

This is a separate loop from explain_service.

explains the current model state over a time window

explains a specific event or trigger through provider fusion

What The Loop Does

For each protocol it:

  1. selects a recent time window
  2. loads recent ProtocolSnapshot
  3. loads recent TxRiskEvent
  4. builds a prompt payload
  5. requests a concise explanation
  6. persists the result into protocol_risk_explanations

Outputs

API Service

Purpose

api/ is an authenticated Next.js backend that reads data already persisted by engine-side services and exposes UI-friendly contracts.

It is responsible for:

Main Route Groups

NextAuth entrypoint

credentials registration

authenticated dashboard-facing data APIs

watchlist and settings flows

websocket JWT issuance

Telegram account linking

liveness/readiness

Core Service Modules

builds bootstrap payloads, metrics, precomputed chart payloads, and fallbacks

watched protocols and alert subscriptions

reads tx_risk_events and produces UI-ready alerts

reads protocol_news, normalizes aliases, and deduplicates articles

exposes stored protocol_risk_explanations

lists explain_jobs and forwards manual explain requests

exposes stored audit artifacts

resolves plan capabilities and protocol limits

signs short-lived websocket tokens

API Module Map

Module Responsibility Main Data / Contract
auth NextAuth config, providers, JWT/session enrichment session, JWT, redirect allowlist
users user and Telegram-link persistence models users, telegram_link_tokens
userContext resolve authenticated Mongo user from session withUser(...) boundary
dashboard bootstrap payloads, metrics, charts, fallbacks protocolsnapshots, protocolchartpayloads, marketcandles
monitor watchlist, subscriptions, monitor settings user_protocols, user_alert_protocols, user_settings
alerts UI-shaped risk event feed and counters tx_risk_events
news normalized news feed for watchlist and protocol pages protocol_news
model-explanation recent interval-level model explanations protocol_risk_explanations
explain list explain jobs and forward manual explain requests explain_jobs, EXPLAIN_SERVICE_URL
contract-audit expose stored audit findings and capability maps protocol_contract_audits
subscription plan limits and feature flags plan to capability mapping
plans minimal shared plan helper plans.ts
notifications in-app notification persistence model user_notifications
protocol warm enabled-protocol cache for reads in-memory protocol cache
candle_chart external price-candle fallback loader CoinGecko candle contract
ws websocket JWT issuance short-lived HS256 token

Main Endpoints

Bootstrap And Metrics

Monitor / Watchlist

Alerts / News / Explanations

Realtime / Ops

Alert System

src/alert_system/ is split into two runtime stages:

Router

Worker

Why This Split Exists

This removes the for user -> await deliver bottleneck and allows delivery to scale horizontally.

Main Files

Forecast System

src/forecast_system/ is a standalone Node.js service for short-horizon protocol forecasting.

Pipeline

  1. read protocol snapshots and tx risk events from MongoDB
  2. build fixed time buckets (15m or 1h) and store them in protocol_metrics_ts
  3. send metric series to the local Chronos endpoint (Python adapter)
  4. recompute future risk from forecasted metrics
  5. store future bars in predicted_risk_ts

Components

Metrics Sent To Chronos

Risk Model

src/risk_model/ is a Rust scoring service that turns normalized protocol features into a base risk score.

Input Features

Runtime Modes

HTTP Contract

POST /score

Request:

{
  "tvl": 1000000,
  "tvl_delta_1d": 0.01,
  "tvl_delta_7d": -0.03,
  "price_delta_1d": 0.02,
  "price_delta_7d": -0.09,
  "volume_spike": 0.6,
  "mcap_tvl_ratio": 0.2
}

Response:

{
  "risk": 0.42
}

Off-Chain Protocol News Worker

This worker ingests RSS/Atom feeds and fallback HTML article pages, matches articles to enabled protocols, and persists them into protocol_news.

Responsibilities

Database Layer

src/db/ is the shared persistence contract between runtime components and the API.

Main Collections

Collection Schema / Role
protocols protocol registry and metadata
protocolsnapshots time-series snapshots
protocolchartpayloads precomputed dashboard chart payloads
marketcandles price candles
tx_risk_events normalized transaction risk events
explain_jobs explain-service job state
protocol_risk_explanations model explanation loop output
users user accounts
user_protocols watchlist entries
user_alert_protocols alert subscriptions
user_settings per-user settings
user_notifications in-app notifications

Repository Helpers

Config Builder

src/config_builder/ generates protocol config for src/onchain_data/config/protocols.json.

What It Generates

Data Sources

Bootstrap And Shared Runtime Helpers

Bootstrap

src/bootstrap/ contains startup helpers for the initial persistent state before long-running loops begin.

Current main scope:

upserts protocol metadata from src/onchain_data/config/protocols.json into the Protocol collection

Shared Runtime Modules

src/modules/ contains small shared domain modules:

Legacy Layers

legacy Express-era service helpers

earlier Express router layer with monitorRoutes.js

New product-facing endpoints should go through api/src/app/api/ and api/src/modules/.

Frontend Integration

The root frontend package in this repository is risk-ui/.

The main runtime contract between risk-ui and the backend looks like this:

risk-ui Runtime Surface

Although risk-ui currently does not have a dedicated root README, the project structure and deployment docs make the frontend scope clear:

Frontend Deploy Notes

Realtime WebSocket Flow

  1. frontend calls POST /api/ws/token
  2. API signs a short-lived HS256 JWT
  3. frontend connects to the alerts websocket with ?token=...
  4. the engine-side websocket server validates the token and streams updates

Environment Variables

Engine

API

Alert System

Forecast System

Explain Service