# Token4u API Reference

**Base URL:** `https://token4u.ai`

Token4u provides an OpenAI-compatible chat completions API with two authentication modes: traditional API keys and x402 pay-per-request micropayments (USDC on Base).

## Authentication

Token4u supports two authentication methods:

### Option A: Use an API Key (Billing via Account Balance)

Create a token in the [Console](https://token4u.ai/console) and send it as a bearer credential. Charges are deducted from your account quota.

```bash
curl https://token4u.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{
    "model": "deepseek/deepseek-v4-flash",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
```

### Option B: Use x402 Pay-Per-Request (Billing via USDC, No API Key)

Send requests without an `Authorization` header, and the server will respond with `HTTP 402 Payment Required` containing x402 v2 payment terms. Sign the EIP-3009 `TransferWithAuthorization` and include it in the next request.

## Quick Start

### cURL Example

```bash
curl https://token4u.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-your-api-key" \
  -d '{
    "model": "deepseek/deepseek-v4-flash",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What is the capital of France?"}
    ],
    "temperature": 0.7,
    "max_tokens": 100
  }'
```

### Response

```json
{
  "id": "chatcmpl-abc123...",
  "object": "chat.completion",
  "created": 1700000000,
  "model": "deepseek/deepseek-v4-flash",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The capital of France is Paris."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 27,
    "completion_tokens": 8,
    "total_tokens": 35
  }
}
```

## MCP Usage (token4u-mcp)

Token4u provides an open-source MCP server — [token4u-mcp](https://www.npmjs.com/package/token4u-mcp) v0.3.0 — that enables AI agents to call LLM APIs and query consumption records through x402 micropayments. Pure external x402 mode: wallet private key is managed locally (`~/.token4u-mcp/wallet.json`, `0o600`), no Token4u account required.

### Installation

**npx (recommended):**
```bash
claude mcp add token4u-mcp -- npx -y token4u-mcp
```

**Local build:**
```bash
npm install && npm run build
```

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `TOKEN4U_API_URL` | `https://token4u.ai` | Token4u API base URL |
| `TOKEN4U_WALLET_KEY` | (optional) | Wallet private key; takes precedence over wallet file |
| `TOKEN4U_BUDGET_LIMIT` | (optional) | USD budget cap for automatic payment approval |
| `TOKEN4U_DATA_DIR` | `~/.token4u-mcp` | Data directory for wallet and configuration |

### Tools

#### `token4u_wallet` — Local Wallet Management

Manage a local x402 wallet for USDC micropayments.

| Action | Description |
|--------|-------------|
| `action=status` | Query wallet status (address, USDC balance) |
| `action=create` | Generate or load a private key from `~/.token4u-mcp/wallet.json` |
| `action=setup` | Get funding instructions (wallet address + deposit guidance) |

#### `token4u_chat` — Paid LLM Call

Make an x402-paid LLM API call. The MCP server handles the 402 flow and EIP-3009 signing automatically.

```
model: deepseek-v3
messages: [{"role": "user", "content": "Hello!"}]
```

#### `token4u_consumption` — Consumption Records

Query on-chain x402 payment history. Public API — no login required.

```
address: 0x...
page: 1
```

### Quick Funding Guide

1. **Create wallet** — use `token4u_wallet` with `action=create`
2. **Get address** — use `token4u_wallet` with `action=setup` to get your deposit address
3. **Send USDC** — transfer USDC (Base) to the address shown
4. **Verify balance** — check on [BaseScan](https://basescan.org) or use `token4u_wallet` with `action=status`

### Security

- Private key is stored locally at `~/.token4u-mcp/wallet.json` with `0o600` permissions and **never uploaded**
- No Token4u account required — all payments are fully on-chain USDC
- Budget limit (`TOKEN4U_BUDGET_LIMIT`) prevents overspending

### Links

- **Product page:** [https://token4u.ai/mcp](https://token4u.ai/mcp)
- **npm:** [https://www.npmjs.com/package/token4u-mcp](https://www.npmjs.com/package/token4u-mcp)
- **GitHub:** [https://github.com/Token4uAi/token4u-mcp](https://github.com/Token4uAi/token4u-mcp)

## Request Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `model` | string | Yes | - | Model ID (see model list below) |
| `messages` | array | Yes | - | Array of message objects |
| `messages[].role` | string | Yes | - | `system`, `user`, or `assistant` |
| `messages[].content` | string | Yes | - | Message content |
| `temperature` | number | No | 1 | Sampling temperature (0-2) |
| `max_tokens` | integer | No | - | Maximum tokens to generate |
| `stream` | boolean | No | false | Enable streaming (SSE) |
| `top_p` | number | No | 1 | Nucleus sampling parameter |
| `frequency_penalty` | number | No | 0 | Frequency penalty (-2 to 2) |
| `presence_penalty` | number | No | 0 | Presence penalty (-2 to 2) |

## Models & Pricing

Prices shown are per 1 million input tokens / per 1 million output tokens in USD.

> **实时完整清单**：见 [`GET /api/pricing`](https://token4u.ai/api/pricing)（含 105+ 个模型全量定价，本文为精选展示）。
> 所有价格均含 5% 平台 margin，来源为 `/api/pricing` 的 `price_per_1m_input_usd` / `price_per_1m_output_usd` 字段。

### DeepSeek

| Model | Input ($/1M) | Output ($/1M) | Context |
|-------|:-----------:|:------------:|:-------:|
| `deepseek/deepseek-v4-flash` | 0.14 | 0.28 | 1M |
| `deepseek/deepseek-v4-pro` | 0.435 | 0.87 | 1M |
| `deepseek-r1` | 0.50 | 2.15 | 128K |
| `deepseek-v3.1` | 0.56 | 1.68 | 128K |
| `deepseek/deepseek-v3.2-251201` | 0.27 | 0.40 | 128K |

### Z.AI (GLM)

| Model | Input ($/1M) | Output ($/1M) | Context |
|-------|:-----------:|:------------:|:-------:|
| `z-ai/glm-5.2` | 0.82 | 2.57 | 1M |
| `z-ai/glm-5.1` | 0.97 | 3.04 | 200K |
| `z-ai/glm-5` | 0.56 | 0.56 | 200K |
| `z-ai/glm-4.7` | 0.40 | 1.75 | 128K |
| `glm-4.5` | 0.60 | 2.20 | 128K |
| `glm-4.5-air` | 0.18 | 0.18 | 128K |

### Qwen (DashScope)

| Model | Input ($/1M) | Output ($/1M) | Context |
|-------|:-----------:|:------------:|:-------:|
| `qwen/qwen3.7-max` | 1.48 | 4.42 | 1M |
| `qwen3.5-flash` | 0.065 | 0.26 | 131K |
| `qwen-plus` | 0.07 | 0.28 | 128K |

### MiniMax

| Model | Input ($/1M) | Output ($/1M) | Context |
|-------|:-----------:|:------------:|:-------:|
| `minimax/minimax-m3` | 0.30 | 1.20 | 1M |
| `minimax/minimax-m2.5` | 0.25 | 1.00 | 200K |

### Moonshot (Kimi)

| Model | Input ($/1M) | Output ($/1M) | Context |
|-------|:-----------:|:------------:|:-------:|
| `moonshotai/kimi-k3` | 3.00 | 15.00 | 1M |
| `moonshotai/kimi-k2.5` | 0.57 | 2.85 | 128K |

### Other Models

| Model | Input ($/1M) | Output ($/1M) | Provider |
|-------|:-----------:|:------------:|:--------:|
| `anthropic/claude-fable-5` | 10.00 | 50.00 | Anthropic |
| `openai/gpt-5.6-sol` | 5.00 | 30.00 | OpenAI |

All prices include a 5% platform margin. The actual on-chain amount may vary slightly due to the x402 pricing formula.

## x402 Payment Flow

Token4u supports the [x402 protocol](https://x402.org) for pay-per-request AI inference. This enables AI agents to make API calls without API keys — payment is handled automatically through USDC on Base (Ethereum L2).

### Payment Schemes

Token4u serves multiple x402 payment schemes simultaneously. The `accepts` array in the 402 response lists all available options:

| Scheme | Facilitator | How to pay |
|--------|-------------|-----------|
| `exact` | Coinbase CDP (`payTo` 0x3ccC...) | EIP-3009 TransferWithAuthorization for exact USDC amount on Base |
| `exact` | PayAI (`payTo` 0x6D20...) | Same as above, different recipient |
| `upto` (default) | Coinbase CDP (`payTo` 0x3ccC...) | EIP-3009 TransferWithAuthorization with prepaid amount + session resuming |
| `upto` | PayAI (`payTo` 0x6D20...) | Same as above, different recipient |
| `nvm:erc4337` | Nevermined | ERC-4337 UserOperation via Nevermined smart accounts |

Choose any `accepts` entry that fits your wallet — sign the EIP-3009 authorization to that entry's `payTo`, and the server routes settlement to the matching facilitator.

### Flow Summary

```
Agent → Token4u: POST /v1/chat/completions (no auth)
Token4u → Agent: 402 Payment Required + x402 terms (multiple accepts)
Agent → Wallet: Sign EIP-3009 TransferWithAuthorization
Agent → Token4u: POST /v1/chat/completions + PAYMENT-SIGNATURE header
Token4u → Agent: 200 OK + AI response (settled on-chain after completion)
```

### Step-by-Step

1. **Send request without API key** → Get `402 Payment Required` with `PAYMENT-REQUIRED` header (base64 JSON containing payment terms)

2. **Parse terms** → Extract `amount`, `network` (eip155:8453 for Base), `asset` (USDC), `payTo` address from your chosen `accepts` entry

3. **Sign EIP-3009** → Create a `TransferWithAuthorization` from your wallet to the chosen `payTo` recipient

4. **Retry with payment** → Send original request again with base64-encoded payment in `PAYMENT-SIGNATURE` header

5. **Receive response** → Token4u verifies, fulfills the request, then settles on-chain after completion

### Exact Scheme: One-Shot Exact-Amount Payment

With the `exact` scheme, the 402 payment is a **one-shot exact amount** covering the full estimated cost:

1. **Single payment** — sign one EIP-3009 authorization for the quoted `amount`, no session resuming needed.

2. **No session management** — `exact` is simpler: one request, one payment, one response. If the request exceeds the estimate, the server may truncate or return an error.

3. **Best for** — short requests where the token estimate is reliably accurate, or when you prefer simplicity over the flexibility of `upto`'s session resuming.

### Upto Scheme: Prepaid-amount Billing & Session Resuming

With the `upto` scheme, the initial 402 payment is a **prepaid amount** (≈3× the estimated cost, shown as `amount` with `maxTokens` in `extra`). The full authorized amount is settled when the request completes. If your request consumes more than the prepaid allowance:

1. **Streaming interruption** — the response stream stops early with an x402 error indicating more funds are needed.

2. **Resume the session** — sign a new EIP-3009 authorization and retry the **same request** with the `X-402-RESUME: <session_id>` header (from the 402 error `resume_session` field):

```bash
curl https://token4u.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "X-402-RESUME: <session_id>" \
  -H "PAYMENT-SIGNATURE: <base64(payment)>" \
  -d '{"model": "deepseek/deepseek-v4-flash", "messages": [...], "stream": true}'
```

3. **Session limits** — each resume requires a new payment. The server enforces:
   - **DefaultMaxTopUp** (configurable, default $5): if your resume authorization exceeds this cap, the server returns `402` with `max_top_up_usd` / `requested_usd` in the error `extra` — re-authorize with an amount ≤ the cap.
   - **MaxResumeRetries** (default 3): after the limit, further resumes return `402 Resume retries exceeded`.
   - **SessionTTL** (default 600s): an expired session returns `402 Session expired`.

### Internal x402 (Server-Side Wallet)

Token4u supports **server-side x402 payments** for users who deposit USDC into their Token4u account balance. The server manages wallets internally — no EIP-3009 signing needed from the client. This is the default flow for API-key-authenticated requests on accounts with x402 enabled.

#### Flow

```
1. User deposits USDC → Token4u internal balance
2. API request arrives → server calculates max estimate price
3. Verify: InternalX402VerifyOnly() → server signs EIP-3009, submits to CDP verify endpoint (no on-chain transfer yet)
4. LLM responds → server calculates actual cost
5. Settle: InternalX402SettlePayment() → server signs fresh EIP-3009 with actual cost, submits to CDP settle
6. If LLM fails → InternalX402RefundPayment() refunds full pre-deducted amount to user balance
```

#### Key Functions (service/internal_x402_payment.go)

| Function | Purpose |
|----------|---------|
| `InternalX402VerifyOnly` | Pre-verify payment capacity without on-chain transfer. Signs EIP-3009 with max estimate, submits to CDP verify endpoint, creates a payment session. |
| `InternalX402SettlePayment` | After LLM responds: signs fresh EIP-3009 with actual cost, submits to CDP settle (up to 3 retries with backoff). Uses the `FacilitatorCDP` facilitator pinned. |
| `InternalX402RefundPayment` | Refunds full pre-deducted balance if payment cannot complete (LLM failure, timeout, etc.). |

#### Facilitator

Internal x402 always routes through **Coinbase CDP** — the facilitator is explicitly pinned to `FacilitatorCDP` in all signing calls, ensuring consistent routing regardless of recipient address.

### Nevermined Details (nvm:erc4337)

The `nvm:erc4337` scheme uses Nevermined's smart account infrastructure for ERC-4337 UserOperations.

#### Dynamic Credits

Token4u converts actual LLM token usage into Nevermined credits via `TokenUsageToCredits()` (`service/nevermined_billing.go`):

- **Exchange rate:** 10,000 credits = 1 USDC ($0.0001 per credit)
- **Formula:** `credits = ceil(costUSD × 10000)`
- Cost mirrors the x402 pricing formula: `(input_tokens + output_tokens) / 1M × ratio × $2 × 1.05` (ratio from `ratio_setting.ResolveRatioFromModel`, fallback 37.5)

#### Chain Auto-Detection

The Nevermined chain is automatically inferred from the deployment environment:

- **Sandbox/test:** `eip155:84532` (Base Sepolia testnet)
- **Live/production:** `eip155:8453` (Base mainnet)

This is controlled by `setting.NeverminedX402Chain()` in `setting/x402_setting.go` and ensures test payments don't accidentally hit mainnet.

#### Payer Smart Account

The Nevermined integration uses a dedicated payer smart account with delegation:

- **Payer address:** `0xFC7DC3097962D1006095B5c716E30D83273044dF`
- **Network:** Base (`eip155:8453` live, `eip155:84532` sandbox)
- **Mechanism:** ERC-4337 UserOperation via Nevermined's smart account infrastructure with delegated execution

### Minimum Payment

- **Minimum:** $0.003 USDC per request
- **Network:** Base (chain ID: 8453)
- **Token:** USDC (`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`)
- **Recipients:** `0x3ccC6565511f404716cAD2D578851ff3Ff95Fd85` (CDP), `0x6D20a02E3F6afE5465397380e10B974cEd8564E0` (PayAI)
- **Facilitators:** Coinbase CDP, PayAI, Nevermined

### Pricing Formula

Actual charge (USD) is calculated from token usage with a **$0.003 / request** floor:

```
charge = (input_tokens × input_price + output_tokens × output_price) / 1_000_000
final  = max(charge, $0.003)
```

- `input_price` = `price_per_1m_input_usd` (USD / 1M input tokens)
- `output_price` = `price_per_1m_output_usd` (USD / 1M output tokens)
- All in USD (USDC 1:1 pegged to USD), 5% platform margin included
- Reference: `x402MinPriceUsd = 0.003` in `service/x402_pricing.go:14`

## Admin API

The following endpoints are available to administrators (requires `AdminAuth`):

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/user/x402/payments` | GET | List all x402 payment records |
| `/api/user/x402/upto-sessions` | GET | List all upto payment sessions |
| `/api/user/x402/upto/config` | GET | Get current upto configuration (scheme, limits, TTL) |
| `/api/user/x402/upto/config` | PUT | Update upto configuration (enabled, scheme, maxTopUp, maxRetries, sessionTTL) |
| `/api/user/x402/upto/sessions/:id` | GET | Get detailed info for a specific upto session |
| `/api/user/x402/upto/statistics` | GET | Get aggregate upto payment statistics |

All admin endpoints are under `/api/user/x402/` and require the `AdminAuth` middleware.

## Security

### Nonce Replay Protection

Every EIP-3009 `TransferWithAuthorization` includes a unique 32-byte nonce. Token4u tracks used nonces in the `X402Nonce` database table to prevent replay attacks:

- **Table:** `X402Nonce` (columns: `nonce_key` primary key, `address`, `created_at`)
- **Verification:** Before processing any payment, `IsX402NonceUsed(nonceKey)` checks if the nonce has been seen
- **Marking:** After successful use, `MarkX402NonceUsed(nonceKey, address)` records the nonce
- If a nonce is reused, the server returns `402 invalid_payment` with a replay rejection

### LLM Failure Protection

If the LLM fails to generate a valid response (API error, timeout, content safety block), the payment is **cancelled and no funds are deducted**:

- **External x402:** The EIP-3009 authorization is not settled — funds never leave the user's wallet
- **Internal x402:** `InternalX402RefundPayment()` refunds the full pre-deducted amount back to the user's balance
- **Nevermined:** Payment is not settled (logged as "nevermined LLM failed, payment not settled")

This ensures users are never charged for failed or empty AI responses.

## Well-Known Endpoints

Token4u exposes standard discovery endpoints for AI agent integration:

| URL | Description |
|-----|-------------|
| `/.well-known/x402` | x402 protocol discovery (redirects to `/api/.well-known/x402`) |
| `/.well-known/ai-plugin.json` | AI plugin manifest (redirects to `/ai-plugin.json`) |
| `/.well-known/agent.json` | AI agent capability declaration |

The `/api/.well-known/x402` endpoint returns the full x402 v2 payment terms including per-model pricing via `services[0].pricing`.

## Streaming

Token4u supports Server-Sent Events (SSE) streaming:

```bash
curl https://token4u.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-your-api-key" \
  -d '{
    "model": "deepseek/deepseek-v4-flash",
    "messages": [{"role": "user", "content": "Tell me a story"}],
    "stream": true
  }'
```

Each event follows the format:

```
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"content":"Once"},"index":0}]}

data: [DONE]
```

## Error Codes

| HTTP Status | Code | Description |
|:-----------:|------|-------------|
| 200 | - | Success |
| 400 | invalid_request_error | Invalid request parameters |
| 401 | invalid_api_key | Invalid or missing API key |
| 402 | payment_required | x402 payment required |
| 402 | invalid_payment | Payment signature verification failed (including nonce replay) |
| 402 | insufficient_payment | Streaming top-up needed (upto scheme) — resume with `X-402-RESUME` |
| 402 | Session expired | Upto session TTL elapsed — start a new request |
| 402 | Resume retries exceeded | MaxResumeRetries reached — start a new request |
| 402 | top-up limit | Authorization over DefaultMaxTopUp — re-authorize ≤ cap (`max_top_up_usd` in error) |
| 429 | rate_limit_error | Rate limit exceeded |
| 500 | api_error | Internal server error |
| 503 | service_unavailable | Service temporarily unavailable |

## Rate Limits

Token4u applies rate limits based on your API key tier. Default limits:

- **Standard:** 60 RPM (requests per minute)
- **Premium:** 300 RPM
- **Enterprise:** Custom limits

Contact support for higher rate limits.

## Support

- **Email:** support@token4u.ai
- **x402 Protocol:** [https://x402.org](https://x402.org)
- **Block Explorer:** [BaseScan](https://basescan.org)
- **API Discovery:** `/.well-known/x402` | `/.well-known/agent.json`
- **API Reference (Scalar):** [https://token4u.ai/docs/api](https://token4u.ai/docs/api)
