cryptoagent-ai 0.3.1
Give your AI agent a wallet. Autonomous agents that send ETH, swap tokens, and manage DeFi — across Ethereum, Base, Arbitrum, and Polygon. Python SDK + CLI.
Requires Python: >=3.11
Keywords: aave, agent, ai, arbitrum, autonomous, base, batch, claude, crypto, defi, erc20, ethereum, llm, polygon, sdk, tool-use, transfer, uniswap, wallet, web3

# CryptoAgent AI

**Give your AI agent a wallet.** Build autonomous agents that send ETH, swap tokens on Uniswap, lend on Aave, and manage portfolios across Ethereum, Base, Arbitrum, and Polygon — all from Python.

[![PyPI version](https://img.shields.io/pypi/v/cryptoagent-ai.svg)](https://pypi.org/project/cryptoagent-ai/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)

---

## Why CryptoAgent AI?

Most crypto libraries make you wire together providers, signers, nonce managers, gas estimators, and ABI encoders just to send a token. CryptoAgent wraps all of that into **one async call**.

```python
from sdk import CryptoAgent

async with CryptoAgent("my-wallet", password="pw", chains=["base"]) as agent:
    await agent.send_eth("0xRecipient...", 0.05, chain="base")
```

Need an AI that can *reason* about your portfolio and execute transactions autonomously? Plug in your Anthropic API key and the agent gets 19 on-chain tools — balances, swaps, lending, transfers — with built-in safety rails.

```python
response = await agent.prompt("Swap 50 USDC to ETH on Base if gas is under 0.1 gwei")
```

### Who is this for?

| Use case | How CryptoAgent helps |
|---|---|
| **Airdrop distribution** | `batch_send_eth()` — send to hundreds of addresses in one call |
| **Treasury management bots** | Autonomous agent loop with spending limits and human approval |
| **Portfolio rebalancers** | AI reasons about allocations, executes swaps and lending |
| **Payment automation** | `send_token("0x...", token="USDC", amount=100)` — one line |
| **Multi-agent systems** | `send_to_agent("treasury-wallet", 0.5)` — transfer by wallet name |
| **DeFi scripting** | Uniswap quotes + swaps, Aave supply/borrow, all async |

---

## Features

### Multi-Chain Support

Ethereum, Base, Arbitrum, and Polygon out of the box. Failover RPC with automatic retry — if one endpoint goes down, the next one picks up.

| Chain | ID | Native | Tokens |
|---|---|---|---|
| Ethereum | 1 | ETH | WETH, USDC, USDT, DAI, WBTC |
| Base | 8453 | ETH | WETH, USDC, USDbC, DAI |
| Arbitrum | 42161 | ETH | WETH, USDC, USDT, DAI, WBTC, ARB |
| Polygon | 137 | MATIC | WMATIC, WETH, USDC, USDT, DAI |

### HD Wallets with Encrypted Key Storage

BIP-44 hierarchical deterministic wallets (`m/44'/60'/0'/0/N`). Private keys are encrypted at rest using **Fernet + PBKDF2** with 600,000 iterations. Keys are decrypted only at signing time and zeroed from memory immediately after.

### 19 AI Agent Tools

Every tool is registered via a `@tool()` decorator that auto-generates Claude-compatible JSON Schema. The AI agent can call any of these autonomously:

| Category | Tools |
|---|---|
| **Blockchain** | `get_balance`, `get_token_balance`, `get_gas_price`, `get_block_number` |
| **Wallet** | `get_address`, `send_eth` |
| **DeFi** | `get_swap_quote`, `swap_tokens`, `aave_supply`, `aave_borrow`, `aave_health_factor` |
| **Portfolio** | `get_portfolio`, `get_pnl` |
| **Memory** | `store_note`, `recall`, `list_notes` |
| **Transfers** | `transfer_to_agent`, `batch_send`, `check_agent_balance` |

### Safety-First Design

Transactions pass through a composable safety pipeline before execution:

1. **Rule Engine** — rejects transactions above configurable USD thresholds
2. **Spending Limits** — per-transaction, hourly, and daily caps tracked in SQLite
3. **Human Approval** — high-value transactions pause and ask for confirmation
4. **Slippage Guards** — basis-point limits on all swaps
5. **Audit Log** — every tool call, every transaction, append-only

### Autonomous Agent Loop

The agent runs a continuous **Perceive - Reason - Act - Reflect** cycle powered by Claude:

```
Perceive   →  gather balances, events, portfolio state
Reason     →  Claude analyzes context, picks tools
Act        →  execute tools with safety checks
Reflect    →  log results, update portfolio
Sleep      →  configurable interval, then loop
```

---

## Install

```bash
pip install cryptoagent-ai
```

Requires Python 3.11+.

---

## Quick Start

### 1. Create a Wallet

```bash
cryptoagent wallet create my-wallet -p "strong-password"
```

This generates a BIP-44 HD wallet, encrypts the private key, and saves it locally. **Back up the seed phrase** — it's only shown once.

### 2. Check Balances

```bash
# All chains
cryptoagent wallet balance my-wallet

# Specific chain with token balances
cryptoagent wallet balance my-wallet --chain base --tokens
```

### 3. Send a Transaction

```bash
# Send ETH
cryptoagent wallet send my-wallet 0xRecipient 0.01 --chain base -p "strong-password"

# Send USDC
cryptoagent wallet send my-wallet 0xRecipient 50 --chain base --token USDC -p "strong-password"
```

### 4. Start the AI Agent

```bash
export ANTHROPIC_API_KEY=sk-ant-...
cryptoagent agent start --wallet my-wallet -p "strong-password"
```

The agent begins its autonomous loop — monitoring your portfolio, reasoning about market conditions, and executing transactions within your safety limits.

---

## Python SDK

The SDK gives you full programmatic control without the CLI. Every method is async and accepts chain names (`"base"`) or chain IDs (`8453`).

### Basic Operations

```python
import asyncio
from sdk import CryptoAgent

async def main():
    async with CryptoAgent("my-wallet", password="pw", chains=["base", "arbitrum"]) as agent:
        # Properties
        print(agent.address)        # 0x742d35Cc6634C0532925a3b844Bc9e7595f...
        print(agent.wallet_name)    # my-wallet

        # Read operations
        bal = await agent.get_balance("base")               # 1.234 (float ETH)
        usdc = await agent.get_token_balance("base", "USDC") # 500.0 (float USDC)
        gas = await agent.get_gas_price("base")               # 0.001 (float gwei)
        all_bal = await agent.get_all_balances()               # {"base": 1.23, "arbitrum": 0.5}

asyncio.run(main())
```

### Send ETH and Tokens

```python
async with CryptoAgent("my-wallet", password="pw", chains=["base"]) as agent:
    # Send native ETH — amount in human-readable units
    receipt = await agent.send_eth("0xRecipient...", 0.05, chain="base")
    print(receipt.tx_hash)       # 0xabc123...
    print(receipt.success)       # True
    print(receipt.gas_used)      # 21000

    # Send ERC-20 tokens — resolve by symbol
    receipt = await agent.send_token(
        "0xRecipient...",
        token="USDC",
        amount=100.0,
        chain="base",
    )

    # Approve a spender (e.g., Uniswap router)
    receipt = await agent.approve_token("USDC", spender="0xRouter...", chain="base")
```

### Agent-to-Agent Transfers

Send funds between wallets by name — no need to look up addresses:

```python
async with CryptoAgent("treasury", password="pw", chains=["base"]) as agent:
    # Send ETH to another wallet in your keystore
    receipt = await agent.send_to_agent("operations-wallet", 0.5, chain="base")

    # Send tokens to another wallet
    receipt = await agent.send_to_agent("payments-wallet", 1000.0, chain="base", token="USDC")
```

### Batch Transfers

Send to multiple recipients in a single call. Each transfer is sequential; failures don't abort the batch.

```python
async with CryptoAgent("payroll", password="pw", chains=["base"]) as agent:
    # Batch ETH send
    results = await agent.batch_send_eth({
        "0xAlice": 0.1,
        "0xBob": 0.2,
        "0xCharlie": 0.15,
    }, chain="base")

    for r in results:
        if isinstance(r, Exception):
            print(f"Failed: {r}")
        else:
            print(f"Sent: {r.tx_hash}")

    # Batch token send
    results = await agent.batch_send_token({
        "0xAlice": 50.0,
        "0xBob": 100.0,
    }, token="USDC", chain="base")
```

### AI-Powered Prompts

Give the agent a natural-language instruction. It reasons with Claude, calls on-chain tools, and returns a response. Requires `ANTHROPIC_API_KEY`.

```python
async with CryptoAgent("my-wallet", password="pw", chains=["base"]) as agent:
    # Ask about portfolio
    response = await agent.prompt("What is my current balance and gas price on Base?")
    print(response)

    # Execute a complex action
    response = await agent.prompt(
        "If my USDC balance is above 500, swap half to ETH on Base"
    )
    print(response)
```

### SDK Method Reference

| Method | Returns | Description |
|---|---|---|
| `agent.address` | `str` | Wallet address (property) |
| `agent.wallet_name` | `str` | Wallet name (property) |
| `get_balance(chain)` | `float` | Native token balance in ETH/MATIC |
| `get_token_balance(chain, token)` | `float` | ERC-20 balance by symbol or address |
| `get_gas_price(chain)` | `float` | Gas price in gwei |
| `get_all_balances()` | `dict[str, float]` | Balances across all configured chains |
| `send_eth(to, amount, chain)` | `TransactionReceipt` | Send native ETH/MATIC |
| `send_token(to, token, amount, chain)` | `TransactionReceipt` | Send ERC-20 tokens |
| `send_to_agent(name, amount, chain, token?)` | `TransactionReceipt` | Send to wallet by name |
| `batch_send_eth(recipients, chain)` | `list` | Send ETH to multiple addresses |
| `batch_send_token(recipients, token, chain)` | `list` | Send tokens to multiple addresses |
| `approve_token(token, spender, chain)` | `TransactionReceipt` | Approve ERC-20 spending |
| `prompt(message)` | `str` | AI-powered natural language execution |
| `close()` | `None` | Shut down providers |

---

## Architecture

```
                         CryptoAgent (SDK / CLI)
                                  |
                    +-------------+-------------+
                    |                           |
              Python SDK                   AI Agent Loop
           (direct calls)          (Perceive → Reason → Act → Reflect)
                    |                           |
                    +-------------+-------------+
                                  |
                          +-------+-------+
                          |               |
                    ChainClient      Guardian
                   (read/write)    (safety pipeline)
                          |               |
                  +-------+-------+   RuleEngine
                  |       |       |   SpendingLimits
              Provider  Signer  Nonce  Approval
              (failover) (encrypt) (mgr) AuditLog
                  |
          +-------+-------+-------+
          |       |       |       |
       Ethereum  Base  Arbitrum  Polygon
```

### Package Structure

```
cryptoagent-ai/
  config/       — Settings, chain configs (YAML), protocol configs
  core/         — Agent loop, Brain (Claude API), tool registry, types, exceptions
  wallet/       — HD derivation, keystore encryption, transaction signing
  chain/        — Multi-chain providers, EIP-1559 builder, nonce manager
  protocols/    — Uniswap V3 quotes + swaps, Aave V3 supply + borrow
  tools/        — 19 registered agent tools (blockchain, DeFi, transfers, memory)
  memory/       — SQLite store, portfolio tracking, audit log
  safety/       — Rule engine, spending limits, approval manager, Guardian
  events/       — Event bus with topic-based pub/sub
  orchestration/ — Multi-agent coordination
  sdk/          — Python SDK (CryptoAgent class, batch helpers)
  cli/          — Typer CLI with Rich output
```

---

## Configuration

### Environment Variables

| Variable | Description | Default |
|---|---|---|
| `ANTHROPIC_API_KEY` | Claude API key (required for AI agent) | — |
| `WALLET_PASSWORD` | Default wallet password | — |
| `ETH_RPC_URL` | Override Ethereum RPC | Public RPCs |
| `BASE_RPC_URL` | Override Base RPC | Public RPCs |
| `ARBITRUM_RPC_URL` | Override Arbitrum RPC | Public RPCs |
| `POLYGON_RPC_URL` | Override Polygon RPC | Public RPCs |
| `MAX_TX_VALUE_USD` | Max single transaction value | `$100` |
| `DAILY_SPENDING_LIMIT_USD` | Daily spending cap | `$1,000` |
| `REQUIRE_HUMAN_APPROVAL_ABOVE_USD` | Approval threshold | `$50` |
| `LOG_LEVEL` | Logging verbosity | `INFO` |

### Chain Configuration

Chains are configured in `config/chains.yaml`. Each chain specifies RPC endpoints, token addresses, and explorer URLs. Environment variable RPC overrides take priority.

---

## CLI Reference

```bash
cryptoagent info                          # Show configuration
cryptoagent gas                           # Gas prices across all chains
cryptoagent gas --chain base              # Gas price on Base

cryptoagent wallet create <name>          # Create HD wallet
cryptoagent wallet list                   # List all wallets
cryptoagent wallet address <name>         # Show wallet address
cryptoagent wallet balance <name>         # Check balances (all chains)
cryptoagent wallet balance <name> -c base --tokens  # Base + ERC-20 balances
cryptoagent wallet send <name> <to> <amount> -c base  # Send ETH

cryptoagent agent start                   # Start autonomous agent
cryptoagent agent start --once            # Run single cycle
cryptoagent agent status                  # Check agent status

cryptoagent tx history <name>             # Transaction history
cryptoagent tx lookup <hash> -c base      # Look up transaction on-chain
```

---

## Security

CryptoAgent is designed with defense-in-depth:

- **Encrypted keys** — Private keys and mnemonics encrypted with Fernet + PBKDF2 (600k iterations). Decrypted only at signing time, zeroed from memory immediately after.
- **Spending limits** — Per-transaction, hourly, and daily USD caps. Tracked persistently in SQLite.
- **Human approval** — Transactions above a configurable USD threshold require explicit confirmation.
- **Slippage protection** — Basis-point limits on all DeFi swaps prevent sandwich attacks.
- **Audit log** — Every tool call, every transaction attempt, and every safety decision is logged.
- **Read-only vs. write tools** — Safety pipeline applies stricter checks to state-changing operations.

---

## Protocol Fee

A micro-fee of **0.000001 ETH** (~$0.0025) is collected per on-chain transaction to support development. The fee is automatically skipped if the wallet balance is too low to cover it. It never blocks your transaction.

---

## Development

```bash
git clone https://github.com/coins/cryptoagent-ai.git
cd cryptoagent-ai
pip install -e ".[dev]"

# Run tests
pytest

# Lint
ruff check .
```

---

## License

MIT