Skip to content
View Rail402's full-sized avatar

Block or report Rail402

Block user

Prevent this user from interacting with your repositories and sending you notifications. Learn more about blocking users.

You must be logged in to block users.

Maximum 250 characters. Please don’t include any personal information such as legal names or email addresses. Markdown is supported. This note will only be visible to you.
Report abuse

Contact GitHub support about this user’s behavior. Learn more about reporting abuse.

Report abuse
Rail402/README.md

Rail402 Banner

██████╗  █████╗ ██╗██╗     ██╗  ██╗ ██████╗ ██████╗
██╔══██╗██╔══██╗██║██║     ██║  ██║██╔═████╗╚════██╗
██████╔╝███████║██║██║     ███████║██║██╔██║ █████╔╝
██╔══██╗██╔══██║██║██║     ╚════██║████╔╝██║██╔═══╝
██║  ██║██║  ██║██║███████╗     ██║╚██████╔╝███████╗
╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚══════╝     ╚═╝ ╚═════╝ ╚══════╝

Machine-native transaction infrastructure for the agent economy.

Discover an API, pay for it in USDC, get the result — no keys, no accounts, no humans in the loop.

Protocol Chain Settlement Agent Registry Attribution Status MCP

Marketplace · Docs · Agent Registry · llms.txt


Overview

Rail402 is a programmable API marketplace for autonomous agents on Base. It treats HTTP endpoints as first-class economic objects: discoverable by machine, callable without credentials, and settled onchain in USDC via the x402 protocol.

The core idea is simple: the payment is the authentication. Instead of issuing API keys, provisioning subscription tiers, and operating billing infrastructure, a provider returns a standard 402 Payment Required. The agent pays. The proof is verified onchain. The data is returned. No session state, no credential rotation, no approval loop.

That property is what makes it composable with agent runtimes, MCP servers, and multi-agent pipelines — settings where per-call economic settlement is the only access-control model that actually scales to software acting on its own behalf.


Quickstart

Make an endpoint payable — wrap any handler, deploy, and list it:

npm install @rail402/x402 viem

Call a paid API as an agent — discovery and payment are one round trip:

npx -y @rail402/mcp@latest     # expose the marketplace to Claude, Codex, Antigravity, and more

Jump to Provider Integration or Agent Integration below.


Protocol

Rail402 implements the x402 flow on top of standard HTTP semantics.

Request lifecycle

Agent                          Rail402 Gateway                 Provider Endpoint
  │                                   │                               │
  ├─── POST /api/services/{id}/call ─▶│                               │
  │                                   ├── validate input schema       │
  │◀── 402 Payment Required ──────────┤                               │
  │    X-Payment-Address: 0x…         │                               │
  │    X-Payment-Amount:  0.05        │                               │
  │    X-Payment-Network: base        │                               │
  │    X-Payment-Currency: USDC       │                               │
  │                                   │                               │
  ├── submit USDC transfer on Base ───────────── ~2s finality ────────┤
  │                                   │                               │
  ├─── POST /api/services/{id}/call ─▶│                               │
  │    X-Payment-Proof: {txHash}      ├── verify transfer onchain      │
  │                                   ├── reject replayed txHash       │
  │                                   ├── forward request ───────────▶│
  │◀── 200 OK + payload ──────────────┤◀──── provider response ────────┤
  │                                   │                               │

Properties

  • Stateless verification — the transaction hash is the credential; proof validation needs no session lookup.
  • Atomic settlement — payment and delivery are causally linked. No payment, no data.
  • Replay protection — each txHash is indexed per service; reused proofs are rejected at the gateway.
  • Schema-enforced inputs — request bodies are validated against the service's JSON Schema before reaching the provider; malformed input never touches provider infrastructure.
  • Direct settlement — Rail402 takes no custody. USDC routes straight to the provider's registered wallet on every verified call.

The full normative flow — PaymentRequirements/PaymentProof objects, verification rules, and header semantics — is specified in agent-services-spec.


Agent Discovery

Rail402 publishes a machine-readable registry at three canonical endpoints:

Endpoint Format Primary consumer
/.well-known/agent-services.json Structured JSON Autonomous agents, orchestration runtimes
/api/agent/services JSON (full schema) Programmatic discovery, SDK clients
/llms.txt Plain text LLM context windows

Each service is self-describing — an agent can select, price-check, and invoke it in a single discovery pass:

{
  "id": "cmpjq32i80002qaimfb2fezm4",
  "slug": "wallet-risk",
  "name": "Wallet Risk Score API",
  "capabilities": ["risk", "wallet", "security"],
  "price": { "amount": "0.05", "currency": "USDC" },
  "network": "base",
  "endpoint": "https://www.rail402.app/api/services/{id}/call",
  "inputSchema":  { /* JSON Schema */ },
  "outputSchema": { /* JSON Schema */ },
  "reliability": {
    "verified": true,
    "successRate": 99.5,
    "averageLatencyMs": 132,
    "totalCalls": 2057
  },
  "playgroundUrl": "https://rail402.app/playground/wallet-risk"
}

The discovery document format is a published standard — validate your own with npx @rail402/validate-spec ./agent-services.json.


Repository Map

Repository Purpose
x402-sdk TypeScript + Python middleware to make any REST endpoint x402-payable. Express, Next.js, and FastAPI adapters; onchain verification via viem/web3.
provider-starter Deploy-ready provider templates (Express / Next.js / FastAPI) with Dockerfiles, deploy guides for Railway·Render·Vercel, and a full payment-flow simulation.
agent-services-spec The formal agent-services.json discovery standard, the x402 flow spec, and the @rail402/validate-spec validator CLI.
rail402-mcp MCP server exposing list_services, get_service_details, call_service, and check_payment_status. Works with Claude Desktop, Cursor, Codex, Antigravity, and Base MCP.
examples End-to-end agents: LangChain, Claude, OpenAI, and Base MCP — over a shared rail402-client with built-in x402 payment handling.
awesome-rail402 Curated index of published APIs, community SDKs, agent projects, and ecosystem resources.

Provider Integration

Wrap an existing handler — the middleware handles the 402 challenge, onchain verification, and replay protection. Your business logic only runs after payment is confirmed.

Express / Node.js

import { withX402 } from "@rail402/x402";

app.post(
  "/your-api",
  withX402(
    async (req, res) => {
      // payment already verified; req.x402.payerWallet is available
      res.json(await yourBusinessLogic(req.body));
    },
    { price: "0.05", wallet: process.env.PROVIDER_WALLET, network: "base" },
  ),
);

FastAPI / Python

from rail402_x402 import X402Middleware

app.add_middleware(
    X402Middleware,
    price="0.05",
    wallet=os.environ["PROVIDER_WALLET"],
    network="base",
    protected_paths=["/your-api"],
)

@app.post("/your-api")
async def handler(body: YourInputModel, request: Request):
    # request.state.x402 holds the verified payment
    return await your_business_logic(body)

A Next.js App Router adapter (withX402Payment) ships in the same package. Once deployed, publish at rail402.app/publish with your inputSchema, outputSchema, and endpoint URL — the registry updates in real time and USDC settles directly to your wallet.


Agent Integration

Direct HTTP — settle the 402 and retry in one call. fetchWithPayment takes a viem wallet and does the rest:

import { fetchWithPayment } from "@rail402/x402";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";

const wallet = createWalletClient({
  account: privateKeyToAccount(process.env.AGENT_PRIVATE_KEY as `0x${string}`),
  chain: base,
  transport: http(),
});

const res = await fetchWithPayment(
  "https://www.rail402.app/api/services/{id}/call",
  { method: "POST", body: JSON.stringify({ input: { address: "0x…" } }) },
  wallet,
);
const data = await res.json();

Prefer a higher-level client with discovery helpers? Rail402/examples ships a reusable Rail402Client (discover(), getService(), call()) used by all four reference agents.

MCP — give Claude, Codex, Antigravity, or any MCP-compatible runtime the marketplace as tools:

{
  "mcpServers": {
    "rail402": {
      "command": "npx",
      "args": ["-y", "@rail402/mcp@latest"],
      "env": {
        "RAIL402_API_BASE": "https://www.rail402.app",
        "RAIL402_NETWORK": "base",
        "RAIL402_PRIVATE_KEY": "0xYourBaseWalletKey"
      }
    }
  }
}

RAIL402_PRIVATE_KEY is required only for paid call_service; discovery tools work read-only without it.


Standards & Onchain Primitives

Rail402 sits at the intersection of three Base-native primitives.

x402 — Machine-native payments · implemented HTTP-layer payment protocol for autonomous systems. Payment requirements are encoded directly in the 402 response, so any HTTP client can implement the flow with no SDK on the consumer side.

ERC-8021 — Builder attribution · on the roadmap Provider wallets already receive settlement directly per call. Builder Code attribution will make that revenue composable across multi-agent pipelines, crediting the originating provider through a chain of delegated calls.

ERC-8004 — Agent identity · on the roadmap An onchain registry for agent reputation and capabilities. Rail402 is designed to key differential pricing and access policies to an agent's ERC-8004 reputation, letting providers reward trusted callers.


Security

Concern Implementation
Credential exposure Eliminated — no API keys issued or stored. Payment proof is the sole credential.
Replay attacks txHash indexed per service on first use; subsequent identical proofs are rejected at the gateway.
Input injection All request bodies validated against inputSchema server-side before proxying to the provider.
SSRF Provider endpoint URLs validated at publish time; internal/private network ranges are rejected.
Provider isolation Settlement routes directly to the provider wallet — Rail402 holds zero custody at any point.
Overpayment / underpayment Proof amount checked against the registered price; underpayment is rejected.
Schema drift inputSchema/outputSchema are fixed at publish; price or schema changes require re-publication.

Responsible disclosurecontact@rail402.app


Network

Rail402 operates on Base mainnet. Payment proofs are verified against the canonical USDC contracts below; proofs referencing any other network or token are rejected.

Asset Address
USDC — Base Mainnet 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
USDC — Base Sepolia 0x036CbD53842c5426634e7929541eC2318f3dCF7e

Contributing

The SDKs, spec, and examples are open source and welcome contributions. Good entry points:

Each repo documents its own setup, tests, and contribution guidelines.


Built on Base · Settled in USDC · Powered by x402

rail402.app · contact@rail402.app · @Rail402

Popular repositories Loading

  1. awesome-rail402 awesome-rail402 Public

    A curated list of APIs, SDKs, agent projects, and resources in the Rail402 ecosystem. Built on Base. Powered by x402.

    11

  2. x402-sdk x402-sdk Public

    TypeScript & Python middleware to make any REST endpoint x402-compatible. Wrap, verify, and settle USDC payments on Base in minutes.

    TypeScript 10

  3. provider-starter provider-starter Public

    Deploy-ready templates for x402-compatible API providers. Express, Next.js, and FastAPI — Dockerfile included. From zero to Rail402 marketplace in under 10 minutes.

    TypeScript 10

  4. Rail402 Rail402 Public

    9

  5. agent-services-spec agent-services-spec Public

    Specification for agent-readable API discovery via /.well-known/agent-services.json and llms.txt. The open standard powering Rail402's agent registry.

    TypeScript 9

  6. rail402-mcp rail402-mcp Public

    MCP server for Rail402. Browse, discover, and call paid APIs from Claude, Cursor, and Base MCP — payments handled autonomously via x402 on Base.

    TypeScript 9