Developer Documentation

Live

Complete API reference, webhooks, code examples, and integration guides. Build real-time DeFi intelligence apps with enriched transaction data from Arbitrum.

Base URL https://defeyes-api.vercel.app

Authentication

Most data endpoints require an API key. Include it in your request headers:

X-API-Key: def_your_api_key_here

Quick Start

🚀 Get Started in 30 Seconds

Here's everything you need to start building:

1. Get Your API Key
# Sign up at /payment to get your API key
API_KEY="def_your_api_key_here"
2. Query Events (Python)
import requests

response = requests.get(
    "https://defeyes-api.vercel.app/api/events",
    headers={"X-API-Key": "def_xxx"},
    params={"action_type": "SWAP", "limit": 10}
)

events = response.json()["events"]
for event in events:
    print(f"{event['protocol_name']}: {event['action_type']} - ${event['amount_usd']:,.2f}")
3. Set Up Webhooks (Node.js)
const axios = require('axios');

// Create webhook
const webhook = await axios.post(
    'https://defeyes-api.vercel.app/api/webhooks',
    {
        url: 'https://your-app.com/webhooks',
        filters: { action_types: ['SWAP'] }
    },
    { headers: { 'X-API-Key': 'def_xxx' } }
);

console.log('Webhook created:', webhook.data.webhook.id);

📊 What Data Do We Provide?

We enrich raw blockchain transactions with:

  • Protocol Classification - Automatically identify Aave, Uniswap, CoW Protocol, etc.
  • Action Types - SUPPLY, BORROW, SWAP, WITHDRAW, REPAY, FLASH_LOAN, LIQUIDATION
  • Yield Data - APY percentages for lending/borrowing positions
  • Token Metadata - Symbols, amounts, USD values
  • Wallet Analytics - Track wallet behavior patterns

💡 Common Use Cases

  • Trading Bots - Monitor large swaps, detect arbitrage opportunities
  • Wallet Monitoring - Track specific addresses for activity
  • Protocol Analytics - Analyze DeFi protocol usage patterns
  • Yield Farming - Find highest APY opportunities
  • Risk Management - Monitor liquidations, large positions
  • AI Agents - Real-time data feeds for LLM-powered applications

Data Endpoints

GET /api/events API Key Query enriched DeFi events

Query enriched transaction events with filtering by protocol, action type, wallet, yield data, and more.

Query Parameters
ParameterTypeDescription
limit integer Number of results (default: 100, max: 1000)
offset integer Pagination offset
action_type string Filter by action: SUPPLY, BORROW, SWAP, FLASH_LOAN, REPAY, WITHDRAW, LIQUIDATION
protocol string Filter by protocol: "Aave V3", "CoW Protocol", "Uniswap", etc.
wallet string Filter by wallet address (origin_user)
apy_min number Minimum APY percentage (yield filter)
apy_max number Maximum APY percentage
# Find high-yield Aave supply events
curl -H "X-API-Key: def_xxx" \
  "https://defeyes-api.vercel.app/api/events?protocol=Aave%20V3&action_type=SUPPLY&apy_min=5"
Response Example
{
  "events": [
    {
      "id": 12345,
      "tx_hash": "0xabc...",
      "block_number": 417390882,
      "origin_user": "0x259B6b9C...",
      "protocol_name": "Aave V3 Pool",
      "action_type": "SUPPLY",
      "apy_percent": 5.23,
      "amount_usd": 1055.60,
      "token_symbol": "WETH",
      "timestamp": "2026-01-03T07:19:29Z"
    }
  ],
  "total": 1523,
  "limit": 100,
  "offset": 0
}
GET /api/events/export API Key Export events as CSV/JSON

Export enriched events in CSV or JSON format for analysis. Includes yield data and protocol classifications.

Query Parameters
ParameterTypeDescription
format string "csv" or "json" (default: csv)
limit integer Number of records (default: 100, max: 500)
enriched_only boolean Only return fully classified events (default: true)
# Export 100 enriched events as CSV
curl -H "X-API-Key: def_xxx" \
  "https://defeyes-api.vercel.app/api/events/export?format=csv&limit=100" \
  -o high_yield_events.csv
CSV Columns
tx_hash,block_number,timestamp,origin_user,protocol_name,action_type,
method_name,amount_usd,token_symbol,apy_percent,yield_pool,...
GET /api/wallets/{address} API Key Get wallet activity profile

Get aggregated statistics and activity profile for a specific wallet address.

Path Parameters
ParameterTypeDescription
addressrequired string Ethereum wallet address (0x...)
# Get wallet profile
curl -H "X-API-Key: def_xxx" \
  "https://defeyes-api.vercel.app/api/wallets/0x4cdba844ceb949567e3dbf94c5b0f7b3c8e5d2a1"
Response Example
{
  "address": "0x4cdba844ceb949567e3dbf94c5b0f7b3c8e5d2a1",
  "total_events": 156,
  "first_seen": "2025-11-15T10:23:45Z",
  "last_seen": "2026-01-05T08:12:33Z",
  "protocols_used": ["Aave V3", "CoW Protocol", "Uniswap"],
  "action_breakdown": {
    "SUPPLY": 45,
    "SWAP": 78,
    "BORROW": 23,
    "WITHDRAW": 10
  },
  "total_volume_usd": 125430.50
}
GET /api/stats Get platform statistics

Returns real-time statistics about enriched events, unique wallets, classification coverage, and protocol breakdown.

Response Example
{
  "enriched_events": 31239,
  "unique_wallets": 7895,
  "enrichment_progress": "99.7%",
  "protocol_breakdown": {
    "Aave V3 Pool": 17188,
    "Cow Protocol": 1305,
    "Uniswap": 856
  },
  "last_updated": "2026-01-05T08:00:00.000Z"
}

Health & Status

GET /api/health Basic health check

Simple health check endpoint to verify API is running.

{
  "status": "ok",
  "time": "2026-01-05T08:00:00.000Z"
}
GET /api/rpc-health RPC connectivity status

Check Reactive Network RPC connectivity and chain status.

{
  "status": "ok",
  "chainId": 4078,
  "blockNumber": 12345678,
  "rpcUrl": "https://mainnet-rpc.rnk.dev"
}
GET /api/storage-health Database connection status

Check database connectivity and event counts.

{
  "status": "ok",
  "database": "connected",
  "total_events": 31239,
  "last_event": "2026-01-05T08:00:00.000Z"
}

Payments & Subscriptions

POST /api/payments/create-customer Create customer & API key

Creates a new customer in the system and Stripe, generates an API key.

Request Body
ParameterTypeDescription
emailrequired string Customer email address
namerequired string Customer full name
company string Company name (optional)
Response Example
{
  "customer": {
    "id": 1,
    "email": "user@example.com",
    "stripe_customer_id": "cus_xxx"
  },
  "apiKey": "def_xxxxxxxxxxxxxxxx",
  "message": "Customer created and API key generated"
}
POST /api/payments/create-subscription Create new subscription

Create a subscription for an existing customer.

Request Body
ParameterTypeDescription
emailrequired string Customer email
planIdrequired integer Plan ID (1=Starter $19, 2=Pro $99)
paymentMethod string "stripe" or "x402"
GET /api/payments/subscriptions/{email} Get customer subscriptions

Retrieve all subscriptions for a customer by email.

Response Example
{
  "subscriptions": [
    {
      "id": 1,
      "plan_name": "Pro",
      "status": "active",
      "current_period_end": "2026-02-05T00:00:00Z"
    }
  ]
}
GET /api/usage API Key Get API usage statistics

Get your current API usage and rate limit status.

curl -H "X-API-Key: def_xxx" \
  "https://defeyes-api.vercel.app/api/usage"
Response Example
{
  "requests_today": 156,
  "requests_this_hour": 23,
  "rate_limit": 1000,
  "plan": "Pro",
  "reset_at": "2026-01-05T09:00:00Z"
}

X402 Pay-Per-Request

What is X402?

X402 enables pay-per-request API access using USDC stablecoins. Perfect for AI agents and users who prefer micropayments over subscriptions.

  • No subscription required
  • Pay only for what you use
  • Supports Base and Arbitrum networks
  • Instant settlement
GET /api/x402/pricing Get X402 pricing and payment info

Returns pricing information, supported networks, and the USDC payment wallet address.

Note: Some endpoints can have metered pricing based on request parameters (e.g. freshness windows like time_range=5m). Use /api/x402/quote for an exact per-request price quote.

Response

{
  "currency": "USDC",
  "wallet": "0x742d35Cc6634C0532925a3b844Bc9e7595f5bE91",
  "networks": [
    {
      "id": "base",
      "name": "Base",
      "chainId": 8453,
      "usdcContract": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
    },
    {
      "id": "arbitrum",
      "name": "Arbitrum One",
      "chainId": 42161,
      "usdcContract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"
    }
  ],
  "pricing": {
    "/api/stats": 0.0005,
    "/api/events": 0.001,
    "/api/events/export": 0.01,
    "/api/analytics": 0.005
  }
}
POST /api/x402/quote Get an exact price quote for a specific request (agents)

Returns an exact USDC price for a specific endpoint + parameters. Agents should call this before paying so they always pay the right amount.

Request Body
ParameterTypeDescription
endpointrequired string Endpoint path (example: /api/events)
params object Query params for that endpoint (example: {"time_range":"5m","limit":100})
url string Optional full URL/path with query string (alternative to params)
# Quote a premium-fresh request (last 5 minutes)
curl -X POST "https://defeyes-api.vercel.app/api/x402/quote" \
  -H "Content-Type: application/json" \
  -d '{"endpoint":"/api/events","params":{"time_range":"5m","limit":100}}'
Response Example
{
  "endpoint": "/api/events",
  "url": "/api/events?time_range=5m&limit=100",
  "price": 0.005,
  "currency": "USDC",
  "wallet": "0xB0EfBb7Bb1d85A0ebd3D71c623560560b1FD8941",
  "requiredConfirmations": 1
}
POST /api/x402/verify Verify a payment transaction

Verify that a USDC payment transaction is valid before using it for API access.

Request Body

ParameterTypeRequiredDescription
txHashstringYesTransaction hash of the USDC payment
networkstringYesNetwork: "base" or "arbitrum"
endpointstringNoEndpoint to check price for (default: /api/events)

Success Response

{
  "valid": true,
  "amount": 0.001,
  "from": "0xYourWalletAddress..."
}

Agent Discovery & OpenAPI

AI agents can discover this API automatically using standard endpoints:

  • /.well-known/x402.json — Service manifest: endpoints, pricing, networks, Bazaar metadata. Crawled by x402 Bazaar.
  • /openapi.json — OpenAPI 3.1 spec for LLM function calling and code generation.
curl https://defeyes-api.vercel.app/.well-known/x402.json
curl https://defeyes-api.vercel.app/openapi.json
FLOW X402 Payment Flow How to use X402 for API access

Two Payment Flows

We support standard x402 v2 (recommended for AI agents) and legacy on-chain flow.

  • Standard: Use Coinbase @x402/core SDK — sign payment authorization off-chain, include in Payment-Signature header. No USDC transfer needed upfront.
  • Legacy: Send USDC on-chain, then retry with X-Payment-Proof and X-Payment-Network headers.

The 402 response includes a PAYMENT-REQUIRED header (x402 v2 JSON) plus legacy X-Price-Amount, X-Payment-Wallet headers.

Step 1: Make Request

Call any data endpoint without authentication:

curl https://defeyes-api.vercel.app/api/events

Step 2: Receive 402 Response

The API returns payment instructions:

{
  "error": "Payment Required",
  "x402": {
    "price": 0.001,
    "currency": "USDC",
    "wallet": "0x742d35Cc..."
  }
}

Step 3: Send USDC Payment

Send the required USDC amount to the payment wallet on Base or Arbitrum.

Step 4: Retry with Payment Proof (Legacy)

Include the transaction hash in your request:

curl https://defeyes-api.vercel.app/api/events \
  -H "X-Payment-Proof: 0xYourTxHash..." \
  -H "X-Payment-Network: base"

Standard x402 v2 (Recommended for Agents)

Use the Coinbase SDK for signed authorization — no on-chain transfer needed:

import { x402HTTPClient } from "@x402/core/client";
import { ethers } from "ethers";

const wallet = new ethers.Wallet("0xYOUR_KEY", provider);
const client = x402HTTPClient("https://defeyes-api.vercel.app", wallet);
const res = await client.get("/api/events");
const data = await res.json();

The SDK reads PAYMENT-REQUIRED header, signs the authorization, and retries with Payment-Signature. Example clients: examples/x402_agent_client.js and examples/x402_agent_client.py.

Python Example

import requests
from web3 import Web3

# 1. Make initial request
response = requests.get("https://defeyes-api.vercel.app/api/events")

if response.status_code == 402:
    payment_info = response.json()["x402"]
    
    # 2. Send USDC (using web3.py)
    w3 = Web3(Web3.HTTPProvider("https://mainnet.base.org"))
    usdc = w3.eth.contract(address=USDC_ADDRESS, abi=ERC20_ABI)
    
    tx = usdc.functions.transfer(
        payment_info["wallet"],
        int(payment_info["price"] * 1e6)  # USDC has 6 decimals
    ).transact()
    
    tx_hash = w3.eth.wait_for_transaction_receipt(tx).transactionHash.hex()
    
    # 3. Retry with payment proof
    response = requests.get(
        "https://defeyes-api.vercel.app/api/events",
        headers={
            "X-Payment-Proof": tx_hash,
            "X-Payment-Network": "base"
        }
    )
    
    data = response.json()

Webhooks

What Are Webhooks?

Webhooks are reverse APIs - instead of polling for new data, we push events to your endpoint instantly when they happen. Perfect for real-time trading bots, alerts, dashboards, and AI agents.

  • Instant notifications - Get events within seconds of on-chain execution
  • Zero polling overhead - No wasted API calls checking for updates
  • Filtered delivery - Only receive events matching your criteria
  • HMAC signatures - Verify webhook authenticity
  • Automatic retries - Built-in retry logic with exponential backoff

Use Cases: Trading bots, wallet monitoring, protocol analytics, real-time dashboards, AI agent integrations, alert systems.

POST /api/webhooks API Key Create a new webhook

Create a webhook to receive real-time notifications when events match your filters. Webhooks trigger automatically when enriched events are detected.

Request Body
ParameterTypeDescription
urlrequired string HTTPS endpoint to receive webhook POST requests
description string Human-readable description (e.g., "Large swap alerts")
filters object Event filters (see filter options below)
Filter Options
FilterTypeDescription
action_types string[] Array of action types: ["SUPPLY", "BORROW", "SWAP", "WITHDRAW", "REPAY", "FLASH_LOAN", "LIQUIDATION"]
protocol_name string[] Array of protocol names: ["Aave V3 Pool", "Uniswap", "CoW Protocol"]
origin_user string[] Array of wallet addresses to monitor
token_symbol string Token symbol to filter (e.g., "WETH", "USDC")
min_value_token number Minimum token amount (works with token_symbol)
# Create webhook for large WETH swaps
curl -X POST "https://defeyes-api.vercel.app/api/webhooks" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: def_xxx" \
  -d '{
    "url": "https://your-app.com/webhooks/defeyes",
    "description": "Large WETH swap alerts",
    "filters": {
      "action_types": ["SWAP"],
      "token_symbol": "WETH",
      "min_value_token": 10.0
    }
  }'
Response Example
{
  "success": true,
  "webhook": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "url": "https://your-app.com/webhooks/defeyes",
    "description": "Large WETH swap alerts",
    "filters": {
      "action_types": ["SWAP"],
      "token_symbol": "WETH",
      "min_value_token": 10.0
    },
    "status": "active",
    "created_at": "2026-01-05T08:00:00Z"
  },
  "message": "Webhook created successfully"
}
GET /api/webhooks API Key List all your webhooks

Get all webhooks associated with your API key.

curl -H "X-API-Key: def_xxx" \
  "https://defeyes-api.vercel.app/api/webhooks"
Response Example
{
  "webhooks": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "url": "https://your-app.com/webhooks/defeyes",
      "description": "Large WETH swap alerts",
      "filters": { ... },
      "status": "active",
      "created_at": "2026-01-05T08:00:00Z"
    }
  ]
}
PUT /api/webhooks/:id API Key Update webhook configuration

Update webhook URL, filters, or status. Use this to pause/resume webhooks or adjust filters.

Request Body (all fields optional)
ParameterTypeDescription
url string New webhook URL
description string New description
filters object Updated filters object
status string "active" or "paused"
# Pause a webhook
curl -X PUT "https://defeyes-api.vercel.app/api/webhooks/550e8400-e29b-41d4-a716-446655440000" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: def_xxx" \
  -d '{"status": "paused"}'
DELETE /api/webhooks/:id API Key Delete a webhook

Permanently delete a webhook. This action cannot be undone.

curl -X DELETE \
  "https://defeyes-api.vercel.app/api/webhooks/550e8400-e29b-41d4-a716-446655440000" \
  -H "X-API-Key: def_xxx"
POST /api/webhooks/:id/test API Key Send a test webhook

Trigger a test webhook delivery with sample event data. Useful for verifying your endpoint is working correctly.

curl -X POST \
  "https://defeyes-api.vercel.app/api/webhooks/550e8400-e29b-41d4-a716-446655440000/test" \
  -H "X-API-Key: def_xxx"
GET /api/webhooks/:id/logs API Key Get webhook delivery logs

View delivery history, success/failure status, and retry attempts for a webhook.

Query Parameters
ParameterTypeDescription
limit integer Number of logs to return (default: 50, max: 200)
offset integer Pagination offset
curl -H "X-API-Key: def_xxx" \
  "https://defeyes-api.vercel.app/api/webhooks/550e8400-e29b-41d4-a716-446655440000/logs?limit=50"
PAYLOAD Webhook Payload Format What you'll receive

When an event matches your webhook filters, we send a POST request to your URL with the following payload:

Headers
# Headers included in webhook POST
Content-Type: application/json
X-Webhook-Signature: sha256=abc123...  # HMAC signature for verification
X-Webhook-Id: 550e8400-e29b-41d4-a716-446655440000
X-Webhook-Timestamp: 1704451200
Payload Body
{
  "event": {
    "id": 12345,
    "ref_tx_hash": "0xabc123...",
    "block_number": 417390882,
    "origin_user": "0x259B6b9C...",
    "protocol_name": "Aave V3 Pool",
    "action_type": "SUPPLY",
    "method_name": "supply",
    "token_in_symbol": "WETH",
    "token_in_amount": 10.5,
    "amount_usd": 25500.00,
    "apy_percent": 5.23,
    "timestamp": "2026-01-05T08:00:00Z",
    "enriched_at": "2026-01-05T08:00:01Z"
  },
  "webhook_id": "550e8400-e29b-41d4-a716-446655440000",
  "delivered_at": "2026-01-05T08:00:02Z"
}

🔒 Verifying Webhook Signatures

Always verify the X-Webhook-Signature header to ensure requests are from Defeyes. The signature is an HMAC-SHA256 hash of the payload body using your webhook secret.

# Python example
import hmac
import hashlib

# Get secret from webhook creation response (stored securely)
secret = "whsec_..."

# Verify signature
payload_body = request.data
signature = request.headers.get('X-Webhook-Signature', '').replace('sha256=', '')
expected = hmac.new(
    secret.encode(),
    payload_body,
    hashlib.sha256
).hexdigest()

if signature != expected:
    return "Invalid signature", 401
EXAMPLES Code Examples Python, JavaScript, Node.js

Complete code examples for receiving and processing webhooks in different languages.

Python (Flask)
# Flask webhook receiver
from flask import Flask, request, jsonify
import hmac
import hashlib

app = Flask(__name__)
WEBHOOK_SECRET = "whsec_..."  # Store securely

@app.route('/webhooks/defeyes', methods=['POST'])
def handle_webhook():
    # Verify signature
    signature = request.headers.get('X-Webhook-Signature', '').replace('sha256=', '')
    payload = request.get_data()
    
    expected = hmac.new(
        WEBHOOK_SECRET.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()
    
    if signature != expected:
        return jsonify({"error": "Invalid signature"}), 401
    
    # Process event
    event = request.json['event']
    
    if event['action_type'] == 'SWAP' and event['amount_usd'] > 10000:
        # Trigger your trading logic
        print(f"Large swap detected: {event['ref_tx_hash']}")
    
    return jsonify({"status": "ok"}), 200

if __name__ == '__main__':
    app.run(port=5000)
Node.js (Express)
// Express webhook receiver
const express = require('express');
const crypto = require('crypto');
const app = express();

const WEBHOOK_SECRET = 'whsec_...';  // Store securely

app.use(express.json());

app.post('/webhooks/defeyes', (req, res) => {
  // Verify signature
  const signature = req.headers['x-webhook-signature']?.replace('sha256=', '');
  const payload = JSON.stringify(req.body);
  
  const expected = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(payload)
    .digest('hex');
  
  if (signature !== expected) {
    return res.status(401).json({ error: 'Invalid signature' });
  }
  
  // Process event
  const event = req.body.event;
  
  if (event.action_type === 'SWAP' && event.amount_usd > 10000) {
    console.log(`Large swap: ${event.ref_tx_hash}`);
    // Your trading logic here
  }
  
  res.json({ status: 'ok' });
});

app.listen(5000, () => {
  console.log('Webhook receiver listening on port 5000');
});
Python (Create Webhook)
# Create webhook programmatically
import requests

API_KEY = "def_xxx"
API_BASE = "https://defeyes-api.vercel.app"

# Create webhook
response = requests.post(
    f"{API_BASE}/api/webhooks",
    headers={"X-API-Key": API_KEY},
    json={
        "url": "https://your-app.com/webhooks/defeyes",
        "description": "Monitor large swaps",
        "filters": {
            "action_types": ["SWAP"],
            "min_value_token": 1000.0
        }
    }
)

webhook = response.json()['webhook']
print(f"Webhook created: {webhook['id']}")
print(f"Secret: {webhook.get('secret', 'Check API response')}")

Admin Endpoints

GET /api/admin/unknown-methods Get unclassified method signatures

Returns method signatures that haven't been classified yet, ordered by frequency.

Response Example
{
  "unknown_methods": [
    {
      "method_id": "0x1ad2cc3b",
      "count": 234,
      "sample_tx": "0xabc..."
    }
  ]
}
POST /api/admin/enrich Commit method classification

Add a new method classification to the enrichment registry.

Request Body
ParameterTypeDescription
method_idrequired string 4-byte method selector (0x...)
method_namerequired string Human-readable method name
action_typerequired string SUPPLY, BORROW, SWAP, FLASH_LOAN, etc.
protocol_name string Associated protocol name