DEV Community

Cover image for Keep Your AI Trading Bot Online: Monitoring 15 DeFi Protocol Health Status
Wallet Guy
Wallet Guy

Posted on

Keep Your AI Trading Bot Online: Monitoring 15 DeFi Protocol Health Status

Keep Your AI Trading Bot Online: Monitoring 15 DeFi Protocol Health Status

Your AI trading bot is only as reliable as the DeFi protocols it trades on — and when a protocol degrades, pauses, or goes offline mid-execution, you need your infrastructure to know about it before you submit a transaction that fails, eats gas, or worse, executes at a bad price. This post walks through how WAIaaS gives trading bot builders a unified layer for monitoring protocol health across 15 integrated DeFi protocols, with built-in risk controls that keep your bot from firing into a broken market.

Why Protocol Health Monitoring Is a Production Problem

Most trading bots are built around the happy path. The swap goes through, the position opens, the bridge confirms. But DeFi protocols are live systems — they pause, they hit liquidity ceilings, they throttle during congestion. If your bot doesn't have a layer that checks provider status before committing capital, you're flying blind.

The stakes are concrete: a failed Hyperliquid order still costs gas. A Jupiter swap submitted during low liquidity might execute at a price your strategy didn't account for. A bridge transaction via LI.FI initiated when the route is degraded might sit unconfirmed for hours. None of these are edge cases — they're regular operating conditions in production DeFi. What you need is a wallet infrastructure layer that surfaces this state and lets your bot act on it intelligently.

What WAIaaS Brings to a Trading Bot Stack

WAIaaS is a self-hosted Wallet-as-a-Service designed specifically for AI agents and automated systems. For trading bots, the relevant architecture is this: a single daemon running locally or on your server, exposing a REST API across 39 route modules, with 15 DeFi protocol providers integrated, 45 MCP tools for AI agent frameworks, and a 7-stage transaction pipeline that handles validation, policy enforcement, gas conditions, execution, and confirmation.

The 15 integrated DeFi protocols are: aave-v3, across, dcent-swap, drift, erc8004, hyperliquid, jito-staking, jupiter-swap, kamino, lido-staking, lifi, pendle, polymarket, xrpl-dex, and zerox-swap. That's spot trading, perpetuals, lending, staking, bridging, and prediction markets — all reachable through the same session-authenticated API.

For a trading bot, this means you're not managing 15 different SDKs, 15 different key management strategies, and 15 different error surfaces. You manage one daemon, one session token, one policy layer.

Checking Protocol Provider Status Before You Trade

The most direct way to protect your bot from executing into a degraded protocol is to check provider status before you act. WAIaaS exposes this through the get-provider-status MCP tool and the corresponding REST surface.

Before your bot submits a Jupiter swap or a Drift perp order, it can query whether that provider is currently available. This is especially important for arbitrage strategies where you're crossing two protocols — if either leg is degraded, the arb doesn't exist in the way your model thinks it does.

Here's the pattern for checking your DeFi positions across all protocols after confirming a provider is healthy:

# Check wallet balance before executing a strategy
curl http://127.0.0.1:3100/v1/wallet/balance \
  -H "Authorization: Bearer wai_sess_eyJhbGciOiJIUzI1NiJ9..."
Enter fullscreen mode Exit fullscreen mode

And here's what a Jupiter swap execution looks like once you've confirmed the route is live:

curl -X POST http://127.0.0.1:3100/v1/actions/jupiter-swap/swap \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "inputMint": "So11111111111111111111111111111111111111112",
    "outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    "amount": "1000000000"
  }'
Enter fullscreen mode Exit fullscreen mode

The session token in the Authorization header is scoped to a specific wallet. This means your trading bot operates with a session that has its own TTL, max renewals, and absolute lifetime — you're not handing the bot unbounded access to the wallet.

Gas Conditional Execution: Don't Trade When It's Expensive

One of the more underrated features for trading bots is gas conditional execution. WAIaaS has a dedicated pipeline stage — stage-gas-condition — that blocks transaction execution until the gas price meets a configured threshold. Your bot submits the transaction, and the pipeline holds it until network conditions are favorable.

For MEV bots and arbitrage systems, this is a double-edged consideration — sometimes you need to execute at any gas price because the opportunity window is seconds wide. But for strategies that are less time-sensitive (rebalancing, yield harvesting, staking compound operations), letting the pipeline handle gas waiting is cleaner than building that polling loop yourself.

The dry-run API is your best friend before committing:

curl -X POST http://127.0.0.1:3100/v1/transactions/send \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "type": "TRANSFER",
    "to": "recipient-address",
    "amount": "0.1",
    "dryRun": true
  }'
Enter fullscreen mode Exit fullscreen mode

Run the simulation first, validate the expected outcome, then execute. For a trading bot operating across 15 protocols with different gas models, this simulation layer is what separates a bot that manages risk from one that doesn't.

Policy Engine as a Risk Management Layer

Here's where WAIaaS gets specifically useful for trading bot builders beyond just API aggregation: the policy engine.

The policy engine has 21 policy types and 4 security tiers (INSTANT, NOTIFY, DELAY, APPROVAL). It enforces default-deny — if you haven't explicitly allowed a token or contract, the transaction is blocked. For an automated system that's supposed to trade specific markets and not others, this is a hard guardrail that doesn't rely on your bot's logic being correct.

Relevant policy types for a trading bot:

  • SPENDING_LIMIT — Amount-based 4-tier security. Transactions under your instant_max_usd execute immediately. Larger ones escalate to notify, delay, or require approval.
  • PERP_MAX_LEVERAGE — Hard cap on perpetual futures leverage. Your Drift or Hyperliquid integration can't open a position beyond what you've configured here, regardless of what the strategy signals.
  • PERP_MAX_POSITION_USD — Max position size in USD. Useful for position sizing guardrails that survive a bug in your strategy code.
  • PERP_ALLOWED_MARKETS — Whitelist of markets your bot is permitted to trade. If the strategy tries to open a position in a market you didn't configure, it's blocked at the infrastructure layer.
  • VENUE_WHITELIST — Allowed trading venues. Restricts which protocols the bot can interact with.
  • CONTRACT_WHITELIST — Default-deny contract whitelist. Only contracts you've explicitly listed can be called.
  • ALLOWED_TOKENS — Default-deny token whitelist. Only listed tokens can move.

Here's how to configure a spending limit policy for a trading wallet:

curl -X POST http://127.0.0.1:3100/v1/policies \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: my-secret-password" \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "SPENDING_LIMIT",
    "rules": {
      "instant_max_usd": 100,
      "notify_max_usd": 500,
      "delay_max_usd": 2000,
      "delay_seconds": 900,
      "daily_limit_usd": 5000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

This means transactions under $100 execute immediately, $100–$500 fire with a notification, $500–$2000 are queued for 15 minutes before executing (cancellable if you catch a bad signal), and anything over $2000 requires explicit human approval. You set these numbers based on your strategy's expected trade size, and then your bot operates within that envelope automatically.

The 7-Stage Transaction Pipeline

Understanding how WAIaaS processes a transaction helps you reason about latency and failure modes for your bot:

  1. stage1-validate — Schema and input validation
  2. stage2-auth — Session token verification
  3. stage3-policy — Policy engine evaluation (all 21 policy types checked here)
  4. stage4-wait — Gas condition check, delay execution if configured
  5. stage5-execute — Transaction broadcast
  6. stage6-confirm — On-chain confirmation monitoring

For a trading bot, stages 3 and 4 are where your risk controls live. If a policy blocks a transaction, you get back a structured error:

{
  "error": {
    "code": "POLICY_DENIED",
    "message": "Transaction denied by SPENDING_LIMIT policy",
    "domain": "POLICY",
    "retryable": false
  }
}
Enter fullscreen mode Exit fullscreen mode

The retryable field tells your bot whether to retry or escalate. POLICY_DENIED is not retryable — the human needs to either approve the transaction or adjust the policy. This is intentional: your bot shouldn't be able to loop around a policy violation.

Multi-Protocol Trading: One Wallet, Full Coverage

The practical implication of 15 integrated protocols is that your bot can execute a multi-leg strategy through a single wallet session without juggling multiple key management systems. Swap on Jupiter, open a hedge on Drift, bridge collateral via LI.FI or Across — all authenticated with the same session token, all subject to the same policy layer.

The TypeScript SDK makes this clean in code:

import { WAIaaSClient } from '@waiaas/sdk';

const client = new WAIaaSClient({
  baseUrl: process.env['WAIAAS_BASE_URL'] ?? 'http://localhost:3100',
  sessionToken: process.env['WAIAAS_SESSION_TOKEN'],
});

// Check balance before executing strategy
const balance = await client.getBalance();
console.log(`Balance: ${balance.balance} ${balance.symbol} (${balance.chain}/${balance.network})`);

// Submit the trade
const sendResult = await client.sendToken({
  type: 'TRANSFER',
  to: 'recipient-address',
  amount: '0.001',
});
console.log(`Transaction submitted: ${sendResult.id} (status: ${sendResult.status})`);

// Poll for confirmation
const POLL_TIMEOUT_MS = 60_000;
const startTime = Date.now();
while (Date.now() - startTime < POLL_TIMEOUT_MS) {
  const tx = await client.getTransaction(sendResult.id);
  if (tx.status === 'COMPLETED') {
    console.log(`Transaction confirmed! Hash: ${tx.txHash}`);
    break;
  }
  if (tx.status === 'FAILED') {
    console.error(`Transaction failed: ${tx.error}`);
    break;
  }
  await new Promise(resolve => setTimeout(resolve, 1000));
}
Enter fullscreen mode Exit fullscreen mode

Error handling in the SDK surfaces policy violations, balance issues, and token expiry as typed errors:

import { WAIaaSClient, WAIaaSError } from '@waiaas/sdk';

try {
  const tx = await client.sendToken({ to: '...', amount: '1.0' });
} catch (error) {
  if (error instanceof WAIaaSError) {
    console.error(`API Error: [${error.code}] ${error.message}`);
    // error.code examples: INSUFFICIENT_BALANCE, POLICY_DENIED, TOKEN_EXPIRED
  }
}
Enter fullscreen mode Exit fullscreen mode

Quick Start for Trading Bot Builders

Getting a trading bot connected to WAIaaS takes five steps:

1. Install and initialize the CLI

npm install -g @waiaas/cli
waiaas init
waiaas start
Enter fullscreen mode Exit fullscreen mode

2. Start the daemon with Docker (production)

git clone https://github.com/waiaas/WAIaaS.git
cd WAIaaS
docker compose up -d
Enter fullscreen mode Exit fullscreen mode

3. Create a trading wallet

curl -X POST http://127.0.0.1:3100/v1/wallets \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: my-secret-password" \
  -d '{"name": "trading-wallet", "chain": "solana", "environment": "mainnet"}'
Enter fullscreen mode Exit fullscreen mode

4. Create a session token for your bot

curl -X POST http://127.0.0.1:3100/v1/sessions \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: my-secret-password" \
  -d '{"walletId": "<wallet-uuid>"}'
Enter fullscreen mode Exit fullscreen mode

5. Configure perp guardrails

curl -X POST http://127.0.0.1:3100/v1/policies \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: my-secret-password" \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "PERP_MAX_LEVERAGE",
    "rules": {"maxLeverage": 5}
  }'
Enter fullscreen mode Exit fullscreen mode

Your bot now has a wallet, a session token with bounded permissions, and a leverage cap enforced at the infrastructure layer — not in your strategy code.

What's Next

The OpenAPI 3.0 spec at http://127.0.0.1:3100/doc and the interactive reference at http://127.0.0.1:3100/reference are the fastest way to explore all 39 route modules and understand what's available for your specific trading use case. From there, the policy engine documentation and the 45 MCP tools give you the full picture of what you can automate and what you should keep under human oversight.

If you're building a serious trading bot and want wallet infrastructure that doesn't require you to also build a risk management layer from scratch, WAIaaS is worth running locally for a weekend:

The daemon runs in Docker, the policy engine is configurable through the REST API, and the 15 protocol integrations mean you're not shipping another bespoke SDK integration every time you want to add a new venue to your strategy.

Top comments (0)