DEV Community

Cover image for Atomic Multi-Operation Trading: Batch Transaction APIs for DeFi Bots
Wallet Guy
Wallet Guy

Posted on

Atomic Multi-Operation Trading: Batch Transaction APIs for DeFi Bots

Automated trading bots fail when they can't execute multi-step DeFi operations atomically. Your arbitrage opportunity disappears while your bot makes separate API calls to swap tokens, hedge positions, and bridge assets across chains. WAIaaS solves this with batch transaction APIs that bundle multiple operations into single atomic executions.

Why Atomic Operations Matter for Trading Bots

In high-frequency DeFi trading, timing is everything. A profitable arbitrage window might last only 2-3 blocks. Your bot spots a price discrepancy between Jupiter and Drift, but by the time it executes separate transactions for the swap, the hedge trade, and the position adjustment, the opportunity is gone.

Traditional wallet infrastructure forces bots into sequential operations. Each transaction requires separate gas estimation, signing, and confirmation. Network congestion can delay any step, and partial execution leaves your bot exposed to slippage and market risk.

Professional trading operations need wallet infrastructure that matches their execution requirements: atomic multi-step operations, gas optimization, and built-in risk controls that don't slow down profitable trades.

Batch Transaction API for Complex Trading Strategies

WAIaaS provides atomic batch execution through its REST API. Instead of managing multiple wallet connections and transaction sequences, your bot sends one batch request containing all operations.

Here's a complete arbitrage strategy executed atomically:

curl -X POST http://127.0.0.1:3100/v1/transactions/batch \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "transactions": [
      {
        "type": "TokenTransfer",
        "to": "jupiter-program",
        "token": "So11111111111111111111111111111111111111112",
        "amount": "10000000000"
      },
      {
        "type": "ContractCall",
        "to": "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4",
        "data": "swap_exact_tokens_for_tokens_data"
      },
      {
        "type": "ContractCall",
        "to": "drift-program-id",
        "data": "open_hedge_position_data"
      }
    ],
    "gasCondition": {
      "maxGasPrice": "50000000000"
    }
  }'
Enter fullscreen mode Exit fullscreen mode

The batch executes all-or-nothing. If any transaction fails, the entire batch reverts, protecting your bot from partial execution risk.

Multi-Protocol Access Through Single API

WAIaaS integrates 15 DeFi protocols: jupiter-swap, drift, hyperliquid, lifi, across, aave-v3, lido-staking, jito-staking, kamino, pendle, polymarket, xrpl-dex, zerox-swap, dcent-swap, and erc8004. Your bot accesses all protocols through consistent REST endpoints.

Execute a cross-chain arbitrage strategy:

# Step 1: Swap on Solana via Jupiter
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": "5000000000",
    "slippageBps": 50
  }'

# Step 2: Bridge to Ethereum via LI.FI
curl -X POST http://127.0.0.1:3100/v1/actions/lifi/bridge \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "fromChain": "solana",
    "toChain": "ethereum",
    "fromToken": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    "toToken": "0xA0b86a33E6441b0094bE12C31a9f63C365b35D48",
    "amount": "1000000"
  }'

# Step 3: Hedge position on Hyperliquid
curl -X POST http://127.0.0.1:3100/v1/actions/hyperliquid/order \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "asset": "ETH",
    "side": "short",
    "orderType": "market",
    "sz": "1.5"
  }'
Enter fullscreen mode Exit fullscreen mode

Each protocol maintains its native API structure while using WAIaaS authentication and risk controls.

Gas Optimization and Conditional Execution

Professional bots need gas optimization built into their execution layer. WAIaaS provides gas conditional execution — transactions only execute when gas meets your price thresholds.

Set gas conditions in any transaction:

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",
    "gasCondition": {
      "maxGasPrice": "30000000000",
      "timeoutSeconds": 300
    }
  }'
Enter fullscreen mode Exit fullscreen mode

The transaction queues until gas drops below 30 gwei, then executes automatically. Your bot maintains profitability by avoiding expensive execution costs.

For high-frequency operations, simulate transactions before execution:

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

The dry-run API returns gas estimates and success probability without spending gas, letting your bot validate strategies before committing capital.

Built-in Risk Management Without Latency

Trading bots need risk controls that don't kill performance. WAIaaS provides 4-tier policy enforcement with microsecond execution for approved operations.

Configure spending limits for your trading bot:

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": 1000,
      "notify_max_usd": 5000,
      "delay_max_usd": 20000,
      "delay_seconds": 60,
      "daily_limit_usd": 100000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Small trades execute instantly. Large trades trigger notifications or delays. This protects against bot malfunctions while maintaining execution speed for normal operations.

Set protocol-specific limits:

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,
      "protocols": ["hyperliquid", "drift"]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Your bot can trade aggressively within defined risk parameters without manual oversight.

TypeScript SDK for Bot Development

The WAIaaS TypeScript SDK provides typed interfaces optimized for algorithmic trading:

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

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

// Execute atomic arbitrage strategy
async function executeArbitrage(token0: string, token1: string, amount: string) {
  // Check current positions
  const positions = await client.getDeFiPositions();
  const balance = await client.getBalance();

  // Execute batch trade
  const batch = await client.sendBatch([
    {
      type: 'ContractCall',
      to: jupiterProgram,
      data: buildSwapInstruction(token0, token1, amount),
    },
    {
      type: 'ContractCall', 
      to: driftProgram,
      data: buildHedgeInstruction(token1, amount),
    }
  ]);

  return batch.id;
}
Enter fullscreen mode Exit fullscreen mode

The SDK handles authentication, error recovery, and response parsing while maintaining the low-latency execution your bot requires.

Real-time Portfolio Monitoring

Monitor your bot's positions across all integrated protocols:

curl http://127.0.0.1:3100/v1/wallet/defi-positions \
  -H "Authorization: Bearer wai_sess_<token>"
Enter fullscreen mode Exit fullscreen mode

Returns consolidated position data:

{
  "lending": {
    "aave-v3": [{"asset": "USDC", "supplied": "50000", "apy": "4.2%"}],
    "kamino": [{"asset": "SOL", "supplied": "100", "apy": "7.8%"}]
  },
  "staking": {
    "lido-staking": [{"asset": "ETH", "staked": "32", "rewards": "1.2"}],
    "jito-staking": [{"asset": "SOL", "staked": "500", "rewards": "12.5"}]
  },
  "trading": {
    "hyperliquid": [{"market": "ETH-USD", "size": "-2.5", "pnl": "+$245"}],
    "drift": [{"market": "SOL-PERP", "size": "100", "pnl": "-$12"}]
  }
}
Enter fullscreen mode Exit fullscreen mode

Your bot can make informed decisions based on real-time position data across all protocols.

Quick Start: Deploy Your Trading Bot

Step 1: Install and Initialize

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

Step 2: Create Trading Wallet

waiaas wallet create --name trading-bot --chain solana --network mainnet
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Risk Policies

# Set up spending limits and protocol restrictions via Admin UI
open http://127.0.0.1:3100/admin
Enter fullscreen mode Exit fullscreen mode

Step 4: Install SDK and Start Trading

npm install @waiaas/sdk
# Build your bot using the SDK examples above
Enter fullscreen mode Exit fullscreen mode

Step 5: Deploy with Docker

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

What's Next

Ready to build profitable trading bots with atomic execution? Start with the WAIaaS GitHub repository at https://github.com/minhoyoo-iotrust/WAIaaS for complete documentation and examples. For production deployment and advanced features, visit https://waiaas.ai to explore enterprise options with dedicated infrastructure and priority support.

Top comments (0)