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.
Quick Start
Get started with xGate in under 5 minutes. Here's a complete example of making a paid API call:
// 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 resultsInstallation
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 devArchitecture
xGate consists of three main components:
Client SDK
Handles HTTP 402 responses, initiates payments, and retries requests with payment proofs.
Gateway Server
Intercepts API requests, enforces payment requirements, verifies proofs, and proxies to upstream services.
Facilitator
Processes x402 payments on-chain using USDC. Can use Coinbase facilitator or self-host.
x402 Protocol
The x402 protocol extends HTTP 402 Payment Required to enable seamless micropayments for API calls.
How It Works
Initial Request
Client makes HTTP request to protected endpoint
GET /tools/ocr HTTP/1.1
Host: gateway.xgate.fiPayment 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..."
}Payment Execution
Client pays via facilitator and receives proof
// SDK handles automatically
const proof = await facilitator.pay({
amount: "0.02",
challenge: "0x..."
})Retry with Proof
Client retries request with payment proof header
GET /tools/ocr HTTP/1.1
Host: gateway.xgate.fi
x-payment-proof: 0xabc123...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
/tools/ocrExtract text from images using OCR
{
"image": "base64_encoded_image",
"language": "en"
}{
"text": "Extracted text",
"confidence": 0.98,
"language": "en"
}/tools/visionAnalyze images with AI vision
{
"image": "base64_encoded_image",
"prompt": "Describe this image"
}{
"description": "A blue car...",
"objects": ["car", "road"],
"confidence": 0.95
}/tools/scrapeScrape and extract web content
?url=https://example.com{
"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=infoPrice 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