Automated Yield Optimization: Building Pendle Protocol Trading Bots

Automated Yield Optimization: Building Pendle Protocol Trading Bots

Pendle trading bots live and die by execution — your bot spotted the PT/YT mispricing, the yield curve shifted, and you have seconds before the market corrects. Building that bot on fragile wallet infrastructure means watching profitable trades fail at the signing step, burning gas on failed transactions, or — worse — having no risk controls when your bot misbehaves at 3am. WAIaaS gives you the wallet layer purpose-built for this: multi-protocol DeFi access, gas conditional execution, a 7-stage transaction pipeline, and a policy engine with 21 policy types so you can automate aggressively without losing sleep.

Why Yield Trading Bots Need Infrastructure, Not Just Code

Pendle splits yield-bearing assets into Principal Tokens (PT) and Yield Tokens (YT), creating a rich surface for yield curve arbitrage, fixed-rate locking, and leveraged yield plays. But the complexity doesn't stop at the strategy layer. Your bot needs to:

These are solved problems at the infrastructure layer. The mistake most bot builders make is solving them at the application layer, in the same codebase as their alpha. Separating concerns here is the difference between a bot you can maintain and one that becomes a liability.

What WAIaaS Brings to Pendle Bot Infrastructure

WAIaaS is a self-hosted Wallet-as-a-Service built for AI agents, but its architecture maps directly onto automated trading bot requirements. Let's walk through what matters for Pendle trading specifically.

15 DeFi Protocol Providers Out of the Box

WAIaaS integrates 15 DeFi protocol providers: aave-v3, across, dcent-swap, drift, erc8004, hyperliquid, jito-staking, jupiter-swap, kamino, lido-staking, lifi, pendle, polymarket, xrpl-dex, and zerox-swap. Pendle is directly integrated — your bot calls the action API, not a hand-rolled contract interaction layer you have to maintain.

For a Pendle yield optimization strategy that also hedges on Drift perpetuals or uses Aave v3 for leverage, all of that is accessible through a single wallet and a single session token. One bot, one API, multiple protocols.

Gas Conditional Execution

This one matters a lot for profitability. WAIaaS includes gas conditional execution — transactions execute only when the gas price meets your configured threshold. For a yield arb strategy where your edge is measured in basis points, paying 3x the expected gas because you submitted during a network spike can erase the trade entirely.

Configure your gas threshold at the infrastructure level and let the pipeline handle it. Your bot submits the intent; WAIaaS waits for the right conditions.

7-Stage Transaction Pipeline

Every transaction runs through a 7-stage pipeline: validate, auth, policy, wait, execute, confirm, and a final stages step. For a trading bot, this means:

You get this pipeline for free. Your bot doesn't need to implement retry logic, gas polling, or confirmation tracking — the daemon handles it.

The Policy Engine as a Risk Management Layer

The policy engine is where WAIaaS becomes genuinely useful for serious trading systems. 21 policy types, 4 security tiers (INSTANT, NOTIFY, DELAY, APPROVAL), and default-deny enforcement.

For a Pendle bot, relevant policies include:

Here's how you configure a spending limit for a Pendle trading session:

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
    }
  }'

Trades under $100 execute immediately. Trades between $100-$500 execute and notify you. Trades between $500-$2000 queue for 15 minutes (giving you time to cancel). Anything over $2000 requires your explicit approval. This is risk management built into the wall, not the application.

Setting Up Your Pendle Bot

Step 1: Spin Up the Daemon

docker run -d \
  --name waiaas \
  -p 127.0.0.1:3100:3100 \
  -v waiaas-data:/data \
  -e WAIAAS_AUTO_PROVISION=true \
  ghcr.io/minhoyoo-iotrust/waiaas:latest

# Retrieve auto-generated master password
docker exec waiaas cat /data/recovery.key

The daemon binds to localhost by default. For a trading bot running on the same machine, this is the right posture — don't expose it externally.

Step 2: Create a Wallet and Session

# 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": "pendle-bot", "chain": "evm", "environment": "mainnet"}'

# Create a session token for the bot process
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>"}'

The session token (wai_sess_...) is what your bot uses for all transaction operations. The master password stays out of the bot process entirely.

Step 3: Configure Your Risk Policies

Apply your CONTRACT_WHITELIST before funding the wallet. This ensures the bot can only touch the contracts you've vetted:

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": "CONTRACT_WHITELIST",
    "rules": {
      "contracts": [
        {"address": "<pendle-router-address>", "name": "Pendle Router", "chain": "ethereum-mainnet"},
        {"address": "<pendle-market-address>", "name": "Pendle Market", "chain": "ethereum-mainnet"}
      ]
    }
  }'

Step 4: Write Your Bot Using the TypeScript SDK

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

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

async function executePendleStrategy() {
  // Check balance before attempting trade
  const balance = await client.getBalance();
  console.log(`Balance: ${balance.balance} ${balance.symbol} (${balance.chain}/${balance.network})`);

  // Dry-run first to validate the transaction will pass policy checks
  // and simulate execution before committing gas
  const dryRun = await client.sendToken({
    type: 'TRANSFER',
    to: 'pendle-contract-address',
    amount: '0.1',
    dryRun: true,
  } as any);
  console.log(`Dry run status: ${dryRun.status}`);

  // Execute the actual Pendle action
  const tx = await client.sendToken({
    type: 'TRANSFER',
    to: 'pendle-contract-address',
    amount: '0.1',
  });

  // Poll for confirmation
  const POLL_TIMEOUT_MS = 60_000;
  const startTime = Date.now();
  while (Date.now() - startTime < POLL_TIMEOUT_MS) {
    const txStatus = await client.getTransaction(tx.id);
    if (txStatus.status === 'COMPLETED') {
      console.log(`Confirmed: ${txStatus.txHash}`);
      break;
    }
    if (txStatus.status === 'FAILED') {
      console.error(`Failed: ${txStatus.error}`);
      break;
    }
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
}

The dry-run API is particularly valuable for yield trading: simulate the transaction before committing gas, verify it passes all policy checks, and confirm the expected output before execution. This is a call to POST /v1/transactions/send with "dryRun": true in the payload.

Handling Policy Denials Gracefully

Your bot will hit policy denials. That's the point — the policy engine is catching things before they become problems. Handle them explicitly:

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
    
    if (error.code === 'POLICY_DENIED') {
      // Log the denied trade, alert, wait for manual approval
      // Do NOT retry automatically — that's how bots get into trouble
    }
  }
}

The error response format gives you a structured code, message, domain, and retryable flag:

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

Non-retryable errors like POLICY_DENIED should trigger an alert to your monitoring system, not a retry loop.

Multi-Protocol Yield Strategies

If your Pendle strategy involves more than just PT/YT swaps — say, borrowing on Aave v3 to lever up a yield position, then hedging duration risk on Drift — WAIaaS handles all of this through the actions API. The same session token, the same wallet, the same policy rules applying across every protocol.

The 15 integrated providers cover the main protocols a yield optimizer would touch. Bridging is covered by LI.FI and Across if your strategy spans chains. Liquid staking via Lido (EVM) and Jito (Solana) is available if part of your yield stack involves staked assets.

Observability and Human Override

For a trading bot running unattended, observability is not optional. WAIaaS provides:

The interactive API reference at http://127.0.0.1:3100/reference is worth bookmarking during development. You can test endpoints directly against your running instance, which speeds up the iteration loop considerably.

Quick Start Checklist

  1. Deploy the daemon via Docker with WAIAAS_AUTO_PROVISION=true — takes about 60 seconds
  2. Create a dedicated trading wallet — never use a wallet for multiple bots
  3. Set up CONTRACT_WHITELIST and SPENDING_LIMIT policies before funding — default-deny means nothing executes until you explicitly allow it
  4. Test with dry-run — use dryRun: true to validate your transaction logic before going live
  5. Configure WalletConnect for APPROVAL-tier override — your kill switch for large positions

The 20-command CLI (waiaas quickset, waiaas start, waiaas status, etc.) handles the initialization flow if you prefer not to script the API directly.

What's Next

The WAIaaS codebase is open-source and self-hosted — you control your keys, your data, and your infrastructure. Start with the GitHub repository to review the policy engine implementation and transaction pipeline before deploying capital:

The interactive API docs at /reference are the fastest way to understand the full surface area once your daemon is running. With 39 REST API routes, 45 MCP tools, and 21 policy types, there's significant depth to explore as your strategy matures — but the core flow for a Pendle trading bot is straightforward enough to have running in an afternoon.