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

# x402 Payments (Set-and-Forget)

> How Delegare makes x402 protocol microtransactions seamless for AI agents, with multi-protocol discovery across CDP Bazaar and MPPScan.

The `x402` protocol (an extension of the HTTP `402 Payment Required` status) allows APIs to monetize individual endpoints by demanding a microtransaction before returning a resource.

While `x402` is powerful for agent-to-agent (A2A) commerce, existing implementations have two critical gaps:

1. **The wallet popup** — every time an agent hits a paywall, the human user must manually confirm a transaction.
2. **Invisible to agents** — endpoints using the official `@x402` packages don't appear in any agent directory until a human manually registers them.

`@delegare/x402` solves both. It combines x402 with Intent Mandates for set-and-forget payments, and simultaneously emits discovery headers that make your endpoint automatically appear on [Delegare Market](https://market.delegare.dev) (which aggregates across protocols), [agentic.market](https://agentic.market) (CDP Bazaar), and [mppscan.com](https://mppscan.com).

***

## How It Works

<Steps>
  <Step title="Agent requests data">
    The agent calls `POST /api/extract` on the merchant's server.
  </Step>

  <Step title="Merchant returns 402 challenge">
    The middleware responds with `402 Payment Required` containing three parallel discovery payloads:

    * **`PAYMENT-REQUIRED` header** (base64 JSON) — x402 v2, read by CDP Bazaar and `@x402/fetch` clients
    * **`WWW-Authenticate: Payment ...` header** — MPP/RFC 7235, read by MPPScan and MPP-compatible wallets
    * **JSON body** — x402 v1, backward-compatible with older clients
  </Step>

  <Step title="SDK auto-pays via Delegare">
    `@delegare/sdk` intercepts the 402, verifies the amount is within the agent's budget, and forwards the intent mandate to Delegare's settlement infrastructure.
  </Step>

  <Step title="Settlement on Base">
    Delegare settles on Base L2 via the mandate's session key and the DelegareRouter contract. USDC arrives directly in the merchant's wallet. No popups.
  </Step>

  <Step title="Agent receives data">
    The agent retries with a payment credential. The middleware verifies it and returns the gated resource.
  </Step>

  <Step title="CDP Bazaar indexes the endpoint">
    On the first settlement via the CDP Facilitator (`PAYMENT-SIGNATURE` credential), CDP writes a catalog entry. The endpoint appears on [agentic.market](https://agentic.market) within \~10 minutes.
  </Step>
</Steps>

***

## For Merchants: Monetizing APIs

### Basic setup

```bash theme={null}
npm install @delegare/x402
```

```typescript theme={null}
import express from 'express';
import { requireX402Payment } from '@delegare/x402';

const app = express();

app.get('/premium-data',
  requireX402Payment({
    price: '0.05',
    payTo: '0xYourMerchantWalletAddress',
  }),
  (req, res) => {
    res.json({ secret: 'AI agents love this data' });
  }
);
```

### Adding agent discovery

Use `declareDiscoveryExtension` before `requireX402Payment` to make your endpoint searchable on [Delegare Market](https://market.delegare.dev), [agentic.market](https://agentic.market), and [mppscan.com](https://mppscan.com):

```typescript theme={null}
import { requireX402Payment, declareDiscoveryExtension } from '@delegare/x402';

app.post('/api/extract',
  declareDiscoveryExtension({
    description: "Extract structured financial data from documents. $0.15/page.",
    inputSchema: {
      type: "object",
      properties: {
        documentId: { type: "string" },
        domain: { type: "string", enum: ["commercial_loan", "equity_investment"] }
      },
      required: ["documentId"]
    },
    bodyType: "json",
    output: {
      example: { extractedData: { gross_income: 1250000 }, costCents: 150 },
      // schema is required — output.example alone is not enough for Bazaar
      schema: {
        type: "object",
        properties: {
          extractedData: { type: "object" },
          costCents: { type: "number" }
        }
      }
    }
  }),
  requireX402Payment({ price: '0.15', payTo: '0xYourWallet' }),
  async (req, res) => { res.json({ data: '...' }); }
);
```

### What the middleware handles

| Client credential        | Rail               | What happens                                               |
| ------------------------ | ------------------ | ---------------------------------------------------------- |
| None                     | —                  | Returns `402` with x402 v2, MPP, and v1 discovery payloads |
| `X-Bundle-Token`         | Fiat credit bundle | Validates JWT, deducts credit from your DB                 |
| `PAYMENT-SIGNATURE`      | x402 v2 USDC       | Settles via CDP Facilitator → indexes on agentic.market    |
| `X-PAYMENT`              | x402 v1 USDC       | Settles via Delegare Facilitator                           |
| `X-DELEGARE-MANDATE`     | AP2 intent mandate | Settles via Delegare Vault using session key               |
| `Authorization: Payment` | MPP/RFC 7235       | Settles via Delegare Facilitator                           |

<Note>
  You never touch private keys or on-chain logic. USDC arrives directly in your wallet from the Base blockchain.
</Note>

### Required env vars for Bazaar indexing

```env theme={null}
COINBASE_API_KEY=your-cdp-key-id       # CDP API key UUID
COINBASE_API_SECRET=your-base64-secret  # Base64-encoded Ed25519 key (64 bytes)
```

When set, the middleware authenticates CDP settlement calls — required for the catalog write to succeed on first settlement.

### Configuration reference

```typescript theme={null}
requireX402Payment({
  price: '0.05',                    // Decimal USDC
  payTo: '0xYourWallet',            // Base wallet address
  testMode: true,                   // Use Base Sepolia (default: false)
  apiUrl: 'https://api.sandbox.delegare.dev/v1',
  resource: 'https://yourapi.com/api/endpoint', // Full URL — used as catalog key
  mimeType: 'application/json',
  maxTimeoutSeconds: 300,
  creditBundle: { ... }
});
```

### Accessing payment context

```typescript theme={null}
app.get('/premium-data',
  requireX402Payment({ price: '0.05', payTo: '0xYourWallet' }),
  (req, res) => {
    const payer = (req as any).x402Payer;        // Payer's wallet address
    const txHash = (req as any).x402Transaction;  // On-chain tx hash
    res.json({ data: '...', paidBy: payer });
  }
);
```

Read the [x402 Middleware Documentation](/sdk-tools/x402-middleware) for the full configuration reference and fiat bundle setup.

***

## For Agents: Seamlessly Paying Paywalls

Replace standard `fetch` calls with `delegare.fetch`. When the API returns a 402, the SDK resolves it automatically using the user's intent mandate.

```typescript theme={null}
import { Delegare } from '@delegare/sdk';

const delegare = new Delegare({ merchantId: '...', apiKey: '...' });

// If the API returns a 402, the SDK auto-pays and retries — no popups.
const response = await delegare.fetch(
  'https://merchant.com/premium-data',
  { method: 'GET' },
  userIntentMandate
);
```

### How the SDK resolves x402

1. Makes the initial request.
2. On `402`, sends the intent mandate via `X-DELEGARE-MANDATE`.
3. Merchant middleware forwards to Delegare for settlement.
4. Delegare settles on-chain via the mandate's KMS-encrypted session key.
5. SDK returns the final response with the gated data.

The agent never holds private keys. The session key is scoped to the individual mandate — not accessible to the agent, merchant, or Delegare.

### x402 v2 clients (`@x402/fetch`)

Agents using Coinbase's `@x402/fetch` client send a `PAYMENT-SIGNATURE` credential. The middleware routes this to the CDP Facilitator, which also triggers Bazaar indexing on first settlement.

### Model Context Protocol (MCP)

If your agent runs on MCP (Claude, ChatGPT, or any MCP-compatible client), the `delegare_fetch` tool handles x402 automatically:

```
"Fetch the data from https://merchant.com/premium-data using my mandate"
```

No code required — the MCP server resolves the 402 challenge behind the scenes.

***

## Discovery: How Agents Find Your API

`declareDiscoveryExtension` embeds metadata in every 402 response. Three directories index it:

| Platform                                           | Protocol      | Header read        | How to appear                            |
| -------------------------------------------------- | ------------- | ------------------ | ---------------------------------------- |
| [market.delegare.dev](https://market.delegare.dev) | x402 v2 + MPP | Both               | Auto-aggregated from the two below       |
| [agentic.market](https://agentic.market)           | x402 v2       | `PAYMENT-REQUIRED` | Auto on first CDP Facilitator settlement |
| [mppscan.com](https://mppscan.com)                 | MPP/RFC 7235  | `WWW-Authenticate` | Register at mppscan.com/register         |

Delegare Market is the primary destination — it aggregates x402 and MPP endpoints from both upstream sources. Agents using the Delegare SDK or searching via Claude/ChatGPT tools query it in one request.

All three read `inputSchema` and `outputSchema` from the metadata to show agents what parameters your endpoint accepts and what it returns.
