DEV Community

Cover image for Smart Gas Management: How AI Agents Execute Only When Network Fees Are Low
Wallet Guy
Wallet Guy

Posted on

Smart Gas Management: How AI Agents Execute Only When Network Fees Are Low

Trading bots fail when gas spikes eat profits or when transactions execute at the worst possible moment. Your arbitrage opportunity vanishes, your MEV strategy becomes unprofitable, and your automated DeFi positions get liquidated because the bot couldn't adapt to network conditions.

Gas fees on Ethereum can swing from 10 gwei to 300+ gwei within minutes. Your trading bot spots a perfect arbitrage — buy on Uniswap, sell on SushiSwap for 2% profit — but by the time it executes, gas costs have consumed all gains. The opportunity was real, but the execution timing killed profitability.

Why Gas Management Makes or Breaks Trading Strategies

Professional trading operations monitor gas prices religiously. They queue transactions for optimal execution windows, cancel unprofitable trades when fees spike, and maintain separate execution strategies for different market conditions.

But building this infrastructure from scratch means writing gas estimation logic, implementing transaction queuing systems, integrating multiple RPC providers, and handling the edge cases that only surface during high-volatility periods. Most trading bot developers spend more time on wallet plumbing than on actual trading logic.

Gas Conditional Execution for Trading Bots

WAIaaS includes gas conditional execution in its 7-stage transaction pipeline. Your trading bot submits transactions with gas price thresholds — they only execute when network conditions meet your profitability requirements.

Here's how a gas-aware arbitrage bot works:

# Submit swap with gas condition — only execute if gas < 50 gwei
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",
    "gasCondition": {
      "maxGasPrice": "50",
      "timeoutSeconds": 300
    }
  }'
Enter fullscreen mode Exit fullscreen mode

The transaction enters a queue and monitors gas prices. When fees drop below 50 gwei, it executes automatically. If gas stays high for 300 seconds, it expires. Your bot's profit margins stay protected.

WAIaaS supports 15 DeFi protocol providers across multiple chains: jupiter-swap and drift on Solana, Uniswap and Aave on Ethereum, plus cross-chain bridges via LI.FI and Across. One API handles swaps, perpetual futures, lending, staking, and bridging operations.

Multi-Protocol Trading Infrastructure

Professional trading requires access to multiple protocols simultaneously. Your bot might swap on Jupiter, open a hedge position on Hyperliquid, stake rewards via Lido, and bridge profits to L2s for cheaper operations.

Here's a complete multi-step trading sequence:

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

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

// Step 1: Check current positions across all protocols
const positions = await client.getDeFiPositions();
console.log('Current DeFi positions:', positions);

// Step 2: Execute arbitrage swap (gas-conditional)
const swapTx = await client.executeAction('jupiter-swap', 'swap', {
  inputMint: 'So11111111111111111111111111111111111111112',
  outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  amount: '1000000000',
  gasCondition: { maxGasPrice: '30', timeoutSeconds: 180 }
});

// Step 3: Open hedge position on Hyperliquid
const hedgeTx = await client.executeAction('hyperliquid', 'openPosition', {
  market: 'SOL-PERP',
  size: '-0.5',  // Short position
  leverage: 3
});

// Step 4: Monitor execution
const POLL_TIMEOUT = 60000;
const startTime = Date.now();
while (Date.now() - startTime < POLL_TIMEOUT) {
  const swap = await client.getTransaction(swapTx.id);
  const hedge = await client.getTransaction(hedgeTx.id);

  if (swap.status === 'COMPLETED' && hedge.status === 'COMPLETED') {
    console.log('Arbitrage + hedge executed successfully');
    break;
  }

  await new Promise(resolve => setTimeout(resolve, 1000));
}
Enter fullscreen mode Exit fullscreen mode

Risk Controls for Automated Trading

Trading bots need circuit breakers. WAIaaS provides a policy engine with 21 policy types and 4 security tiers to prevent runaway strategies from draining accounts.

Set spending limits that adapt to market volatility:

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": 300,
      "daily_limit_usd": 50000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Trades under $1,000 execute instantly. Larger trades trigger notifications or delays for review. Daily limits prevent catastrophic losses from strategy malfunctions.

Create token and contract whitelists to prevent your bot from interacting with malicious contracts:

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": "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4", "name": "Jupiter", "chain": "solana"},
        {"address": "dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH", "name": "Drift", "chain": "solana"}
      ]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Your bot can only interact with approved protocols. Attempts to call unknown contracts get blocked automatically.

Production Deployment for Trading Operations

Trading bots need zero-downtime infrastructure. WAIaaS runs in Docker with health checks, automatic restarts, and volume persistence:

services:
  daemon:
    image: ghcr.io/minhoyoo-iotrust/waiaas:latest
    container_name: trading-wallet
    ports:
      - "127.0.0.1:3100:3100"
    volumes:
      - trading-data:/data
    environment:
      - WAIAAS_DATA_DIR=/data
      - WAIAAS_DAEMON_LOG_LEVEL=warn
      - WAIAAS_RPC_SOLANA_MAINNET=https://mainnet.helius-rpc.com/?api-key=<key>
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3100/health"]
      interval: 10s
      timeout: 3s
      retries: 5

volumes:
  trading-data:
    driver: local
Enter fullscreen mode Exit fullscreen mode

Use dedicated RPC endpoints for reliable access during high-traffic periods. The daemon handles connection failures, retries, and transaction confirmation tracking automatically.

Quick Start for Trading Bot Integration

Get your trading infrastructure running in 5 minutes:

  1. Deploy WAIaaS daemon:
git clone https://github.com/minhoyoo-iotrust/WAIaaS.git
cd WAIaaS
docker compose up -d
Enter fullscreen mode Exit fullscreen mode
  1. Create trading wallet and session:
npm install -g @waiaas/cli
waiaas init
waiaas start
waiaas wallet create --name "trading-bot" --chain solana
waiaas session prompt  # Creates session for your bot
Enter fullscreen mode Exit fullscreen mode
  1. Set up risk policies:
# Daily spending limit + contract whitelist
waiaas quickset --mode mainnet  # Creates sensible defaults
Enter fullscreen mode Exit fullscreen mode
  1. Install SDK and start trading:
npm install @waiaas/sdk
Enter fullscreen mode Exit fullscreen mode
  1. Test gas-conditional execution:
const { WAIaaSClient } = require('@waiaas/sdk');
const client = new WAIaaSClient({
  baseUrl: 'http://127.0.0.1:3100',
  sessionToken: 'your-session-token'
});

// Your first gas-aware trade
const result = await client.executeAction('jupiter-swap', 'swap', {
  inputMint: 'So11111111111111111111111111111111111111112',
  outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  amount: '100000000',
  gasCondition: { maxGasPrice: '25', timeoutSeconds: 120 }
});
Enter fullscreen mode Exit fullscreen mode

Your trading bot now has professional-grade wallet infrastructure with gas optimization, multi-protocol access, and built-in risk controls. Focus on alpha generation, not wallet management.

What's Next

Gas conditional execution is just one piece of automated trading infrastructure. WAIaaS provides the complete foundation: multi-chain wallets, DeFi protocol integrations, policy enforcement, and production deployment tools. Explore the full platform at GitHub or visit waiaas.ai for documentation and examples.

Top comments (0)