> ## 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

> Access the Venice API without an API key by paying per request with the x402 protocol and authenticating with a crypto wallet on Base.

X402 lets you use Venice's paid API routes by authenticating with a wallet and maintaining a prepaid USDC balance. No API key or account required. Sign a message, top up on Base or Solana, and call any supported route.

<CardGroup cols={3}>
  <Card title="Wallet Auth" icon="wallet">
    Authenticate with a signed Sign-In-With-X payload in the `X-Sign-In-With-X` header.
  </Card>

  <Card title="Pay with USDC" icon="coins">
    Maintain spendable balance with USDC on Base or Solana.
  </Card>

  <Card title="DIEM First" icon="sparkles">
    If the wallet is linked to a Venice account with DIEM balance, that is spent first.
  </Card>
</CardGroup>

## What is X402?

[X402](https://www.x402.org/) is an open payment standard that lets applications and agents pay for services programmatically using cryptocurrency. Venice implements X402 so that wallets can authenticate and pay for inference directly with USDC on Base or Solana.

## Prerequisites

* A wallet on Base or Solana
* Native token for gas on the selected chain, such as ETH on Base or SOL on Solana
* USDC on the selected chain (or existing DIEM-backed balance from a linked Venice account)

<Tip>
  Consider using a dedicated wallet for automation rather than your main treasury wallet.
</Tip>

## Quick start

The [`venice-x402-client`](https://github.com/veniceai/x402-client) SDK provides helpers for wallet auth, top-ups, and balance tracking.

```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!' }]
})
```

The client generates a fresh `X-Sign-In-With-X` header for each request and automatically tracks balance from `X-Balance-Remaining` response headers.

### With OpenAI-compatible tools

If you're using a tool that accepts a custom `fetch`, use `createAuthFetch` to add wallet auth to any request:

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

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

### Available helpers

The SDK includes first-class helpers for the most common Venice x402 routes. For anything not covered, use `request()` or `createAuthFetch()` directly.

| Category   | Methods                                                                                                                             |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| 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()`                                                                                      |

***

## Manual flow

If you're not using the SDK or need to understand the underlying protocol, here's the step-by-step flow. For a new wallet, assume you need to top up first unless it already has spendable DIEM balance.

### Step 1: Create the X-Sign-In-With-X header

Venice expects a Base64-encoded JSON payload containing a signed Sign-In-With-X message. EVM wallets sign an EIP-4361 SIWE message on Base. Solana wallets sign the Solana SIWX message with Ed25519. Generate a fresh nonce and timestamp for each request flow.

For Solana, set `chainId` to `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`, include `type: "ed25519"` in the encoded JSON payload, and provide the Ed25519 signature as base58 or base64. The signed message starts with `<domain> wants you to sign in with your Solana account:`, followed by the wallet address and the standard `URI`, `Version`, `Chain ID`, `Nonce`, `Issued At`, and optional `Expiration Time` fields.

```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)
```

### Step 2: Check balance

Before making a paid request, verify the wallet has spendable balance:

```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"
```

The response includes:

* `canConsume`: whether the wallet can make paid requests
* `balanceUsd`: current spendable balance
* `minimumTopUpUsd` and `suggestedTopUpUsd`: guidance for top-ups
* `diemBalanceUsd`: DIEM-backed balance, if any

The `walletAddress` path parameter accepts either an EVM address (`0x...`) or a Solana base58 address.

### Step 3: Top up

Top up with USDC on Base or Solana:

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

The first call returns `402 Payment Required` with a `PAYMENT-REQUIRED` header containing an `accepts` array. Each entry describes one accepted payment option, including `network`, `asset`, `payTo`, and `amount`. Choose the Base or Solana option you want to pay with, use those exact details to build an `X-402-Payment` header, and retry the same route.

#### Building the X-402-Payment header for Base

The following script creates a signed x402 payment on Base and sends the top-up request. Requires the `x402` and `viem` npm packages.

```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>
  Use the latest `PAYMENT-REQUIRED` / `accepts` response as the source of truth in production instead of hardcoding these values. For Solana top-ups, build the payment from the Solana entry returned in `accepts`. Solana entries use `network: "solana"`, the USDC mint as `asset`, and may include network-specific metadata such as `extra.feePayer`.
</Note>

### Step 4: Make a request

Once the wallet has spendable balance, call any supported endpoint with the `X-Sign-In-With-X` header:

```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."
      }
    ]
  }'
```

Successful responses may include an `X-Balance-Remaining` header.

### Step 5: Inspect transactions (optional)

Review the wallet's transaction history:

```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"
```

The ledger includes entries such as `TOP_UP`, `CHARGE`, and `REFUND`.

The `walletAddress` path parameter accepts either an EVM address (`0x...`) or a Solana base58 address.

***

## Supported routes

### Paid inference routes

The following public paid Venice routes currently support x402 wallet authentication.

| Category   | Endpoints                                                                                                                                                                                          |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 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`                                                                      |

### Top-up route

| Endpoint                   | Auth                                          | Purpose                                                                                            |
| -------------------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `POST /api/v1/x402/top-up` | Initial request: none. Retry: `X-402-Payment` | Add USDC credits to the wallet's spendable balance using an accepted Base or Solana payment option |

### Wallet-only routes

These routes use `X-Sign-In-With-X` for identity but do not charge balance.

| Endpoint                                        | Purpose                                                      |
| ----------------------------------------------- | ------------------------------------------------------------ |
| `GET /api/v1/x402/balance/{walletAddress}`      | Check spendable balance for an EVM or Solana wallet address  |
| `GET /api/v1/x402/transactions/{walletAddress}` | View transaction history for an EVM or Solana wallet address |

***

## Errors

| Status                           | Likely cause                                   | What to do                                                                 |
| -------------------------------- | ---------------------------------------------- | -------------------------------------------------------------------------- |
| `401`                            | Malformed or expired Sign-In-With-X payload    | Rebuild `X-Sign-In-With-X` with a fresh nonce and timestamp                |
| `402` on a paid route            | Not enough spendable balance                   | Top up and retry                                                           |
| `402` on `/x402/top-up`          | Expected. This is the payment initiation flow. | Use the returned payment details to build `X-402-Payment` and retry        |
| `403` on balance or transactions | Wallet mismatch                                | Ensure the authenticated wallet matches the `walletAddress` path parameter |
| `400` on top-up                  | Malformed payment header                       | Rebuild from the latest `402` response                                     |

***

## For agents

The flow is the same. Store private keys in environment variables or a secret manager, and check balance before requests to avoid unnecessary `402` round-trips.

***

## Related resources

<CardGroup cols={2}>
  <Card title="x402 Client SDK" icon="npm" href="https://github.com/veniceai/x402-client">
    Official Venice x402 client for Node.js/TypeScript.
  </Card>

  <Card title="API Pricing" icon="coins" href="/overview/pricing">
    Check model pricing and how Venice charges usage.
  </Card>

  <Card title="Chat Completions" icon="message" href="/api-reference/endpoint/chat/completions">
    A common paid route for wallet-based access.
  </Card>

  <Card title="API Spec" icon="code" href="/api-reference/api-spec">
    Reference documentation and raw spec access.
  </Card>
</CardGroup>
