---
name: x402-agent-payments
description: Instructions for AI agents with Solana wallets to pay for Tetrac API access using the x402 protocol. No facilitator needed — agents submit USDC payments directly on-chain.
license: Proprietary
compatibility: Designed for Claude Code (or similar products)
metadata:
  author: tetrac
  version: "2.2"
  category: "payments"
  emoji: "💸"
---

# x402 Payment Instructions for AI Agents

You are an AI agent with a Solana wallet. You can access Tetrac's paid market-data and exchange endpoints (listed under Available Endpoints) by paying USDC per request directly on Solana mainnet — $0.05 for standard endpoints, more for a few heavier ones (e.g. $0.50 for the full-market scanner snapshot). Always pay the exact amount quoted in the 402 challenge (`accepts[].amount`). No API key, no facilitator, no intermediary.

## Constants

| Field           | Value                                                                                                                                                                                           |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Base URL        | `https://www.tetrac.xyz`                                                                                                                                                                        |
| Treasury Wallet | `2uSZu6jhF7ZT7bREmQZeiJCEgynN2Qwpqa3BtaxhxxBM`                                                                                                                                                  |
| USDC Mint       | `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`                                                                                                                                                  |
| Price           | $0.05 (50,000 microUSDC) for most endpoints; heavier ones cost more (e.g. $0.50 / 500,000 for the full-market scanner snapshot). The exact amount is in the 402 challenge (`accepts[].amount`). |
| Network         | Solana Mainnet                                                                                                                                                                                  |
| Payment Timeout | 300 seconds                                                                                                                                                                                     |

> **Note:** The treasury wallet address and the exact amount are returned in the 402 challenge's top-level `accepts[0]` (`payTo`, `amount`). The legacy `paymentRequired` block repeats them for v1 clients. Always pay the address and amount from the challenge.

## Payment Flow

### Step 1: Call the endpoint (no auth)

Make a request to any endpoint listed under Available Endpoints without authentication. You will receive a `402 Payment Required` response with payment details in the top-level `accepts[0]` (the legacy `paymentRequired` block repeats them for v1 clients). You can skip this step if you already know the treasury wallet and price.

### Step 2: Send USDC on Solana

Transfer exactly the amount quoted in the 402 challenge (`accepts[].amount`, in microUSDC) to the treasury wallet — **$0.05** (50,000) for standard endpoints, **$0.50** (500,000) for the full-market scanner snapshot (`ttc-scanner-cache`). Your wallet needs USDC for the payment and a small amount of SOL (~0.000005) for gas. Wait for the transaction to reach `confirmed` status before proceeding.

### Step 3: Replay the request with the payment header

Encode your payment proof as base64 JSON and attach it as the `x-x402-payment` header:

- `signature` — the Solana transaction signature from Step 2
- `payer` — your wallet's public key (base58)
- `amount` — the microUSDC amount as a **string**: `"50000"` ($0.05) for standard endpoints, `"500000"` ($0.50) for `/api/v1/markets/ttc-scanner-cache`. It must match the `accepts[].amount` quoted in that endpoint's 402 challenge and the amount you actually transferred on-chain.
- `timestamp` — epoch **milliseconds**, i.e. `Date.now()`. Optional and informational only: the server records it on the receipt but never uses it to judge freshness — expiry is measured from the transaction's on-chain block time (see Rules).
- `payTo` — optional and ignored: the server always checks the transfer against its own treasury address

Format: `"x402:" + base64(JSON.stringify(paymentData))`

### Step 4: Use the response

On successful verification you get a normal `200` response with the requested data.

## Rules

- **One payment = one request.** Each tx signature can only be used once.
- **Pay before you call.** The transaction must be confirmed on-chain before you send the header.
- **Payments expire.** Transactions whose on-chain block time is older than 300 seconds are rejected. The `timestamp` you put in the header has no effect on this — only the block time counts.
- **USDC only.** No SOL, no other tokens.
- **You pay gas.** Solana fees are ~0.000005 SOL per tx. You need SOL in your wallet for gas.
- **No facilitator needed.** You submit the transaction yourself. The server verifies it on-chain. That's it.
- **You are the fee payer.** We never sponsor gas and never co-sign. Any transaction handed to us whose fee-payer slot is unsigned is rejected — see the next section if you use a stock x402 SDK.

## Using a canonical x402 v2 SDK (`PAYMENT-SIGNATURE`)

Everything above describes our `x-x402-payment` header. We **also** accept the canonical x402 v2 receipt on the `PAYMENT-SIGNATURE` header, so an off-the-shelf client (`@x402/core` + `@x402/svm` + `@x402/fetch`) can pay us directly.

Header value is standard base64 of:

```json
{ "x402Version": 2, "accepted": { ...the accepts[] entry you chose... }, "payload": { ... } }
```

`payload` may be either shape:

| Shape             | Meaning                                                          |
| ----------------- | ---------------------------------------------------------------- |
| `{ signature }`   | You already broadcast and confirmed the transfer. We verify it.  |
| `{ transaction }` | Base64 **fully-signed** Solana transaction. We relay it for you. |

### The one thing you must configure: `feePayer`

Our 402 challenge deliberately omits `extra.feePayer`, because the fee payer is **you**, and we cannot know your address when we issue the challenge. `@x402/svm`'s `ExactSvmScheme` throws without it:

```
feePayer is required in paymentRequirements.extra for SVM transactions
```

Set it to **your own wallet address**. That is not a workaround — it is the correct value: it makes you the fee payer, and because you are also the transfer authority, your single signature fills both slots and the transaction we receive is complete and relayable.

Use the SDK's supported `paymentRequirementsSelector` hook — no patching required:

```ts
import { x402Client } from "@x402/core/client";
import { registerExactSvmScheme } from "@x402/svm";

const client = new x402Client();

registerExactSvmScheme(client, {
  signer,
  // Runs after the SDK filters accepts[] down to entries it can pay. Return the
  // chosen entry with YOUR address as the fee payer.
  paymentRequirementsSelector: (_x402Version, accepts) => ({
    ...accepts[0],
    extra: { ...accepts[0].extra, feePayer: MY_WALLET_ADDRESS },
  }),
});
```

The entry you return is also what gets echoed back as `accepted` in your receipt. We compare `scheme`, `network`, `amount`, `asset` and `payTo` against our own config and reject a mismatch — but we ignore `extra` entirely, so your `feePayer` passes through without being trusted.

### Notes for SDK clients

- **We emit no `PAYMENT-RESPONSE` header.** The SDK swallows its absence and returns `kind: "passthrough"` on a `200` — your data is in the body. A `passthrough` result is a success, not a failure.
- **Network id** is `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`. `solana:mainnet` is not a valid CAIP-2 id and the SDK will reject it.
- **Base64 must be the standard alphabet.** The SDK's own validator rejects base64url (`-`, `_`).
- **Same replay guard, both formats.** A signature spent via `x-x402-payment` cannot be respent via `PAYMENT-SIGNATURE`, or vice versa.

## Available Endpoints

These endpoints accept x402 payment:

| Endpoint                                   | Data                                                        |
| ------------------------------------------ | ----------------------------------------------------------- |
| `/api/v1/markets/ttc-scanner`              | Per-symbol technical scanner ($0.05)                        |
| `/api/v1/markets/ttc-scanner-cache?full=1` | Full-market signal snapshot ($0.50) — `?full=1` is required |
| `/api/v1/markets/hybrid-tickers`           | Aggregated perpetual futures tickers                        |
| `/api/v1/markets/funding-rates`            | Perpetual funding rates                                     |
| `/api/v1/markets/open-interest`            | Open interest from one venue per call                       |
| `/api/v1/markets/volume-snapshot`          | Per-exchange volume snapshots                               |
| `/api/v1/markets/swap-volume`              | Perp DEX daily volume history                               |
| `/api/v1/markets/symbol-venues`            | Which venues list each symbol                               |
| `/api/v1/markets/listings`                 | New market listings (`GET` only)                            |
| `/api/v1/markets/insights`                 | Top movers with funding-rate context                        |
| `/api/v1/markets/news`                     | Market news (Alpha Vantage)                                 |
| `/api/v1/markets/calendar`                 | Macro economic calendar                                     |
| `/api/v1/markets/quakes`                   | Significant earthquakes (USGS)                              |
| `/api/v1/solana-perps/long-short`          | Solana perp long/short open interest                        |
| `/api/v1/solana-perps/pacifica-watchlist`  | Top Pacifica trader accounts by open interest               |
| `/api/v1/exchanges`                        | Unified Trading API                                         |
| `/api/v1/exchanges/latency`                | Exchange latency monitor                                    |

Other `/api/v1/*` routes do not take x402 — some are session-only (for example `POST /api/v1/markets/ttc-scanner-cache`) and some have no paid path at all. Request and response formats are in the [market-data](https://www.tetrac.xyz/skills/market-data/SKILL.md) and [trading](https://www.tetrac.xyz/skills/trading/SKILL.md) skills.

> **Pricing:** every paid endpoint is $0.05 except `/api/v1/markets/ttc-scanner-cache`, which is $0.50 (one call returns every scanned market's signal). Call it with `?full=1` — without it the endpoint returns only freshness timestamps and the $0.50 is still charged. The 402 challenge always quotes the exact `amount` to pay. `GET /api/v1/markets` is free and rate-limited: it lists every market-data endpoint with its price, so read it before paying for anything.

## Error Handling

| Status              | Meaning                          | Action                                                                                                                                                            |
| ------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `402` (no header)   | Payment required                 | Send USDC and retry with header                                                                                                                                   |
| `402` (with header) | Invalid/expired/replayed payment | Send a **new** payment — see below                                                                                                                                |
| `429`               | Rate limited                     | Wait `Retry-After` seconds, then resend the **same** payment header. The body says `paymentRedeemed: false`: the payment was not used.                            |
| `401`               | Your session headers are expired | You sent `ttc-auth-token` / `ttc-public-key` and the session expired or was replaced by a newer login. Log in again. Never pay to work around an expired session. |
| `200`               | Success                          | Parse response body as JSON                                                                                                                                       |

**A signature that fails on-chain verification cannot be retried.** Once the server starts verifying a signature it is locked for 15 minutes, which is longer than the transaction's 300-second validity, so a failed verification means paying again. Before sending the header, confirm the transaction reached `confirmed` and that the amount matches the challenge.

**Stay under the rate limit.** x402 calls are limited per paying wallet at the Free tier (30/min for market data, 20/min for `/api/v1/exchanges`). A payment that names no valid wallet address is limited by your IP instead. The limit is checked **before** the payment is redeemed, so a `429` never consumes a payment. Wait `Retry-After` seconds and resend the same header; a landed transaction stays valid for 300 seconds.

## Solana Rust CLI (Recommended)

A Rust-based CLI with built-in wallet management and USDC transfers. Download from source: `https://gitlab.com/tradingtoolcrypto/solana-rust-cli`

### Install

```bash
git clone https://gitlab.com/tradingtoolcrypto/solana-rust-cli.git
cd solana-rust-cli
cp .env.example .env
```

### 1. Generate a wallet

```bash
cargo run --bin new_wallet
# Pubkey:
# 7xKXtg2CW87aJRHSvqBuGrT8...
#
# Base58 private key:
# 4wBqpZM9k3JRvNeGfXkCzUiE7...
#
# JSON private key:
# [174, 47, 154, 16, 202, ...]
#
# SIGNER_KEYPAIR saved to .env
```

The keypair is saved as a base58 string to `SIGNER_KEYPAIR` in your `.env` file automatically. You still need to set `WALLET_PUBKEY` and optionally `RPC_URL` in `.env`.

### 2. Fund your wallet

Send SOL (for gas) and USDC (for payments) to your wallet's pubkey. Check balances:

```bash
# SOL balance — requires RPC_URL + WALLET_PUBKEY in .env
cargo run --bin sol_balance
# Wallet: 7xKXtg2CW87a...
# Balance: 0.5 SOL (500000000 lamports)

# USDC balance — also needs MINT_ACCOUNT_PUBKEY in .env
# Set MINT_ACCOUNT_PUBKEY=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
cargo run --bin associated_token_balance
# Wallet pubkey: 7xKXtg2CW87a...
# Mint account: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
# Associated token account: F59618aQB8r6...
# Amount: 12.50
# Decimals: 6
```

### 3. Send $0.05 USDC to the treasury

Send `0.05` for a standard endpoint. For `/api/v1/markets/ttc-scanner-cache` send `0.50` instead — that endpoint's 402 challenge quotes `500000` microUSDC.

```bash
cargo run --bin send_usdc -- 0.05 2uSZu6jhF7ZT7bREmQZeiJCEgynN2Qwpqa3BtaxhxxBM
# USDC sent successfully.
# Signature: 5VqBgkR9xH7mZxTnPa8K3VqBgkR9xH7mZxTnPa8K3...
# Amount: 0.05 USDC
# Recipient: 2uSZu6jhF7ZT7bREmQZeiJCEgynN2Qwpqa3BtaxhxxBM
# Recipient ATA: F59618aQB8r6asXeMcB9jWuY6NEx1VduT9yFo1GTi1ks
```

`send_usdc` reads `SIGNER_KEYPAIR` from `.env`. `RPC_URL` is optional — defaults to `https://api.mainnet-beta.solana.com` if not set. Auto-creates the recipient's USDC token account if needed.

### 4. Call the API with payment proof

Use the signature printed by `send_usdc`:

```bash
SIGNATURE="5VqBgkR9xH7mZxTnPa8K3VqBgkR9xH7mZxTnPa8K3..."
PAYER="7xKXtg2CW87a..."  # your wallet pubkey
AMOUNT="50000"           # $0.05 standard rate; use 500000 for /api/v1/markets/ttc-scanner-cache

# `date +%s000` = epoch MILLISECONDS (epoch seconds with "000" appended), which is
# the unit the server expects for `timestamp`. It is informational only — freshness
# is judged from the transaction's on-chain block time.
# `tr -d '\n'` strips the line breaks GNU base64 (Linux) inserts every 76 characters.
PAYLOAD=$(echo -n '{"signature":"'$SIGNATURE'","payer":"'$PAYER'","amount":"'$AMOUNT'","timestamp":'$(date +%s000)'}' | base64 | tr -d '\n')

curl -s "https://www.tetrac.xyz/api/v1/markets/ttc-scanner?symbol=BTCUSDT&timeframe=1h" \
  -H "x-x402-payment: x402:$PAYLOAD"
```

### All CLI commands

| Command                                    | Purpose                 | Env Vars                                                                        |
| ------------------------------------------ | ----------------------- | ------------------------------------------------------------------------------- |
| `cargo run --bin new_wallet`               | Generate keypair        | None                                                                            |
| `cargo run --bin send_usdc -- <amt> <to>`  | Transfer USDC (mainnet) | `SIGNER_KEYPAIR`, `RPC_URL` (optional)                                          |
| `cargo run --bin send_sol -- <amt> <to>`   | Transfer native SOL     | `SIGNER_KEYPAIR`, `RPC_URL`                                                     |
| `cargo run --bin send_spl`                 | Transfer any SPL token  | `SIGNER_KEYPAIR`, `RPC_URL`, `MINT_ACCOUNT_PUBKEY`, `RECEIVER_PUBKEY`, `AMOUNT` |
| `cargo run --bin sol_balance`              | Check SOL balance       | `RPC_URL`, `WALLET_PUBKEY`                                                      |
| `cargo run --bin associated_token_balance` | Check SPL token balance | `RPC_URL`, `WALLET_PUBKEY`, `MINT_ACCOUNT_PUBKEY`                               |

## JavaScript Examples

### Option A: With `@solana/web3.js` + `@solana/spl-token`

```javascript
import { Connection, PublicKey, Transaction } from "@solana/web3.js";
import {
  getAssociatedTokenAddress,
  createTransferInstruction,
} from "@solana/spl-token";

const USDC_MINT = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
const TREASURY = new PublicKey("2uSZu6jhF7ZT7bREmQZeiJCEgynN2Qwpqa3BtaxhxxBM");

// Standard rate: 50_000 microUSDC = $0.05. /api/v1/markets/ttc-scanner-cache is
// 500_000 ($0.50) — pass that endpoint's `accepts[].amount` from the 402 challenge.
const AMOUNT = 50_000;

async function callTTCWithPayment(endpoint, amount = AMOUNT) {
  const connection = new Connection("https://api.mainnet-beta.solana.com");

  // 1. Send the USDC the challenge asked for (0.05 USDC at the standard rate)
  const senderATA = await getAssociatedTokenAddress(
    USDC_MINT,
    wallet.publicKey,
  );
  const treasuryATA = await getAssociatedTokenAddress(USDC_MINT, TREASURY);
  const ix = createTransferInstruction(
    senderATA,
    treasuryATA,
    wallet.publicKey,
    amount,
  );
  const tx = new Transaction().add(ix);
  tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
  tx.feePayer = wallet.publicKey;
  const signed = await wallet.signTransaction(tx);
  const signature = await connection.sendRawTransaction(signed.serialize());
  await connection.confirmTransaction(signature, "confirmed");

  // 2. Build payment header
  const payment = {
    signature,
    payer: wallet.publicKey.toBase58(),
    // String microUSDC — must equal what you just transferred and what the
    // endpoint's 402 challenge quoted ("50000" standard, "500000" scanner-cache).
    amount: String(amount),
    // Epoch MILLISECONDS. Informational only — the server stores it on the
    // receipt; expiry is judged from the transaction's on-chain block time.
    timestamp: Date.now(),
    payTo: TREASURY.toBase58(),
  };
  const header =
    "x402:" + Buffer.from(JSON.stringify(payment)).toString("base64");

  // 3. Call the endpoint
  const res = await fetch(`https://www.tetrac.xyz${endpoint}`, {
    headers: { "x-x402-payment": header },
  });
  return res.json();
}

const news = await callTTCWithPayment("/api/v1/markets/news");
// The $0.50 tier: pay 500_000 microUSDC for the full-market snapshot.
const snapshot = await callTTCWithPayment(
  "/api/v1/markets/ttc-scanner-cache?full=1", // ?full=1 returns the signals; without it you pay for timestamps only
  500_000,
);
```

### Option B: Without Solana SDK — raw `fetch` + JSON-RPC

No Solana SDK needed. Uses `tweetnacl` (signing), `bs58` (encoding), `@noble/curves` (PDA derivation), and Node.js `crypto` (sha256). Verified to produce byte-identical transactions to `@solana/web3.js`.

```javascript
import nacl from "tweetnacl";
import bs58 from "bs58";
import crypto from "crypto";
import { ed25519 } from "@noble/curves/ed25519";

// --- Constants ---

const RPC = "https://api.mainnet-beta.solana.com";
const TREASURY = "2uSZu6jhF7ZT7bREmQZeiJCEgynN2Qwpqa3BtaxhxxBM";
const USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const ATA_PROGRAM_ID = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
// Standard rate: 50_000 microUSDC = 0.05 USDC (6 decimals). The full-market
// snapshot /api/v1/markets/ttc-scanner-cache costs 500_000 ($0.50) — pass that
// as `amount` below. Always pay the `accepts[].amount` from the 402 challenge.
const AMOUNT = 50_000;

// --- JSON-RPC Helper ---

async function rpc(method, params = []) {
  const res = await fetch(RPC, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
  });
  const json = await res.json();
  if (json.error) throw new Error(`RPC ${method}: ${json.error.message}`);
  return json.result;
}

// --- Ed25519 / PDA Helpers ---

function isOnCurve(bytes) {
  try {
    ed25519.ExtendedPoint.fromHex(Buffer.from(bytes));
    return true;
  } catch {
    return false;
  }
}

function findPDA(seeds, programId) {
  const programIdBytes =
    typeof programId === "string" ? bs58.decode(programId) : programId;
  for (let bump = 255; bump >= 0; bump--) {
    const hasher = crypto.createHash("sha256");
    for (const seed of seeds) hasher.update(Buffer.from(seed));
    hasher.update(Buffer.from([bump]));
    hasher.update(Buffer.from(programIdBytes));
    hasher.update(Buffer.from("ProgramDerivedAddress"));
    const hash = new Uint8Array(hasher.digest());
    if (!isOnCurve(hash)) return { address: hash, bump };
  }
  throw new Error("Could not find valid PDA bump");
}

function getATA(wallet, mint) {
  const walletBytes = typeof wallet === "string" ? bs58.decode(wallet) : wallet;
  const mintBytes = typeof mint === "string" ? bs58.decode(mint) : mint;
  const tokenProgramBytes = bs58.decode(TOKEN_PROGRAM_ID);
  const { address } = findPDA(
    [walletBytes, tokenProgramBytes, mintBytes],
    ATA_PROGRAM_ID,
  );
  return bs58.encode(address);
}

// --- Transaction Serialization ---

function compactU16(value) {
  if (value < 0x80) return Buffer.from([value]);
  if (value < 0x4000) return Buffer.from([(value & 0x7f) | 0x80, value >> 7]);
  return Buffer.from([
    (value & 0x7f) | 0x80,
    ((value >> 7) & 0x7f) | 0x80,
    value >> 14,
  ]);
}

function buildTransactionMessage(
  walletPubkey,
  senderATA,
  treasuryATA,
  blockhash,
  // microUSDC to transfer — 50_000 standard, 500_000 for ttc-scanner-cache.
  amount = AMOUNT,
) {
  const senderATABytes =
    typeof senderATA === "string" ? bs58.decode(senderATA) : senderATA;
  const treasuryATABytes =
    typeof treasuryATA === "string" ? bs58.decode(treasuryATA) : treasuryATA;
  const tokenProgramBytes = bs58.decode(TOKEN_PROGRAM_ID);
  const blockhashBytes =
    typeof blockhash === "string" ? bs58.decode(blockhash) : blockhash;

  const header = Buffer.from([1, 0, 1]); // 1 signer, 0 ro-signed, 1 ro-unsigned
  const accountKeys = Buffer.concat([
    Buffer.from(walletPubkey), // [0] signer + fee payer
    Buffer.from(senderATABytes), // [1] source ATA (writable)
    Buffer.from(treasuryATABytes), // [2] dest ATA (writable)
    Buffer.from(tokenProgramBytes), // [3] token program (readonly)
  ]);

  const instructionData = Buffer.alloc(9);
  instructionData.writeUInt8(3, 0); // SPL Token Transfer
  // Node-only. Browser Buffer polyfills (including the one Next.js bundles) omit
  // the BigInt writers — in a browser, use:
  //   new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
  //     .setBigUint64(1, BigInt(amount), true)  // true = little-endian
  instructionData.writeBigUInt64LE(BigInt(amount), 1);

  return Buffer.concat([
    header,
    compactU16(4), // 4 account keys
    accountKeys, // 4 * 32 = 128 bytes
    Buffer.from(blockhashBytes), // 32 bytes
    compactU16(1), // 1 instruction
    Buffer.from([3]), // programIdIndex (tokenProgram)
    compactU16(3),
    Buffer.from([1, 2, 0]), // accounts: source, dest, authority
    compactU16(instructionData.length),
    instructionData,
  ]);
}

// --- Main: Pay and call API ---

// `amount` = microUSDC to pay: AMOUNT (50_000, $0.05) for standard endpoints,
// 500_000 ($0.50) for /api/v1/markets/ttc-scanner-cache.
async function callTTCWithPayment(endpoint, amount = AMOUNT) {
  const secretKey = new Uint8Array(/* your 64-byte secret key */);
  const keypair = nacl.sign.keyPair.fromSecretKey(secretKey);
  const walletAddress = bs58.encode(keypair.publicKey);

  // 1. Derive ATAs
  const senderATA = getATA(walletAddress, USDC_MINT);
  const treasuryATA = getATA(TREASURY, USDC_MINT);

  // 2. Build, sign, and send USDC transfer
  const {
    value: { blockhash },
  } = await rpc("getLatestBlockhash", [{ commitment: "confirmed" }]);
  const message = buildTransactionMessage(
    keypair.publicKey,
    senderATA,
    treasuryATA,
    blockhash,
    // Transfer exactly the microUSDC this endpoint's 402 challenge quoted.
    amount,
  );
  const sig = nacl.sign.detached(new Uint8Array(message), keypair.secretKey);
  const txBytes = Buffer.concat([compactU16(1), Buffer.from(sig), message]);

  const signature = await rpc("sendTransaction", [
    txBytes.toString("base64"),
    { encoding: "base64", preflightCommitment: "confirmed" },
  ]);

  // 3. Wait for confirmation
  for (let i = 0; i < 30; i++) {
    const status = await rpc("getSignatureStatuses", [[signature]]);
    const st = status?.value?.[0];
    if (st?.err)
      throw new Error(`Transaction failed: ${JSON.stringify(st.err)}`);
    if (
      st?.confirmationStatus === "confirmed" ||
      st?.confirmationStatus === "finalized"
    )
      break;
    await new Promise((r) => setTimeout(r, 1000));
  }

  // 4. Build payment header and call API
  const payment = {
    signature,
    payer: walletAddress,
    // String microUSDC — the same value transferred above ("50000" standard,
    // "500000" for ttc-scanner-cache).
    amount: String(amount),
    // Epoch MILLISECONDS. Informational only — expiry is judged from the
    // transaction's on-chain block time, not from this field.
    timestamp: Date.now(),
    payTo: TREASURY,
  };
  const header =
    "x402:" + Buffer.from(JSON.stringify(payment)).toString("base64");
  const res = await fetch(`https://www.tetrac.xyz${endpoint}`, {
    headers: { "x-x402-payment": header },
  });
  return res.json();
}

const news = await callTTCWithPayment("/api/v1/markets/news");
// The $0.50 tier: 500_000 microUSDC for the full-market snapshot.
const snapshot = await callTTCWithPayment(
  "/api/v1/markets/ttc-scanner-cache?full=1", // ?full=1 returns the signals; without it you pay for timestamps only
  500_000,
);
```
