{"slug": "show-hn-x402-vercel-gateway-serverless-http-402-for-fastapi", "title": "Show HN: X402 Vercel Gateway – Serverless HTTP 402 for FastAPI", "summary": "A new open-source reference implementation, the X402 Vercel Gateway, enables serverless FastAPI endpoints to enforce the HTTP 402 Payment Required (x402) protocol for autonomous AI agents, using Solana USDC micro-transactions and Upstash Redis atomic locks to prevent replay attacks. The project, published on GitHub by developer Rob Lambert, addresses the statelessness of serverless platforms like Vercel and AWS Lambda, which otherwise allow attackers to reuse a single payment proof across concurrent requests.", "body_md": "**A production-ready reference implementation for protecting FastAPI endpoints with the `HTTP 402 Payment Required` (x402) protocol on serverless infrastructure.**\n\nAutonomous AI agents (via AutoGPT, LangChain, MCP, or custom bots) cannot fill out credit card forms or complete 2FA challenges. As agent-to-agent (A2A) economic interactions grow, APIs need a machine-native monetization standard.\n\nThe **x402 protocol** leverages standard HTTP error codes combined with cryptographic micro-transactions (Solana USDC / EVM) to challenge callers for payment before serving protected compute or data.\n\nMost developers protect their gateway using an in-memory dictionary or local cache to track spent transaction hashes:\n\n```\n# ❌ THE VULNERABILITY (Works in Docker, fails on Serverless)\n_burned_hashes = {}\nif tx_hash in _burned_hashes:\n    raise HTTPException(status_code=402, detail=\"Replay Attack\")\n_burned_hashes[tx_hash] = True\n```\n\n**Why this breaks:**\nOn serverless platforms (Vercel, AWS Lambda), compute is stateless and horizontally ephemeral. If an attacker pays 0.005 USDC once and sends 10,000 concurrent requests with the identical `tx_hash`, Vercel spins up dozens of cold micro-VMs. **Every single instance starts with an empty dictionary.** All 10,000 requests pass validation, draining your upstream LLM or database quotas while you only get paid once.\n\nThis gateway resolves the serverless state dilemma through a two-phase cryptographic & atomic protocol:\n\n1. **On-Chain Delta Verification:** We query Solana JSON-RPC (`getTransaction` with`jsonParsed` ) to mathematically prove that the target Associated Token Account (ATA) received the exact payment by computing`postTokenBalances - preTokenBalances` .\n2. **Atomic Distributed Lock (`SETNX`):** We leverage Upstash Redis with the` SETNX` (Set if Not eXists) command to achieve a globally atomic burn of the transaction hash across all serverless regions.\n\n```\n# ✅ THE FIX: Verify On-Chain, then Burn Globally\nis_valid = await verify_solana_transaction(tx_hash, required_memo=invoice_id)\nif not is_valid:\n    raise HTTPException(status_code=402, detail=\"Invalid payment proof\")\n\n# Atomic lock across all serverless cold starts (24h TTL)\nacquired = redis_client.set(f\"x402:tx:{tx_hash}\", current_time, ex=86400, nx=True)\nif not acquired:\n    raise HTTPException(status_code=402, detail=\"Replay Attack Detected\")\nsequenceDiagram\n    autonumber\n    participant Agent as Autonomous AI Agent\n    participant Gateway as Vercel Edge (FastAPI)\n    participant Redis as Upstash Redis (SETNX)\n    participant RPC as Solana JSON-RPC Node\n\n    Agent->>Gateway: POST /api/v1/protected-data\n    Gateway-->>Agent: HTTP 402 Payment Required<br/>{recipient, amount_usdc, invoice_id}\n    Note over Agent: Agent signs & broadcasts SPL token transfer\n    Agent->>RPC: Broadcast USDC Transfer + Memo(invoice_id)\n    RPC-->>Agent: tx_hash confirmed\n    Agent->>Gateway: POST /api/v1/protected-data<br/>Header: X-Payment-Proof: <tx_hash>\n    Gateway->>RPC: getTransaction(tx_hash)\n    RPC-->>Gateway: Transaction metadata & token balances\n    Note over Gateway: Verify postTokenBalance - preTokenBalance == amount\n    Gateway->>Redis: SETNX x402:tx:<tx_hash> (24h TTL)\n    alt Lock Acquired (nx=True)\n        Redis-->>Gateway: OK (1)\n        Gateway-->>Agent: HTTP 200 OK (Protected Data Delivered)\n    else Replay Attempt (nx=False)\n        Redis-->>Gateway: Nil (0)\n        Gateway-->>Agent: HTTP 402 Payment Required (Replay Attack)\n    end\ngit clone https://github.com/roblambert9/x402-vercel-gateway.git\ncd x402-vercel-gateway\npython -m venv .venv\nsource .venv/bin/activate  # Or: .venv\\Scripts\\activate on Windows\npip install -r requirements.txt\n```\n\nCreate a `.env` file or set in your Vercel Dashboard:\n\n| Variable | Description | Example | \n|---|---|---|\n| `SOLANA_RPC_URL` | Solana JSON-RPC endpoint | `https://api.devnet.solana.com` | \n| `RECIPIENT_WALLET` | Your receiving Solana address | `YourWalletPublicKey...` | \n| `USDC_MINT_ADDRESS` | Mint address for USDC | Devnet: `4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU` | \n| `UPSTASH_REDIS_REST_URL` | Upstash Redis REST URL | `https://your-db.upstash.io` | \n| `UPSTASH_REDIS_REST_TOKEN` | Upstash Redis REST Token | `AXxxxx...` | \n\n```\nuvicorn main:app --reload --port 8000\n```\n\nTo run an automated test that signs and broadcasts a real SPL transfer on Devnet and verifies the gateway's 402 challenge response:\n\n```\npython tests/live_fire_devnet.py\nvercel --prod\n```\n\nEnsure your Upstash Redis integration is bound to your Vercel project environment variables.\n\nMIT License — free to use and integrate into your own agentic services. Built by [Rob Lambert](https://github.com/roblambert9).", "url": "https://wpnews.pro/news/show-hn-x402-vercel-gateway-serverless-http-402-for-fastapi", "canonical_source": "https://github.com/roblambert9/x402-vercel-gateway", "published_at": "2026-09-08 17:15:27+00:00", "updated_at": "2026-09-08 17:28:45.436011+00:00", "lang": "en", "topics": ["ai-infrastructure", "ai-agents", "ai-products"], "entities": ["Rob Lambert", "X402 Vercel Gateway", "FastAPI", "Vercel", "AWS Lambda", "Solana", "Upstash Redis", "AutoGPT"], "alternates": {"html": "https://wpnews.pro/news/show-hn-x402-vercel-gateway-serverless-http-402-for-fastapi", "markdown": "https://wpnews.pro/news/show-hn-x402-vercel-gateway-serverless-http-402-for-fastapi.md", "text": "https://wpnews.pro/news/show-hn-x402-vercel-gateway-serverless-http-402-for-fastapi.txt", "jsonld": "https://wpnews.pro/news/show-hn-x402-vercel-gateway-serverless-http-402-for-fastapi.jsonld"}}