三个 npm 包、一个持有 USDC 的 Solana 钱包,即可查询 Polymarket、Hyperliquid 和 Meteora 上的聪明钱数据。整个流程无需 Gas,不需要 SOL。
您将实现的效果
以下是一个 AI 代理实时查询 Polymarket 聪明钱数据的演示:
准备工作
- 持有 USDC 的 Solana 钱包(x402 无需 Gas,不需要 SOL)
- Node.js 18+ 或 Bun 运行时
- 三个依赖包:
npm install @x402/core @x402/svm @solana/kit
x402 工作原理
x402 协议将 HTTP 402(“需要付费”)转化为机器可读的支付流程。无需 API 密钥,无需账户。您的钱包就是您的身份。
首次请求返回 402
您调用一个端点。服务器返回 HTTP 402 和一个 PAYMENT-REQUIRED 头部,包含精确的 USDC 价格和支付指令。
本地签署支付
您的代理解析支付要求,使用 Solana 密钥对签署 USDC 转账,并构建支付签名。此时资金尚未转移。
附带支付重新发送
附加 PAYMENT-SIGNATURE 头部并重新发送相同请求。服务器验证签名,在链上结算支付,并返回您的数据。
验证结算
200 响应包含一个 PAYMENT-RESPONSE 头部,附带链上结算证明。
如果查询失败(超时、服务器错误、参数错误),不会进行支付结算。您只为成功的响应付费。
设置代码
一次性设置,您的代理在所有请求中复用:
import { x402Client, x402HTTPClient } from "@x402/core/client";
import { registerExactSvmScheme } from "@x402/svm/exact/client";
import { toClientSvmSigner } from "@x402/svm";
import { getBase58Encoder, createKeyPairSignerFromBytes } from "@solana/kit";
import type { PaymentRequired, SettleResponse } from "@x402/core/types";
// Load your Solana keypair
const bytes = getBase58Encoder().encode(process.env.SOLANA_PRIVATE_KEY!);
const signer = await createKeyPairSignerFromBytes(bytes);
// Initialize x402 client
const client = new x402Client();
registerExactSvmScheme(client, { signer: toClientSvmSigner(signer) });
const httpClient = new x402HTTPClient(client);
paidFetch 函数
将两步握手流程封装为可复用函数:
const BASE_URL = "https://agent.metengine.xyz";
async function paidFetch(
path: string,
options?: { method?: string; body?: Record<string, unknown> },
): Promise<{ data: unknown; settlement: SettleResponse; price: number }> {
const method = options?.method ?? "GET";
const url = `${BASE_URL}${path}`;
const fetchOpts: RequestInit = { method };
if (options?.body) {
fetchOpts.headers = { "Content-Type": "application/json" };
fetchOpts.body = JSON.stringify(options.body);
}
// Step 1: Get 402 with price
const initial = await fetch(url, fetchOpts);
if (initial.status !== 402)
throw new Error(`Expected 402, got ${initial.status}`);
const body = await initial.json();
// Step 2: Parse payment requirements
const paymentRequired: PaymentRequired =
httpClient.getPaymentRequiredResponse(
(name) => initial.headers.get(name),
body,
);
const price = Number(paymentRequired.accepts[0]!.amount);
// Step 3: Sign payment locally
const paymentPayload =
await httpClient.createPaymentPayload(paymentRequired);
const paymentHeaders =
httpClient.encodePaymentSignatureHeader(paymentPayload);
// Step 4: Re-send with payment
const paid = await fetch(url, {
...fetchOpts,
headers: {
...(fetchOpts.headers as Record<string, string>),
...paymentHeaders,
},
});
if (paid.status !== 200) {
const err = await paid.json();
throw new Error(
`Payment failed (${paid.status}): ${JSON.stringify(err)}`,
);
}
const paidBody = (await paid.json()) as { data: unknown };
// Step 5: Extract settlement proof
const settlement = httpClient.getPaymentSettleResponse(
(name) => paid.headers.get(name),
);
return { data: paidBody.data, settlement, price };
}
您的第一个查询
获取 Polymarket 热门市场:
const { data, price } = await paidFetch(
"/api/v1/markets/trending?timeframe=24h&limit=5"
);
console.log(`Paid $${price} USDC for ${(data as any[]).length} markets`);
POST 端点(特定市场的聪明钱情报):
const { data } = await paidFetch("/api/v1/markets/intelligence", {
method: "POST",
body: { condition_id: "0xabc123...", top_n_wallets: 10 },
});
代理的会话记忆
如果您的代理跨多个会话运行,请持久化设置详情以避免每次重新读取完整规范。存储在 ~/.claude/agents/metengine-memory.md:
- 钱包地址和余额验证状态
- 可用的引导代码片段
- 最近 10 次端点调用的延迟和费用
- 发现的任何问题或回退策略
这可以在后续会话中减少约 80% 的 Token 开销。
错误处理
| 状态码 | 含义 | 操作 |
|---|
| 402 | 需要付费 | 正常的第一步。解析并签名。 |
| 200 | 成功 | 数据已返回。支付已结算。 |
| 504 | 超时 | 不收费。使用更窄的参数重试或使用回退端点。 |
| 503/429 | 速率限制 | 不收费。根据 Retry-After 头部进行退避。 |
| 500 | 服务器错误 | 不收费。部分端点有已知的回退方案(参见端点列表)。 |
下一步
浏览所有端点
73 个端点,按平台分类,包含定价、参数和已知问题。
完整规范
包含所有参数、回退方案和集成模式的完整技能规范。