X402 TypeScript SDK 串接教學
TypeScript 是串接 Ace Data Cloud X402 最推薦的方式之一。官方 SDK 負責一般 API 呼叫、任務輪詢、錯誤處理和自動重試;@acedatacloud/x402-client 負責在遇到 402 Payment Required 時簽出 PAYMENT-SIGNATURE 請求標頭。
原始碼與套件位址:
- SDK 儲存庫:https://github.com/AceDataCloud/SDK
- X402 Client 儲存庫:https://github.com/AceDataCloud/X402Client
- npm SDK:https://www.npmjs.com/package/@acedatacloud/sdk
- npm X402 Client:https://www.npmjs.com/package/@acedatacloud/x402-client
¶ 安裝相依套件
npm install @acedatacloud/sdk @acedatacloud/x402-client
如果使用 Base,需要 EVM 簽名能力:
npm install ethers
如果使用 Solana,需要 Solana wallet adapter 或 @solana/web3.js:
npm install @solana/web3.js
乾淨 npm 專案的安裝和匯入檢查輸出:
imports_ok true true true true true
@acedatacloud/sdk@2026.504.2
@acedatacloud/x402-client@2026.531.3
ethers@6.16.0
@solana/web3.js@1.98.4
結果說明:
@acedatacloud/sdk和@acedatacloud/x402-client均可從 npm 安裝並由 Node.js 匯入。ethers用於 EVM typed data 簽名,@solana/web3.js用於 Solana transaction 建構。
¶ Base 範例
瀏覽器中可以直接使用 window.ethereum。Node.js 中可以用 ethers.Wallet 包裝一層 EIP-1193 風格的 provider。
import { Wallet } from 'ethers';
import { AceDataCloud } from '@acedatacloud/sdk';
import { createX402PaymentHandler } from '@acedatacloud/x402-client';
const wallet = new Wallet(process.env.EVM_PRIVATE_KEY!);
const evmProvider = {
async request({ method, params }: { method: string; params?: unknown[] }) {
if (method !== 'eth_signTypedData_v4') {
throw new Error(`unsupported method: ${method}`);
}
const [, typedDataJson] = params as [string, string];
const typedData = JSON.parse(typedDataJson);
return wallet.signTypedData(typedData.domain, typedData.types, typedData.message);
}
};
const client = new AceDataCloud({
paymentHandler: createX402PaymentHandler({
network: 'base',
evmProvider,
evmAddress: wallet.address
})
});
const result = await client.openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Say hi in 3 words' }],
max_tokens: 10
});
console.log(result.choices[0].message.content);
¶ 瀏覽器錢包範例
在前端應用程式中使用 MetaMask、Coinbase Wallet 或 WalletConnect 時,通常直接傳入 EIP-1193 provider:
import { AceDataCloud } from '@acedatacloud/sdk';
import { createX402PaymentHandler } from '@acedatacloud/x402-client';
const [address] = await window.ethereum.request({ method: 'eth_requestAccounts' });
const client = new AceDataCloud({
paymentHandler: createX402PaymentHandler({
network: 'base',
evmProvider: window.ethereum,
evmAddress: address
})
});
const image = await client.images.generate({
provider: 'nano-banana',
prompt: 'a yellow banana on a white background'
});
瀏覽器錢包會跳出簽名確認。使用者簽名的不是任意訊息,而是 API 回傳的支付要求:收款位址、USDC 合約、金額、有效期和 nonce 都包含在簽名裡。
¶ Solana 範例
Solana 使用 SPL USDC TransferChecked。傳入的 wallet adapter 需要暴露 publicKey 和 signAndSendTransaction。
import { AceDataCloud } from '@acedatacloud/sdk';
import { createX402PaymentHandler } from '@acedatacloud/x402-client';
const client = new AceDataCloud({
paymentHandler: createX402PaymentHandler({
network: 'solana',
solanaWallet: phantomWallet
})
});
const result = await client.openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Say hi in 3 words' }],
max_tokens: 10
});
Solana 路徑目前只支援 exact,不支援 upto。如果 API 回傳多個 accepts,handler 會選擇 network = 'solana' 的那一項。
Solana 路徑在同一公開 API 上已驗證 paid retry 能回傳 HTTP 200 和 ADC_SOLANA_E2E_OK。公開 RPC 查詢可能會被限流,因此本文不寫 Solana tx hash;需要鏈上對帳時,請使用你自己的 Solana RPC 或控制台記錄確認。
¶ 選擇 exact 或 upto
目前 TypeScript handler 會選擇伺服器回傳的第一個符合網路的 payment requirement。Ace Data Cloud 的 API 通常會將同一網路的 exact 放在 upto 前面,因此如果你明確要走後置計量,需要傳入 preferScheme: 'upto'。
範例:
const client = new AceDataCloud({
paymentHandler: createX402PaymentHandler({
network: 'base',
evmProvider,
evmAddress: wallet.address,
preferScheme: 'upto'
})
});
如果服務端沒有回傳該網路的 upto requirement,handler 會自動回退到該網路可用的第一個 requirement,通常是 exact。
upto 需要一次性授權 Permit2。upto 目前只在 Base 上提供,因此只需要對 Base USDC 做一次授權:
npx tsx scripts/approve-permit2.ts --network base
Base upto 已完成公開 API 驗證:HTTP 402 -> HTTP 200,後置 settlement tx 為 0x4b0b836ce1cd1171cdbc37df1637150b024214ec28e7f6f2d09122f15cbfc036。完整輸出見計費方案說明。
¶ SDK 做了什麼
@acedatacloud/sdk 的 transport 會在收到 402 時執行一次 payment handler:
type PaymentHandler = (ctx: {
url: string;
method: string;
body?: unknown;
accepts: PaymentRequirement[];
}) => Promise<{ headers: Record<string, string> }>;
@acedatacloud/x402-client 回傳的 handler 會:
- 從
ctx.accepts中選擇目標網路的 payment requirement。 - 依網路建構 EVM EIP-712 簽名或 Solana transfer transaction。
- 將 envelope 序列化為 Base64。
- 回傳
{ headers: { 'PAYMENT-SIGNATURE': '<base64>' } }。 - SDK 自動使用原始請求主體重試。
這表示業務程式碼只需要像一般 SDK 呼叫一樣撰寫,不需要手動處理 402 重試。
