> For the complete documentation index, see [llms.txt](https://developers.coincircuit.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.coincircuit.io/promp-library/x402-api-monetization.md).

# x402 API monetization

Charge agents per request with x402 and CoinCircuit settlement.

Use this prompt to gate API access behind x402 payments and settle agent-signed authorizations through CoinCircuit.

`x402` `Agent Payments` `Payments` `Node.js`

### What this prompt covers

* Create per-request payment sessions
* Return `402` responses with payment details
* Verify and settle signed agent payments on-chain

{% code title="x402-api-monetization.prompt.md" expandable="true" collapsedlinecount="20" %}

````markdown
You are helping me add per-request crypto payments to my existing API using the x402 protocol and CoinCircuit for settlement. I have the CoinCircuit MCP server connected.

**If you have access to the CoinCircuit MCP server, call these tools for the most accurate and detailed schema outputs:**
- Call `get_api_overview` in the CoinCircuit MCP for base URLs, auth method, and available features.
- Call `get_endpoint` with method `post` and path `/api/v1/payments` for the checkout session creation schema.
- Call `get_endpoint` with method `post` and path `/api/v1/payments/agent/settle` for the agent settlement schema.
- Call `get_endpoint` with method `post` and path `/api/v1/payments/agent/verify` for the pre-validation schema.
- Call `search_api` with query `agent settle` and type `endpoints` to find all agent payment endpoints.
- Call `get_schema` with name `PaymentCompletedWebhookDto` for the payment.completed webhook payload.

Use the live MCP data as your source of truth. The details below are a guide, but if the MCP returns something different, trust the MCP.

## API Basics

- **Base URL (production):** `https://api.coincircuit.io`
- **Base URL (sandbox):** `https://sandbox-api.coincircuit.io`
- **Auth:** Pass your API key in the `x-api-key` header on every request.

## Project Context

I have an API backend and I'm adding x402 payment gating so AI agents pay per-request. The flow:

1. Agent hits a paid endpoint on my API
2. My server creates a CoinCircuit payment session for the resource price
3. Returns a 402 response with the payment details (deposit address, amount, chain)
4. Agent signs the payment and sends it back
5. My server submits the signed payload to CoinCircuit for on-chain settlement
6. Delivers the resource once settlement confirms

The agent only needs a wallet and signing key. No CoinCircuit API key, no gas tokens.

## What I Need You to Implement

### 1. Middleware: check for payment

Create middleware that intercepts requests to paid endpoints. If the request has no payment proof, proceed to step 2 (create session + return 402). If it includes a signed payload, proceed to step 5 (settle).

### 2. Create a payment session

When an agent hits a paid endpoint without payment:

**Endpoint:** `POST /api/v1/payments`
*(Call `get_endpoint` with method `post`, path `/api/v1/payments`, section `request` in the CoinCircuit MCP for the full request body.)*

```json
{
  "amount": "1.00",
  "currency": "USD",
  "title": "API call - /api/premium-data",
  "description": "Single API request",
  "asset": "USDC",
  "chain": "base",
  "customer": {
    "email": "agent@example.com"
  },
  "metadata": {
    "endpoint": "/api/premium-data",
    "agentWallet": "0xAgentAddress..."
  }
}
```

**Response (201):** Returns a session object with:
- `data.reference` - session reference (keep this server-side for settlement)
- `data.payment.address` - the deposit address
- `data.payment.amount` - the required crypto amount
- `data.expiresAt` - session expiration

*(Call `get_endpoint` with method `post`, path `/api/v1/payments`, section `success` in the CoinCircuit MCP for the full response.)*

### 3. Return the 402 response

Send the payment details back to the agent. Your server stores the session reference internally, keyed by the deposit address or a short-lived token, so you can match the agent's payment to the session.

### 4. Agent signs the payment (client-side reference)

The agent picks a signing scheme and produces a flat payload. Each scheme produces a payload with `from`, `to`, `value`, and scheme-specific fields:

- **EIP-3009:** `validAfter`, `validBefore`, `nonce` (random 32-byte hex), `signature`
- **Permit2:** `deadline`, `nonce` (numeric), `signature`
- **Solana:** `transaction` (base64 partially signed tx)

The agent sends this back to your server.

### 5. Pre-validate the payment (optional but recommended)

Before settling, dry-run the payment:

**Endpoint:** `POST /api/v1/payments/agent/verify`
*(Call `get_endpoint` with method `post`, path `/api/v1/payments/agent/verify` in the CoinCircuit MCP for the full schema.)*

Returns 200 if the payment will succeed, or 400 with per-check pass/fail results. Catches issues like insufficient balance, expired nonces, and invalid signatures before touching the blockchain.

### 6. Settle the payment on-chain

**Endpoint:** `POST /api/v1/payments/agent/settle`
*(Call `get_endpoint` with method `post`, path `/api/v1/payments/agent/settle` in the CoinCircuit MCP for the full request/response schema.)*

**Always include `sessionReference` from step 2 in the settle request.** CoinCircuit uses it to verify the signed payment against the original session's required amount, deposit address, chain, and asset. Without it, these checks are skipped and the payment is not validated against the session. Also include the scheme, chain, asset, and the signed payload. CoinCircuit submits the transaction on-chain, covers gas, and returns the transaction hash and block confirmation.

### 7. Deliver the resource

Once the settle response confirms success, return the requested data to the agent along with the transaction hash as a receipt.

### Integration Flow Summary

```
Agent -> GET /api/premium-data
Server -> CoinCircuit: POST /payments (creates session)
Server -> Agent: 402 (deposit address, amount, schemes)
Agent -> Signs payment (eip3009 / permit2 / solana)
Agent -> Server: POST /api/premium-data/pay (signed payload)
Server -> CoinCircuit: POST /payments/agent/verify (optional)
Server -> CoinCircuit: POST /payments/agent/settle
Server -> Agent: 200 (resource + tx receipt)
```

### Supported Chains and Assets

| Scheme | Asset | Chains |
|--------|-------|--------|
| eip3009 | USDC | Base, Arbitrum |
| permit2 | USDC, USDT | Base, Arbitrum, BSC |
| solana | SOL, USDC, USDT | Solana |

## Constraints

- **Always pass `sessionReference` in the settle call.** This is how CoinCircuit verifies the payment matches the session's required amount, deposit address, chain, and asset. Without it, those checks are skipped.
- The agent signs the authorization, but your server submits it. This lets you control the session lifecycle and validate amounts before settlement.
- The agent needs no CoinCircuit API key and no gas tokens. It only needs a wallet and signing capability.
- Session `amount` is a **string** in fiat (e.g. `"1.00"`)
- Always use the verify endpoint first in production to catch bad signatures before spending gas
- Solana transactions expire in ~60 seconds based on the blockhash. Generate the session close to when the agent will sign.
- EIP-3009 nonces are random 32-byte hex values. Permit2 nonces are numeric.
- For Permit2, the agent must have done a one-time on-chain approval of the Permit2 contract (`0x000000000022D473030F116dDEE9F6B43aC78BA3`) for the token
- All EVM networks offer sub-second block times and gas costs under a cent. Solana settles in under a second with fees below $0.001.
````

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developers.coincircuit.io/promp-library/x402-api-monetization.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
