๐Ÿ†• Free Credits โ€” No Payment Needed

Build an AI Agent That Pays For APIs Automatically

In this tutorial, you'll build a complete AI agent that discovers services, calls paid APIs, and pays in USDC โ€” all without API keys, signup forms, or KYC. Copy-paste. Works in 10 minutes.

๐ŸŽ Get 500 Free Credits โ†’

๐Ÿ“‹ What You'll Build

  1. Why M2M payments matter โ€” the agent economy in 2026
  2. Register your agent wallet โ€” 10 seconds, 500 free credits
  3. Make your first paid API call โ€” gas prices via curl
  4. Build a Python agent โ€” auto-discovers and calls services
  5. Build a JavaScript agent โ€” Node.js + x402 protocol
  6. Wire it into an LLM agent loop โ€” GPT + function calling
  7. Go to production โ€” real USDC, @x402/fetch, Base L2

1. Why M2M Payments Matter in 2026

AI agents can't sign up for API keys. They can't fill out credit card forms. They can't click "I'm not a robot." But they can hold a wallet and pay for what they use โ€” if the payment layer supports it.

x402 is that layer. It's an open protocol for machine-to-machine micropayments on Base L2. An agent sends USDC with each API request via an HTTP header. No registration. No API key. No monthly subscription. Just pay-per-call.

๐Ÿ’ก The numbers

x402 processed 75 million transactions in July 2026. Visa, Mastercard, and Stripe are building on it. The agent economy isn't coming โ€” it's already here. minia2a.uk is the largest marketplace with 174 x402-payable services.

This tutorial shows you how to build an agent that participates in this economy. By the end, you'll have a working agent that can discover APIs, decide which to call, pay for them in USDC, and use the results.

2. Register Your Agent Wallet

First, your agent needs an identity. Registration takes 10 seconds and gives you 500 free credits ($2.50 value). No KYC. No MetaMask required โ€” we generate a wallet for you.

1

Register via the API

Pick a name for your agent. This creates a wallet with 500 credits instantly.

curl -s -X POST https://minia2a.uk/api/register \
  -H "Content-Type: application/json" \
  -d '{"name":"my-first-agent"}'
2

Save the response

You'll get back a wallet address, private key, and confirmation of your 500 credits. Save the private key โ€” it won't be shown again.

Response
{
  "ok": true,
  "wallet": "0x...",
  "privateKey": "0x...",
  "credits": 500,
  "message": "Agent registered. 500 free credits granted."
}
โš ๏ธ Save your private key

It's generated client-side and never stored on the server. If you lose it, you lose access to your wallet and any credits. Store it in an environment variable: export AGENT_KEY="0x..."

3. Make Your First Paid API Call

Let's call the gas price oracle. It returns current gas fees for Ethereum, Base, Arbitrum, and other chains. Cost: 1 credit from your free balance.

With free credits (x402-credits header)

curl -s https://minia2a.uk/x402/gas \
  -H "x402-credits: 1" \
  -H "x402-wallet: 0xYOUR_WALLET" \
  -H "x402-signature: YOUR_SIGNATURE"
๐Ÿ”‘ Authentication with credits

When using free credits, sign the request with your wallet's private key. The server verifies your signature and deducts credits from your balance. Learn the exact signing format at /x402-help.

With real USDC (x402 protocol header)

For production, you send real USDC via the x402 protocol. One HTTP header carries the payment:

curl -s https://minia2a.uk/x402/gas \
  -H "x402-payment: base:0xf16F...ECA:1000000" \
  -H "x402-signature: 0x..."

This sends 1,000,000 USDC units (= $1.00) from your wallet to minia2a's platform wallet. The server processes the payment, runs the gas lookup, and returns the result โ€” all in one round trip.

Response
{
  "ethereum": {"slow": 2.1, "normal": 3.5, "fast": 5.2},
  "base": {"slow": 0.001, "normal": 0.002, "fast": 0.003},
  "arbitrum": {"slow": 0.01, "normal": 0.02, "fast": 0.03},
  "timestamp": "2026-08-01T01:00:00Z"
}

4. Build a Python Agent That Pays For APIs

Now let's build a complete agent. It will:

  1. Discover available services from minia2a
  2. Decide which service to call based on a user's question
  3. Pay for the API call with credits
  4. Return the result

Step 1: Install dependencies

pip install requests eth-account web3

Step 2: The agent

#!/usr/bin/env python3
"""minia2a Agent โ€” discovers and calls paid APIs with USDC credits."""

import os
import json
import requests
from eth_account import Account
from eth_account.messages import encode_defunct
from web3 import Web3

# โ”€โ”€ Config โ”€โ”€
MINIA2A = "https://minia2a.uk"
WALLET = os.getenv("AGENT_WALLET", "0xYOUR_WALLET")
PRIVATE_KEY = os.getenv("AGENT_KEY", "0xYOUR_PRIVATE_KEY")

# โ”€โ”€ Sign a request for credit-based auth โ”€โ”€
def sign_message(message: str) -> str:
    """Sign a message with the agent's private key."""
    acct = Account.from_key(PRIVATE_KEY)
    signed = acct.sign_message(encode_defunct(text=message))
    return signed.signature.hex()

# โ”€โ”€ Discover available services โ”€โ”€
def discover_services():
    """Fetch the list of available x402 services."""
    resp = requests.get(f"{MINIA2A}/api/stats")
    data = resp.json()
    endpoints = data.get("trials", {}).get("byEndpoint", {})
    return [
        {"name": k, "calls": v["used"], "users": v["users"]}
        for k, v in endpoints.items()
        if k.startswith("x402-")
    ]

# โ”€โ”€ Call a service with credits โ”€โ”€
def call_service(endpoint: str, params: dict = None):
    """Call a minia2a service, paying with credits."""
    url = f"{MINIA2A}/x402/{endpoint}"
    timestamp = requests.get(f"{MINIA2A}/api/time").json()["iso"]

    # Sign: "{wallet}:{endpoint}:{timestamp}"
    message = f"{WALLET}:{endpoint}:{timestamp}"
    signature = sign_message(message)

    headers = {
        "x402-credits": "1",
        "x402-wallet": WALLET,
        "x402-signature": f"0x{signature}",
        "x402-timestamp": timestamp,
    }

    if params:
        resp = requests.post(url, json=params, headers=headers)
    else:
        resp = requests.get(url, headers=headers)

    return resp.json()

# โ”€โ”€ Decide which service to call โ”€โ”€
SERVICE_KEYWORDS = {
    "gas": "gas",
    "fee": "gas",
    "token": "token-security",
    "security": "token-security",
    "scrape": "web-scrape",
    "web": "web-scrape",
    "url": "web-scrape",
    "captcha": "captcha-solve",
    "time": "time",
    "date": "time",
    "wallet": "wallet-intel",
    "address": "address-parse",
    "domain": "domain-intel",
    "dns": "dns",
    "price": "price-oracle",
    "swap": "swap-safety",
    "email": "email-verify",
    "sentiment": "sentiment",
    "summary": "summarize",
}

def pick_service(question: str) -> str | None:
    """Pick the best service for a user's question."""
    q = question.lower()
    for keyword, service in SERVICE_KEYWORDS.items():
        if keyword in q:
            return service
    return None

# โ”€โ”€ Main agent loop โ”€โ”€
def run_agent(question: str):
    """Run the agent: pick a service, call it, return the answer."""
    print(f"๐Ÿค– Agent received: {question}")

    # 1. Pick the right service
    service = pick_service(question)
    if not service:
        # 2. Show what's available
        services = discover_services()
        top = sorted(services, key=lambda s: s["calls"], reverse=True)[:5]
        return {
            "answer": "I don't know which service to use for that.",
            "available_services": top,
        }

    print(f"๐Ÿ” Calling: {service}")

    # 3. Call the service (pays 1 credit)
    result = call_service(service)
    print(f"โœ… Result: {json.dumps(result, indent=2)[:200]}")

    return {
        "service_used": service,
        "cost": "1 credit",
        "result": result,
    }


if __name__ == "__main__":
    import sys
    question = sys.argv[1] if len(sys.argv) > 1 else "What are current gas fees?"
    result = run_agent(question)
    print(json.dumps(result, indent=2))

Step 3: Run it

export AGENT_WALLET="0xYOUR_WALLET"
export AGENT_KEY="0xYOUR_PRIVATE_KEY"

python3 agent.py "What are current Ethereum gas fees?"
python3 agent.py "Is this token 0xabc... a scam?"
python3 agent.py "Scrape https://example.com"
python3 agent.py "What's the sentiment on BTC?"
โœ… That's it!

Your agent automatically picks the right service for each question and pays 1 credit per call. No API keys. No signup forms. Just a wallet and code.

5. Build a JavaScript Agent

Same agent, Node.js version. Uses viem for wallet operations and @x402/fetch for the payment layer.

Step 1: Install

npm install viem @x402/fetch

Step 2: The agent

import { createWalletClient, http, createPublicClient } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { base } from 'viem/chains'

const MINIA2A = 'https://minia2a.uk'
const WALLET = process.env.AGENT_WALLET
const PRIVATE_KEY = process.env.AGENT_KEY

// โ”€โ”€ Service router โ”€โ”€
const ROUTER = {
  gas: ['gas', 'fee', 'gwei'],
  'token-security': ['token', 'security', 'scam', 'honeypot', 'rug'],
  'web-scrape': ['scrape', 'web', 'url', 'fetch page'],
  'captcha-solve': ['captcha', 'recaptcha', 'hcaptcha'],
  time: ['time', 'date', 'timezone', 'utc'],
  'wallet-intel': ['wallet', 'intel', 'portfolio'],
  'address-parse': ['address', 'parse', '0x'],
  'domain-intel': ['domain', 'whois', 'dns'],
  'price-oracle': ['price', 'oracle', 'usd'],
  'swap-safety': ['swap', 'safety', 'sandwich'],
  sentiment: ['sentiment', 'mood', 'fear', 'greed'],
  summarize: ['summary', 'summarize', 'tldr'],
  'email-verify': ['email', 'verify', 'valid'],
}

function pickService(question) {
  const q = question.toLowerCase()
  for (const [service, keywords] of Object.entries(ROUTER)) {
    if (keywords.some(k => q.includes(k))) return service
  }
  return null
}

// โ”€โ”€ Call with credits โ”€โ”€
async function callService(endpoint, params = {}) {
  const account = privateKeyToAccount(PRIVATE_KEY)
  const timestamp = new Date().toISOString()
  const message = `${WALLET}:${endpoint}:${timestamp}`
  const signature = await account.signMessage({ message })

  const url = `${MINIA2A}/x402/${endpoint}`
  const options = {
    method: Object.keys(params).length ? 'POST' : 'GET',
    headers: {
      'x402-credits': '1',
      'x402-wallet': WALLET,
      'x402-signature': signature,
      'x402-timestamp': timestamp,
      'Content-Type': 'application/json',
    },
  }
  if (options.method === 'POST') options.body = JSON.stringify(params)

  const resp = await fetch(url, options)
  return resp.json()
}

// โ”€โ”€ Agent โ”€โ”€
async function runAgent(question) {
  console.log(`๐Ÿค– Agent: "${question}"`)

  const service = pickService(question)
  if (!service) {
    // Show available services
    const stats = await fetch(`${MINIA2A}/api/stats`).then(r => r.json())
    const top = Object.entries(stats.trials.byEndpoint)
      .filter(([k]) => k.startsWith('x402-'))
      .sort((a, b) => b[1].used - a[1].used)
      .slice(0, 5)
      .map(([k, v]) => ({ service: k.replace('x402-', ''), calls: v.used }))
    return { answer: "I don't know which service to use.", available: top }
  }

  console.log(`๐Ÿ” Calling: ${service} (1 credit)`)
  const result = await callService(service)
  console.log(`โœ… Done`)

  return { service_used: service, cost: '1 credit', result }
}

// โ”€โ”€ CLI โ”€โ”€
const question = process.argv[2] || 'What are current gas fees?'
runAgent(question).then(r => console.log(JSON.stringify(r, null, 2)))

Step 3: Production with real USDC

For production, use @x402/fetch โ€” it handles the x402 payment header automatically:

import { x402Fetch } from '@x402/fetch'

const resp = await x402Fetch('https://minia2a.uk/x402/gas', {
  wallet: account,
  maxPayment: '1000000', // $1.00 USDC (6 decimals)
  network: 'base',
})
const gasData = await resp.json()

One line. Your agent pays with real USDC on Base L2. No credits, no mock payments โ€” real money flowing for real API calls.

6. Wire It Into an LLM Agent Loop

Now the real magic: an AI agent that decides which paid APIs to call, calls them, pays for them, and uses the results โ€” all autonomously.

Python + OpenAI Function Calling

import openai
import json
from agent import call_service, pick_service, discover_services

openai.api_key = os.getenv("OPENAI_API_KEY")

# โ”€โ”€ Define minia2a services as OpenAI tools โ”€โ”€
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "call_minia2a_service",
            "description": "Call a paid API on minia2a. Costs 1 credit per call. Use for real-time data: gas prices, token security, web scraping, domain intel, sentiment, etc.",
            "parameters": {
                "type": "object",
                "properties": {
                    "service": {
                        "type": "string",
                        "description": "Service to call: gas, token-security, web-scrape, captcha-solve, time, wallet-intel, address-parse, domain-intel, dns, price-oracle, swap-safety, email-verify, sentiment, summarize, ip-lookup, language-detect, etc."
                    },
                    "query": {
                        "type": "string",
                        "description": "Optional parameter for the service (token address, URL to scrape, domain name, etc.)"
                    }
                },
                "required": ["service"]
            }
        }
    }
]

def call_minia2a_service(service, query=None):
    """Bridge: OpenAI function โ†’ minia2a API call."""
    params = {"query": query} if query else {}
    result = call_service(service, params)
    return json.dumps(result)

def agent_loop(user_message):
    """Run the full agent loop: LLM โ†’ tool calling โ†’ response."""
    messages = [
        {"role": "system", "content": "You are an AI agent with access to 174 paid APIs on minia2a. Each call costs 1 credit. Use them freely โ€” the user has 500 free credits. Always use real-time data from API calls, never guess."},
        {"role": "user", "content": user_message}
    ]

    while True:
        response = openai.chat.completions.create(
            model="gpt-4o",
            messages=messages,
            tools=TOOLS,
            tool_choice="auto"
        )

        msg = response.choices[0].message

        # If no tool call, the agent is done โ€” return the answer
        if not msg.tool_calls:
            return msg.content

        # Process tool calls
        messages.append(msg)
        for tool_call in msg.tool_calls:
            if tool_call.function.name == "call_minia2a_service":
                args = json.loads(tool_call.function.arguments)
                result = call_minia2a_service(
                    args.get("service"),
                    args.get("query")
                )
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": result
                })

# โ”€โ”€ Run โ”€โ”€
if __name__ == "__main__":
    question = "What are ETH gas fees right now and is it a good time to swap?"
    answer = agent_loop(question)
    print(answer)
๐Ÿค– What just happened?

The LLM received a question, decided it needed real-time gas data and swap safety analysis, called two separate minia2a APIs, paid 2 credits ($0.01), and synthesized the results into a coherent answer. This is the agent economy in action โ€” AI agents paying for APIs as they need them.

7. Go to Production

When you're ready to move beyond free credits, here's the production setup:

Fund your wallet

# 1. Get USDC on Base (Coinbase, Binance, or bridge from Ethereum)
# 2. Send to your agent's wallet address
# 3. Keep ~$2 of ETH on Base for gas (tx fees are <$0.01)

Production agent with real USDC

import { x402Fetch } from '@x402/fetch'
import { privateKeyToAccount } from 'viem/accounts'
import { base } from 'viem/chains'

const account = privateKeyToAccount(process.env.AGENT_KEY)

// Call any minia2a service with real USDC
async function callProduction(endpoint) {
  const resp = await x402Fetch(
    `https://minia2a.uk/x402/${endpoint}`,
    {
      wallet: account,
      maxPayment: '1000000', // $1.00 max
      network: base,
    }
  )
  return resp.json()
}

// Your agent now pays real USDC per API call
const gasData = await callProduction('gas')
const security = await callProduction('token-security')
console.log({ gasData, security })

Cost comparison

ApproachSetupPer CallMonthly (1000 calls)
Traditional APIsKYC, credit card, API key"Free tier" โ†’ $100+/mo$100โ€“$500
minia2a credits10-second registration$0.005 (1 credit)$5.00
minia2a USDCFund wallet with USDC$0.001โ€“$0.01$1โ€“$10
๐Ÿ’ก Why credits?

Credits let you test and iterate without spending real money. Once your agent works, switch to USDC for production. Credits also let you sell your own API on minia2a and earn USDC from other agents.

๐Ÿš€ Ready to Build?

Your agent gets 500 free credits. That's 500 API calls. Zero cost. Zero risk.

Get 500 Free Credits โ†’

๐Ÿ“ฆ Clone the code: github.com/minia2a/minia2a-agent-demo โ†’

Already have a wallet? Check your balance โ†’ ยท Need more examples? Agent Cookbook โ†’