xGate Documentation

Complete guide to building pay-per-tool AI agent infrastructure with xGate.

🚧 Self-Hosting Available Now

The xGate code is open source (MIT) and ready to deploy. Our managed hosting service is coming soon. Follow@xgatefifor updates!

What is xGate?

xGate is an API gateway that enables pay-per-call monetization for any HTTP endpoint. Built on the x402 protocol, it allows AI agents and applications to make micropayments for individual API calls using USDC on Base blockchain—no accounts, no API keys, just plain HTTP with payment headers.

Zero Setup
No API Keys
Instant Payments
USDC on Base
HTTP 402
Standard Protocol

Quick Start

Get started with xGate in under 5 minutes. Here's a complete example of making a paid API call:

example.ts
// Make a request through your xGate gateway
const response = await fetch('https://gateway.xgate.fi/tools/ocr', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ image: 'base64_encoded_image' })
});

// Handle 402 Payment Required
if (response.status === 402) {
  const challenge = response.headers.get('x-402-challenge');
  // Pay via facilitator, then retry with proof
}

const result = await response.json();
console.log(result); // OCR results
That's it! Your client makes standard HTTP requests. The gateway handles x402 payment challenges, verification, and routing.

Installation

Clone the Repository

Get the xGate gateway from GitHub:

git clone https://github.com/xgatefi/xgate.git
cd xgate
npm install

# Configure environment variables
cp .env.example .env
# Edit .env with your settings

# Start the gateway
npm run dev

Architecture

xGate consists of three main components:

Client SDK

Handles HTTP 402 responses, initiates payments, and retries requests with payment proofs.

TypeScriptJavaScriptPython

Gateway Server

Intercepts API requests, enforces payment requirements, verifies proofs, and proxies to upstream services.

Next.jsFastifyExpress

Facilitator

Processes x402 payments on-chain using USDC. Can use Coinbase facilitator or self-host.

Coinbase x402Lightning L402

x402 Protocol

The x402 protocol extends HTTP 402 Payment Required to enable seamless micropayments for API calls.

How It Works

1

Initial Request

Client makes HTTP request to protected endpoint

GET /tools/ocr HTTP/1.1
Host: gateway.xgate.fi
2

Payment Challenge

Gateway responds with 402 and payment details

HTTP/1.1 402 Payment Required
Content-Type: application/json

{
  "amount": "0.02",
  "asset": "USDC",
  "chain": "base",
  "payment_url": "https://facilitator...",
  "challenge": "0x..."
}
3

Payment Execution

Client pays via facilitator and receives proof

// SDK handles automatically
const proof = await facilitator.pay({
  amount: "0.02",
  challenge: "0x..."
})
4

Retry with Proof

Client retries request with payment proof header

GET /tools/ocr HTTP/1.1
Host: gateway.xgate.fi
x-payment-proof: 0xabc123...
5

Success Response

Gateway verifies proof and returns requested data

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

{
  "text": "Extracted text...",
  "confidence": 0.98
}

API Reference

Gateway Endpoints

POST/tools/ocr

Extract text from images using OCR

$0.02
Request
{
  "image": "base64_encoded_image",
  "language": "en"
}
Response
{
  "text": "Extracted text",
  "confidence": 0.98,
  "language": "en"
}
POST/tools/vision

Analyze images with AI vision

$0.03
Request
{
  "image": "base64_encoded_image",
  "prompt": "Describe this image"
}
Response
{
  "description": "A blue car...",
  "objects": ["car", "road"],
  "confidence": 0.95
}
GET/tools/scrape

Scrape and extract web content

$0.01/100KB
Request
?url=https://example.com
Response
{
  "html": "<!DOCTYPE html>...",
  "text": "Page content",
  "size_kb": 45
}

Payment Flows

Fixed-Price Endpoints

Charge a flat fee per request, regardless of input size or processing time.

// Gateway config
{
  "/tools/ocr": {
    "price": "0.02",
    "currency": "USDC",
    "type": "fixed"
  }
}

Metered Endpoints

Charge based on usage metrics like data size, compute time, or API calls.

// Gateway config
{
  "/tools/scrape": {
    "price_per_kb": "0.0001",
    "currency": "USDC",
    "type": "metered",
    "metric": "response_size"
  }
}

Tiered Priority

Offer free tier with rate limits, and paid tier for priority access.

// Gateway config
{
  "/llm/chat": {
    "free_tier": {
      "rate_limit": "10/hour"
    },
    "priority_tier": {
      "price": "0.02",
      "rate_limit": "1000/hour"
    }
  }
}

Configuration

Environment Variables

# Gateway Configuration
GATEWAY_PORT=3000
GATEWAY_URL=https://gateway.xgate.fi

# Database
DATABASE_URL=postgresql://...
REDIS_URL=redis://...

# x402 Facilitator
FACILITATOR_URL=https://facilitator.coinbase.com
FACILITATOR_API_KEY=your_api_key

# Blockchain
CHAIN_ID=8453  # Base mainnet
RPC_URL=https://mainnet.base.org
USDC_CONTRACT=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913

# Security
JWT_SECRET=your_secret_key
ENCRYPTION_KEY=your_encryption_key

# Monitoring
SENTRY_DSN=your_sentry_dsn
LOG_LEVEL=info

Price Configuration

// prices.config.ts
export const priceConfig = {
  endpoints: {
    '/tools/ocr': {
      price: '0.02',
      currency: 'USDC',
      type: 'fixed',
      description: 'OCR text extraction'
    },
    '/tools/vision': {
      price: '0.03',
      currency: 'USDC',
      type: 'fixed',
      description: 'AI vision analysis'
    },
    '/tools/scrape': {
      pricePerKb: '0.0001',
      currency: 'USDC',
      type: 'metered',
      metric: 'response_size',
      description: 'Web scraping'
    }
  },
  refund: {
    enabled: true,
    conditions: ['5xx_error', 'timeout'],
    window: 60 // seconds
  }
}

Database Schema

xGate uses PostgreSQL (via Neon) with Prisma ORM for data management.

// schema.prisma
model Receipt {
  id          String   @id @default(cuid())
  txHash      String   @unique
  payer       String
  endpoint    String
  amount      Decimal
  currency    String   @default("USDC")
  bytes       Int?
  status      String   @default("completed")
  metadata    Json?
  createdAt   DateTime @default(now())
  
  @@index([payer])
  @@index([endpoint])
  @@index([createdAt])
}

model PriceRule {
  id          String   @id @default(cuid())
  endpoint    String   @unique
  price       Decimal
  currency    String   @default("USDC")
  type        String   // fixed, metered, tiered
  metric      String?  // response_size, compute_time, etc
  isActive    Boolean  @default(true)
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model ApiKey {
  id          String   @id @default(cuid())
  key         String   @unique
  name        String
  permissions Json
  isActive    Boolean  @default(true)
  createdAt   DateTime @default(now())
  lastUsed    DateTime?
}

Security

Payment Verification

All payment proofs are cryptographically verified on-chain before granting access:

  • Verify signature matches challenge
  • Check transaction exists on Base blockchain
  • Validate amount and recipient address
  • Ensure payment hasn't been reused
  • Confirm timestamp within validity window

Best Practices

  • Use HTTPS for all gateway communications
  • Store facilitator API keys securely (never in code)
  • Implement rate limiting to prevent abuse
  • Monitor for suspicious payment patterns
  • Keep dependencies updated
  • Use environment variables for sensitive config
  • Enable audit logging for all transactions

Non-Custodial Architecture

xGate never holds user funds. All payments flow directly from payer to facilitator on-chain. The gateway only verifies payment proofs—it cannot access, freeze, or reverse transactions.

Need Help?

Join our community or reach out to the team