DEV Community

Cover image for Python SDK for AI Agents: Async Wallet Control with Zero Dependencies
Wallet Guy
Wallet Guy

Posted on

Python SDK for AI Agents: Async Wallet Control with Zero Dependencies

Your AI agents can browse the web, write code, and manage files—but can they control a crypto wallet? Most AI agent frameworks stop at the edge of financial transactions, leaving a critical gap for agents that need to interact with DeFi protocols, pay for API calls with crypto, or manage digital assets autonomously.

Why Wallet Integration Matters for AI Agents

AI agents are becoming increasingly autonomous, but they hit a wall when they need to handle money. Whether it's an agent that needs to:

  • Pay for premium API calls using crypto micropayments
  • Execute DeFi strategies based on market conditions
  • Manage NFT portfolios automatically
  • Bridge assets between different blockchain networks

The missing piece has always been secure, programmable wallet access. Traditional wallet solutions require manual approval for every transaction, breaking the autonomous flow that makes AI agents powerful.

Python SDK: Zero Dependencies, Maximum Control

WAIaaS provides a Python SDK (waiaas) with async/await support and zero external dependencies. This means your AI agents can control wallets without bloating your dependency tree or introducing security vulnerabilities from third-party packages.

The Python SDK gives your agents access to 18 networks across 2 chain types (solana, evm), with built-in support for 15 DeFi protocol providers integrated including Jupiter swap, Lido staking, Hyperliquid perpetual futures, and Polymarket prediction markets.

Getting Started with the Python SDK

Here's how to give your AI agent wallet superpowers:

pip install waiaas
Enter fullscreen mode Exit fullscreen mode

First, you'll need a running WAIaaS daemon. The fastest way is with Docker:

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
Enter fullscreen mode Exit fullscreen mode

Now your agent can interact with the wallet:

from waiaas import WAIaaSClient

async with WAIaaSClient("http://localhost:3100", "wai_sess_xxx") as client:
    balance = await client.get_balance()
    print(balance.balance, balance.symbol)
Enter fullscreen mode Exit fullscreen mode

Real-World Agent Integration Example

Let's build an agent that can autonomously manage a DeFi portfolio. This example shows how an AI agent can check balances, execute swaps, and monitor positions:

from waiaas import WAIaaSClient
import asyncio

class DeFiAgent:
    def __init__(self, session_token):
        self.client = WAIaaSClient("http://localhost:3100", session_token)

    async def rebalance_portfolio(self, target_usdc_ratio=0.5):
        """Rebalance portfolio to maintain target USDC ratio"""

        # Check current positions
        balance = await self.client.get_balance()
        assets = await self.client.get_assets()

        print(f"Current balance: {balance.balance} {balance.symbol}")

        # Calculate if rebalancing is needed
        total_value_usd = float(balance.balance) * balance.price_usd
        usdc_balance = next((a for a in assets if a.symbol == "USDC"), None)
        current_usdc_ratio = (usdc_balance.balance_usd / total_value_usd) if usdc_balance else 0

        if abs(current_usdc_ratio - target_usdc_ratio) > 0.05:  # 5% threshold
            # Execute rebalancing trade
            if current_usdc_ratio < target_usdc_ratio:
                # Need more USDC - sell SOL for USDC
                amount_to_swap = (target_usdc_ratio - current_usdc_ratio) * float(balance.balance)
                await self.swap_tokens("SOL", "USDC", str(amount_to_swap))
            else:
                # Need less USDC - buy SOL with USDC  
                amount_to_swap = (current_usdc_ratio - target_usdc_ratio) * usdc_balance.balance_usd
                await self.swap_tokens("USDC", "SOL", str(amount_to_swap))

    async def swap_tokens(self, from_token, to_token, amount):
        """Execute token swap via Jupiter"""
        try:
            result = await self.client.execute_action(
                "jupiter-swap", 
                "swap",
                {
                    "inputMint": self.get_token_mint(from_token),
                    "outputMint": self.get_token_mint(to_token), 
                    "amount": amount
                }
            )
            print(f"Swap executed: {result.id}")
            return result
        except Exception as e:
            print(f"Swap failed: {e}")
            return None

    async def monitor_positions(self):
        """Monitor DeFi positions across protocols"""
        positions = await self.client.get_defi_positions()

        for position in positions:
            if position.health_factor and position.health_factor < 1.2:
                print(f"WARNING: Low health factor on {position.protocol}: {position.health_factor}")
                # Agent could automatically add collateral or reduce leverage here

    def get_token_mint(self, symbol):
        """Get token mint address for common tokens"""
        mints = {
            "SOL": "So11111111111111111111111111111111111111112",
            "USDC": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
        }
        return mints.get(symbol)

# Usage
async def main():
    agent = DeFiAgent("wai_sess_your_token_here")

    # Run autonomous rebalancing
    await agent.rebalance_portfolio(target_usdc_ratio=0.6)

    # Monitor positions for risk
    await agent.monitor_positions()

if __name__ == "__main__":
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Security Through Policy Engine

The key to safe autonomous operation is WAIaaS's policy engine with 21 policy types and 4 security tiers: INSTANT, NOTIFY, DELAY, APPROVAL. You can configure policies that allow your agent to operate within safe boundaries:

# Set spending limits via REST API
curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "SPENDING_LIMIT",
    "rules": {
      "instant_max_usd": 10,
      "notify_max_usd": 100,
      "delay_max_usd": 1000,
      "delay_seconds": 300,
      "daily_limit_usd": 500
    }
  }'
Enter fullscreen mode Exit fullscreen mode

This creates a 4-tier security system where small transactions execute instantly, medium amounts trigger notifications, larger amounts have a time delay for review, and the largest amounts require explicit human approval via WalletConnect integration for owner approval of agent transactions.

Advanced Features for AI Agents

x402 HTTP Payment Protocol

Your agents can automatically pay for API calls using the x402 HTTP payment protocol support:

# Agent pays for premium API access automatically
response = await client.x402_fetch("https://api.premium-service.com/data")
Enter fullscreen mode Exit fullscreen mode

Multi-Chain Operation

The Python SDK supports 18 networks across Ethereum, Solana, and other chains. Your agent can bridge assets automatically:

# Bridge from Ethereum to Solana via LI.FI
await client.execute_action("lifi", "bridge", {
    "fromChain": "ethereum",
    "toChain": "solana", 
    "amount": "100.0",
    "token": "USDC"
})
Enter fullscreen mode Exit fullscreen mode

NFT Operations

Agents can manage NFT portfolios with NFT support for EVM (ERC-721/ERC-1155) and Solana (Metaplex) with metadata caching:

# List agent's NFT collection
nfts = await client.list_nfts()

# Transfer NFT to another address  
await client.transfer_nft({
    "to": "recipient-address",
    "tokenId": "123",
    "contractAddress": "0x..."
})
Enter fullscreen mode Exit fullscreen mode

Quick Start: Agent-Ready Wallet in 5 Minutes

  1. Start WAIaaS 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
Enter fullscreen mode Exit fullscreen mode
  1. Get the master password:
docker exec waiaas cat /data/recovery.key
Enter fullscreen mode Exit fullscreen mode
  1. Create wallet and session (using CLI for convenience):
npm install -g @waiaas/cli
waiaas quickset --mode mainnet
Enter fullscreen mode Exit fullscreen mode
  1. Install Python SDK:
pip install waiaas
Enter fullscreen mode Exit fullscreen mode
  1. Test agent wallet access:
from waiaas import WAIaaSClient

async with WAIaaSClient("http://localhost:3100", "your_session_token") as client:
    balance = await client.get_balance()
    print(f"Agent wallet ready! Balance: {balance.balance} {balance.symbol}")
Enter fullscreen mode Exit fullscreen mode

MCP Integration for Claude and Other AI Frameworks

If you're building with Claude Desktop, LangChain, or other MCP-compatible frameworks, WAIaaS provides 45 MCP tools for AI agent integration. The MCP server can be configured alongside the Python SDK for maximum flexibility:

{
  "mcpServers": {
    "waiaas": {
      "command": "npx",
      "args": ["-y", "@waiaas/mcp"],
      "env": {
        "WAIAAS_BASE_URL": "http://127.0.0.1:3100",
        "WAIAAS_SESSION_TOKEN": "wai_sess_<your-token>"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

This gives your Claude agent direct access to wallet operations through natural language commands, while your Python agents can use the SDK for programmatic control.

The Python SDK's async/await design makes it perfect for building reactive agents that respond to market conditions, user requests, or scheduled tasks without blocking execution. Combined with the policy engine's safety guarantees, you can deploy autonomous financial agents with confidence.

Ready to give your AI agents financial superpowers? Check out the full documentation and examples on GitHub or explore more advanced integrations at waiaas.ai.

What's next? Try integrating WAIaaS with your existing AI agent framework, set up some basic spending policies, and watch your agents start interacting with DeFi protocols autonomously. The combination of zero-dependency architecture and comprehensive blockchain support makes it the fastest path from idea to autonomous financial agent.

Top comments (1)

Collapse
 
ali_muwwakkil_a776a21aa9c profile image
Ali Muwwakkil

In our latest accelerator, we discovered that integrating AI agents with crypto wallets often stumbles not on tech, but on security protocols. It's fascinating how teams overlook embedding security-first practices into their workflows. Async operations can be a game-changer here, especially when managing concurrent transactions. Emphasizing secure and async handling of sensitive tasks can significantly enhance both performance and trustworthiness of AI agents in financial contexts. - Ali Muwwakkil (ali-muwwakkil on LinkedIn)