Skip to main content
X402 is an on-chain payment protocol proposed by Coinbase for “billing by HTTP 402”: the server returns 402 Payment Required for requests without a token, with an accepts: [...] field listing acceptable chains / assets / prices; the client signs an authorization locally (Permit2 / EIP-712 on EVM, SPL token transfer authorization on Solana), puts the base64-encoded envelope into the PAYMENT-SIGNATURE header and resends. After verification, the server actually settles on-chain, then returns the business result.
Ace Data Cloud’s X402 client directly calls the target API, and uses the 402 Payment Required and accepts returned in real time by that request as the basis for pricing and signing. The Facilitator’s payment capabilities can be verified at /.well-known/x402.
Both @acedatacloud/sdk and acedatacloud expose a paymentHandler hook: when a request sent by the SDK itself receives 402, it calls the handler you inject to obtain the PAYMENT-SIGNATURE header, then resends the original request. Combining @acedatacloud/x402-client / acedatacloud-x402 with the SDK, the entire process is completely transparent to business code—you only use client.openai.chat.completions.create(...), which looks exactly the same as token mode, but the underlying mechanism is pay-per-call and requires no advance top-up. This article:
  • Actually runs through the TS-side “no token + X402 handler injection” flow (T12 verification)
  • Lists the differences between the EVM / Solana signing flows
  • Provides three adaptations: viem private-key mode, browser-wallet mode, and Python EVMAccountSigner mode
  • Clearly explains the easily confusing preferScheme / prefer_scheme field

I. Protocol Overview (Must Read)

One successful X402 call involves 3 HTTP RTTs:
An X402 envelope is JSON, base64-encoded and placed in the PAYMENT-SIGNATURE header. Structure (excerpt):
The envelope top level is x402Version: 2, and uses the accepted object to declare the scheme and network selected for this transaction (CAIP-2 identifier). preferScheme / prefer_scheme is used to select a preference when the server simultaneously provides multiple schemes. If the server only exposes exact, this field is ignored; if upto is set but not exposed by the server, it falls back to the first matching option.

II. TypeScript: Two Approaches for Browser Wallets + Server-Side viem

Installation

Tested version numbers:

Full Signature of createX402PaymentHandler

The return value is a (ctx) => Promise&lt;{ headers: Record<string, string> }> that exactly matches the SDK’s paymentHandler hook signature.

Approach 1: Browser (MetaMask / WalletConnect)

The first browser call will show two signature prompts: the first is a one-time Permit2 approve for USDC (the amount is MaxUint256, written on-chain); the second is the EIP-712 signature for the X402 envelope (not on-chain, only for facilitator verification). Subsequent calls only require the second signature; in terms of experience, it is “click one signature → get the result”.

Approach 2: Node Server-Side + viem Private Key (Suitable for Backend / CLI)

@acedatacloud/x402-client only accepts an EIP-1193 provider on the TS side—it does not directly handle private keys. In Node / CLI scenarios, the standard approach is to use viem to wrap the private key as a WalletClient, then use @ethereumjs/util or viem’s internal EIP-1193 adapter.
If you feel that viem’s EIP-1193 compatibility is not stable enough, you can also use the lower-level signEVMUptoPayment, and wire together the accepts → signed envelope → PAYMENT-SIGNATURE header path yourself, bypassing the SDK hook; however, createX402PaymentHandler is still recommended as the first choice, so that you do not need to maintain protocol upgrades yourself.

Usage 3: Solana

On Solana, only the exact scheme is currently exposed, so preferScheme does not take effect on Solana.

3. Python: Private Key Mode

Python’s acedatacloud-x402 uses the path of signing directly with a private key (without an EIP-1193 abstraction), which is more suitable for servers / task runners.

Installation

Tested version numbers:

EVM (Base)

Solana

One-Time Approve (EVM First Time Only)

X402 on EVM Base uses Permit2, requiring the wallet to perform a one-time MaxUint256 approve of USDC for the Permit2 contract. acedatacloud-x402 has approve_permit2 built in:
This transaction only needs to be sent once; all subsequent X402 EVM payments use this authorization. Solana does not need it.

4. Real Runtime Verification

Test objective: The TS SDK does not receive a token, injects an X402 handler, and can normally construct and initiate requests (a lightweight verification that does not consume real on-chain USDC).
Output:
The results indicate:
  • Without passing apiToken, SDK construction does not throw an error, proving that X402 mode is indeed a valid substitute for tokens.
  • createX402PaymentHandler returns a function (hook), which the SDK invokes only after receiving a 402 response.
  • The end-to-end test for actual on-chain payments was not included in this tutorial because it involves real USDC deductions; you can refer to the e2e examples in the X402 Integration Guide.
Python’s create_x402_payment_handler also performs the same verification — the function return value is callable, and AceDataCloud(...) construction does not throw an error when injecting payment_handler=.... The semantics are aligned on both sides.

5. Comparison with “Bearer Token Mode”

6. Common Pitfalls

  1. Chat-type requests must use preferScheme=upto: Using exact will cause the facilitator to deduct USDC based on maxAmountRequired (not actual usage).
  2. Do not pass a raw private key to createX402PaymentHandler on the Node side: The TS package does not accept { privateKey }; it must be wrapped as an EIP-1193 provider (viem WalletClient is recommended).
  3. The first call requires two signatures: The first signs a Permit2 approve (on-chain, requires gas), and the second signs an X402 envelope (off-chain). Subsequent calls only require the second one.
  4. Solana does not have the Permit2 concept: It directly signs SPL token transfer authorization, with no approve required; however, only exact is currently supported on the Solana chain.
  5. Distinguish business errors from payment errors: 402 → handler failure throws X402SignError (the specific type varies by chain); after retrying, errors from the business API (401 / 422 / 5xx) are still classified as regular SDK exceptions.
  6. The most stable way to adapt viem: evmProvider: walletClient as any loses type checking but offers the best compatibility; if you want to preserve types, separately wrap viem’s .transport.request in a { request } object and pass it in.

Learn More