Skip to content
BofAIPublic

About

x402 payments protocol

Resources

Contributing

Stars

60 stars

Watchers

3 watching

Forks

Latest commit

Β 

History

709 Commits

Folders and files

Repository files navigation

x402

x402 is an open-source SDK for the x402 open payment standard β€” a protocol built on the HTTP 402 Payment Required status code. It enables web services to charge for APIs or content through a "pay-before-response" mechanism β€” without relying on traditional account systems or session management.

x402 currently supports the TRON and BSC networks, with plans to expand to a broader multi-chain ecosystem in the future.


πŸ“š Full Documentation


Release 2.1.1

Release target 2.1.1. The SDK is a TypeScript-only pnpm/turbo monorepo published as granular @bankofai/x402-* packages (there is no umbrella package). The TRON mechanism is maintained here; current EVM integrations use the official @x402/evm package rather than a local fork. Supported schemes: exact (ERC-3009 / Permit2), upto, batch-settlement, auth-capture (EVM), and exact_gasfree (TRON). See the v2.1.1 release notes for upgrade details.

TRON 2.1 migration

TRON 2.1.1 uses official Core 2.29.0 and publishes resource sponsorship as a separate package. This requires source migration from 2.0. Read the TRON 2.1 migration guide before upgrading. The workspace examples use the same official Core version. Historical 2.0 installation details remain in the release notes.

Features

  • Protocol Native: Restores the HTTP 402 status code to its intended purpose.
  • AI Ready: First-class support for AI Agents via specialized x402 skills.
  • Trust Minimized: Uses TIP-712/EIP-712 structured data signing. Facilitators cannot modify payment terms.
  • Stateless & Accountless: No user accounts or session management required. Payments are verified per request.
  • Framework Integrations (TypeScript): a wrapped-fetch client plus middleware for Express, Fastify, Hono, Next.js, Axios, and an MCP transport.

Installation

The Zod security upgrade on this branch requires official Core 2.29.0. It is not yet published as a BOA release; published TRON 2.1.0 still requires Core 2.28.0. Build and use the workspace packages until the next BOA release:

cd typescript
pnpm install
pnpm build

For EVM, install official @x402/evm@2.29.0 with matching official Core and transports. Use the upstream examples for EVM signer configuration.

The repo itself is a pnpm (>=11) workspace; from typescript/ run pnpm install && pnpm build. The examples/ workspace links these packages and builds from source.

Quick Start

A full loop has three roles: Client (payer), Resource Server (seller), Facilitator (verify + settle on-chain). Runnable TRON trios live under examples/typescript/. For general framework and upstream-chain examples, use the official examples.

Client (Buyer)

The client wraps fetch so 402 challenges are paid automatically. Key custody is in @bankofai/agent-wallet; the signer factory adapts the wallet and builds the chain client internally from the CAIP-2 network.

TRON (Nile) example:

import { x402Client } from "@x402/core/client";
import { wrapFetchWithPayment } from "@x402/fetch";
import { createClientTronSigner } from "@bankofai/x402-tron";
import { ExactTronScheme } from "@bankofai/x402-tron/exact/client";

const wallet = /* resolve your @bankofai/agent-wallet */;
// The factory builds TronWeb from the network and auto-broadcasts the one-time
// Permit2 approve that USDT/USDD need. When TRON_GRID_API_KEY is unset, mainnet
// RPC falls back to a BankofAI-operated endpoint.
const signer = await createClientTronSigner(wallet, {
  network: "tron:3448148188",
  apiKey: process.env.TRON_GRID_API_KEY,
});

// The selector is the payment-selection policy: pick which advertised option to pay.
const client = new x402Client((_x402Version, accepts) => accepts[0]);
client.register("tron:*", new ExactTronScheme(signer));

const fetchWithPay = wrapFetchWithPayment(fetch, client);
const res = await fetchWithPay("http://localhost:4021/weather"); // 402 handled automatically
const data = await res.json();

Server (Seller)

Construct new x402ResourceServer(facilitatorClient) from @x402/core/server, connect with HTTPFacilitatorClient, and protect routes with official middleware such as paymentMiddlewareFromHTTPServer from @x402/express. The server is keyless (it only holds a payout address). Facilitator requests default to a 120-second timeout; set timeoutMs explicitly when your chain or deployment needs a different bound. See examples/typescript/servers/express for the full wiring.

Facilitator

The facilitator verifies signatures and settles on-chain. Construct new x402Facilitator() (from @x402/core/facilitator) and register(network, scheme) per chain with a facilitator signer. Self-host it, or use the officially hosted Facilitator. See examples/typescript/facilitator/basic.

AI Agent Integration

x402 is designed for the Agentic Web. AI agents can autonomously negotiate and pay for resources using the x402-payment skill, which lets agents detect 402 responses, sign TIP-712/EIP-712 authorizations, and manage the challenge-response loop.

Configuration: set up agent-wallet 3.0 or newer and let the signer factories resolve the active wallet. Use a raw_secret, wallet_cli, or privy wallet; agent-wallet 3.0 removed the former local_secure password flow. When TRON_GRID_API_KEY is unset, mainnet TRON RPC routes to a BankofAI-operated fallback (https://hptg.bankofai.io); set it for production.

export AGENT_WALLET_PRIVATE_KEY="your_private_key_here"
export TRON_GRID_API_KEY="your_trongrid_api_key_here"  # recommended for production

Architecture

The x402 protocol involves three parties:

  • Client: Entity wanting to pay for a resource
  • Resource Server: HTTP server providing protected resources
  • Facilitator: Server that verifies and settles payments on-chain

Payment Flow

sequenceDiagram
    participant Client
    participant Server as Resource Server
    participant Facilitator
    participant Blockchain as Blockchain

    Note over Facilitator: Facilitators are optional,<br/>all logical steps could be<br/>performed by the server<br/>when accepting stablecoins<br/>or crypto

    Client->>Server: GET /api
    Server->>Client: 402 PAYMENT-REQUIRED: {...}

    Note over Client: Create payment<br/>payload

    Client->>Server: GET /api<br/>PAYMENT-SIGNATURE: {...}
    Server->>Facilitator: POST /verify<br/>PAYMENT-SIGNATURE<br/>PAYMENT-REQUIRED
    Facilitator->>Server: 200 Verification: {...}

    Note over Server: Do work

    Server->>Facilitator: POST /settle<br/>PAYMENT-SIGNATURE<br/>PAYMENT-REQUIRED
    Facilitator->>Blockchain: Submit tx
    Blockchain->>Facilitator: tx confirmed
    Facilitator->>Server: 200 Settled, tx_hash
    Server->>Client: 200 Ok<br/>PAYMENT-RESPONSE<br/>Content
Loading

Supported Networks & Assets

x402 currently supports TRC-20 tokens on the TRON network and BEP-20 tokens on the BSC network.

Network ID Status Recommended For
TRON Nile tron:3448148188 Testnet Development & Testing
TRON Shasta tron:2494104990 Testnet Alternative Testing
TRON Mainnet tron:728126428 Mainnet Production
BSC Testnet eip155:97 Testnet Development & Testing
BSC Mainnet eip155:56 Mainnet Production

Tokens in the local TRON examples: Nile USDT and USDD (Permit2).

Supported Payment Schemes

Scheme Chain Description
exact EVM, TRON Fixed, pre-quoted single payment. Transfer method chosen via extra.assetTransferMethod: eip3009 (ERC-3009 TransferWithAuthorization, e.g. USDC/DHLU) or permit2 (Uniswap Permit2).
upto EVM, TRON Usage-based: the payer signs an up-to-max authorization; the server settles the actual amount used (≀ max).
batch-settlement EVM, TRON Payment channels: deposit once, pay many requests with off-chain vouchers, settle a batch (with refund of the remainder).
auth-capture EVM Refundable payments via Base's Commerce Payments escrow β€” authorize, then capture / void / refund.
exact_gasfree TRON Pay with USDT/USDD without holding TRX for gas; a relayer submits and pays energy via the official GasFree Proxy.

Development

Prerequisites

  • Node.js 24.22.1+ (use the pinned version in .nvmrc)
  • pnpm >= 11
  • A TRON wallet with TRX for gas/energy, and/or a BSC wallet with BNB for gas.

Build & test

cd typescript
pnpm install
pnpm build           # turbo run build (all packages β†’ dist/, gitignored)
pnpm build:release   # bypass build cache before packing/publishing
pnpm test            # vitest unit tests (offline, no secrets)
pnpm test:integration  # real-chain tests; self-skip without .env creds

Use pnpm build:release before pnpm pack or pnpm publish. The forced build lets each package clean its output first, preventing stale hashed declaration files from entering release tarballs.

Configuration

  • Configure wallet access through agent-wallet.
  • TRON_GRID_API_KEY: recommended for production. When unset, mainnet TRON RPC uses a BankofAI fallback endpoint automatically.

Security & Risk

Warning

Use at your own risk. Handling private keys involves significant risk of asset loss.

  • Never commit secrets: Do not hardcode private keys or commit .env files to version control.
  • Wallet Isolation: Use dedicated wallets for development with only necessary funds.
  • Environment Variables: Always use environment variables or secure vaults to manage sensitive credentials.
  • Protocol Status: x402 is in active development. Ensure you test thoroughly on Nile or Shasta testnets before any mainnet deployment.

Contributing

We welcome contributions! Start normal work from develop and submit it back to develop. Stable releases reach main through a release_* branch. See CONTRIBUTING.md and BRANCHING.md for the complete workflow.

License

MIT License - see LICENSE for details.

About

x402 payments protocol

Resources

Contributing

Stars

60 stars

Watchers

3 watching

Forks

Releases

Packages

Contributors

Languages