Documentation

Build AI agent payment systems. Integrate x402 micropayments for autonomous fantasy predictions and Kalshi betting.

What is x402?

x402 is GameFlow's payment protocol infrastructure for autonomous AI agent transactions. Every prediction becomes a micropayment opportunity, enabling true usage-based validation with instant on-chain settlement. AI agents place real bets on Kalshi using x402 payment rails.

Core Principles

Usage-Based Validation

AI agents pay per prediction analyzed. No monthly fees, no commitments. Just pure value exchange per request backed by real capital.

Autonomous Testing

Explore and test any prediction before committing. Validate integration before AI agents deploy capital on live Kalshi odds.

Instant Settlement

Payments settle on-chain in under a second. No chargebacks, no disputes, complete transparency for every x402 transaction.

Multi-Chain Native

Built for a multi-chain future. Deploy once, transact everywhere with x402 agent payment infrastructure.

Base Base Solana Solana Polygon Polygon Sei Sei Peaq Peaq

Quick Start

Deploy your first x402-enabled service for GameFlow AI agents in under 5 minutes.

Choose Your Path

Building a prediction service or consuming existing APIs? Pick your path and get started.

Service Providers

Launch an AI agent that accepts x402 micropayments for fantasy predictions.

1

Select Framework

→ Express.js / Node.js
→ Python (FastAPI/Flask)

2

Install Package

Add the x402 middleware to your project via npm or pip

3

Configure Middleware

Set your payment address and facilitator endpoint in the headers

4

Deploy

Push to production and start accepting micropayments instantly from AI agents

Consumers

Start calling x402-protected prediction APIs with AI agents.

1

Discover Services

Browse the marketplace to find AI prediction services, data APIs, and specialized fantasy analysis tools

2

Test Free

Use built-in testing interfaces to validate service behavior before AI agents commit capital

3

Connect Wallet

Link your MetaMask, Phantom, or preferred wallet for x402 agent transactions

4

Install Client

Add the x402 client library to handle payments automatically in your AI agent code

5

Start Transacting

Make API calls with AI agents—x402 payments execute automatically in the background per request

Why x402?

1
Request to Protected Endpoint

AI agent sends standard HTTP GET/POST request to x402 endpoint for GameFlow predictions

2
402 Response

Server returns HTTP 402 with payment instructions (address, amount, network)

3
Client Pays On-Chain

x402 client library automatically creates and broadcasts a blockchain payment

4
Validation & Response

Server verifies payment on-chain and returns requested resource if valid

Core Advantages

True Micropayments

Charge $0.0001 per request for AI agent predictions. Traditional payment rails collapse at this scale.

Sub-Second Settlement

Payments finalize on-chain in under a second. No multi-day clearing windows for autonomous agent transactions.

Borderless Commerce

Anyone with a wallet can transact. No geographic restrictions or card networks for AI agents placing Kalshi bets.

Machine Economy Ready

Perfect for AI agents and autonomous systems that need to pay for fantasy prediction services without human intervention.

Multi-Chain Support

Base Base

L2 Ethereum • Low fees

Solana Solana

High performance • Sub-cent fees

Polygon Polygon

EVM compatible • Fast

Sei Sei

Optimized L1 • Speed

Peaq Peaq

DePIN-optimized • IoT

Start Building

Ready to integrate x402 payments for AI agents? Choose your stack and start building in minutes.

View Guides

Express.js Server

Start accepting x402 payments in your Express server in 5 minutes. Built a universal GameFlow API with just a few lines of code.

Quick Start

Use the official Express server templates to bootstrap a ready-to-run x402 fantasy prediction server. For partners infra/use needed - just add your wallet address and start earning.

Step 1: Create Project

Initialize your Express project or use a new base folder from the starter template:

npm init -y
npm install express @gameflow/x402-server

# Or clone starter
git clone https://github.com/gameflow-labs/x402-express-starter
cd x402-express-starter

Step 2: Configure Environment

Create your project's .env file and add:

# Production Environment
NODE_ENV=production

# Payment Configuration  
FACILITATOR_URL=https://facilitator.gameflowlabs.com/api
X402_PAY_TO=0x1234...abcd (Your wallet address)
X402_NETWORK=base (Preferred chain: base, solana, polygon, etc)

# API Keys (if using external data)
KALSHI_API_KEY=your_api_key
OPENAI_API_KEY=your_openai_key

Step 3: Server Code

Add to your server index.js file. It creates your server and applies the x402 payment middleware with relative protected routes:

const express = require('express');
const { x402Middleware } = require('@gameflow/x402-server');

const app = express();

// Apply x402 to all /api/* routes
app.use('/api/*', x402Middleware({
  payTo: process.env.X402_PAY_TO,
  facilitatorUrl: process.env.FACILITATOR_URL,
  network: process.env.X402_NETWORK || 'base',
  price: 0.001 // $0.001 per API call
}));

// Protected endpoint
app.get('/api/prediction', (req, res) => {
  res.json({
    player: req.query.player,
    prediction: "Will score 2+ goals",
    confidence: 0.87,
    kalshi_odds: 3.2,
    edge_detected: true,
    x402_paid: true
  });
});

// Health check
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`x402 server listening on ${PORT}`);
});

Step 4: Run Your Server

node index.js

Your service is now accepting x402 payments! Test it by calling http://localhost:3000/api/prediction

How It Works

1
Client Requests Resource

AI agent or client makes an initial HTTP-402 payment-protected request

2
Server Returns 402

The server responds with HTTP-402 and payment instructions in the headers

3
Client Pays

AI agent initiates blockchain transaction for the specified payment address

4
Payment Verified

The facilitator verifies the payment on-chain and validates the request (Proxy)

5
Response Delivered

Your endpoint handler runs and returns the requested resource to the AI agent client

Pricing Options

Fixed Amount Pricing

Simplest model - charge the same amount per API call regardless of usage

x402Middleware({
  price: 0.001, // $0.001 per call
  payTo: "0xabcd1234..."
})

Token-Based Pricing

Charge agents based on LLM or usage token count - ideal for compute-heavy AI fantasy predictions

x402Middleware({
  pricing: {
    model: 'token',
    rate: 0.00001, // per token
    currency: 'USDC'
  }
})

Deploy to Production

Deployment Options

  • Vercel - Zero config, auto-scaling, HTTPS out of box
  • Railway.app - Simple container deployment
  • DigitalOcean/AWS/GCP - Full control with traditional cloud hosting

Next Steps

Learn how to add client libraries to consume your x402-protected GameFlow APIs.

View Client Integration View on GitHub

Python Server

Add x402 payments to your Flask or FastAPI server. Perfect for AI-powered GameFlow data APIs, ML services, and Python-based fantasy prediction backends.

Python Support

The x402 Python SDK works with FastAPI, Flask, and ASGI/WSGI frameworks. Perfect for machine learning APIs, Python-based AI agent microservices, and Python-based x402 fantasy data backends.

Installation

pip install x402-python

poetry add x402-python

FastAPI Example

Add x402 fantasy payments protection to your FastAPI endpoints:

from fastapi import FastAPI, Request
from x402 import X402Middleware, require_payment

app = FastAPI()

# Initialize x402 middleware
x402 = X402Middleware(
    pay_to="0x1234...abcd",
    facilitator_url="https://facilitator.gameflowlabs.com/api",
    network="base"
)

@app.get("/api/predict")
@require_payment(price=0.001)
async def predict(player: str):
    return {
        "player": player,
        "prediction": "2+ goals",
        "confidence": 0.92,
        "kalshi_odds": 2.8,
        "x402_validated": True
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Flask Example

Use x402 with Flask (sync or async):

from flask import Flask, jsonify
from x402 import X402Client, require_payment

app = Flask(__name__)

x402 = X402Client(
    pay_to="0x1234...abcd",
    network="base"
)

@app.route("/api/data")
@require_payment(price=0.001)
def get_data():
    return jsonify({
        "data": "Paid fantasy data",
        "status": "x402 validated"
    })

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

Configuration

Set up your environment variables:

# .env
X402_PAY_TO=0x1234...abcd  # Your wallet address to receive payments
X402_NETWORK=base  # Network: base, solana, polygon, bsc, sei, peaq
FACILITATOR_URL=https://facilitator.gameflowlabs.com/api

# For advanced use
X402_MIN_AMOUNT=0.0001  # Minimum payment amount
X402_TIMEOUT=30  # Seconds to wait for payment confirmation

Advanced Usage

Custom Pricing Logic

@app.get("/api/predict")
@require_payment(calculate_price_func=lambda request: {
    'basic': 0.001,
    'premium': 0.01,
    'enterprise': 0.1
}.get(request.query_params.get('tier'), 0.001))
async def predict_custom_price(tier: str, player: str):
    # Dynamic x402 pricing based on tier for AI agents
    return generate_prediction(player, tier)

Multiple Networks

# Accept fantasy predictions payments on multiple chains
@app.get("/api/multi-network")
@require_payment(
    networks=['base', 'solana', 'polygon'],
    price=0.001
)
async def multi_network_endpoint():
    return {"message": "Paid on any supported network"}

Use Cases

AI & ML Services

Monetize AI model inferences, image generation, data analysis, and machine learning APIs with x402 for fantasy predictions and autonomous agents

Data APIs

Charge per query for financial data, market odds, real-time feeds, and specialized fantasy sports datasets with x402 micropayments

Scraping Services

Offer AI agents web scraping, data extraction, and content aggregation with instant x402 payments per request

Processing APIs

Batch operations, image/video processing, and long-running AI agent jobs—charge based on compute time via x402

Deploy Your Python Service

Ready to deploy? Learn about client integration and production-deployment options for GameFlow AI agents.

Deployment Guide Development Guide

Client Libraries

Integrate x402 payments into your applications using our client libraries. Automate payment handling for HTTP requests from AI agents consuming GameFlow APIs.

How Client Libraries Work

Our client libraries automatically handle the HTTP-402 payment flow so that you make a request to a protected endpoint. The library detects the 402 response, initiates the required x402 payment, and retries the request with payment proof. All x402 transactions happen automatically.

JavaScript / TypeScript

Install via npm/yarn to enable AI agent x402 payment automation:

npm install @gameflow/x402-client

Basic Usage

import { X402Client } from '@gameflow/x402-client';

const client = new X402Client({
  signer: wallet, // ethers.js wallet signer
  network: 'base'
});

// Make paid request - x402 payment happens automatically
const data = await client.get('https://api.example.com/predictions');
console.log(data);

POST Requests

// AI agent submitting x402-protected prediction requests
const response = await client.post('https://api.example.com/bet', {
  player: 'Haaland',
  market: 'goals',
  amount: 100
});

React Integration

import { X402Provider, useX402 } from '@gameflow/x402-react';

function App() {
  return (
    <X402Provider network="base" signer={wallet}>
      <MyComponent />
    </X402Provider>
  );
}

function MyComponent() {
  const { client } = useX402();
  
  const fetchData = async () => {
    const data = await client.get('/api/predictions');
    // x402 payment handled automatically for AI agents
  };
}

Python

Install the Python client library for AI agent automation:

pip install x402-client

Basic Usage

from x402_client import X402Client

# Initialize client with wallet for AI agent x402 payments
client = X402Client(
    private_key="0x...",
    network="base"
)

# Make x402 paid request - payment automatic
response = client.get('https://api.example.com/predictions')
print(response.json())

Async Support

import asyncio
from x402_client import AsyncX402Client

async def main():
    client = AsyncX402Client(
        private_key="0x...",
        network="base"
    )
    
    # Multiple concurrent x402 paid requests for AI agent
    results = await asyncio.gather(
        client.get('https://api1.example.com/data'),
        client.get('https://api2.example.com/predictions'),
        client.get('https://api3.example.com/odds')
    )

asyncio.run(main())

Configuration Options

Network Selection

const client = new X402Client({
  signer: wallet,
  network: 'base'  // base | solana | polygon | bsc | sei | peaq
});

Payment Limits

const client = new X402Client({
  signer: wallet,
  network: 'base',
  maxPayment: 0.01,  // Max $0.01 per request - AI agent safety
  confirmationThreshold: 1  // Blocks to wait for x402 confirmation
});

Custom Headers

// Add custom GameFlow API headers for AI agents
const data = await client.get('/api/data', {
  headers: {
    'X-API-Version': '2',
    'X-Agent-Type': 'claude-sonnet'
  }
});

Error Handling

try {
  const data = await client.get('/api/predictions');
} catch (error) {
  if (error.code === 'INSUFFICIENT_BALANCE') {
    // AI agent wallet lacks funds for x402 payment
    console.log('Top up your wallet to continue');
  }
  
  if (error.code === 'PAYMENT_REJECTED') {
    // x402 transaction failed on-chain
    console.log('Payment was not accepted');
  }
  
  if (error.code === 'NETWORK_ERROR') {
    // Blockchain RPC issue for x402 transaction
    console.log('Network connectivity problem');
  }
}

Advanced Features

Payment Caching

Automatically cache x402 payment proofs to avoid redundant blockchain transactions for AI agent repeat calls

Retry Logic

Built-in retry logic with exponential backoff for x402 payment failures and network issues

Multi-Network

Switch between Base, Solana, Polygon, and other chains seamlessly for x402 AI agent payments

TypeScript Types

Full TypeScript support with type definitions for all x402 GameFlow API responses

Learn More

Check out advanced examples and understand the complete payment flow for AI agents on GameFlow x402 infrastructure.

Payment Flow Code Examples

Payment Flow

Understand how x402 facilitates payments end-to-end for AI agents. From initial request to service delivery on GameFlow predictions.

The x402 Payment Protocol

x402 uses the HTTP-402 "Payment Required" status code to implement payments between AI agent clients and servers. The entire flow is automatic when using x402 client libraries, enabling true usage-based pricing with instant on-chain settlement for GameFlow micropayments.

Step-by-Step Flow

1
Client Initiates Request

AI agent sends a standard HTTP request to an x402-protected endpoint

GET /api/predictions HTTP/1.1
Host: api.example.com
User-Agent: x402-client/2.0
2
402 Response

Server returns HTTP-402 with payment instructions: account, address, and accepted tokens for x402 GameFlow

HTTP/1.1 402 Payment Required
X-Accept-Payment: base, solana
X-Payment-Required: true
X-Payment-Amount: 0.001
X-Payment-Address: 0x1234...abcd
X-Payment-Network: base

{
  "error": "payment_required",
  "price": "0.001",
  "network": "base"
}
3
Client Parses Payment Info

x402 client library extracts payment details from the response headers for AI agent wallet

const paymentInfo = {
  amount: headers['x-payment-amount'],
  address: headers['x-payment-address'],
  network: headers['x-payment-network']
};
4
Payment Verified

AI agent creates and signs blockchain transaction via x402 payment instructions, sends payment proof to facilitator

{
  "chain": "base",
  "tx": "0x123abc...",
  "from": "0xabcd...",
  "to": "0x1234...",
  "amount": "0.001 USDC",
  "timestamp": 1698234567
}
5
Sign & Broadcast

AI agent's wallet signs the transaction and broadcasts it to the blockchain network (Base, Solana, etc.) for x402 settlement

6
Retry with Proof

Client retries the original request with transaction signature as payment proof in headers for x402 validation

GET /api/predictions HTTP/1.1
Host: api.example.com
X-Payment-Hash: 0x123abc...
X-Payment-Network: base
X-Payment-Proof: test-proof-123
7
Server Validates Payment

Server queries the blockchain (or uses facilitator) to verify the transaction exists & matches the request (Proxy) for x402 GameFlow

8
Service Delivered

Payment valid -> Server processes the request and returns the requested resource to AI agent client

HTTP/1.1 200 OK
Content-Type: application/json

{
  "player": "Haaland",
  "prediction": "2+ goals",
  "confidence": 0.94,
  "x402_paid": true
}

Payment Verification

Facilitator Role

What Facilitators Do

Facilitators provide REST APIs that x402 servers query to verify AI agent payments without requiring complex blockchain infrastructure. They handle on-chain reads, caching, and provide a simple true/false x402 validation response for GameFlow payment verification. Providers can run their own facilitators or use public ones.

Edge Cases

Insufficient Payment

If AI agent pays less than required via x402, server rejects the request with error code. The remaining amount needed is returned for retry.

Unconfirmed Transaction

Server will wait for x402 confirmation (depending on configuration). By default transactions under a second on L2s/Base/Solana are fast enough.

Network Mismatch

Client pays on wrong network -> Server rejects. Error indicates the correct networks accepted for AI agent x402 GameFlow payments.

Replay Attack Prevention

Each x402 transaction hash can only be used once per endpoint. Servers track used hashes to prevent AI agents reusing payment proofs.

Dive Deeper

Learn about facilitators and dive into examples of the complete x402 GameFlow AI agent flow.

Code Examples Facilitators

API Reference

Complete API docs for x402 Express middleware, Python decorators, and facilitator endpoints for GameFlow AI agent payments.

Express Middleware

x402Middleware

Creates Express middleware for x402 payment protection for GameFlow AI agent endpoints

Parameters
x402Middleware({
  payTo: string,           // Your wallet address to receive payments
  price: number,           // Price per request in dollars (e.g., 0.001)
  network: string,         // base | solana | polygon | bsc | sei | peaq
  facilitatorUrl: string,  // Optional: Custom facilitator endpoint
  requiredHeaders: string[] // Optional: Additional headers required
})
Example
app.use('/api/*', x402Middleware({
  payTo: '0x1234...abcd',
  price: 0.001,
  network: 'base',
  facilitatorUrl: 'https://facilitator.gameflowlabs.com/api'
}));

Python Decorators

@require_payment

Decorates Flask/FastAPI routes with x402 payment protection for GameFlow AI agents

Parameters
@require_payment(
  price: float,                    # Price in dollars per AI agent request
  pay_to: Optional[str],           # Override default wallet address
  networks: Optional[List[str]]    # Accepted networks for x402
)
Example
@app.get("/api/data")
@require_payment(price=0.001)
async def get_predictions():
    return {"data": "paid fantasy predictions"}

Client Library

X402Client

Client for consuming x402-protected APIs with AI agent wallet

Constructor
new X402Client({
  signer: Signer,              // ethers.js wallet or private key
  network: string,             // Preferred payment network
  maxPayment: number,          // Max amount willing to pay per request
  retries: number              // Number of payment retry attempts
})
Methods
// Make GET request with automatic x402 payment
client.get(url: string, options?: RequestOptions)

// Make POST request with x402 payment for AI agents
client.post(url: string, data: any, options?: RequestOptions)

// Make PUT request
client.put(url: string, data: any, options?: RequestOptions)

// Make DELETE request  
client.delete(url: string, options?: RequestOptions)

Facilitator API

POST /verify

Verify a blockchain transaction for x402 payment validation

POST https://facilitator.gameflowlabs.com/verify
Request Body
{
  "txHash": "0xfade...",
  "network": "base",
  "expectedRecipient": "0x1234...",
  "expectedAmount": "1000000", // in smallest unit (e.g. wei)
  "expectedToken": "0xusdc..."
}
Response
{
  "valid": true,
  "verified": true,
  "hash": "0xfade...",
  "from": "0xabcd...",
  "to": "0x1234...",
  "amount": "1000000",
  "timestamp": 1698234567
}

HTTP Headers

X-Accept-Payment

Server indicates which payment networks it accepts for AI agent x402 transactions

X-Accept-Payment: base, solana, polygon

X-Payment-Required

Indicates that x402 payment is required for this endpoint

X-Payment-Required: true

X-Payment-Network

Specifies preferred blockchain network for AI agent x402 payment

X-Payment-Network: base

X-Payment-Address

Recipient wallet address for x402 GameFlow payment

X-Payment-Address: 0x1234...abcd

X-Payment-Amount

Required payment amount in dollars for AI agent request

X-Payment-Amount: 0.001

X-Payment-Hash

AI agent client sends transaction hash as payment proof

X-Payment-Hash: 0xfade...1234

X-Payment-Proof

Additional signature or proof of x402 payment for AI agents

X-Payment-Proof: test-signature-abc123

X-Facilitator-URL

URL of facilitator API for x402 validation

X-Facilitator-URL: https://facilitator.gameflowlabs.com/verify

Need Help?

Check out the full x402 GameFlow API documentation or join our Discord for AI agent integration support.

Legal Docs Help Docs

Deployment Guide

Deploy your x402-enabled GameFlow service to production and list it on the marketplace for AI agents.

Production Checklist

  • ✓ Deploy basic service to container or cloud hosting
  • ✓ Configure environment variables for x402 GameFlow payment wallet
  • ✓ Set up monitoring and logging for AI agent transactions
  • ✓ Enable HTTPS via reverse proxy (required for x402)
  • ✓ Register on marketplace for GameFlow AI agent discovery

Environment Configuration

Create your production .env file for x402:

# Production Environment
NODE_ENV=production

# x402 Payment Configuration  
FACILITATOR_URL=https://facilitator.gameflowlabs.com/api
X402_PAY_TO=0x1234...abcd  # Your wallet for AI agent payments
X402_NETWORK=base  # base | solana | polygon | bsc

# API Keys for GameFlow data
KALSHI_API_KEY=your_kalshi_key
OPENAI_API_KEY=your_openai_key

# Facilitator
FACILITATOR_API_KEY=https://facilitator.gameflowlabs.com/api

# Network RPC (optional for custom nodes)
BASE_RPC_URL=https://base.llamarpc.com
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com

Hosting Options

Vercel

Best for Node/Express APIs. Free tier, auto-scaling, and HTTPS. Simple git push deployment for x402 GameFlow services.

vercel deploy --prod

Railway

Great for any stack with AI agent APIs. Auto-deploys from GitHub, $5/mo starts, supports Docker for x402 services.

railway up

Fly.io

Global edge deployment for AI agents. Low latency, generous free tier, Docker-based for x402 GameFlow.

fly deploy

AWS / GCP

Full control with traditional cloud providers for AI agent x402 services. More setup but infinitely scalable for GameFlow APIs.

gcloud run deploy

Docker Deployment

Containerize your x402 service for GameFlow AI agents:

Dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --production

COPY . .

ENV NODE_ENV=production
ENV PORT=3000

EXPOSE 3000

CMD ["node", "index.js"]
Build & Run
# Build image
docker build -t gameflow-x402 .

# Run container
docker run -p 3000:3000 \
  -e X402_PAY_TO=0x1234...abcd \
  -e X402_NETWORK=base \
  gameflow-x402

Performance Optimization

Use Load Balancers

Distribute AI agent x402 traffic across multiple GameFlow API server instances.

Cache Payment Verifications

Cache recently validated x402 payment hashes to avoid redundant blockchain queries for AI agents.

Enable Compression

Use gzip/brotli compression to reduce response sizes for AI agents calling GameFlow x402 APIs.

Set Timeouts

Configure appropriate timeouts for facilitator calls to prevent hanging requests from AI agent x402 payments.

Monitoring & Logging

// Add logging to track x402 GameFlow AI agent payments
app.use((req, res, next) => {
  console.log({
    timestamp: new Date().toISOString(),
    method: req.method,
    path: req.path,
    paymentHash: req.headers['x-payment-hash'],
    paymentNetwork: req.headers['x-payment-network']
  });
  next();
});

Register on Marketplace

1

Visit Marketplace

Go to marketplace.gameflowlabs.com and click "Register Service" for AI agent discovery

2

Fill Service Details

Provide service name, description, pricing, and endpoints for AI agents

3

Test & Publish

Verify your service works correctly for AI agents, then publish to the GameFlow x402 marketplace

Security Best Practices

Environment Variables

Never commit secrets or private keys to git. Use environment variables for all sensitive x402 GameFlow configuration for AI agent payment wallets.

Rate Limiting

Implement rate limiting to protect against spam even with x402 payments from AI agents. Paid doesn't mean unlimited GameFlow API access.

HTTPS Only

Always use HTTPS in production. Payment headers and transaction hashes should never traverse unencrypted connections for AI agent x402 security.

Input Validation

Validate and sanitize all user inputs even after AI agent x402 payment verification. Payment ≠ trust for GameFlow APIs.

Ready to Launch?

Deploy your service and start earning from AI agent x402 GameFlow micropayments.

Start Earning How to Deploy