💡

Examples & Code Snippets

Ready-to-use code examples for common integrations. Copy, paste, and customize for your needs.


Position Monitoring

Monitor All Positions

Fetch and display all your DeFi positions with health status

typescript
import { DeFiGuardian } from '@defiguardian/sdk';

const client = new DeFiGuardian({ apiKey: process.env.API_KEY });

async function monitorPositions() {
  const positions = await client.positions.list();
  
  for (const pos of positions) {
    const status = pos.health_factor > 2 ? '🟢 Safe' :
                   pos.health_factor > 1.5 ? '🟡 Warning' : '🔴 Danger';
    
    console.log(`[${status}] ${pos.protocol} on ${pos.chain}`);
    console.log(`  Health Factor: ${pos.health_factor.toFixed(2)}`);
    console.log(`  Collateral: $${pos.collateral_usd.toLocaleString()}`);
    console.log(`  Debt: $${pos.debt_usd.toLocaleString()}`);
    console.log('');
  }
}

monitorPositions();

Health Factor Dashboard (React)

Real-time health factor display component for your frontend

tsx
import { useEffect, useState } from 'react';
import { DeFiGuardian } from '@defiguardian/sdk';

export function HealthDashboard() {
  const [positions, setPositions] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // IMPORTANT: Never expose API keys in client-side code.
    // Use a server-side API route to proxy calls instead.
    const client = new DeFiGuardian({ apiKey: process.env.DG_API_KEY });
    
    async function fetch() {
      const data = await client.positions.list();
      setPositions(data);
      setLoading(false);
    }
    
    fetch();
    const interval = setInterval(fetch, 30000); // Refresh every 30s
    return () => clearInterval(interval);
  }, []);

  if (loading) return <div>Loading positions...</div>;

  return (
    <div className="grid gap-4">
      {positions.map(pos => (
        <div key={pos.id} className="p-4 bg-gray-800 rounded-lg">
          <div className="flex justify-between items-center">
            <span className="font-bold">{pos.protocol}</span>
            <HealthBadge factor={pos.health_factor} />
          </div>
          <div className="text-sm text-gray-400 mt-2">
            Collateral: ${pos.collateral_usd.toLocaleString()}
          </div>
        </div>
      ))}
    </div>
  );
}

function HealthBadge({ factor }) {
  const color = factor > 2 ? 'bg-green-600' : 
                factor > 1.5 ? 'bg-yellow-600' : 'bg-red-600';
  return (
    <span className={`px-2 py-1 rounded text-sm ${color}`}>
      HF: {factor.toFixed(2)}
    </span>
  );
}

Python Portfolio Analyzer

Analyze your DeFi portfolio with pandas and visualize in Jupyter

python
from defiguardian import DeFiGuardian
import pandas as pd
import matplotlib.pyplot as plt

client = DeFiGuardian(api_key="your_api_key")

# Fetch positions as DataFrame
positions = client.positions.list()
df = pd.DataFrame([{
    'protocol': p.protocol,
    'chain': p.chain,
    'health_factor': p.health_factor,
    'collateral': p.collateral_usd,
    'debt': p.debt_usd,
    'net_value': p.collateral_usd - p.debt_usd
} for p in positions])

# Summary statistics
print("Portfolio Summary")
print(f"Total Collateral: ${df['collateral'].sum():,.2f}")
print(f"Total Debt: ${df['debt'].sum():,.2f}")
print(f"Net Value: ${df['net_value'].sum():,.2f}")
print(f"Lowest Health Factor: {df['health_factor'].min():.2f}")

# Visualization
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# Pie chart by protocol
df.groupby('protocol')['collateral'].sum().plot.pie(ax=axes[0], autopct='%1.1f%%')
axes[0].set_title('Collateral by Protocol')

# Bar chart of health factors
df.plot.bar(x='protocol', y='health_factor', ax=axes[1], color='green')
axes[1].axhline(y=1.5, color='red', linestyle='--', label='Warning Threshold')
axes[1].set_title('Health Factors')
axes[1].legend()

plt.tight_layout()
plt.show()

Alert Notifications

Create Health Factor Alert

Set up an alert that triggers when health factor drops below threshold

typescript
import { DeFiGuardian } from '@defiguardian/sdk';

const client = new DeFiGuardian({ apiKey: process.env.API_KEY });

async function setupHealthAlert() {
  const rule = await client.rules.create({
    name: 'Critical Health Factor Alert',
    type: 'health_factor',
    conditions: {
      operator: '<',
      threshold: 1.3,  // Alert when HF drops below 1.3
    },
    actions: {
      type: 'alert',
      channels: {
        email: true,
        telegram: true,
        discord: false,
      },
    },
    priority: 'high',
  });

  console.log(`✅ Alert created: ${rule.id}`);
  console.log(`   Will trigger when health factor < 1.3`);
}

setupHealthAlert();

Telegram Bot Integration

Receive DeFi Guardian alerts directly in Telegram

typescript
import TelegramBot from 'node-telegram-bot-api';
import express from 'express';

const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, { polling: false });
const app = express();

// Store user chat IDs (in production, use a database)
const userChatIds = new Map<string, number>();

// Webhook endpoint for DeFi Guardian alerts
app.post('/webhook/defi-guardian', express.json(), async (req, res) => {
  const { type, data } = req.body;
  
  if (type === 'alert.created') {
    const chatId = userChatIds.get(data.user_id);
    if (chatId) {
      await bot.sendMessage(chatId, 
        `🚨 *DeFi Alert*\n\n` +
        `*${data.rule_name}*\n` +
        `Health Factor: ${data.current_value}\n` +
        `Protocol: ${data.protocol}\n\n` +
        `⚠️ ${data.message}`,
        { parse_mode: 'Markdown' }
      );
    }
  }
  
  res.sendStatus(200);
});

app.listen(3000, () => console.log('Webhook server running'));

Slack Alert Bot

Send alerts to a Slack channel using incoming webhooks

typescript
import express from 'express';

const app = express();
const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL;

app.post('/webhook/defi-guardian', express.json(), async (req, res) => {
  const { type, data } = req.body;
  
  if (type === 'alert.created') {
    const color = data.severity === 'critical' ? '#ff0000' : 
                  data.severity === 'warning' ? '#ffcc00' : '#00ff00';
    
    await fetch(SLACK_WEBHOOK_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        attachments: [{
          color,
          title: `🚨 ${data.rule_name}`,
          fields: [
            { title: 'Protocol', value: data.protocol, short: true },
            { title: 'Health Factor', value: data.current_value.toFixed(2), short: true },
            { title: 'Message', value: data.message },
          ],
          footer: 'DeFi Guardian',
          ts: Math.floor(Date.now() / 1000),
        }],
      }),
    });
  }
  
  res.sendStatus(200);
});

app.listen(3000);

Automation

Auto-Repay on Low Health

Automatically trigger repayment when health factor drops

typescript
import { DeFiGuardian } from '@defiguardian/sdk';
import { ethers } from 'ethers';

const client = new DeFiGuardian({ apiKey: process.env.API_KEY });
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
// WARNING: This example uses a hot wallet for demonstration only.
// In production, use a hardware wallet, multisig, or dedicated relayer service.
// Never store private keys in environment variables on internet-facing servers.
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);

// Listen to position updates
client.on('position.updated', async (event) => {
  const { position_id, health_factor, protocol } = event.data;
  
  if (health_factor < 1.3) {
    console.log(`⚠️ Low health detected: ${health_factor}`);
    
    // Calculate repay amount (example: repay 10% of debt)
    const position = await client.positions.get(position_id);
    const repayAmount = position.debt_usd * 0.1;
    
    // Execute repayment (protocol-specific logic)
    console.log(`💰 Initiating repay of $${repayAmount.toFixed(2)}`);
    
    // ... your repayment logic here ...
    
    console.log('✅ Repayment successful');
  }
});

console.log('🤖 Auto-repay bot running...');

Scheduled Health Check Cron

Run health checks on a schedule using node-cron

typescript
import cron from 'node-cron';
import { DeFiGuardian } from '@defiguardian/sdk';
import nodemailer from 'nodemailer';

const client = new DeFiGuardian({ apiKey: process.env.API_KEY });

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: { user: process.env.EMAIL, pass: process.env.EMAIL_PASS },
});

// Run every hour
cron.schedule('0 * * * *', async () => {
  console.log('⏰ Running hourly health check...');
  
  const positions = await client.positions.list();
  const atRisk = positions.filter(p => p.health_factor < 1.5);
  
  if (atRisk.length > 0) {
    const report = atRisk.map(p => 
      `- ${p.protocol}: HF ${p.health_factor.toFixed(2)} ($${p.collateral_usd.toLocaleString()})`
    ).join('\n');
    
    await transporter.sendMail({
      from: process.env.EMAIL,
      to: process.env.ALERT_EMAIL,
      subject: `⚠️ ${atRisk.length} Positions At Risk`,
      text: `The following positions have low health factors:\n\n${report}`,
    });
    
    console.log(`📧 Alert sent for ${atRisk.length} positions`);
  } else {
    console.log('✅ All positions healthy');
  }
});

console.log('📅 Cron job scheduled: Hourly health checks');

Webhook Handlers

Express.js Webhook Server

Complete webhook handler with signature verification

typescript
import express from 'express';
import crypto from 'crypto';

const app = express();
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;

// Parse raw body for signature verification
app.use('/webhook', express.raw({ type: 'application/json' }));

function verifySignature(payload: Buffer, signature: string): boolean {
  const expected = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(payload)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expected}`)
  );
}

app.post('/webhook', (req, res) => {
  const signature = req.headers['x-dg-signature'] as string;
  
  if (!verifySignature(req.body, signature)) {
    console.error('❌ Invalid signature');
    return res.status(400).send('Invalid signature');
  }
  
  const event = JSON.parse(req.body.toString());
  console.log(`📥 Received: ${event.type}`);
  
  switch (event.type) {
    case 'alert.created':
      handleAlert(event.data);
      break;
    case 'position.updated':
      handlePositionUpdate(event.data);
      break;
    case 'position.liquidated':
      handleLiquidation(event.data);
      break;
    default:
      console.log(`Unknown event type: ${event.type}`);
  }
  
  res.status(200).send('OK');
});

function handleAlert(data: any) {
  console.log(`🚨 Alert: ${data.message}`);
}

function handlePositionUpdate(data: any) {
  console.log(`📊 Position ${data.position_id} updated: HF ${data.health_factor}`);
}

function handleLiquidation(data: any) {
  console.log(`💀 Position ${data.position_id} liquidated! Loss: $${data.loss_usd}`);
}

app.listen(3000, () => console.log('🚀 Webhook server listening on port 3000'));

Next.js API Route Handler

Handle webhooks in a Next.js application

typescript
// app/api/webhook/route.ts
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

export async function POST(req: NextRequest) {
  const body = await req.text();
  const signature = req.headers.get('x-defi-guardian-signature');
  const eventType = req.headers.get('x-defi-guardian-event');

  // Verify HMAC-SHA256 signature (timing-safe)
  const expected = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET!)
    .update(body)
    .digest('hex');

  if (!signature || !crypto.timingSafeEqual(
    Buffer.from(signature, 'hex'),
    Buffer.from(expected, 'hex')
  )) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  const payload = JSON.parse(body);

  // Process event
  switch (payload.event) {
    case 'alert.created':
      await prisma.alert.create({
        data: {
          title: payload.data.title,
          alertType: payload.data.alertType,
          severity: payload.data.severity,
          healthFactor: payload.data.position?.healthFactor,
        },
      });
      break;

    case 'position.updated':
      console.log('Position updated:', payload.data.positionId,
        'HF:', payload.data.healthFactor);
      break;
  }

  return NextResponse.json({ received: true });
}

FastAPI Webhook Handler (Python)

Python webhook server using FastAPI

python
from fastapi import FastAPI, Request, HTTPException
import hmac
import hashlib
import os

app = FastAPI()
WEBHOOK_SECRET = os.environ["WEBHOOK_SECRET"]

def verify_signature(payload: bytes, signature: str) -> bool:
    expected = hmac.new(
        WEBHOOK_SECRET.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(f"sha256={expected}", signature)

@app.post("/webhook")
async def handle_webhook(request: Request):
    body = await request.body()
    signature = request.headers.get("x-dg-signature", "")
    
    if not verify_signature(body, signature):
        raise HTTPException(status_code=400, detail="Invalid signature")
    
    event = await request.json()
    event_type = event.get("type")
    
    print(f"📥 Received: {event_type}")
    
    if event_type == "alert.created":
        data = event["data"]
        print(f"🚨 Alert: {data['message']}")
        # Send notification, store in DB, etc.
    
    elif event_type == "position.liquidated":
        data = event["data"]
        print(f"💀 Liquidated! Loss: ${data['loss_usd']:.2f}")
        # Emergency notification
    
    return {"status": "ok"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=3000)