DEV Community

Nikhil Ranka
Nikhil Ranka

Posted on

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

The traditional web is built for humans with credit cards. If you want to build an autonomous, machine-to-machine (M2M) economy where AI agents hire and pay other AI agents, API keys secured by Stripe subscriptions fall apart. An autonomous agent cannot easily open a bank account, sign up for a SaaS tier, or manage a monthly billing cycle.

To solve this, I built an autonomous agent that exposes its capabilities as an API and charges per invocation using HTTP 402 Payment Required and USDC on the Base network.

Here is the architectural blueprint, the code, and the honest trade-offs of building a self-monetizing AI agent.


The Architecture: The x402 Protocol Flow

Rather than using complex smart contract escrow accounts, we can leverage a lightweight HTTP-native payment protocol. This flow mimics the L402 (formerly LSAT) specification but uses EVM-native USDC on Base to keep gas fees sub-cent and settlement instantaneous.

┌──────────────┐             1. POST /agent/task              ┌──────────────┐
│  Consumer    │ ───────────────────────────────────────────> │  Provider    │
│  AI Agent    │ <─────────────────────────────────────────── │   Agent      │
└──────────────┘         2. HTTP 402: Payment Required       └──────────────┘
       │            { invoiceId, amount, token, destination }        ▲
       │                                                             │
       │ 3. Transfer USDC (Base)                                     │
       └──────────────────────────┐                                  │
                                  ▼                                  │
                          ┌──────────────┐                           │
                          │ Base Network │                           │
                          └──────────────┘                           │
                                  │                                  │
       ┌──────────────────────────┘                                  │
       │ 4. Retry POST with `Authorization: x402 <tx_hash>`          │
       └─────────────────────────────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

Implementing the Payment Verification Middleware

The core of the provider agent is a validation middleware. When a client requests an execution, the server checks for an Authorization header containing a transaction hash.

If missing or invalid, it returns an HTTP 402 with the payment details. If present, it validates the transaction directly on the Base blockchain before running the LLM workload.

Here is the Node.js/TypeScript implementation using viem to verify USDC transactions on Base.


typescript
import { createPublicClient, http, parseAbi } from 'viem';
import { base } from 'viem/chains';

const publicClient = createPublicClient({
  chain: base,
  transport: http(process.env.BASE_RPC_URL),
});

const USDC_BASE_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bda02913';
const ERC20_ABI = parseAbi([
  'event Transfer(address indexed from, address indexed to, uint256 value)'
]);

interface PaymentConfig {
  recipientAddress: string;
  expectedAmountUsdc: number; // e.g., 0.05
}

export async function verifyPayment(
  txHash: `0x${string}`,
  config: PaymentConfig
): Promise<{ success: boolean; reason?: string }> {
  try {
    // 1. Fetch transaction receipt
    const receipt = await public
Enter fullscreen mode Exit fullscreen mode

Top comments (0)