SDK + X402 Payment Hook
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 Requiredandacceptsreturned 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:
viemprivate-key mode, browser-wallet mode, and PythonEVMAccountSignermode - Clearly explains the easily confusing
preferScheme/prefer_schemefield
¶ I. Protocol Overview (Must Read)
One successful X402 call involves 3 HTTP RTTs:
1. SDK -> /openai/v1/chat/completions (no Authorization)
<- 402 Payment Required
{ accepts: [{ scheme:'upto', network:'eip155:8453', maxAmountRequired:'10000', ... }] }
2. Inside SDK -> paymentHandler({ url, method, body, accepts }) (local signing, 0 RTT)
<- { headers: { 'PAYMENT-SIGNATURE': '<base64-envelope>' } }
3. SDK -> /openai/v1/chat/completions (PAYMENT-SIGNATURE header injected)
<- 200 + business response (settlement is completed on the server)
An X402 envelope is JSON, base64-encoded and placed in the PAYMENT-SIGNATURE header. Structure (excerpt):
{
"x402Version": 2,
"accepted": {
"scheme": "upto",
"network": "eip155:8453"
},
"payload": {
"permit2": {
"permitted": [{ "token": "0x...USDC", "amount": "10000" }],
"nonce": "...",
"deadline": "..."
},
"witness": { "...metered-billing-fields..." },
"signature": "0x..."
}
}
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).
| scheme | Meaning |
|---|---|
exact |
Fixed price (priced scenarios such as image / video generation and search). The signed amount = the amount required by the server. |
upto |
Metered billing (chat completions / token-like). Sign a maximum amount, and only the portion actually used is settled (based on Permit2 + witness). Strongly recommended for session-based APIs. |
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
npm install @acedatacloud/sdk @acedatacloud/x402-client
Tested version numbers:
@acedatacloud/sdk@2026.504.2
@acedatacloud/x402-client@2026.531.3
¶ Full Signature of createX402PaymentHandler
export interface X402PaymentHandlerOptions {
network: 'solana' | 'base';
solanaWallet?: SolanaWalletAdapter; // required when network='solana'
evmProvider?: EVMProvider; // required when network='base', EIP-1193
evmAddress?: string; // required when network='base'
preferScheme?: 'exact' | 'upto';
}
The return value is a (ctx) => Promise<{ headers: Record<string, string> }> that exactly matches the SDK's paymentHandler hook signature.
¶ Approach 1: Browser (MetaMask / WalletConnect)
import { AceDataCloud } from '@acedatacloud/sdk';
import { createX402PaymentHandler } from '@acedatacloud/x402-client';
// 1. Have the user connect their wallet
const accounts: string[] = await (window as any).ethereum.request({
method: 'eth_requestAccounts'
});
const userAddress = accounts[0];
// 2. Switch to the Base mainnet
await (window as any).ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0x2105' }] // 8453 = Base
});
// 3. Construct the SDK client and inject the X402 handler
// Note: do not pass apiToken, so the SDK takes the 402 path
const client = new AceDataCloud({
paymentHandler: createX402PaymentHandler({
network: 'base',
evmProvider: (window as any).ethereum,
evmAddress: userAddress,
preferScheme: 'upto' // upto is required for chat-like requests
})
});
// 4. Call normally
const res: any = await client.openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'hi' }],
max_tokens: 20
});
console.log(res.choices[0].message.content);
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.
import { AceDataCloud } from '@acedatacloud/sdk';
import { createX402PaymentHandler } from '@acedatacloud/x402-client';
import { createWalletClient, http } from 'viem';
import { base } from 'viem/chains';
import { privateKeyToAccount } from 'viem/accounts';
const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: base,
transport: http(process.env.BASE_RPC_URL)
});
// viem WalletClient 自带 EIP-1193 兼容的 .request(),可以直接当 evmProvider
const client = new AceDataCloud({
paymentHandler: createX402PaymentHandler({
network: 'base',
evmProvider: walletClient as any, // walletClient.request 满足 EIP-1193
evmAddress: account.address,
preferScheme: 'upto'
})
});
const res: any = await client.openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'hi' }],
max_tokens: 20
});
console.log(res.choices[0].message.content);
If you feel that viem's EIP-1193 compatibility is not stable enough, you can also use the lower-level
signEVMUptoPayment, and wire together theaccepts → signed envelope → PAYMENT-SIGNATURE headerpath yourself, bypassing the SDK hook; however,createX402PaymentHandleris still recommended as the first choice, so that you do not need to maintain protocol upgrades yourself.
¶ Usage 3: Solana
import { AceDataCloud } from '@acedatacloud/sdk';
import { createX402PaymentHandler } from '@acedatacloud/x402-client';
import { Keypair } from '@solana/web3.js';
const kp = Keypair.fromSecretKey(/* Uint8Array */);
const client = new AceDataCloud({
paymentHandler: createX402PaymentHandler({
network: 'solana',
solanaWallet: {
publicKey: kp.publicKey,
signTransaction: async (tx) => {
tx.sign([kp]);
return tx;
}
}
})
});
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
pip install acedatacloud acedatacloud-x402
Tested version numbers:
acedatacloud==2026.4.26.1
acedatacloud-x402==2026.5.31.3
¶ EVM (Base)
import os
from acedatacloud import AceDataCloud
from acedatacloud_x402 import (
create_x402_payment_handler,
EVMAccountSigner,
)
# 1. 从私钥构造签名器
signer = EVMAccountSigner.from_private_key(os.environ["EVM_PRIVATE_KEY"])
# 2. 构造 SDK:不传 api_token,让 SDK 走 402 路径
client = AceDataCloud(
payment_handler=create_x402_payment_handler(
network="base",
evm_signer=signer,
prefer_scheme="upto", # chat 类一定选 upto
)
)
# 3. 正常调
res = client.openai.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "hi"}],
max_tokens=20,
)
print(res["choices"][0]["message"]["content"])
¶ Solana
import os
from acedatacloud import AceDataCloud
from acedatacloud_x402 import (
create_x402_payment_handler,
SolanaKeypairSigner,
)
signer = SolanaKeypairSigner.from_secret_key_base58(os.environ["SOLANA_PRIVATE_KEY"])
client = AceDataCloud(
payment_handler=create_x402_payment_handler(
network="solana",
solana_signer=signer,
rpc_url="https://api.mainnet-beta.solana.com", # 可选
)
)
¶ 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:
from acedatacloud_x402 import approve_permit2
tx_hash = approve_permit2(
evm_signer=signer,
rpc_url=os.environ["BASE_RPC_URL"],
)
print("permit2_approve_tx", tx_hash)
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).
// /tmp/sdk-tests/ts/x402-wire-test.ts
import { AceDataCloud } from '@acedatacloud/sdk';
import { createX402PaymentHandler } from '@acedatacloud/x402-client';
const handler = createX402PaymentHandler({
network: 'base',
evmProvider: { request: async () => '0x0' } as any, // 占位 provider
evmAddress: '0x0000000000000000000000000000000000000000',
preferScheme: 'upto'
});
console.log('handler_type', typeof handler); // function
const client = new AceDataCloud({
paymentHandler: handler
});
console.log('client_ctor_ok', client.constructor.name); // AceDataCloud
Output:
handler_type function
client_ctor_ok AceDataCloud
The results indicate:
- Without passing
apiToken, SDK construction does not throw an error, proving that X402 mode is indeed a valid substitute for tokens. createX402PaymentHandlerreturns 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_handleralso performs the same verification — the function return value is callable, andAceDataCloud(...)construction does not throw an error when injectingpayment_handler=.... The semantics are aligned on both sides.
¶ 5. Comparison with “Bearer Token Mode”
| Dimension | API Token | X402 |
|---|---|---|
| Applicable scenarios | Your own backend, long-term projects | Third-party developers, per-use on-demand payments, Agentic calls |
| Registration | Requires applying in the console | Not required; only an on-chain wallet is needed |
| Billing precision | Prepaid, charged according to the token pricing table | Settled on-chain in real time per call |
| Balance | Can be viewed in the console | Check the on-chain wallet's USDC |
| Initial cost | Free credits upon email registration | Requires bridging USDC to Base, first Permit2 approve |
| Suitable for chat | ✅ | ✅ (must use preferScheme=upto) |
| Suitable for one-time payments / cross-account sponsored payments | ❌ | ✅ |
| Code changes | apiToken: '...' |
paymentHandler: createX402PaymentHandler(...) |
The two modes can coexist — within the same process, simply configure different authentication methods for different client instances. |
¶ 6. Common Pitfalls
- Chat-type requests must use
preferScheme=upto: Usingexactwill cause the facilitator to deduct USDC based onmaxAmountRequired(not actual usage). - Do not pass a raw private key to
createX402PaymentHandleron the Node side: The TS package does not accept{ privateKey }; it must be wrapped as an EIP-1193 provider (viemWalletClientis recommended). - 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.
- Solana does not have the Permit2 concept: It directly signs SPL token transfer authorization, with no approve required; however, only
exactis currently supported on the Solana chain. - 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. - The most stable way to adapt
viem:evmProvider: walletClient as anyloses type checking but offers the best compatibility; if you want to preserve types, separately wrap viem's.transport.requestin a{ request }object and pass it in.
