DEV Community

Cover image for Multi-Chain Trading Bots: Jupiter Swaps + Drift Perps in One Wallet
Wallet Guy
Wallet Guy

Posted on

Multi-Chain Trading Bots: Jupiter Swaps + Drift Perps in One Wallet

Multi-chain trading bots face a fundamental challenge: every protocol swap, perpetual trade, or bridge operation requires separate wallet integrations, gas management, and risk controls. Your arbitrage opportunity might be profitable on paper, but execution across Jupiter swaps and Drift perpetuals means juggling multiple SDKs, monitoring gas prices, and hoping your bot doesn't drain funds on a bad trade.

Why Unified Trading Infrastructure Matters

Modern DeFi arbitrage and trading strategies span multiple protocols and chains. You might spot a price discrepancy that requires swapping on Jupiter, opening a hedge position on Drift perpetuals, then bridging profits via LI.FI — all within the same block to capture the spread.

Traditional bot architectures force you to integrate each protocol separately: Jupiter SDK for swaps, Drift SDK for perpetuals, custom bridge logic for cross-chain moves. Each integration brings its own wallet management, error handling, and security considerations. Your bot becomes a patchwork of different APIs, gas estimation strategies, and failure modes.

The stakes get higher when you add risk management. A successful trading bot needs spending limits, position size controls, and emergency shutoffs. Building these safeguards into every protocol integration multiplies complexity exponentially.

One Wallet, All Protocols

WAIaaS provides unified wallet infrastructure specifically designed for trading bots. Instead of managing separate integrations for 15 DeFi protocols, your bot makes HTTP calls to a single API that handles Jupiter swaps, Drift perpetuals, Hyperliquid futures, cross-chain bridges, and more.

Here's how your bot executes a multi-protocol arbitrage trade:

# 1. Check current positions across all protocols
curl http://127.0.0.1:3100/v1/defi/positions \
  -H "Authorization: Bearer wai_sess_<token>"
# Returns: Jupiter LP positions, Drift perp positions, Hyperliquid futures

# 2. Execute Jupiter swap (Solana)
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",
    "slippagePercentage": 0.5
  }'

# 3. Open hedge position on Drift perpetuals
curl -X POST http://127.0.0.1:3100/v1/actions/drift/place-order \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "marketIndex": 1,
    "direction": "short",
    "baseAssetAmount": "100000000",
    "price": "65000000000",
    "orderType": "limit"
  }'
Enter fullscreen mode Exit fullscreen mode

Each protocol action returns a consistent transaction format with standardized error codes. Your bot doesn't need to understand Jupiter's transaction structure versus Drift's order format — WAIaaS normalizes everything into the same response schema.

Gas Conditional Execution

Trading bots often waste profits on high gas fees during network congestion. WAIaaS includes gas conditional execution — transactions only execute when gas prices meet your threshold.

# Set gas condition: only execute when gas < 50 gwei
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": "CONTRACT_CALL",
    "to": "0x7a250d5630b4cf539739df2c5dacb4c659f2488d",
    "data": "0x...",
    "gasCondition": {
      "maxGasPrice": "50000000000",
      "timeoutSeconds": 300
    }
  }'
Enter fullscreen mode Exit fullscreen mode

The transaction enters a queue and executes automatically when gas drops below 50 gwei, or times out after 5 minutes. Your arbitrage logic runs continuously while WAIaaS handles the timing optimization.

Built-in Risk Management

Professional trading bots need multiple layers of risk control. WAIaaS provides policy-based risk management that prevents runaway bots from draining wallets:

# Create spending limits with 4-tier security
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": 1000,
      "delay_max_usd": 5000,
      "delay_seconds": 300,
      "daily_limit_usd": 10000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Small trades (under $100) execute instantly. Medium trades ($100-1000) execute with notifications. Large trades ($1000-5000) wait 5 minutes before execution, giving you time to cancel. Trades over $5000 require manual approval via WalletConnect or Telegram.

Add protocol-specific limits:

# Limit perpetual futures leverage and position sizes
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}
  }'

# Restrict to specific trading venues
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": "VENUE_WHITELIST",
    "rules": {
      "venues": ["jupiter-swap", "drift", "hyperliquid"]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Real-Time Position Monitoring

Trading bots need continuous visibility into positions across all protocols. WAIaaS aggregates positions from all 15 integrated DeFi protocols into a single dashboard:

# Get unified portfolio view
curl http://127.0.0.1:3100/v1/defi/positions \
  -H "Authorization: Bearer wai_sess_<token>"
Enter fullscreen mode Exit fullscreen mode

Response includes:

  • Jupiter liquidity provider positions
  • Drift perpetual futures positions and PnL
  • Hyperliquid spot and perpetual positions
  • Aave lending positions and health factors
  • Kamino yield farming positions

Your monitoring logic gets a complete portfolio snapshot in one API call instead of querying each protocol separately.

TypeScript SDK for High-Performance Bots

The TypeScript SDK provides zero-dependency, high-performance access optimized for trading bots:

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

const client = new WAIaaSClient({
  baseUrl: 'http://127.0.0.1:3100',
  sessionToken: process.env.WAIAAS_SESSION_TOKEN,
});

// Execute multi-protocol arbitrage strategy
async function executeArbitrage() {
  // 1. Check current positions
  const positions = await client.getDeFiPositions();

  // 2. Execute Jupiter swap
  const swap = await client.executeAction('jupiter-swap', 'swap', {
    inputMint: 'So11111111111111111111111111111111111111112',
    outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
    amount: '1000000000'
  });

  // 3. Wait for swap confirmation
  await client.waitForTransaction(swap.id);

  // 4. Open Drift hedge position
  const hedge = await client.executeAction('drift', 'place-order', {
    marketIndex: 1,
    direction: 'short',
    baseAssetAmount: '100000000'
  });

  console.log(`Arbitrage complete: swap=${swap.txHash}, hedge=${hedge.txHash}`);
}
Enter fullscreen mode Exit fullscreen mode

The SDK handles connection pooling, request retries, and error normalization. Your bot logic focuses on trading strategy while WAIaaS handles the infrastructure.

Quick Start: Multi-Protocol Trading Bot

Get a trading bot running with Jupiter swaps and Drift perpetuals in under 5 minutes:

  1. Deploy WAIaaS with Docker:
git clone https://github.com/minhoyoo-iotrust/WAIaaS.git
cd WAIaaS
docker compose up -d
Enter fullscreen mode Exit fullscreen mode
  1. Create a trading wallet:
npm install -g @waiaas/cli
waiaas quickset --mode mainnet
# Creates Solana + Ethereum wallets, prints session tokens
Enter fullscreen mode Exit fullscreen mode
  1. Install SDK and run your first trade:
npm install @waiaas/sdk
Enter fullscreen mode Exit fullscreen mode
import { WAIaaSClient } from '@waiaas/sdk';

const client = new WAIaaSClient({
  baseUrl: 'http://127.0.0.1:3100',
  sessionToken: 'wai_sess_<your-token>',
});

// Check SOL balance, execute Jupiter swap
const balance = await client.getBalance();
console.log(`SOL balance: ${balance.balance}`);

if (parseFloat(balance.balance) > 0.01) {
  const swap = await client.executeAction('jupiter-swap', 'swap', {
    inputMint: 'So11111111111111111111111111111111111111112', // SOL
    outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
    amount: '10000000' // 0.01 SOL
  });
  console.log(`Swap initiated: ${swap.id}`);
}
Enter fullscreen mode Exit fullscreen mode
  1. Add risk controls:
waiaas policy create SPENDING_LIMIT --instant-max 50 --daily-limit 500
Enter fullscreen mode Exit fullscreen mode
  1. Monitor via Web UI:
http://127.0.0.1:3100/admin
Enter fullscreen mode Exit fullscreen mode

Your trading bot now has access to Jupiter swaps, Drift perpetuals, Hyperliquid futures, and 12 other DeFi protocols through a single wallet interface.

What's Next

Professional trading bots need robust wallet infrastructure with multi-protocol access and built-in risk controls. WAIaaS provides the foundation to build sophisticated trading strategies without the complexity of managing multiple SDKs and wallet integrations.

Start building at GitHub or explore the full platform at waiaas.ai.

Top comments (0)