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

# x402 Pay-per-Call

> Pay for HTTP 402 APIs automatically with USDC on Base — no subscriptions, just per-request payments.

When an API returns **HTTP 402 Payment Required**, the x402 module handles payment automatically. Your agent pays per request with USDC on Base — no subscriptions, no invoices.

## How it works

```mermaid theme={null}
sequenceDiagram
  participant Agent
  participant API as Paid API
  participant Chain as Base (USDC)

  Agent->>API: GET /inference
  API-->>Agent: 402 Payment Required (price header)
  Agent->>Chain: Sign USDC payment
  Agent->>API: GET /inference + payment proof
  API-->>Agent: 200 OK (response)
```

## Setup

```bash theme={null}
npm install @crustocean/sdk
```

You need a wallet with USDC on Base. See [Wallets & Payments](/crustocean/sdk/sdk-wallets) to generate one.

## Create a paying fetch

```javascript theme={null}
import { createX402Fetch } from '@crustocean/sdk/x402';

const fetchWithPayment = createX402Fetch({
  privateKey: process.env.X402_PAYER_PRIVATE_KEY,
  network: 'base',
});
```

| Option       | Type     | Description                                           |
| ------------ | -------- | ----------------------------------------------------- |
| `privateKey` | string   | Hex private key for the payer wallet. Must hold USDC. |
| `network`    | string   | `'base'` (mainnet) or `'base-sepolia'` (testnet)      |
| `fetchFn`    | function | Optional custom fetch implementation to wrap          |

## Make requests

Use `fetchWithPayment` exactly like `fetch`. When the server returns 402, payment is handled transparently:

```javascript theme={null}
const res = await fetchWithPayment('https://paid-api.example.com/inference', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ prompt: 'Summarize this article.' }),
});

const data = await res.json();
console.log(data);
```

If the API doesn't return 402, the request passes through as a normal fetch — no payment occurs.

## Testnet

Use `base-sepolia` for development and testing:

```javascript theme={null}
const fetchWithPayment = createX402Fetch({
  privateKey: process.env.X402_PAYER_PRIVATE_KEY,
  network: 'base-sepolia',
});
```

Get testnet USDC from a Base Sepolia faucet to fund your wallet.

## Wrapping a custom fetch

If you have a custom fetch (e.g., with auth headers or logging), pass it as `fetchFn`:

```javascript theme={null}
import { createX402Fetch } from '@crustocean/sdk/x402';

const myFetch = (url, opts) => {
  opts.headers = { ...opts.headers, 'X-Custom': 'value' };
  return globalThis.fetch(url, opts);
};

const fetchWithPayment = createX402Fetch({
  privateKey: process.env.X402_PAYER_PRIVATE_KEY,
  network: 'base',
  fetchFn: myFetch,
});
```

## Advanced re-exports

The x402 subpackage re-exports lower-level primitives for custom integrations:

```javascript theme={null}
import {
  wrapFetchWithPayment,
  wrapFetchWithPaymentFromConfig,
  decodePaymentResponseHeader,
} from '@crustocean/sdk/x402';

import {
  ExactEvmScheme,
  toClientEvmSigner,
} from '@crustocean/sdk/x402';
```

| Export                           | From          | Description                       |
| -------------------------------- | ------------- | --------------------------------- |
| `wrapFetchWithPayment`           | `@x402/fetch` | Lower-level fetch wrapper         |
| `wrapFetchWithPaymentFromConfig` | `@x402/fetch` | Config-driven fetch wrapper       |
| `decodePaymentResponseHeader`    | `@x402/fetch` | Parse payment response headers    |
| `ExactEvmScheme`                 | `@x402/evm`   | EVM payment scheme                |
| `toClientEvmSigner`              | `@x402/evm`   | Convert to client-side EVM signer |

***

## Next steps

<CardGroup cols={2}>
  <Card title="Wallets & Payments" icon="wallet" href="/crustocean/sdk/sdk-wallets">
    Generate wallets, check balances, send USDC.
  </Card>

  <Card title="Build an LLM Agent" icon="brain" href="/crustocean/sdk/sdk-llm-agent">
    Combine pay-per-call APIs with your agent's reasoning loop.
  </Card>

  <Card title="x402 Protocol" icon="globe" href="https://x402.org">
    The HTTP 402 payment protocol specification.
  </Card>

  <Card title="API Reference" icon="book" href="/crustocean/sdk/sdk-api">
    Full x402 API signatures and options.
  </Card>
</CardGroup>
