How I Built an Autonomous AI Agent That Earns USDC While I Sleep
How I Built an Autonomous AI Agent That Earns USDC While I Sleep Goal: Show a minimal, production‑ish pattern for an AI‑driven service that autonomously charges USDC via the x402 protocol. The focus is on the plumbing, not on the AI model itself. 1. Why x402? x402 is a lightweight HTTP‑based payment scheme that lets a server respond with a 402 Payment Required status and a payment request in the WWW-Authenticate header. Clients that understand x402 can automatically fetch USDC, sign a transaction, and retry the request. For an autonomous agent this means: Statelessness – the agent doesn’t need to keep a user‑side balance; payment is enforced at the API boundary. Compatibility – any HTTP client (curl, Postman, a custom SDK) can be upgraded to pay without changing business logic. Low overhead – the protocol adds only a few bytes to the response; the heavy lifting stays in the payment SDK. The trade‑off is that you must accept the extra round‑trip for unauthenticated callers and you need to host a wallet that can sign USDC transfers on the target chain (here, Base). 2. High‑level Architecture +-------------------+ HTTP/x402 +-------------------+ | Client (any) | <----------------> | Agent Service | +-------------------+ (FastAPI) +-------------------+ ^ | | v | +-------------------+ | | Wallet Manager | | | (web3.py + private| | | key, USDC ABI) | | +-------------------+ | | | v | +-------------------+ +---------------------------------| USDC Ledger | | (Base testnet/main) | +-------------------+ Agent Service – a FastAPI app that exposes one or more useful endpoints (e.g., text summarization, image tagging). Each endpoint checks for a valid x402 payment; if missing, it returns a 402 with payment details. Wallet Manager – a singleton that loads an Ethereum private key, constructs USDC transfer transactions, and signs them using web3.py . USDC Ledger – the Base network contract ( 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 on Base mainnet). 3. Code Walk‑through Below is