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:
- Execute across Pendle and connected protocols (lending, bridging, staking) without managing separate wallet integrations for each
- Avoid wasting gas on transactions that will fail policy checks or hit insufficient balances
- Apply risk controls at the infrastructure level — not bolted on in application code that can have bugs
- Let you observe and intervene when positions move against you, without shutting down the entire system
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:
- Validate catches malformed transactions before they touch the network
- Auth verifies your session is valid — no surprise authorization failures mid-trade
- Policy applies your risk rules before execution — spending limits, allowed tokens, contract whitelists
- Wait handles gas conditions and time delays
- Execute submits to chain
- Confirm tracks the transaction to completion
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:
- SPENDING_LIMIT — 4-tier security based on transaction amount. Small routine trades execute instantly; large position entries require your approval via WalletConnect or Telegram
- CONTRACT_WHITELIST — default-deny contract whitelist. Your bot can only interact with Pendle contracts and the other protocols you explicitly list. No scope creep, no accidental interactions with unvetted contracts
- ALLOWED_TOKENS — default-deny token whitelist. The bot can only transact in assets you've approved
- PERP_MAX_LEVERAGE — if your strategy involves leveraged positions on Drift, cap the leverage at the infrastructure level
- PERP_MAX_POSITION_USD — hard cap on position size in USD, enforced before execution
- LENDING_LTV_LIMIT — max loan-to-value ratio for lending positions, relevant if your strategy uses Aave v3 leverage
- RATE_LIMIT — max transactions per period, useful for preventing runaway bots from draining gas
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:
- Incoming transaction monitoring with real-time notifications for deposits — you know when funds arrive
- WalletConnect integration for owner approval of APPROVAL-tier transactions — your phone becomes the hardware approval step for large trades
- Transaction history queryable via the SDK with
listTransactions() - 39 REST API route modules exposed for custom monitoring integrations
- OpenAPI 3.0 spec at
/docand interactive reference at/reference— useful when building custom dashboards
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
- Deploy the daemon via Docker with
WAIAAS_AUTO_PROVISION=true— takes about 60 seconds - Create a dedicated trading wallet — never use a wallet for multiple bots
- Set up CONTRACT_WHITELIST and SPENDING_LIMIT policies before funding — default-deny means nothing executes until you explicitly allow it
- Test with dry-run — use
dryRun: trueto validate your transaction logic before going live - 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:
- GitHub: https://github.com/minhoyoo-iotrust/WAIaaS
- Official site: https://waiaas.ai
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.