Real-Time DeFi Monitoring: Architecture and Security

After deploying a smart contract, the real work begins: you need to understand what's happening with it in real time. We've seen projects without monitoring—and it led to fund loss. Without an on-chain metrics system, you find out about a problem only when users start complaining, while the attacker

Blockchain Development Services

Frequently Asked Questions

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1451
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1309
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    1005
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1270
  • image_logo-advance_0.webp
    B2B Advance company logo design
    719
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    1011

After deploying a smart contract, the real work begins: you need to understand what's happening with it in real time. We've seen projects without monitoring—and it led to fund loss. Without an on-chain metrics system, you find out about a problem only when users start complaining, while the attacker has already drained liquidity. Monitoring on-chain metrics is not a luxury but a necessity for any DeFi project with TVL above $1M. In this article, I'll share real experience setting up such a system and provide ready-to-use code you can adapt for your contracts.

"Real-time on-chain monitoring is the first line of defense for any DeFi protocol." — say our engineers with experience on over 100 projects.

We use the stack: Ethereum (via viem with WebSocket), Prometheus + Alertmanager, Grafana, TimescaleDB. All components are battle-tested in production on projects with TVL over $10M. Our system processes up to 2,000 events per second—enough for any DeFi protocol. We have over 5 years of blockchain development experience, completed more than 50 DeFi monitoring projects.

Which On-Chain Metrics Matter for DeFi?

Main Metric Groups

Metric Type Latency Importance
TVL Operational Real-time Critical
DAU/MAU Business Real-time High
Failed transactions (%) Operational Real-time Medium
Large withdrawals > $100K Security Real-time Alert

Operational metrics: call frequency of key functions, gas consumption by method (anomalous growth may indicate expensive operations or attack), failed transaction ratio (increase above 10% triggers alert), TVL.

Business metrics: on-chain DAU/MAU (unique addresses per period), retention—addresses returning after N days, volume in USD via specific functions, top-N addresses by activity (whale alert detector).

Security: large withdrawals, unusual call patterns (flash loan + contract in same block), admin role changes, calls from new addresses with large balance.

Why Real-Time Monitoring Is Critical?

A missed anomaly can cost millions. Example from our practice: a client's TVL suddenly dropped 30% in an hour. Without monitoring, the team found out a day later via Twitter. It turned out an attacker used a flash loan to manipulate the price. We set up an alert on sharp TVL drop—now such incidents are detected in minutes. On-chain metrics are the eyes of your protocol.

Architecture of On-Chain Metrics Monitoring System

Data Sources

Source Latency Complexity Applicability
Event logs Real-time (WebSocket) Low Main: any contract action
Trace calls Real-time (debug) High Fund movement between contracts
Storage slots Real-time (RPC) Medium TVL, balances, non-emitted metrics
Dune Analytics 10–30 min Low Retrospective analysis, SQL queries

Event logs are the fastest and cheapest way to obtain data (Event logging). They provide latency under 500 ms, 20x faster than Dune Analytics. If your contract doesn't emit needed events—add them (if upgradable) or use trace calls.

Flow Diagram

 ┌─────────────────┐ │ Blockchain RPC │ │ (Alchemy/own) │ └────────┬────────┘ │ eth_getLogs / WebSocket ┌────────────▼──────────────┐ │ Event Collector │ │ (subscription to contract)│ └────────────┬──────────────┘ │ ┌────────────▼──────────────┐ │ Metrics Processor │ │ Decode ABI, aggregation, │ │ enrichment │ └──────┬────────────┬────────┘ │ │ ┌────────────▼──┐ ┌──────▼──────────────┐ │ TimescaleDB │ │ Prometheus/VictoriaDB│ │ (history) │ │ (real-time metrics) │ └───────────────┘ └──────────────────────┘ │ ┌─────────▼──────────┐ │ Grafana Dashboard │ │ + Alertmanager │ └────────────────────┘ 

Technical Implementation

Event collector on viem

import { createPublicClient, webSocket, parseAbiItem, decodeEventLog } from 'viem'; import { mainnet } from 'viem/chains'; const client = createPublicClient({ chain: mainnet, transport: webSocket('wss://eth-mainnet.g.alchemy.com/v2/YOUR_KEY'), }); const CONTRACT_ABI = [ parseAbiItem('event Deposit(address indexed user, uint256 amount)'), parseAbiItem('event Withdraw(address indexed user, uint256 amount)'), parseAbiItem('event Swap(address indexed user, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut)'), ]; const unwatch = client.watchContractEvent({ address: CONTRACT_ADDRESS, abi: CONTRACT_ABI, onLogs: async (logs) => { for (const log of logs) { await processEvent(log); } }, onError: (error) => { console.error('WS error, reconnecting...', error); }, }); async function processEvent(log: any) { const decoded = decodeEventLog({ abi: CONTRACT_ABI, ...log }); await db.query(` INSERT INTO contract_events (time, block_number, tx_hash, event_name, user_address, amount_usd) VALUES (NOW(), $1, $2, $3, $4, $5) `, [log.blockNumber, log.transactionHash, decoded.eventName, decoded.args.user, await convertToUSD(decoded.args.amount)]); eventCounter.labels(decoded.eventName).inc(); } 

Prometheus metrics and alerts

import { Counter, Gauge, Registry } from 'prom-client'; const registry = new Registry(); const eventCounter = new Counter({ name: 'contract_events_total', help: 'Total contract events by type', labelNames: ['event_name'], registers: [registry], }); const tvlGauge = new Gauge({ name: 'contract_tvl_usd', help: 'Total Value Locked in USD', registers: [registry], }); const largeWithdrawalCounter = new Counter({ name: 'contract_large_withdrawals_total', help: 'Withdrawals above threshold', labelNames: ['threshold_category'], registers: [registry], }); app.get('/metrics', async (req, res) => { res.set('Content-Type', registry.contentType); res.send(await registry.metrics()); }); 
Alertmanager rules
groups: - name: contract_security rules: - alert: LargeWithdrawal expr: rate(contract_large_withdrawals_total[5m]) > 0 for: 0m labels: severity: critical annotations: summary: "Large withdrawal detected" - alert: HighFailureRate expr: | rate(contract_failed_txns_total[10m]) / rate(contract_total_txns_total[10m]) > 0.1 for: 5m annotations: summary: "More than 10% of transactions failing" - alert: TVLDrop expr: | (contract_tvl_usd - contract_tvl_usd offset 1h) / contract_tvl_usd offset 1h < -0.2 for: 2m annotations: summary: "TVL dropped by more than 20% in 1 hour" 

The event collector processes up to 2,000 events per second without loss when backpressure is properly configured.

Security Alerts

In addition to real-time alerts, it's useful to track large transactions and flash loan patterns. We implement this via a separate service that analyzes events by threshold (e.g., $100,000) and checks call sequences in one block. When detected, an alert with details is sent. Everything runs on the same event logs.

Grafana Dashboard

Key panels for a DeFi protocol:

  • Overview: TVL (gauge + time series), 24h Volume, DAU, Total Users (cumulative)
  • Activity: Events per minute (breakdown by type), Gas used per block, Failed tx ratio
  • Security: Large transactions (table with recent whale transactions), New whale addresses, Flash loan detection events
  • Economics: Fee revenue over time, Token price correlation with contract activity

The dashboard is versioned in git along with the contract code.

Historical Data and Retrospective Analysis

For retrospectives, use TimescaleDB and SQL:

-- Daily active users SELECT date_trunc('day', time) AS day, COUNT(DISTINCT user_address) AS dau, SUM(amount_usd) AS volume_usd FROM contract_events WHERE event_name IN ('Deposit', 'Swap') GROUP BY 1 ORDER BY 1 DESC; -- Retention: users returning after 7 days WITH first_use AS ( SELECT user_address, MIN(time) AS first_time FROM contract_events GROUP BY 1 ), return_use AS ( SELECT DISTINCT e.user_address FROM contract_events e JOIN first_use f ON e.user_address = f.user_address WHERE e.time > f.first_time + INTERVAL '7 days' AND e.time < f.first_time + INTERVAL '14 days' ) SELECT COUNT(r.user_address)::float / COUNT(f.user_address) AS week1_retention FROM first_use f LEFT JOIN return_use r ON f.user_address = r.user_address; 

Scope of Work

  • Event collector: set up subscription to contract events via WebSocket, write to TimescaleDB.
  • Prometheus metrics: export key metrics (TVL, volume, failure rate) via prom-client.
  • Grafana dashboard: visualize operational, business, and security metrics, versioned in git.
  • Alertmanager alerts: rules for critical events (TVL drop, large withdrawal, high failure rate).
  • Whale detector: notifications for large transactions and flash loan patterns.
  • Documentation and runbook: incident response instructions.
  • Team training: knowledge transfer for system operation.

Deployment Process: Step-by-Step

Step 1: Set up event collector. Connect to RPC, create subscription to contract events via viem WebSocket. Write raw events to TimescaleDB. Test on real transactions. (Est. cost: $500–$1,000)

Step 2: Prometheus and Grafana. Define metrics, export them via prom-client. Build initial dashboard with TVL, volume, event frequency. Set up basic alerts (TVL drop, high failure rate). (Est. cost: $1,000–$2,000)

Step 3: Security and Whale detector. Add alerts for large withdrawals and flash loan patterns. Integrate notifications into Telegram/PagerDuty. Test via attack simulation. Prepare runbook. (Est. cost: $1,500–$3,000)

Total 1–3 days depending on contract complexity. We work with Ethereum, Polygon, Arbitrum, Solana. Guarantee SLA on system operation.

To order a monitoring system for your DeFi project, contact us.

Choosing the Stack

The main choice is between ready-made platforms (Dune, Flipside) and custom infrastructure. Dune is good for quick analytics but has 10–30 minute latency and vendor lock-in. A custom monitoring stack (Prometheus + Grafana) provides real-time and full control. We recommend combining: custom stack for real-time response and Dune for retrospective reports. For projects with TVL over $1M, a custom stack is mandatory.

Losses from a single attack can be huge, while monitoring setup costs are a fraction. Get a consultation on monitoring setup—contact us for a project audit. We'll assess your project for free.