BlogAI Agents·16 min read

Build an autonomous AI agent that pays for its own compute.

x402 tutorial. The agent earns USDC by sharing bandwidth, then spends USDC on proxies and data APIs — no credit card, no human in the loop. Working Python code with Anthropic Claude as the brain.

tl;dr · the loop

Generate a Solana wallet → fund with $5 USDC → agent registers as a peer (earns USDC routing bandwidth) → agent uses x402_fetch to pay for proxies and APIs (spends USDC) → if earnings > spending, the loop is self-sustaining. An agent that funds its own infrastructure is the actual use case for x402. Below: the full implementation.

why this matters

The agent economy thesis

The first generation of AI agents (2023-2024) was assistive — humans clicked buttons, agents helped. The second generation (2025-2026) is autonomous — agents make decisions and execute them, including transactions. For agents to actually function as economic actors, they need to pay for the things they consume: inference, proxies, APIs, storage. Credit cards don't work — agents have no legal personhood, no card-issuing relationship. Crypto micropayments do work.

x402 is the open protocol that makes this practical. When an agent hits a paid endpoint, the server returns HTTP 402 with payment instructions. The agent sends USDC on-chain (Solana settles in 400ms, Base in 2s), retries with the transaction hash as proof, and receives the resource. No keys, no signups, no monthly billing relationship. Just request → pay → receive.

step 1

Setup

bash
pip install anthropic solana web3 httpx playwright

# Generate a Solana wallet (or use Phantom export)
# Fund it with $5-20 USDC for initial seed
step 2

Generate a Solana wallet for the agent

python
from solana.keypair import Keypair
import json

# Generate fresh wallet
agent_wallet = Keypair()
print("Public:", agent_wallet.public_key)
print("Private:", agent_wallet.secret_key.hex())

# Save securely. The agent reads the private key from env var or a vault.
# Don't commit to git.
with open(".agent_wallet.json", "w") as f:
    json.dump({
        "public": str(agent_wallet.public_key),
        "private_hex": agent_wallet.secret_key.hex(),
    }, f)

# Manually fund it with $5-20 USDC SPL token to that public address.
# Phantom / Solflare → send USDC → paste public key.
step 3

Register as a peer (the earning side)

The agent registers itself as a peer in the PROXIES.SX network. While running, it routes traffic for paying customers and earns USDC per GB into the wallet you just created.

python
import httpx

PEER_NAME = "autonomous_agent_001"
WALLET = "YOUR_AGENT_PUBLIC_KEY_HERE"
API_KEY = "psx_YOUR_API_KEY"  # Optional, but auto-links to your dashboard

response = httpx.post(
    "https://api.proxies.sx/v1/peer/agents/register",
    json={
        "name": PEER_NAME,
        "type": "claude",
        "walletAddress": WALLET,
        "apiKey": API_KEY,
    },
).json()

device_id = response["deviceId"]
jwt = response["jwt"]
relay_url = response["relay"]  # wss://relay.proxies.sx

# Save device_id + jwt for the relay-connection step (separate process or thread).
# See /peers for the full WebSocket peer-routing client code.

The peer-routing client runs as a background thread or separate process. See /peers for the full WebSocket implementation.

step 4

Spend USDC via x402

With USDC in the agent's wallet (initial seed + ongoing peer earnings), the agent can pay for proxies, APIs, and other paid resources via x402. Here's a generic x402_fetch wrapper:

python
import httpx
from solana.rpc.api import Client
from solana.transaction import Transaction
from spl.token.instructions import transfer_checked, get_associated_token_address
from solana.keypair import Keypair

USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"  # Solana USDC mint
SOLANA_RPC = "https://api.mainnet-beta.solana.com"

async def x402_fetch(url: str, agent_kp: Keypair, params: dict | None = None) -> dict:
    """
    Generic x402 client. Hits the endpoint, handles 402, sends USDC,
    retries with payment proof.
    """
    async with httpx.AsyncClient() as client:
        # Step 1: initial request (no payment)
        r = await client.get(url, params=params)

        # Step 2: handle 402 response
        if r.status_code == 402:
            payment = r.json()  # { "price": ..., "recipient": ..., "network": "solana" }

            # Step 3: send USDC on Solana
            tx_hash = await send_usdc_solana(
                from_kp=agent_kp,
                to_addr=payment["recipient"],
                amount_usdc=payment["price"]["amount"],
            )

            # Step 4: retry with Payment-Signature header
            r = await client.get(
                url,
                params=params,
                headers={"Payment-Signature": tx_hash},
            )

        r.raise_for_status()
        return r.json()

async def send_usdc_solana(from_kp: Keypair, to_addr: str, amount_usdc: int) -> str:
    """Send USDC SPL token. amount_usdc is in micro-USDC (1 USDC = 1_000_000)."""
    client = Client(SOLANA_RPC)
    sender_ata = get_associated_token_address(from_kp.public_key, PublicKey(USDC_MINT))
    receiver_ata = get_associated_token_address(PublicKey(to_addr), PublicKey(USDC_MINT))

    tx = Transaction()
    tx.add(transfer_checked(
        program_id=...,  # SPL token program
        source=sender_ata,
        mint=PublicKey(USDC_MINT),
        dest=receiver_ata,
        owner=from_kp.public_key,
        amount=amount_usdc,
        decimals=6,
    ))
    result = client.send_transaction(tx, from_kp)
    return result["result"]  # tx hash

Pseudocode-condensed for clarity. Production code uses the maintained @solana/web3.js or solana-py SDKs and handles associated token account creation, fee estimation, and retry logic.

step 5

The full research-agent loop

Now wire it together. The agent uses Claude as the brain, x402_fetch to pay for proxies + APIs, and the peer network to earn while running.

python
from anthropic import Anthropic

anthropic = Anthropic(api_key="sk-ant-...")

async def research_agent(query: str, agent_kp: Keypair):
    """
    Autonomous research loop:
    1. Ask Claude to plan
    2. Execute web requests via x402-paid proxies
    3. Synthesize findings
    """
    # Plan
    plan = anthropic.messages.create(
        model="claude-opus-4-7",
        max_tokens=1024,
        messages=[{"role": "user", "content": f"Plan how to research: {query}. Output a list of URLs to fetch."}],
    )

    urls = parse_urls(plan.content[0].text)
    findings = []

    for url in urls:
        # Use x402-paid proxy: hit the proxy x402 endpoint, pay USDC, get session
        # Then route the actual fetch through that session
        proxy_session = await x402_fetch(
            "https://api.proxies.sx/v1/x402/proxy",
            agent_kp,
            params={"country": "US", "traffic": 1},  # 1 GB
        )

        # Use the proxy credentials to fetch the URL
        async with httpx.AsyncClient(proxies=proxy_session["proxy_url"]) as client:
            r = await client.get(url)
            findings.append(r.text[:5000])

    # Synthesize
    summary = anthropic.messages.create(
        model="claude-opus-4-7",
        max_tokens=2048,
        messages=[{"role": "user", "content": f"Summarize: {findings}"}],
    )
    return summary.content[0].text
the magic

Self-funding economics

Here's where it gets interesting. The agent's wallet is the same address that:

  • +Receives USDC payouts when the peer-routing thread routes customer traffic
  • Sends USDC payments when the agent pays for proxies via x402

If you run the agent on a device with a real mobile or residential IP, peer earnings can offset agent spending. The agent becomes self-funding at scale — it generates the USDC it needs by selling its own bandwidth. This is the future of autonomous infrastructure: agents that don't need a credit card or a human-controlled subscription to operate.

Math you should run for your specific case:

text
Daily peer earnings (1 mobile phone, 24/7) = E
Daily agent spending (proxies + APIs) = S

Self-funding if E > S
Subsidized (some external funding needed) if E < S

Mobile-tier IPs earn the most → if your agent runs on a phone, the math
favors self-funding. If it runs on a Hetzner VPS, datacenter-tier
earnings probably won't cover usage.
production

Production considerations

  • Wallet safety. Treat the agent wallet like prod credentials. Use a hardware wallet or HSM for the seed; load private key from a vault, never commit. Set spend limits in the agent's logic so it won't drain unbounded.
  • Tx fees. Solana fees are ~$0.0001 per tx. Base fees are ~$0.01. For sub-cent payments x402 calculates the math (don't pay $0.01 fee for a $0.005 API call).
  • Idempotency. If a payment goes through but the agent dies before recording it, it might re-pay on retry. Use payment intent IDs server-side and tx-hash dedup.
  • Rate limits on payouts. Peer network has 3 withdrawal requests per hour. Don't code an aggressive auto-withdraw loop.
  • Observability. Log every x402 payment, every peer earning credit, every agent decision. Wire it into your normal observability stack (DataDog, Honeycomb, etc).

FAQ

Why Solana over Base for payments?
Solana has 400ms finality and ~$0.0001 fees, both better for sub-cent payments. Base settles in ~2s with ~$0.01 fees, fine for larger payments. Both are supported by x402; the agent picks per-call based on price.
Can the agent run without ever earning?
Yes — fund the wallet manually with $20-50 USDC, the agent spends until balance hits zero, then errors. Earning is the self-funding angle but not required for the protocol to work.
Is there an MCP server I can use instead of building this myself?
Yes. @proxies-sx/mcp-server exposes 55 tools to Claude Desktop / Cursor that wrap exactly this — agent calls a tool, the tool handles x402 payment and proxy fetch transparently. See /mcp.
What about non-USDC payments?
x402 currently supports USDC on Base and Solana. Other tokens are theoretically possible but not common — USDC is the agent-economy stable asset of choice.
Where does the peer earning rate come from?
Returned in your registration response based on your IP type (mobile / residential / datacenter), location, and current network demand. See /peers for the full spec.
next step
Generate a wallet, register a peer, ship the loop.