> ## Documentation Index
> Fetch the complete documentation index at: https://docs.metengine.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# 几分钟内开始查询

> 设置支付并对 MetEngine Data Agent 发起您的第一个聪明钱查询。支持 x402、MPP Tempo 和 MPP Solana。

一个持有 USDC 的钱包和几行代码。这就是查询 Polymarket、Hyperliquid 和 Meteora 上聪明钱数据所需的全部。选择适合您技术栈的支付协议。

## 您将实现的效果

以下是一个 AI 代理实时查询 Polymarket 聪明钱数据的演示：

<Frame>
  <video controls playsInline className="w-full rounded-xl" src="https://metengine-pnl-cards.s3.eu-central-1.amazonaws.com/agent/final-poly.mp4" />
</Frame>

## 支付流程（所有协议）

每种协议遵循相同的先执行后结算模式。服务器持有您的签名交易，仅在成功查询并返回数据后才在链上广播。

```
CLIENT                          SERVER                          BLOCKCHAIN
  |                               |                               |
  |  1. GET /api/v1/endpoint      |                               |
  |------------------------------>|                               |
  |                               |                               |
  |  2. 402 + price + challenges  |                               |
  |  (x402, Tempo, Solana)        |                               |
  |<------------------------------|                               |
  |                               |                               |
  |  3. Sign USDC transfer        |                               |
  |  (NO broadcast)               |                               |
  |                               |                               |
  |  4. Re-send + signed tx       |                               |
  |------------------------------>|                               |
  |                               |  5. Validate tx               |
  |                               |  6. Run query                 |
  |                               |                               |
  |                               |--- fail/empty? DISCARD tx --->|
  |  error, no charge             |                               |
  |<------------------------------|                               |
  |                               |                               |
  |                               |--- success? Broadcast tx ---->|
  |                               |                    USDC moves |
  |  8. 200 + data + receipt      |<------------------------------|
  |<------------------------------|                               |
```

<Tip>如果查询失败（超时、服务器错误、空结果），签名交易将被丢弃，您不会被收费。只有在获得数据时才需付费。</Tip>

## 选择您的协议

<Tabs>
  <Tab title="x402 on Solana（推荐）">
    最成熟的协议。您需要一个持有 USDC 的 Solana 钱包（以及用于交易费的 SOL）。

    ### 安装

    ```bash theme={null}
    npm install @x402/core @x402/svm @solana/kit
    ```

    ### 设置

    ```typescript theme={null}
    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

    ```typescript theme={null}
    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 };
    }
    ```

    | 头部                                        | 方向         | 说明         |
    | ----------------------------------------- | ---------- | ---------- |
    | `PAYMENT-REQUIRED` / `X-PAYMENT-REQUIRED` | 服务器 -> 客户端 | 402 挑战及价格  |
    | `PAYMENT-SIGNATURE` 或 `X-PAYMENT`         | 客户端 -> 服务器 | 签名交易（均可接受） |
    | `PAYMENT-RESPONSE`                        | 服务器 -> 客户端 | 结算收据       |
  </Tab>

  <Tab title="MPP on Tempo (EVM)">
    适用于拥有 EVM 钱包和 Tempo 区块链上 USDC.e 的代理。客户端支付 Gas 费。

    ### 安装

    ```bash theme={null}
    npm install mppx
    ```

    ### 设置

    ```typescript theme={null}
    import { Mppx, tempo } from "mppx/client";

    const mppx = Mppx.create({
      methods: [
        tempo.charge({
          signer: yourEvmWalletSigner, // viem WalletClient 或类似对象
        }),
      ],
    });
    ```

    ### paidFetch

    ```typescript theme={null}
    // mppx.fetch 自动处理 402 握手流程
    const response = await mppx.fetch(
      "https://agent.metengine.xyz/api/v1/markets/trending?timeframe=24h&limit=5"
    );
    const { data } = await response.json();
    ```

    `mppx` 客户端自动：

    1. 检测 402 响应
    2. 解析 `WWW-Authenticate: Payment method="tempo"` 挑战
    3. 签署 TIP-20 USDC.e 转账
    4. 附带 `Authorization: Payment` 头部重新发送

    | 头部                       | 方向         | 说明                         |
    | ------------------------ | ---------- | -------------------------- |
    | `WWW-Authenticate`       | 服务器 -> 客户端 | 402 挑战，包含 `method="tempo"` |
    | `Authorization: Payment` | 客户端 -> 服务器 | 带签名交易的凭证                   |
    | `Payment-Receipt`        | 服务器 -> 客户端 | 结算收据                       |
  </Tab>

  <Tab title="MPP on Solana">
    适用于基于 MPP 协议使用 Solana 钱包构建的代理。客户端支付交易费。

    ### 安装

    ```bash theme={null}
    npm install @solana/mpp mppx @solana/kit
    ```

    ### 设置

    ```typescript theme={null}
    import { Mppx, solana } from "@solana/mpp/client";
    import { createKeyPairSignerFromBytes, getBase58Encoder } from "@solana/kit";

    const bytes = getBase58Encoder().encode(process.env.SOLANA_PRIVATE_KEY!);
    const signer = await createKeyPairSignerFromBytes(bytes);

    const mppx = Mppx.create({
      methods: [
        solana.charge({
          signer,
          rpcUrl: "https://api.mainnet-beta.solana.com", // 或您的 RPC
        }),
      ],
    });
    ```

    ### paidFetch

    ```typescript theme={null}
    // mppx.fetch 自动处理 402 握手流程
    const response = await mppx.fetch(
      "https://agent.metengine.xyz/api/v1/markets/trending?timeframe=24h&limit=5"
    );
    const { data } = await response.json();
    ```

    `@solana/mpp` 客户端自动：

    1. 检测 402 响应
    2. 解析 `WWW-Authenticate: Payment method="solana"` 挑战
    3. 签署 USDC SPL 转账到服务器的接收方
    4. 附带 `Authorization: Payment` 头部重新发送

    | 头部                       | 方向         | 说明                          |
    | ------------------------ | ---------- | --------------------------- |
    | `WWW-Authenticate`       | 服务器 -> 客户端 | 402 挑战，包含 `method="solana"` |
    | `Authorization: Payment` | 客户端 -> 服务器 | 带签名交易的凭证                    |
    | `Payment-Receipt`        | 服务器 -> 客户端 | 结算收据                        |
  </Tab>
</Tabs>

## 您的第一个查询

获取 Polymarket 热门市场：

```typescript theme={null}
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 端点（特定市场的聪明钱情报）：

```typescript theme={null}
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     | 服务器错误 | 不收费。部分端点有已知的回退方案（参见[端点列表](/data-agent/endpoints)）。 |

## 下一步

<CardGroup cols={2}>
  <Card title="浏览所有端点" icon="list" href="/data-agent/endpoints">
    74 个端点，按平台分类，包含定价、参数和已知问题。
  </Card>

  <Card title="完整规范" icon="file-code" href="https://www.metengine.xyz/skill.md">
    包含所有参数、回退方案和集成模式的完整技能规范。
  </Card>
</CardGroup>
