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

# X402

> 无需 API 密钥即可访问 Venice API —— 通过 x402 协议按请求付费，并使用 Base 上的加密钱包进行身份验证。

X402 让您通过钱包认证并维护预付的 USDC 余额来使用 Venice 的付费 API 路由。无需 API 密钥或账户。签署一条消息、在 Base 或 Solana 上充值，即可调用任何支持的路由。

<CardGroup cols={3}>
  <Card title="钱包认证" icon="wallet">
    在 `X-Sign-In-With-X` 头中使用已签名的 Sign-In-With-X 负载进行身份验证。
  </Card>

  <Card title="使用 USDC 付款" icon="coins">
    使用 Base 或 Solana 上的 USDC 维护可消费余额。
  </Card>

  <Card title="DIEM 优先" icon="sparkles">
    如果钱包链接到有 DIEM 余额的 Venice 账户，会优先消费 DIEM。
  </Card>
</CardGroup>

## 什么是 X402？

[X402](https://www.x402.org/) 是一个开放的支付标准，让应用程序和 agent 可以使用加密货币以编程方式支付服务。Venice 实现了 X402，使钱包可以在 Base 或 Solana 上直接使用 USDC 进行推理认证和支付。

## 前置条件

* 在 Base 或 Solana 上的钱包
* 所选链的 gas 原生代币，例如 Base 上的 ETH 或 Solana 上的 SOL
* 所选链上的 USDC（或来自已链接 Venice 账户的现有 DIEM 支持余额）

<Tip>
  考虑为自动化使用专用钱包，而不是您的主资金钱包。
</Tip>

## 快速开始

[`venice-x402-client`](https://github.com/veniceai/x402-client) SDK 提供了钱包认证、充值和余额跟踪的辅助函数。

```bash theme={"system"}
npm install venice-x402-client
```

```typescript theme={"system"}
import { VeniceClient } from 'venice-x402-client'

const venice = new VeniceClient(process.env.WALLET_KEY)

await venice.topUp(10) // skip if the wallet already has spendable balance

const response = await venice.chat({
  model: 'kimi-k2-5',
  messages: [{ role: 'user', content: 'Hello!' }]
})
```

客户端为每个请求生成新的 `X-Sign-In-With-X` 头，并自动从 `X-Balance-Remaining` 响应头跟踪余额。

### 与 OpenAI 兼容工具配合使用

如果您使用接受自定义 `fetch` 的工具，使用 `createAuthFetch` 为任何请求添加钱包认证：

```typescript theme={"system"}
import { createAuthFetch } from 'venice-x402-client'

const authFetch = createAuthFetch(process.env.WALLET_KEY)
```

### 可用辅助函数

SDK 包括最常见 Venice x402 路由的一流辅助函数。对于未覆盖的内容，直接使用 `request()` 或 `createAuthFetch()`。

| 类别         | 方法                                                                                                                             |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------ |
| Chat       | `chat()`、`chatStream()`                                                                                                        |
| Responses  | `responses.create()`、`responses.stream()`                                                                                      |
| Images     | `images.generate()`、`images.generations()`、`images.upscale()`、`images.edit()`、`images.multiEdit()`、`images.backgroundRemove()` |
| Audio      | `audio.speech()`、`audio.transcribe()`、`audio.queue()`、`audio.retrieve()`、`audio.complete()`                                    |
| Video      | `video.queue()`、`video.retrieve()`、`video.generate()`、`video.complete()`、`video.transcribe()`                                  |
| Embeddings | `embeddings()`                                                                                                                 |
| Models     | `models()`                                                                                                                     |
| Wallet     | `getBalance()`、`getTransactions()`、`topUp()`                                                                                   |

***

## 手动流程

如果您不使用 SDK 或需要了解底层协议，下面是逐步流程。对于新钱包，假设您需要先充值，除非它已经有可消费的 DIEM 余额。

### 步骤 1：创建 X-Sign-In-With-X 头

Venice 期望一个 Base64 编码的 JSON 负载，包含已签名的 Sign-In-With-X 消息。EVM 钱包在 Base 上签署 EIP-4361 SIWE 消息。Solana 钱包使用 Ed25519 签署 Solana SIWX 消息。为每个请求流程生成新的 nonce 和时间戳。

对于 Solana，将 `chainId` 设置为 `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`，在编码的 JSON 负载中包含 `type: "ed25519"`，并以 base58 或 base64 提供 Ed25519 签名。已签名消息以 `<domain> wants you to sign in with your Solana account:` 开头，后跟钱包地址和标准 `URI`、`Version`、`Chain ID`、`Nonce`、`Issued At` 和可选的 `Expiration Time` 字段。

```typescript theme={"system"}
import { Wallet } from 'ethers'
import { SiweMessage, generateNonce } from 'siwe'

const wallet = new Wallet(process.env.EVM_PRIVATE_KEY)
const now = new Date()
const resourceUrl = 'https://api.venice.ai/api/v1/chat/completions'

const siwe = new SiweMessage({
  domain: 'api.venice.ai',
  address: wallet.address,
  statement: 'Sign in to Venice AI',
  uri: resourceUrl,
  version: '1',
  chainId: 8453,
  nonce: generateNonce(),
  issuedAt: now.toISOString(),
  expirationTime: new Date(now.getTime() + 5 * 60 * 1000).toISOString(),
})

const message = siwe.prepareMessage()
const signature = await wallet.signMessage(message)

const xSignInWithX = Buffer.from(
  JSON.stringify({
    address: wallet.address,
    message,
    signature,
    timestamp: now.getTime(),
    chainId: 8453,
  }),
  'utf8',
).toString('base64')

console.log(xSignInWithX)
```

### 步骤 2：检查余额

在发出付费请求之前，验证钱包是否有可消费余额：

```bash theme={"system"}
export WALLET_ADDRESS=0xYOUR_WALLET_ADDRESS_OR_SOLANA_ADDRESS
export X402_AUTH=YOUR_BASE64_SIWX_HEADER

curl --request GET \
  --url "https://api.venice.ai/api/v1/x402/balance/$WALLET_ADDRESS" \
  --header "X-Sign-In-With-X: $X402_AUTH"
```

响应包括：

* `canConsume`：钱包是否可以发出付费请求
* `balanceUsd`：当前可消费余额
* `minimumTopUpUsd` 和 `suggestedTopUpUsd`：充值指引
* `diemBalanceUsd`：DIEM 支持余额（如有）

`walletAddress` 路径参数接受 EVM 地址（`0x...`）或 Solana base58 地址。

### 步骤 3：充值

使用 Base 或 Solana 上的 USDC 充值：

```bash theme={"system"}
curl --request POST \
  --url https://api.venice.ai/api/v1/x402/top-up
```

首次调用返回 `402 Payment Required`，带有包含 `accepts` 数组的 `PAYMENT-REQUIRED` 头。每个条目描述一个接受的支付选项，包括 `network`、`asset`、`payTo` 和 `amount`。选择您要支付的 Base 或 Solana 选项，使用这些精确详情构建 `X-402-Payment` 头，并重试相同的路由。

#### 为 Base 构建 X-402-Payment 头

以下脚本在 Base 上创建已签名的 x402 支付并发送充值请求。需要 `x402` 和 `viem` npm 包。

```bash theme={"system"}
export EVM_PRIVATE_KEY=0xYOUR_PRIVATE_KEY
```

```bash theme={"system"}
export X402_PAYMENT="$(
node --input-type=module <<'EOF'
import { createPaymentHeader } from "x402/client";
import { privateKeyToAccount } from "viem/accounts";

const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY);
const amountUsd = 5;
const amountBaseUnits = String(Math.round(amountUsd * 1e6));

const header = await createPaymentHeader(signer, 2, {
  scheme: "exact",
  network: "base",
  maxAmountRequired: amountBaseUnits,
  resource: "https://api.venice.ai/api/v1/x402/top-up",
  description: "Venice x402 top-up",
  mimeType: "application/json",
  payTo: "0x2670B922ef37C7Df47158725C0CC407b5382293F",
  maxTimeoutSeconds: 300,
  asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  extra: { name: "USD Coin", version: "2" },
});

process.stdout.write(header);
EOF
)"

curl -X POST "https://api.venice.ai/api/v1/x402/top-up" \
  -H "X-402-Payment: $X402_PAYMENT"
```

<Note>
  在生产环境中，使用最新的 `PAYMENT-REQUIRED` / `accepts` 响应作为权威来源，而不是硬编码这些值。对于 Solana 充值，从 `accepts` 中返回的 Solana 条目构建支付。Solana 条目使用 `network: "solana"`、USDC mint 作为 `asset`，并可能包括网络特定元数据，如 `extra.feePayer`。
</Note>

### 步骤 4：发出请求

一旦钱包有可消费余额，使用 `X-Sign-In-With-X` 头调用任何支持的端点：

```bash theme={"system"}
export X402_AUTH=YOUR_BASE64_SIWX_HEADER

curl --request POST \
  --url https://api.venice.ai/api/v1/chat/completions \
  --header "Content-Type: application/json" \
  --header "X-Sign-In-With-X: $X402_AUTH" \
  --data '{
    "model": "kimi-k2-5",
    "messages": [
      {
        "role": "user",
        "content": "Hello from an x402-authenticated wallet."
      }
    ]
  }'
```

成功响应可能包含 `X-Balance-Remaining` 头。

### 步骤 5：检查交易（可选）

查看钱包的交易历史：

```bash theme={"system"}
export WALLET_ADDRESS=0xYOUR_WALLET_ADDRESS_OR_SOLANA_ADDRESS
export X402_AUTH=YOUR_BASE64_SIWX_HEADER

curl --request GET \
  --url "https://api.venice.ai/api/v1/x402/transactions/$WALLET_ADDRESS?limit=10&offset=0" \
  --header "X-Sign-In-With-X: $X402_AUTH"
```

账本包括 `TOP_UP`、`CHARGE` 和 `REFUND` 等条目。

`walletAddress` 路径参数接受 EVM 地址（`0x...`）或 Solana base58 地址。

***

## 支持的路由

### 付费推理路由

以下公开付费 Venice 路由当前支持 x402 钱包认证。

| 类别         | 端点                                                                                                                                                                                            |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Chat       | `POST /api/v1/chat/completions`、`POST /api/v1/responses`                                                                                                                                      |
| Image      | `POST /api/v1/image/generate`、`POST /api/v1/images/generations`、`POST /api/v1/image/upscale`、`POST /api/v1/image/edit`、`POST /api/v1/image/multi-edit`、`POST /api/v1/image/background-remove` |
| Embeddings | `POST /api/v1/embeddings`                                                                                                                                                                     |
| Audio      | `POST /api/v1/audio/speech`、`POST /api/v1/audio/transcriptions`、`POST /api/v1/audio/complete`、`POST /api/v1/audio/queue`、`POST /api/v1/audio/retrieve`                                        |
| Video      | `POST /api/v1/video/complete`、`POST /api/v1/video/queue`、`POST /api/v1/video/retrieve`、`POST /api/v1/video/transcriptions`                                                                    |

### 充值路由

| 端点                         | 认证                        | 用途                                              |
| -------------------------- | ------------------------- | ----------------------------------------------- |
| `POST /api/v1/x402/top-up` | 首次请求：无。重试：`X-402-Payment` | 使用接受的 Base 或 Solana 支付选项向钱包的可消费余额添加 USDC credit |

### 仅钱包路由

这些路由使用 `X-Sign-In-With-X` 进行身份识别，但不收取余额。

| 端点                                              | 用途                         |
| ----------------------------------------------- | -------------------------- |
| `GET /api/v1/x402/balance/{walletAddress}`      | 检查 EVM 或 Solana 钱包地址的可消费余额 |
| `GET /api/v1/x402/transactions/{walletAddress}` | 查看 EVM 或 Solana 钱包地址的交易历史  |

***

## 错误

| 状态                     | 可能原因                      | 应对方式                                 |
| ---------------------- | ------------------------- | ------------------------------------ |
| `401`                  | Sign-In-With-X 负载格式错误或已过期 | 使用新的 nonce 和时间戳重建 `X-Sign-In-With-X` |
| 付费路由上 `402`            | 可消费余额不足                   | 充值并重试                                |
| `/x402/top-up` 上 `402` | 预期。这是支付发起流程。              | 使用返回的支付详情构建 `X-402-Payment` 并重试      |
| 余额或交易上 `403`           | 钱包不匹配                     | 确保已认证钱包与 `walletAddress` 路径参数匹配      |
| 充值上 `400`              | 支付头格式错误                   | 从最新的 `402` 响应重建                      |

***

## 对于 agent

流程相同。将私钥存储在环境变量或机密管理器中，并在请求之前检查余额，以避免不必要的 `402` 往返。

***

## 相关资源

<CardGroup cols={2}>
  <Card title="x402 客户端 SDK" icon="npm" href="https://github.com/veniceai/x402-client">
    官方 Venice x402 Node.js/TypeScript 客户端。
  </Card>

  <Card title="API 定价" icon="coins" href="/overview/pricing">
    查看模型定价以及 Venice 如何收取使用费用。
  </Card>

  <Card title="Chat Completions" icon="message" href="/api-reference/endpoint/chat/completions">
    用于基于钱包访问的常见付费路由。
  </Card>

  <Card title="API 规范" icon="code" href="/api-reference/api-spec">
    参考文档和原始规范访问。
  </Card>
</CardGroup>
