Building an Agent That Pays for Its Own API Calls
A practical guide to building an AI agent with a wallet, discovery logic, and x402 payment handling — so it can call any Proxagora API without human setup.
Most agent tutorials hand the agent a pre-configured API key and call it a day. But a truly autonomous agent shouldn't need human setup for every new data source it wants to call.
This guide walks through building an agent that:
- Discovers APIs on Proxagora
- Funds itself with USDC on Base
- Makes x402-authenticated API calls without any pre-configured keys
Prerequisites
- Node.js 18+
- A Base wallet with USDC (testnet or mainnet)
viemfor wallet interaction
npm install viem @coinbase/x402
Step 1: Set Up a Wallet
Your agent needs a wallet. For production, use a hardware wallet or KMS. For this tutorial, we'll generate one:
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'
import { base } from 'viem/chains'
import { createWalletClient, http } from 'viem'
const privateKey = generatePrivateKey() // store this securely
const account = privateKeyToAccount(privateKey)
const walletClient = createWalletClient({
account,
chain: base,
transport: http('https://mainnet.base.org'),
})
console.log('Agent wallet:', account.address)
// Fund this address with USDC on Base before proceeding
Step 2: Discover APIs
Proxagora's discovery endpoint returns a catalogue of available APIs with pricing:
const discover = await fetch('https://proxagora.com/api/discover')
const { apis } = await discover.json()
// Find what you need
const weatherApi = apis.find(api => api.category === 'weather')
console.log(weatherApi)
// { id: 'weather-live', endpoint: '/api/weather', price: '0.001', ... }
Step 3: Handle x402 Payments
The x402 flow is a two-step HTTP dance. Here's a reusable handler:
import { parsePaymentRequirements, createPayment } from '@coinbase/x402'
async function callWithPayment(url: string, walletClient: any) {
// First attempt — expect 402
const firstResponse = await fetch(url)
if (firstResponse.status !== 402) {
return firstResponse // Free endpoint or already paid
}
// Parse the payment requirements
const paymentRequired = firstResponse.headers.get('X-Payment-Required')
const requirements = parsePaymentRequirements(paymentRequired)
// Sign the payment
const payment = await createPayment(requirements, walletClient)
// Retry with payment header
const paidResponse = await fetch(url, {
headers: {
'X-Payment': JSON.stringify(payment),
},
})
return paidResponse
}
Step 4: Call an API
const response = await callWithPayment(
'https://proxagora.com/api/weather?q=Bangkok',
walletClient
)
const data = await response.json()
console.log(data)
// { temperature: 34, condition: 'Sunny', humidity: 72, ... }
The agent discovered the API, authorized the payment, and got the data — no API key, no account, no human in the loop.
Using MCP Instead
If your agent uses MCP (Claude, Cursor, etc.), you don't need to implement any of this manually. The proxagora-mcp package handles discovery and x402 payments for you:
npx proxagora-mcp
Configure your wallet via env vars and the MCP server registers every Proxagora API as a callable tool. Your agent calls weather — the MCP layer handles everything else.
Balance Management
Agents that run continuously need to manage their USDC balance. A simple pattern:
import { createPublicClient } from 'viem'
import { erc20Abi } from 'viem'
const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'
const MIN_BALANCE = 1_000_000n // 1 USDC
async function checkBalance(address: string, publicClient: any) {
const balance = await publicClient.readContract({
address: USDC_BASE,
abi: erc20Abi,
functionName: 'balanceOf',
args: [address],
})
if (balance < MIN_BALANCE) {
// Alert or auto-top-up logic here
console.warn('Low balance — agent may not be able to complete tasks')
}
return balance
}
What's Next
The x402 model means any API can be agent-native with minimal changes to the server side. As more APIs list on Proxagora, agents can discover and use them without any developer involvement.
Browse the full API catalogue at proxagora.com or read the x402 protocol docs for a deeper dive.