> ## 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.

# Start Querying in Minutes

> Set up payments and make your first smart money query against the MetEngine Data Agent. Supports x402, MPP Tempo, and MPP Solana.

A wallet with USDC and a few lines of code. That's all you need to query smart money data across Polymarket, Hyperliquid, and Meteora. Pick a payment protocol that fits your stack.

## What You're Building Toward

Here's an AI agent querying Polymarket smart money data in real time:

<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>

## Payment Flow (All Protocols)

Every protocol follows the same settle-after-execute pattern. The server holds your signed transaction and only broadcasts it on-chain after a successful query with data.

```
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>If the query fails (timeout, server error, empty results), the signed transaction is discarded and you are never charged. You only pay for successful responses with data.</Tip>

## Choose Your Protocol

<Tabs>
  <Tab title="x402 on Solana (Recommended)">
    The most established protocol. You need a Solana wallet with USDC (and SOL for transaction fees).

    ### Install

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

    ### Setup

    ```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 };
    }
    ```

    | Header                                    | Direction        | Description                        |
    | ----------------------------------------- | ---------------- | ---------------------------------- |
    | `PAYMENT-REQUIRED` / `X-PAYMENT-REQUIRED` | Server -> Client | 402 challenge with price           |
    | `PAYMENT-SIGNATURE` or `X-PAYMENT`        | Client -> Server | Signed transaction (both accepted) |
    | `PAYMENT-RESPONSE`                        | Server -> Client | Settlement receipt                 |
  </Tab>

  <Tab title="MPP on Tempo (EVM)">
    For agents with an EVM wallet and USDC.e on the Tempo blockchain. Client pays gas.

    ### Install

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

    ### Setup

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

    const mppx = Mppx.create({
      methods: [
        tempo.charge({
          signer: yourEvmWalletSigner, // viem WalletClient or similar
        }),
      ],
    });
    ```

    ### paidFetch

    ```typescript theme={null}
    // mppx.fetch handles the 402 handshake automatically
    const response = await mppx.fetch(
      "https://agent.metengine.xyz/api/v1/markets/trending?timeframe=24h&limit=5"
    );
    const { data } = await response.json();
    ```

    The `mppx` client automatically:

    1. Detects the 402 response
    2. Parses the `WWW-Authenticate: Payment method="tempo"` challenge
    3. Signs the TIP-20 USDC.e transfer
    4. Re-sends with `Authorization: Payment` header

    | Header                   | Direction        | Description                         |
    | ------------------------ | ---------------- | ----------------------------------- |
    | `WWW-Authenticate`       | Server -> Client | 402 challenge with `method="tempo"` |
    | `Authorization: Payment` | Client -> Server | Credential with signed tx           |
    | `Payment-Receipt`        | Server -> Client | Settlement receipt                  |
  </Tab>

  <Tab title="MPP on Solana">
    For agents built on the MPP protocol with a Solana wallet. Client pays transaction fees.

    ### Install

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

    ### Setup

    ```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", // or your RPC
        }),
      ],
    });
    ```

    ### paidFetch

    ```typescript theme={null}
    // mppx.fetch handles the 402 handshake automatically
    const response = await mppx.fetch(
      "https://agent.metengine.xyz/api/v1/markets/trending?timeframe=24h&limit=5"
    );
    const { data } = await response.json();
    ```

    The `@solana/mpp` client automatically:

    1. Detects the 402 response
    2. Parses the `WWW-Authenticate: Payment method="solana"` challenge
    3. Signs a USDC SPL transfer to the server's recipient
    4. Re-sends with `Authorization: Payment` header

    | Header                   | Direction        | Description                          |
    | ------------------------ | ---------------- | ------------------------------------ |
    | `WWW-Authenticate`       | Server -> Client | 402 challenge with `method="solana"` |
    | `Authorization: Payment` | Client -> Server | Credential with signed tx            |
    | `Payment-Receipt`        | Server -> Client | Settlement receipt                   |
  </Tab>
</Tabs>

## Your First Query

Fetch trending Polymarket markets:

```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 endpoint (smart money intelligence for a specific market):

```typescript theme={null}
const { data } = await paidFetch("/api/v1/markets/intelligence", {
  method: "POST",
  body: { condition_id: "0xabc123...", top_n_wallets: 10 },
});
```

## Session Memory for Agents

If your agent runs across multiple sessions, persist setup details to avoid re-reading the full spec every time. Store in `~/.claude/agents/metengine-memory.md`:

* Wallet address and balance verification status
* Working bootstrap code snippet
* Last 10 endpoint calls with latency and cost
* Any quirks or fallback strategies discovered

This cuts token overhead by roughly 80% on subsequent sessions.

## Error Handling

| Status  | Meaning          | Action                                                                                   |
| ------- | ---------------- | ---------------------------------------------------------------------------------------- |
| 402     | Payment required | Normal first step. Parse and sign.                                                       |
| 200     | Success          | Data returned. Payment settled.                                                          |
| 504     | Timeout          | No charge. Retry with narrower parameters or use a fallback endpoint.                    |
| 503/429 | Rate limit       | No charge. Back off per `Retry-After` header.                                            |
| 500     | Server error     | No charge. Some endpoints have known fallbacks (see [Endpoints](/data-agent/endpoints)). |

## Next Steps

<CardGroup cols={2}>
  <Card title="Browse All Endpoints" icon="list" href="/data-agent/endpoints">
    74 endpoints with pricing, parameters, and known quirks per platform.
  </Card>

  <Card title="Full Specification" icon="file-code" href="https://www.metengine.xyz/skill.md">
    Complete skill spec with every parameter, fallback, and integration pattern.
  </Card>
</CardGroup>
