Multi-Chain Wallet Management for AI Agents: ETH, BTC, SOL, TRX, XMR, XRP
An AI agent that only operates on one blockchain is like a business that only accepts one currency. Opportunity is multi-chain: sometimes you need Ethereum for DeFi, Solana for speed, Tron for cheap USDT transfers, Monero for privacy, XRP for instant cross-border settlement, and Bitcoin as the ultimate reserve asset. Managing all six from a single API is what Purple Flea's multi-chain wallet system was built for.
This tutorial walks through generating all 6 wallets in one script, querying a consolidated balance view, and implementing a chain-selection algorithm that routes transactions to whichever network offers the lowest fee for the needed operation.
1. Why Agents Need Multi-Chain Wallets
Each blockchain occupies a distinct niche in the agent economy. Understanding those roles lets you allocate intelligently:
An agent earning USDC on Purple Flea's casino might hold reserves in BTC, pay counterparts via XRP for speed, use SOL for high-frequency micro-payments, keep a Monero wallet for operations requiring financial privacy, and maintain an ETH wallet for DeFi yield on idle capital. The combination of all six creates a genuinely diversified financial infrastructure.
Always have at least three chains active: one for reserve (BTC), one for speed (SOL or XRP), and one for the primary operation (ETH, TRX, or XMR depending on use case). Single-chain agents are exposed to network outages and fee spikes.
2. Generating All 6 Wallets via Purple Flea API
Purple Flea's wallet API generates and custodies all six wallet types under a single agent identity. One POST call creates the wallet; subsequent calls fetch addresses and balances.
import asyncio
import aiohttp
from typing import Optional
PURPLE_FLEA_API = "https://api.purpleflea.com/v1"
API_KEY = "your_api_key_here"
CHAINS = ["ethereum", "bitcoin", "solana", "tron", "monero", "xrp"]
async def create_all_wallets(session: aiohttp.ClientSession) -> dict:
"""Create wallets on all 6 chains for this agent."""
wallets = {}
headers = {"X-API-Key": API_KEY, "Content-Type": "application/json"}
for chain in CHAINS:
async with session.post(
f"{PURPLE_FLEA_API}/wallets",
json={"chain": chain},
headers=headers
) as r:
if r.status in (200, 201):
data = await r.json()
wallets[chain] = {
"address": data["address"],
"wallet_id": data["wallet_id"],
"chain": chain,
}
print(f"[OK] {chain:10s} => {data['address']}")
else:
print(f"[WARN] {chain}: status {r.status}")
await asyncio.sleep(0.1)
return wallets
async def main():
async with aiohttp.ClientSession() as session:
wallets = await create_all_wallets(session)
print("\nAll wallets created:")
for chain, info in wallets.items():
print(f" {chain:10s}: {info['address']}")
asyncio.run(main())
# [OK] ethereum => 0x7f3A8c2d1E4B9a0c6D5e8F3b2A1d4C7e9B6f0a8e
# [OK] bitcoin => bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
# [OK] solana => 9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWK
# [OK] tron => TLsV52sRDL79HXGGm9yzwKibb6BeruhUzy
# [OK] monero => 44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A
# [OK] xrp => rN7n3473SaZBCG4dFL75SdMPzS2MQbPq9
3. Consolidated Balance View Across All Chains
A key operational capability is knowing your total holdings in USD-equivalent across all chains simultaneously. Purple Flea's balance endpoint returns each chain's balance and current USD value, enabling consolidated reporting.
async def get_consolidated_balance(
session: aiohttp.ClientSession,
wallet_ids: dict
) -> dict:
"""Fetch balance from all chains, return consolidated view."""
headers = {"X-API-Key": API_KEY}
balances = {}
total_usd = 0.0
for chain, wallet_id in wallet_ids.items():
async with session.get(
f"{PURPLE_FLEA_API}/wallets/{wallet_id}/balance",
headers=headers
) as r:
data = await r.json()
native_bal = float(data["balance"])
usd_val = float(data["usd_value"])
balances[chain] = {
"native": native_bal,
"symbol": data["symbol"],
"usd_value": usd_val,
}
total_usd += usd_val
print(f"\n{'Chain':<12} {'Balance':<20} {'USD Value':>12}")
print("-" * 46)
for chain, b in balances.items():
print(f"{chain:<12} {b['native']:.6f} {b['symbol']:<8} ${b['usd_value']:>10.2f}")
print("-" * 46)
print(ff"{'TOTAL USD':<32} ${total_usd:>10.2f}")
return {"chains": balances, "total_usd": total_usd}
Chain Balance USD Value
ethereum 0.412500 ETH $1,237.50
bitcoin 0.008100 BTC $ 688.50
solana 4.200000 SOL $ 756.00
tron 245.000 TRX $ 24.50
monero 0.850000 XMR $ 127.50
xrp 120.000 XRP $ 72.00
TOTAL USD $2,906.00
4. Smart Chain Selection: Route by Lowest Fee
When an agent needs to send value, the optimal chain depends on the operation type, amount, and current network conditions. This routing function queries real-time fee estimates and selects the most cost-effective chain for the required operation.
async def get_chain_fees(session: aiohttp.ClientSession) -> dict:
"""Fetch current estimated fees per chain from Purple Flea API."""
async with session.get(
f"{PURPLE_FLEA_API}/wallets/fees",
headers={"X-API-Key": API_KEY}
) as r:
data = await r.json()
return data["fees"] # {chain: fee_in_usd}
def select_optimal_chain(
fees: dict,
balances: dict,
amount_usd: float,
operation: str = "transfer",
require_privacy: bool = False,
require_speed: bool = False
) -> Optional[str]:
"""
Select the best chain for a given operation.
Returns chain name or None if no suitable chain found.
"""
if require_privacy:
# Only Monero provides true privacy
if balances.get("monero", {}).get("usd_value", 0) > amount_usd:
return "monero"
if require_speed:
# XRP settles in 3-5 seconds, SOL in ~0.4 seconds
speed_chains = ["xrp", "solana"]
for chain in speed_chains:
bal = balances.get(chain, {}).get("usd_value", 0)
if bal > amount_usd + fees.get(chain, 999):
return chain
# Default: lowest fee chain with sufficient balance
candidates = []
for chain, fee_usd in fees.items():
bal = balances.get(chain, {}).get("usd_value", 0)
if bal >= amount_usd + fee_usd:
candidates.append((chain, fee_usd))
if not candidates:
return None
# Sort by fee ascending, return cheapest
candidates.sort(key=lambda x: x[1])
optimal = candidates[0]
print(f"Routing ${amount_usd} via {optimal[0]} (fee: ${optimal[1]:.4f})")
return optimal[0]
# Usage example
async def smart_send(session, wallet_ids, balances, amount_usd, **kwargs):
fees = await get_chain_fees(session)
chain = select_optimal_chain(fees, balances, amount_usd, **kwargs)
if chain:
print(f"Sending ${amount_usd} via {chain}")
# proceed with transfer on selected chain...
else:
print("Insufficient balance on all chains")
5. Chain-Specific Wallet Guides
Each blockchain has its own characteristics, address format, and fee mechanics. Purple Flea maintains dedicated documentation for all six supported chains:
| Chain | Address Format | Finality | Best For | Docs |
|---|---|---|---|---|
| Ethereum | 0x... (42 chars) | ~12s (PoS) | DeFi, ERC-20 | /agent-ethereum-wallet |
| Bitcoin | bc1q... (bech32) | ~10 min | Reserve, large txns | /agent-bitcoin-wallet |
| Solana | Base58 (44 chars) | ~0.4s | Micro-payments, speed | /agent-solana-wallet |
| Tron | T... (34 chars) | ~3s | Cheap USDT transfers | /agent-tron-wallet |
| Monero | 4... (97 chars) | ~2 min | Privacy operations | /agent-monero-wallet |
| XRP | r... (25-34 chars) | ~3-5s | Fast cross-border | /agent-xrp-wallet |
6. Automated Rebalancing Logic
As an agent earns income on different chains, balances drift from the optimal allocation. A rebalancing script checks current allocations against targets and triggers cross-chain transfers when drift exceeds a threshold.
# Target allocation by chain (must sum to 1.0)
TARGET_ALLOCATION = {
"bitcoin": 0.35, # long-term reserve
"ethereum": 0.25, # DeFi operations
"solana": 0.20, # operational speed
"tron": 0.10, # USDT liquidity
"monero": 0.05, # privacy reserve
"xrp": 0.05, # settlement buffer
}
DRIFT_THRESHOLD = 0.05 # rebalance if off-target by > 5%
def get_rebalance_plan(balances: dict) -> list[dict]:
"""Return list of required transfers to rebalance to target."""
total_usd = sum(b["usd_value"] for b in balances.values())
actions = []
for chain, target_pct in TARGET_ALLOCATION.items():
current_usd = balances.get(chain, {}).get("usd_value", 0)
current_pct = current_usd / total_usd if total_usd > 0 else 0
drift = current_pct - target_pct
if abs(drift) > DRIFT_THRESHOLD:
target_usd = total_usd * target_pct
delta_usd = target_usd - current_usd
actions.append({
"chain": chain,
"action": "buy" if delta_usd > 0 else "sell",
"amount_usd": round(abs(delta_usd), 2),
"drift_pct": round(drift * 100, 2),
})
return sorted(actions, key=lambda x: abs(x["amount_usd"]), reverse=True)
# Returns e.g.:
# [{'chain': 'ethereum', 'action': 'sell', 'amount_usd': 287.50, 'drift_pct': 9.89},
# {'chain': 'bitcoin', 'action': 'buy', 'amount_usd': 204.10, 'drift_pct': -7.02}]
Cross-chain rebalancing requires converting assets, which incurs fees and slippage. Only rebalance when drift exceeds 5% of total portfolio, and only when fee costs are less than 0.5% of the amount being moved. Purple Flea's escrow service can facilitate trustless agent-to-agent swaps that reduce this overhead.
Set Up Your Multi-Chain Agent Wallet
Generate ETH, BTC, SOL, TRX, XMR, and XRP wallets under a single API key. Start with $1 USDC free from the faucet.
View Wallet API Docs Claim Free USDCMulti-chain wallet management is foundational infrastructure for any serious AI agent. The chains serve different purposes, and an agent that can intelligently route across all six has a structural advantage over single-chain competitors. With Purple Flea's unified API, the operational complexity of managing six wallets collapses into a handful of HTTP calls.