x402 Fast Monetization Template

March 14, 2026 · View on GitHub

Turn any Python function into a zero-gas AI Agent API — monetized with USDC, live in 3 steps.

Python USDC License x402


What is this?

This template lets you monetize any Python function as a pay-per-call API using USDC and the x402 protocol. One decorator is all it takes. No subscription logic, no API keys to manage for your callers, no billing infrastructure.

The killer feature: SKALE on Base is the default chain. SKALE on Base has ultra-low gas fees (~$0.0007/tx via CREDITS) — AI agents and bots can make hundreds of micro-payments per minute without burning money on gas. On Base you pay ~$0.001 per transaction; on SKALE on Base you pay a fraction of a cent.


Quick Start (3 Steps)

1. Clone and install

git clone https://github.com/Wintyx57/x402-fast-monetization-template.git
cd x402-fast-monetization-template
pip install -r requirements.txt

2. Set your wallet

cp .env.example .env

Open .env and set your wallet address:

Need USDC? Bridge from any chain → SKALE in 1 click: x402bazaar.org/fund

WALLET_ADDRESS=0xYOUR_ACTUAL_WALLET_ADDRESS

3. Run

python main.py

Your API is live at http://localhost:8000/docs — open it to see the interactive Swagger UI.


How It Works

The x402 protocol reuses the HTTP 402 status code ("Payment Required") to create a machine-readable payment flow that AI agents can navigate autonomously:

Client / AI Agent                 Your API                      Chain (SKALE or Base)
        |                              |                                  |
        |  1. GET /generate_qr         |                                  |
        |----------------------------->|                                  |
        |                              |                                  |
        |  2. 402 + payment_details    |                                  |
        |    (amount, wallet, network) |                                  |
        |<-----------------------------|                                  |
        |                              |                                  |
        |  3. Send USDC on SKALE       |                                  |
        |---------------------------------------------------------------->|
        |                              |                                  |
        |  4. GET /generate_qr         |                                  |
        |    + X-Payment-TxHash: 0x... |                                  |
        |    + X-Payment-Chain: skale  |                                  |
        |----------------------------->|                                  |
        |                              |  5. Verify tx on-chain           |
        |                              |--------------------------------->|
        |                              |                                  |
        |  6. 200 + result             |                                  |
        |<-----------------------------|                                  |
  1. Client calls your API without payment
  2. Server responds 402 with payment details (amount, recipient, USDC contract, all supported networks)
  3. Client sends USDC on the chain of its choice
  4. Client retries with X-Payment-TxHash and optionally X-Payment-Chain headers
  5. Server verifies the on-chain transaction (correct recipient, sufficient amount, not replayed)
  6. Access granted — your function executes and returns the result

Supported Networks

ChainGas CostUSDC ContractChain ID
Base~$0.0010x833589fCD6eDb6E08f4c7C32D4f71b54bdA029138453
SKALE on Base (default)~$0.0007 (CREDITS gas token)0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb201187947933
Polygon~$0.001 (MATIC)0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359137

All chains are listed in the 402 response under payment_details.networks so agents can pick the cheapest option automatically.

To change the default chain, set DEFAULT_CHAIN=base or DEFAULT_CHAIN=polygon in your .env.


The @x402_paywall Decorator

One decorator turns any Python function into a paid FastAPI endpoint:

@x402_paywall(price=0.05, description="My paid API", tags=["cool"])
def my_function(param: str) -> dict:
    return {"result": f"You sent: {param}"}

What happens automatically:

  • The function name becomes the endpoint path (/my_function)
  • Function parameters become URL query parameters (?param=hello)
  • The return type hint controls the response format:
    • dict -- JSON response
    • bytes -- Binary response (e.g., PNG image)
    • str -- Plain text response
  • Callers without a valid payment get a 402 with full payment instructions
  • Callers with a valid X-Payment-TxHash get the function result

The 402 response body that agents receive:

{
  "error": "Payment Required",
  "payment_details": {
    "amount": "0.05",
    "currency": "USDC",
    "network": "SKALE on Base",
    "chain_id": 1187947933,
    "recipient": "0xYOUR_WALLET_ADDRESS",
    "usdc_contract": "0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",
    "networks": [
      { "chain": "base", "label": "Base", "chain_id": 8453, "gas": "~\$0.001", ... },
      { "chain": "skale", "label": "SKALE on Base", "chain_id": 1187947933, "gas": "~\$0.0007 (CREDITS)", ... }
    ],
    "instructions": "Send USDC on SKALE on Base to the recipient address, then retry with headers X-Payment-TxHash: 0x... and X-Payer-Address: 0x... Optionally add X-Payment-Chain: base|skale to select the network."
  }
}

Add Your Own API

Open main.py and go to Section 5. Adding a new paid endpoint is 3 lines:

@x402_paywall(price=0.02, description="Search my database", tags=["search", "data"])
def my_api(query: str, limit: int = 10) -> dict:
    results = do_something(query, limit)
    return {"data": results}

Restart the server — your endpoint is live at GET /my_api?query=hello&limit=5 and visible in /docs.

Decorator parameters:

ParameterTypeRequiredDescription
pricefloatYesPrice in USDC per call
descriptionstrNoShown in Swagger UI and marketplace
tagslist[str]NoUsed for categorization

Included Examples

The template ships with 3 working endpoints, no external API keys required:

EndpointPrice (USDC)DescriptionReturns
/generate_qr0.05Generate a QR code image from textPNG image
/summarize0.03Summarize text (extractive, word-freq)JSON
/random_joke0.01Get a random programming jokeJSON

Environment Variables

VariableRequiredDefaultDescription
WALLET_ADDRESSYes--Your Ethereum address to receive USDC payments
DEFAULT_CHAINNoskaleDefault payment chain: skale or base
BASE_RPC_URLNochain defaultOverride the Base RPC endpoint
BAZAAR_REGISTRY_URLNo--x402 Bazaar URL for auto-registering your endpoints
API_BASE_URLNohttp://localhost:8000Public URL of your API (used for marketplace)
PORTNo8000Server listening port

Deploy

Replit (one-click):

Run on Replit

  1. Click the button above
  2. Set WALLET_ADDRESS in the Replit Secrets tab
  3. Hit Run — your API is live with a public URL

Railway / Render:

# Set environment variables in the dashboard, then deploy:
git push

Both platforms detect Python automatically. Set WALLET_ADDRESS and optionally DEFAULT_CHAIN in the environment variables panel.


ResourceURL
x402 Bazaar marketplacex402bazaar.org
Backend APIx402-api.onrender.com
CLI (npx x402-bazaar)x402-bazaar-cli
TypeScript SDKx402-sdk
LangChain toolsx402-langchain
MCP Serverx402-backend

License

MIT — Use it, fork it, monetize with it.