DEV Community

Cover image for Smart Contract Calls for AI Agents: Encoding and Execution
Wallet Guy
Wallet Guy

Posted on

Smart Contract Calls for AI Agents: Encoding and Execution

Smart contracts are the backbone of DeFi, but integrating them into AI agent workflows remains a complex challenge for developers building automated trading systems, yield optimizers, and portfolio rebalancers. Each protocol has its own SDK, data formats, and quirks — forcing teams to maintain dozens of integrations just to access basic DeFi functionality.

Why DeFi Integration Complexity Matters

Modern DeFi strategies require interaction with multiple protocols: swap on Jupiter or Uniswap, lend on Aave or Kamino, stake with Lido or Jito, bridge via LI.FI or Across. A simple yield strategy might touch 5+ protocols, each requiring separate authentication, transaction encoding, gas estimation, and error handling.

For AI agents, this complexity multiplies. They need to understand not just how to call contracts, but when to call them based on market conditions, how to handle failures gracefully, and how to respect user-defined risk limits. Traditional smart contract libraries weren't designed for autonomous decision-making.

The Unified DeFi API Solution

WAIaaS provides a single REST API that abstracts away protocol-specific complexity while preserving the full power of smart contract interactions. Instead of learning 14 different DeFi protocol SDKs, developers can access Jupiter, Aave, Lido, Drift, Hyperliquid, and 9 other protocols through consistent endpoints.

Universal Action Execution

The core concept is "actions" — protocol-specific operations that handle encoding, gas estimation, and execution automatically:

# Swap SOL for USDC on 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": "1000000000",
    "slippageBps": 50
  }'
Enter fullscreen mode Exit fullscreen mode

This single call handles Jupiter API integration, transaction building, signing, submission, and confirmation tracking. No need to understand Solana's instruction format or Jupiter's SDK specifics.

Cross-Chain Protocol Coverage

WAIaaS integrates 14 DeFi protocols across EVM and Solana:

Trading & Swaps:

  • Jupiter (Solana DEX aggregator)
  • 0x Protocol (EVM DEX aggregator)
  • D'CENT Swap (hardware wallet integration)

Lending & Borrowing:

  • Aave v3 (multi-chain lending)
  • Kamino (Solana lending with leveraged strategies)

Liquid Staking:

  • Lido (ETH/MATIC/SOL staking)
  • Jito (Solana MEV-optimized staking)

Cross-Chain:

  • LI.FI (bridge aggregator)
  • Across (optimistic bridging)

Derivatives:

  • Hyperliquid (perpetual futures)
  • Drift (Solana perps and spot)
  • Polymarket (prediction markets)

Yield Strategies:

  • Pendle (yield tokenization)

Smart Contract Call Abstraction

For protocols not yet integrated, WAIaaS provides low-level contract call capabilities with automatic encoding:

# Call any contract method
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": "0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9",
    "value": "0",
    "data": "0xa415bcad000000000000000000000000a0b86a33e6411",
    "gasLimit": "200000"
  }'
Enter fullscreen mode Exit fullscreen mode

Or use the encoding helper to build transaction data:

# Encode function call data
curl -X POST http://127.0.0.1:3100/v1/contracts/encode \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "contractAddress": "0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9",
    "functionName": "deposit",
    "inputs": [
      {"type": "address", "value": "0xA0b86a33E6411"},
      {"type": "uint256", "value": "1000000000000000000"},
      {"type": "address", "value": "0x742d35Cc6634C0532925a3b8D2b3D3b"}
    ]
  }'
Enter fullscreen mode Exit fullscreen mode

Policy-Driven Risk Management

DeFi operations carry significant financial risk. WAIaaS implements a 21-policy system with 4 security tiers to ensure AI agents operate within defined boundaries:

Protocol and Asset Whitelisting

# Create DeFi asset whitelist policy
curl -X POST http://127.0.0.1:3100/v1/policies \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: <password>" \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "LENDING_ASSET_WHITELIST",
    "rules": {
      "allowed_assets": [
        {"symbol": "USDC", "address": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"},
        {"symbol": "SOL", "address": "native:solana"}
      ]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Leverage and Position Limits

# Set maximum leverage for perpetual futures
curl -X POST http://127.0.0.1:3100/v1/policies \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: <password>" \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "PERP_MAX_LEVERAGE",
    "rules": {
      "max_leverage": 5.0,
      "allowed_venues": ["hyperliquid", "drift"]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Spending Limits with Time Delays

# 4-tier spending controls
curl -X POST http://127.0.0.1:3100/v1/policies \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: <password>" \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "SPENDING_LIMIT",
    "rules": {
      "instant_max_usd": 100,
      "notify_max_usd": 1000,
      "delay_max_usd": 5000,
      "delay_seconds": 900,
      "daily_limit_usd": 10000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Multi-Protocol Portfolio Management

WAIaaS aggregates positions across all integrated protocols, providing a unified view of DeFi exposure:

# Get all DeFi positions across protocols
curl http://127.0.0.1:3100/v1/defi/positions \
  -H "Authorization: Bearer wai_sess_<token>"
Enter fullscreen mode Exit fullscreen mode

Example response shows positions across multiple protocols:

{
  "positions": [
    {
      "protocol": "aave-v3",
      "type": "LENDING",
      "asset": "USDC",
      "amount": "5000.00",
      "apy": 4.2,
      "healthFactor": 2.1
    },
    {
      "protocol": "lido-staking",
      "type": "STAKING",
      "asset": "ETH",
      "amount": "2.5",
      "apy": 3.8,
      "rewards": "0.095"
    },
    {
      "protocol": "hyperliquid",
      "type": "PERPETUAL",
      "market": "BTC-PERP",
      "size": "0.1",
      "pnl": "+125.50",
      "leverage": 3.0
    }
  ],
  "totalValueUsd": 18742.33
}
Enter fullscreen mode Exit fullscreen mode

Quick Start: Build a DeFi Yield Strategy

Step 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

Step 2: Create Wallets and Sessions

npm install -g @waiaas/cli
waiaas quickset --mode mainnet  # Creates EVM + Solana wallets automatically
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Up DeFi Policies

# Allow specific protocols and set spending limits
waiaas quickstart --template defi-trader
Enter fullscreen mode Exit fullscreen mode

Step 4: Execute Multi-Protocol Strategy

Use the TypeScript SDK to build a simple yield optimizer:

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

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

// Get current DeFi positions
const positions = await client.getDeFiPositions();
console.log('Current positions:', positions);

// Rebalance based on APY opportunities
if (positions.aave_usdc_apy < 4.0 && positions.kamino_usdc_apy > 5.0) {
  // Withdraw from Aave, deposit to Kamino
  await client.executeAction('aave-v3', 'withdraw', {
    asset: 'USDC',
    amount: '1000'
  });

  await client.executeAction('kamino', 'deposit', {
    asset: 'USDC', 
    amount: '1000'
  });
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Monitor and Adjust

The Admin Web UI at http://127.0.0.1:3100/admin provides real-time monitoring of DeFi positions, transaction history, and policy enforcement across all integrated protocols.

Building DeFi integrations doesn't have to mean managing 14 different SDKs and APIs. WAIaaS provides the unified interface that lets your AI agents focus on strategy rather than protocol plumbing.

Ready to simplify your DeFi development? Check out the WAIaaS GitHub repository for the complete source code, or visit waiaas.ai to dive deeper into the documentation and see more protocol examples in action.

Top comments (0)