x402nano-agent-sdk 0.1.3
Python SDK for x402Nano Agent - AI-to-AI Nano payments
Requires Python: >=3.8
Keywords: ai-to-ai-payments, ai-agents, autonomous-payments, machine-to-machine-payments, llm-payments, agent-payments, merchant-payments, payment-gateway, e-commerce, payment-api, instant-payments, micropayments, zero-fee-payments, nano-cryptocurrency, cryptocurrency-payments, langchain, autonomous-ai

# x402Nano Agent SDK

Professional Python SDK for building AI agents with autonomous Nano cryptocurrency payments.

[![PyPI version](https://badge.fury.io/py/x402nano-agent-sdk.svg)](https://pypi.org/project/x402nano-agent-sdk/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Quick Installation

```bash
# Install SDK (includes CLI tool)
pip install x402nano-agent-sdk

# Setup agent (installs + starts everything)
python -m x402nano_agent_sdk.cli setup
```

That's it! The agent is now running on `http://localhost:7860` 🎉

> **Note for Windows users**: Use `python -m x402nano_agent_sdk.cli` instead of `x402nano-agent` command due to PATH limitations with Microsoft Store Python.

## Using the Agent

### 1. Web Interface (Natural/Hybrid Modes)
Open your browser and visit `http://localhost:7860` to use the interactive chat interface:
- 💬 Natural language commands
- 🔓 Wallet management (create, unlock, lock)
- 💰 Send and receive Nano payments
- 📊 Check balances and transaction history
- 🤖 AI-powered assistance

**Note**: Set `AGENT_MODE=natural` or `AGENT_MODE=hybrid` in `.env` to enable the chat UI.

### 2. SDK (Strict Mode - Programmatic)
Use the Python SDK for AI-to-AI automated payments (see Quick Start below).

## What Gets Installed?

1. **SDK Package**: Python library with type hints and error handling
2. **x402Nano-Agent**: Self-hosted Flask agent (cloned to `~/.x402nano/agent/`)
3. **Docker Containers**: Agent + Ollama dependencies (auto-configured)

**Non-custodial & Open Source**: You run everything locally. You control the wallet keys.

## Quick Start

```python
from x402nano_agent_sdk import Agent, AgentError

# Connect to your local agent (strict mode for AI-to-AI payments)
agent = Agent(agent_url="http://localhost:7860")

try:
    # Check balance (auto-receives pending blocks)
    balance = agent.check_balance(auto_receive_pending_blocks=True)
    print(f"Balance: {balance.balance} NANO")
    print(f"Pending: {balance.pending} NANO")
    print(f"Address: {balance.address}")
    
    # Request payment (for AI-to-AI transactions)
    payment_req = agent.request_payment(amount="0.001")
    print(f"Transaction ID: {payment_req.transaction_id}")
    print(f"Pay to: {payment_req.receive_address}")
    print(f"⚠️  EXACT Amount (with offset): {payment_req.amount} NANO")
    print(f"    → Payer must send this exact amount!")
    
    # Respond to payment request (use exact amount with offset)
    result = agent.pay(
        address=payment_req.receive_address,
        amount=payment_req.amount  # Payment request amount (with offset)
    )
    print(f"✅ Payment sent: {result.hash}")
    
    # Or send to any address (normal payment - use any amount)
    result2 = agent.pay(
        address="nano_1ebhjnii43rx9fs41njqam86q9uwgcfbap18beoyrpheekw7wniu9e3g6rb3",
        amount="0.001"  # Your own amount
    )
    print(f"✅ Normal payment sent: {result2.hash}")
    
    # Check payment status
    status = agent.check_payment_status(payment_req.transaction_id)
    print(f"Status: {status.get('response')}")
    print(f"Message: {status.get('message')}")

except AgentError as e:
    print(f"❌ Error [{e.error_code}]: {e.message}")
```

## Agent Configuration

The agent uses a `.env` file for configuration, located at `~/.x402nano/agent/.env`:

```bash
# Edit configuration before starting
nano ~/.x402nano/agent/.env
```

**Key settings:**
- `AGENT_MODE` - Set to `strict`, `hybrid`, or `natural` (strict mode disables chat UI for programmatic control)
- `AI_WALLET_PASSWORD` - Auto-generated secure password for wallet encryption
- `NANO_WORK_MODE` - `cpu` or `cuda` for proof-of-work generation

The `.env` file is automatically created from `.env.example` during setup.

## CLI Commands

```bash
# Complete setup (first time)
python -m x402nano_agent_sdk.cli setup

# Start agent (auto-checks for updates)
python -m x402nano_agent_sdk.cli start

# Stop agent
python -m x402nano_agent_sdk.cli stop

# Check if running
python -m x402nano_agent_sdk.cli status

# View logs (Ctrl+C to exit)
python -m x402nano_agent_sdk.cli logs

# Update SDK and Agent to latest versions
python -m x402nano_agent_sdk.cli update
```

> **Windows shortcut**: You can also use `python -m x402nano_agent_sdk.cli` as `x402nano-agent` if your Python Scripts folder is in PATH.

## Automatic Updates

The SDK automatically checks for updates:
- **On agent start**: Shows available updates before starting
- **On Agent() init**: Warns if SDK/Agent versions mismatch

```bash
# Update both SDK and Agent
python -m x402nano_agent_sdk.cli update

# Output:
🔄 Checking for updates...
📦 SDK version: 0.1.2
   ⚠️  Update available: 0.1.3
🤖 Agent:
   ⚠️  Update available

Update now? [Y/n]:
```
## Features

- ✅ **One-line setup**: Complete agent installation and configuration
- ✅ **Auto-updates**: SDK and Agent version checking and updates
- ✅ **Type-safe**: Full dataclass support with type hints for IDE autocomplete
- ✅ **Error handling**: Custom `AgentError` exception with error codes
- ✅ **Auto-receive**: Pending blocks automatically received on balance check
- ✅ **CLI tool**: Manage agent with simple commands
- ✅ **Docker-based**: Containerized deployment with automatic configuration
- ✅ **Self-hosted**: You run everything locally, you control all keys
- 🛡️ **Secure**: Automatic wallet cleanup in strict mode (zero in-memory exposure)
- ✅ **Production-ready**: Used in real AI-to-AI payment systems

## Security Features

### Automatic Wallet Cleanup (Strict Mode)

When using the agent in strict mode for AI-to-AI transactions, wallet data is automatically cleared from memory after **every request**:

**🛡️ Security Benefits:**
- **Zero in-memory exposure** - Private keys and seeds removed immediately after use
- **Stateless per-request** - Each API call independently initializes and cleans up
- **Attack surface minimization** - No persistent sensitive data between requests
- **Session hijacking prevention** - Compromised sessions contain no wallet information

**How it works:**
```python
# Each SDK call in strict mode:
agent = Agent("http://localhost:7860", mode="strict")

# 1. Wallet initialized from encrypted storage
# 2. Command executed
balance = agent.check_balance()
# 3. Response returned
# 4. Wallet data immediately cleared from agent memory
# 5. Next call repeats the cycle

# Natural/Interactive mode maintains session for better UX
agent_interactive = Agent("http://localhost:7860", mode="natural")
```

**Performance:** Minimal overhead (~50-100ms per request)

### Security Model

**Strict Mode: Custodial by Design**

Strict mode prioritizes automation over self-custody - a common trade-off in payment APIs:

**How it works:**
- Server operator manages the AI wallet infrastructure
- SDK users make payments through the API
- Similar model to: Stripe, PayPal APIs, exchange trading APIs

**This means:**
- ✅ **Zero wallet management** - No keys, seeds, or passwords to handle
- ✅ **Fully automated** - Perfect for AI-to-AI payments
- ℹ️ **Trust-based** - Like any payment processor, you trust the server operator

**Recommended Practices:**
1. ✅ **Appropriate fund levels** - Based on your transaction needs
2. ✅ **Choose trusted operators** - Vet your service provider
3. ✅ **Regular settlements** - Automated withdrawals to your cold storage
4. ✅ **Monitor activity** - Track transactions and set alerts

**When to use each mode:**
- **Strict Mode**: Automation, micropayments, AI agents, testing
- **Natural/Hybrid**: User-facing wallets, self-custody, large holdings

**Production tip:** Combine strict mode automation with cold storage sweeps for the best of both worlds.

## SDK Methods

### Strict Mode (AI-to-AI Payments)
All methods use strict commands for autonomous agent operations:

- `check_balance(auto_receive_pending_blocks: bool = True)` - Check balance with optional auto-receive
- `pay(address: str, amount: str)` - Send Nano payment
- `request_payment(amount: str)` - Create payment request (returns amount with unique offset for payment matching)
- `check_payment_status(transaction_id: str)` - Check payment request status
- `get_credits_info()` - Get available credits and pricing
- `topup_credits(amount: int)` - Top-up credits (10, 50, 100, 500, 1000, etc.)
- `donate(amount: str)` - Donates amount to x402Nano 
- `clear_session()` - Clear session and lock wallet

### Payments & Links

- 📦 **PyPI Package**: https://pypi.org/project/x402nano-agent-sdk/
- 📖 **Full Documentation**: https://x402nano.com/ai/sdk
- 🐙 **GitHub Repository**: https://github.com/x402nano-com/x402Nano-Agent-SDK
- 🤖 **Agent Backend**: https://github.com/x402nano-com/x402Nano-Agent
- 💬 **Discord Community**: https://discord.gg/CcxMmMuXM6

## Support

If you find this SDK useful, consider supporting development:

**Donate Nano**: `nano_3ep6fd8p1zcypgi3fsm7x3jr7n8qj57tk5ahpseqynaq7uafzo68bk6tci9n`

All methods raise `AgentError` on failure with `error_code` and `message` attributes.

## Error Handling

```python
from x402nano_agent_sdk import Agent, AgentError

agent = Agent("http://localhost:7860")

try:
    result = agent.pay("nano_address", "0.001")
except AgentError as e:
    # Handle specific errors
    if e.error_code == "INSUFFICIENT_BALANCE":
        print("💡 Fund your wallet first!")
    elif e.error_code == "INVALID_ADDRESS":
        print("💡 Check the Nano address format")
    elif e.error_code == "PAYMENT_NOT_FOUND":
        print("💡 Transaction ID not found")
    else:
        print(f"Error: {e.error_code} - {e.message}")
```

The CLI checks these automatically during setup.

## Documentation

See [full documentation](https://x402nano.com/ai/sdk) for advanced usage.

## License

MIT License - see [LICENSE](LICENSE) file.

---

**Built with ❤️ for the Nano and AI communities**