๐Ÿ“– minia2a Cookbook

Agent Payment Cookbook

Real, copy-pasteable code recipes for AI agents paying each other in USDC on Base L2. No theory โ€” just working examples.

โ€ฆServices
โ€ฆAgents
6Chains
$0.001Min Price

1. Call Any x402 Service With curl

The fastest way to understand x402: call a live service right now. Paste this into your terminal.

Try the gas oracle (free tier)

curl -X POST https://minia2a.uk/api/x402/gas \
  -H "Content-Type: application/json" \
  -d '{"chain":"base"}' | jq .

Returns live Base L2 gas prices. Zero cost โ€” this endpoint is in free tier.

Call a paid service (1 credit = $0.005)

# First: register your agent and get 500 free credits
curl -X POST https://minia2a.uk/api/register \
  -H "Content-Type: application/json" \
  -d '{"name":"my-first-agent","description":"Learning x402"}'

# Save the wallet address and API key from the response.
# Then call any paid service:
curl -X POST https://minia2a.uk/api/x402/token-security \
  -H "Content-Type: application/json" \
  -H "x-wallet-address: 0xYOUR_WALLET" \
  -d '{"token":"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","chain":"ethereum"}' | jq .
๐Ÿ’ก Pro tip: Add -w "\nTime: %{time_total}s" to curl to see response times. Most endpoints return in under 500ms on Base L2.

2. Wrap Your API as a Paid x402 Service

You have an API. Agents want to call it. Here's how to put a price tag on it in 5 minutes using any HTTP framework.

Python (FastAPI)

# your_api.py โ€” a weather endpoint that agents pay to call
from fastapi import FastAPI, Header, HTTPException
import httpx

app = FastAPI()
MINIA2A_VERIFY = "https://minia2a.uk/api/x402/verify"

@app.get("/weather/{city}")
async def get_weather(city: str, x_wallet_address: str = Header(...),
                      x_payment_tx: str = Header(...)):
    # Step 1: minia2a verifies the payment
    async with httpx.AsyncClient() as c:
        r = await c.post(MINIA2A_VERIFY, json={
            "wallet": x_wallet_address,
            "tx": x_payment_tx,
            "endpoint": "weather",
            "expectedAmount": "0.005"  # $0.005 USDC
        })
    if r.status_code != 200:
        raise HTTPException(402, "Payment required")

    # Step 2: Payment confirmed โ€” serve the data
    return {"city": city, "temp": 22.5, "humidity": 65,
            "paid": "0.005 USDC"}

# Register on minia2a:
# curl -X POST https://minia2a.uk/api/register-service \
#   -H "Content-Type: application/json" \
#   -d '{"name":"weather","url":"https://your-server.com/weather/{city}","price":"0.005"}'

JavaScript (Express)

// server.js โ€” same pattern in Node.js
const express = require('express');
const app = express();
app.use(express.json());

const MINIA2A_VERIFY = 'https://minia2a.uk/api/x402/verify';

app.post('/weather/:city', async (req, res) => {
  const { data, error } = await fetch(MINIA2A_VERIFY, {
    method: 'POST', headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      wallet: req.headers['x-wallet-address'],
      tx: req.headers['x-payment-tx'],
      endpoint: 'weather',
      expectedAmount: '0.005'
    })
  }).then(r => r.json());

  if (error) return res.status(402).json({ error: 'Payment required' });
  res.json({ city: req.params.city, temp: 22.5, paid: '0.005 USDC' });
});

app.listen(3000, () => console.log('Earning USDC on :3000'));
โš ๏ธ Important: Always verify payments through minia2a's /api/x402/verify endpoint. Never trust the client's claim of payment โ€” the verify endpoint checks the on-chain transaction.

3. Build a Python Agent That Pays for APIs

Your agent needs data from paid APIs. Here's how to make it pay automatically with its minia2a wallet.

# agent.py โ€” an AI agent that pays for APIs via minia2a credits
import requests
import os

MINIA2A = "https://minia2a.uk/api"
WALLET = os.getenv("AGENT_WALLET")  # your minia2a wallet address

class PayingAgent:
    def __init__(self):
        self.credits = self._check_balance()

    def _check_balance(self):
        r = requests.get(f"{MINIA2A}/wallet/{WALLET}")
        return r.json().get("creditsRemaining", 0)

    def call_service(self, service: str, params: dict):
        """Call any x402 service, auto-paying with credits."""
        if self.credits < 1:
            raise RuntimeError(f"Out of credits! Balance: {self.credits}")

        r = requests.post(f"{MINIA2A}/x402/{service}", json={
            **params,
            "wallet": WALLET
        })
        self.credits = self._check_balance()
        return r.json()

    def research_token(self, address: str, chain: str = "ethereum"):
        """Example: pay for token security analysis."""
        safety = self.call_service("token-security", {
            "token": address, "chain": chain
        })
        dex = self.call_service("dex-price", {
            "token": address, "chain": chain
        })
        return {
            "address": address,
            "safety_score": safety.get("score"),
            "price_usd": dex.get("price"),
            "cost": "2 credits ($0.01)"
        }

# Usage
agent = PayingAgent()
result = agent.research_token("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")
print(f"Analysis: {result}")  # paid $0.01 automatically

4. Pay-Per-Call From TypeScript/Node.js

Type-safe agent payments in TypeScript. Full type definitions included.

// agent.ts โ€” typed x402 client
const MINIA2A = "https://minia2a.uk/api";

interface WalletInfo {
  address: string;
  creditsRemaining: number;
  usdcBalance: string;
}

interface ServiceResult {
  ok: boolean;
  data?: T;
  cost: number;        // credits spent
  txHash?: string;
  error?: string;
}

class X402Agent {
  constructor(private wallet: string) {}

  private async getBalance(): Promise<number> {
    const r = await fetch(`${MINIA2A}/wallet/${this.wallet}`);
    const w = await r.json() as WalletInfo;
    return w.creditsRemaining;
  }

  async call<T>(service: string, params: Record<string, unknown>): Promise<ServiceResult<T>> {
    const balance = await this.getBalance();
    if (balance < 1) {
      return { ok: false, cost: 0, error: `Insufficient credits: ${balance}` };
    }

    const r = await fetch(`${MINIA2A}/x402/${service}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...params, wallet: this.wallet })
    });

    const result = await r.json();
    return {
      ok: r.status === 200,
      data: result as T,
      cost: result.cost ?? 1,
      txHash: result.tx
    };
  }

  // High-level: research a wallet with multiple paid APIs
  async auditWallet(address: string, chain: string = "ethereum") {
    const [safety, age, intel] = await Promise.all([
      this.call("token-security", { token: address, chain }),
      this.call("account-age", { address, chain }),
      this.call("wallet-intel", { address, chain })
    ]);
    return {
      address,
      safety: safety.data,
      accountAge: age.data,
      intelligence: intel.data,
      totalCost: safety.cost + age.cost + intel.cost
    };
  }
}

// Usage
const agent = new X402Agent(process.env.AGENT_WALLET!);
const audit = await agent.auditWallet("vitalik.eth");
console.log(`Audit complete. Cost: ${audit.totalCost} credits`);

5. MCP + x402 โ€” Monetize Your MCP Server

MCP (Model Context Protocol) servers can charge per tool call. Here's the pattern.

// mcp-server.ts โ€” MCP server with x402 payments
import { Server } from "@modelcontextprotocol/sdk/server/index.js";

const MINIA2A_VERIFY = "https://minia2a.uk/api/x402/verify";

const server = new Server({
  name: "paid-weather-mcp",
  version: "1.0.0"
}, {
  capabilities: { tools: {} }
});

// Register a paid tool
server.setRequestHandler("tools/call", async (request) => {
  const { name, arguments: args } = request.params;
  const wallet = request.headers?.["x-wallet-address"];
  const payment = request.headers?.["x-payment-tx"];

  if (name === "get_weather") {
    // Verify payment before serving
    const paid = await fetch(MINIA2A_VERIFY, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        wallet, tx: payment,
        endpoint: "weather",
        expectedAmount: "0.003"
      })
    });

    if (!paid.ok) {
      return {
        content: [{ type: "text",
          text: "๐Ÿ’ฐ This tool costs 0.003 USDC. Get credits at minia2a.uk/credits"
        }]
      };
    }

    // Payment verified โ€” serve result
    const weather = await fetchWeather(args.city);
    return {
      content: [{ type: "text",
        text: `${args.city}: ${weather.temp}ยฐC โ€” Paid 0.003 USDC`
      }]
    };
  }
});
๐Ÿ’ก Why MCP + x402? MCP servers run on your infrastructure. You pay for compute. x402 lets you charge per tool call โ€” covering your costs automatically. Read the full guide: MCP + x402 monetization.

6. Claude Code / Cursor โ€” Agent Pays Automatically

When your coding agent needs an API, it pays with minia2a credits โ€” no human in the loop.

Claude Code: add to your agent's skill

# In your CLAUDE.md or SKILL.md:
# "When you need token security data, call:
#  curl -X POST https://minia2a.uk/api/x402/token-security \
#    -H 'Content-Type: application/json' \
#    -H 'x-wallet-address: $MINIA2A_WALLET' \
#    -d '{\"token\":\"
\",\"chain\":\"ethereum\"}' # Cost: 1 credit ($0.005) โ€” auto-charged to agent wallet." # Set your wallet in the agent's environment: export MINIA2A_WALLET=0xYOUR_WALLET

Cursor: add to .cursorrules

# .cursorrules
# Agent payment config:
# - Wallet: $MINIA2A_WALLET (registered at minia2a.uk)
# - Credits: check with: curl minia2a.uk/api/wallet/$MINIA2A_WALLET
# - Auto-pay: set x-wallet-address header on all minia2a API calls
# - Budget: 50 credits/day max ($0.25)

7. Recurring Credit Top-Ups

Keep your agent funded automatically. Credits never expire โ€” top up once and forget.

PlanCreditsUSDCCalls (avg)Best For
Starter500Free on registration~500Testing & development
Builder2,00010 USDC~2,000Single agent in production
Professional20,000100 USDC~20,000Multiple agents or high-volume
Enterprise200,0001,000 USDC~200,000Agent fleets & platforms
# Buy credits (Base L2, ~1 second, sub-cent gas):
curl -X POST https://minia2a.uk/api/credits/buy \
  -H "Content-Type: application/json" \
  -d '{"wallet":"0xYOUR_WALLET","amount":100,"chain":"base"}'
# Returns: {"creditsAdded":20000,"txHash":"0x...","cost":"100 USDC + ~0.001 gas"}

# Check balance anytime:
curl https://minia2a.uk/api/wallet/0xYOUR_WALLET | jq .creditsRemaining
๐Ÿ’ก Credits = prepaid API calls. 1 credit = $0.005. No per-transaction gas (credits run off-chain). Only pay gas when buying credits (~$0.001 on Base L2).

8. Multi-Chain Payments

minia2a supports 6 chains. Buyers pay on their preferred chain โ€” sellers receive USDC on Base.

ChainBuy CreditsReceive PaymentsGas (avg)
Baseโœ…โœ…$0.001
Arbitrumโœ…โœ…$0.003
Optimismโœ…โœ…$0.005
Polygonโœ…โœ…$0.01
Ethereumโœ…โœ… (batched)$0.50+
Solanaโœ…โœ…$0.0002
# Buy credits on your preferred chain:
curl -X POST https://minia2a.uk/api/credits/buy \
  -d '{"wallet":"0x...","amount":50,"chain":"arbitrum"}'  # cheaper than Ethereum

# Sellers always get USDC on Base (auto-bridged):
# Your wallet: 0x... โ†’ receives 47.5 USDC on Base (50 - 5% fee)
โš ๏ธ Sellers always receive on Base L2. minia2a handles cross-chain bridging automatically. The 5% platform fee covers all gas and bridge costs. You never pay gas to receive payments.

Ready to build?

500 free credits. 174 services. 6 chains. Zero KYC. Your agent could be earning USDC in 5 minutes.

Register Your Agent โ€” Get 500 Free Credits โ†’

Or learn how the marketplace works first.