# XGEN API — Reference

> AI image and video generation API with pay-per-use via Coinbase x402 protocol (USDC on Base network).

## Base URL

```
https://api.xgen.world
```

## Authentication

No API keys. Access is controlled by **x402 payment** — if you pay, you get access.

## How Payments Work (x402 Protocol)

XGEN uses the **x402 open payment standard** — an HTTP-native protocol built around the `402 Payment Required` status code. It enables programmatic, pay-per-use access without accounts, sessions, or API keys. Payments are made in USDC on the Base network.

### Why x402?

- **Zero fees** — x402 has no built-in fees
- **Stateless** — no accounts, credentials, or session management needed, just a crypto wallet
- **Machine-friendly** — designed for AI agents and automated clients to pay and access resources programmatically
- **Micropayments** — pay exactly per request, no subscriptions

### Payment Flow

```
┌────────────┐                              ┌───────────┐                    ┌─────────────┐
│  Client    │                              │  XGEN API │                    │ Facilitator │
│ (or Agent) │                              │  (Server) │                    │  x402.org   │
└─────┬──────┘                              └─────┬─────┘                    └─────┬───────┘
      │                                           │                                │
      │── 1. POST /v1/images/generate ──────────> │                                │
      │   (no payment header)                     │                                │
      │                                           │                                │
      │<── 2. HTTP 402 Payment Required ───────── │                                │
      │    Body: payment requirements             │                                │
      │    (amount, payTo, network, scheme)       │                                │
      │                                           │                                │
      │── 3. Pay USDC on Base network             │                                │
      │    (client signs transaction via wallet)  │                                │
      │                                           │                                │
      │── 4. POST /v1/images/generate ──────────> │                                │
      │    PAYMENT-SIGNATURE: <base64 payload>    │                                │
      │                                           │── 5. Verify payment ──────────>│
      │                                           │<── 6. Payment valid ───────────│
      │                                           │── 7. Settle on-chain ─────────>│
      │                                           │                                │
      │<── 8. HTTP 202 + resource ─────────────── │                                │
      │    PAYMENT-RESPONSE: <base64 settlement>  │                                │
      │                                           │                                │
```

**Step-by-step:**

1. **Client requests a resource** — sends a normal HTTP request to a paid endpoint (e.g. `POST /v1/images/generate`).
2. **Server responds `402 Payment Required`** — the response body contains payment requirements: the amount, the recipient wallet address, the network (Base), the USDC contract address, and a payment scheme identifier.
3. **Client pays USDC on Base** — using the payment requirements, the client constructs and submits an on-chain USDC transfer to the specified wallet address. This requires an EVM-compatible wallet with USDC on Base.
4. **Client resends request with payment proof** — the original request is retried with a `PAYMENT-SIGNATURE` header containing a Base64-encoded JSON payload proving the payment was made.
5. **Server verifies the payment** — the server (or its facilitator service at `https://facilitator.x402.org`) independently verifies the on-chain transaction is valid, correctly addressed, and for the right amount.
6. **Facilitator confirms validity** — verification result returned to the server.
7. **Server settles the payment** — the facilitator settles the transaction on-chain, completing the payment.
8. **Server returns the resource** — the requested resource is returned with a `PAYMENT-RESPONSE` header (Base64-encoded) confirming settlement.

### Payment Headers

| Header | Direction | Description |
|---|---|---|
| `PAYMENT-SIGNATURE` | Client → Server | Base64-encoded JSON payload with proof of payment. Sent by the client when retrying after a 402. |
| `PAYMENT-RESPONSE` | Server → Client | Base64-encoded JSON payload confirming the payment was verified and settled. Returned in the successful response. |

### Payment Details

| Property | Value |
|---|---|
| **Currency** | USDC |
| **Network** | Base mainnet (`eip155:8453`) |
| **USDC Contract** | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` |
| **Payment Scheme** | `exact` — exact amount, single payment per request |
| **Facilitator** | `https://facilitator.x402.org` — verifies and settles payments on-chain |
| **Fees** | None (x402 protocol has zero built-in fees) |

### What an AI Agent Needs

To use this API autonomously, an agent needs:
1. **An EVM wallet** with USDC on Base (e.g. via a private key or wallet SDK)
2. **Ability to sign on-chain transactions** — send USDC to the `payTo` address from the 402 response
3. **Ability to construct the `PAYMENT-SIGNATURE` header** — Base64-encoded JSON with payment proof
4. **Retry logic** — send request → receive 402 → pay → retry with payment header

### x402 SDKs

Use these packages to handle the payment flow automatically — the SDK intercepts 402 responses, pays, and retries transparently.

#### TypeScript/Node — `@x402/fetch`

```bash
npm install @x402/fetch @x402/evm viem
```

```typescript
import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount("0xYourPrivateKey");

const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
  schemes: [
    {
      network: "eip155:8453", // Base mainnet
      client: new ExactEvmScheme(account),
    },
  ],
});

// Generate an image — payment is handled automatically
const response = await fetchWithPayment("https://api.xgen.world/v1/images/generate", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "nano-banana-pro",
    prompt: "A serene Japanese garden with cherry blossoms",
    aspect_ratio: "16:9",
  }),
});

const generation = await response.json();
// { id: "gen_abc123", status: "pending" }

// Poll for result (free — no payment needed)
const result = await fetchWithPayment(`https://api.xgen.world/v1/generations/${generation.id}`);
const data = await result.json();
// { id: "gen_abc123", status: "completed", output: [{ url: "...", type: "image/png" }] }
```

#### TypeScript/Node — `@x402/axios`

```bash
npm install @x402/axios @x402/evm viem axios
```

```typescript
import axios from "axios";
import { wrapAxiosWithPaymentFromConfig } from "@x402/axios";
import { ExactEvmScheme } from "@x402/evm";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount("0xYourPrivateKey");

const api = wrapAxiosWithPaymentFromConfig(axios.create(), {
  schemes: [
    {
      network: "eip155:8453", // Base mainnet
      client: new ExactEvmScheme(account),
    },
  ],
});

// Generate a video — payment is handled automatically
const response = await api.post("https://api.xgen.world/v1/videos/generate", {
  model: "veo-3.1-fast",
  prompt: "A cat walking through a mystical forest",
  mode: "t2v",
  aspect_ratio: "landscape",
});

const generation = response.data;
// { id: "gen_xyz789", status: "pending" }
```

## Endpoints

### `POST /v1/images/generate` — $0.05

Generate an image from a text prompt.

**Request:**
```json
{
  "model": "nano-banana-pro",
  "prompt": "A serene Japanese garden with cherry blossoms",
  "aspect_ratio": "16:9",
  "resolution": "2k"
}
```

| Field | Type | Required | Description |
|---|---|---|---|
| `model` | enum | Yes | `nano-banana-2`, `nano-banana-pro`, `seedream-4.6`, `seedream-4.0` |
| `prompt` | string | Yes | Text prompt describing the image |
| `aspect_ratio` | string | No | Aspect ratio (e.g. "16:9") |
| `resolution` | string | No | Output resolution (e.g. "2k") |

**Response `202`:**
```json
{
  "id": "gen_abc123",
  "status": "pending"
}
```

Use the returned `id` to poll `GET /v1/generations/{id}` until complete.

---

### `POST /v1/videos/generate` — $0.25

Generate a video from a text prompt.

**Request:**
```json
{
  "model": "veo-3.1-fast",
  "prompt": "A cat walking through a mystical forest",
  "mode": "t2v",
  "aspect_ratio": "landscape"
}
```

| Field | Type | Required | Description |
|---|---|---|---|
| `model` | enum | Yes | `veo-3.1-fast`, `veo-3.1-lite` |
| `prompt` | string | Yes | Text prompt describing the video |
| `mode` | enum | Yes | `t2v` (text-to-video) |
| `aspect_ratio` | string | No | Aspect ratio (e.g. "landscape") |

**Response `202`:**
```json
{
  "id": "gen_xyz789",
  "status": "pending"
}
```

---

### `GET /v1/generations/{id}` — Free

Poll the status of a generation. No payment required.

**Path params:**

| Param | Type | Description |
|---|---|---|
| `id` | string | Generation ID from a generate response |

**Response `200`:**
```json
{
  "id": "gen_abc123",
  "status": "completed",
  "progress": 100,
  "output": [
    { "url": "https://cdn.xgen.world/image.png", "type": "image/png" }
  ]
}
```

**Status lifecycle:** `pending` → `processing` → `completed` | `failed`

**Response `404`:**
```json
{
  "error": "not_found",
  "message": "Generation not found"
}
```

## Error Responses

All errors follow this format:

```json
{
  "error": "error_code",
  "message": "Human-readable description"
}
```

| Status | Meaning |
|---|---|
| `400` | Invalid request body or parameters |
| `402` | Payment required — send x402 payment and retry |
| `404` | Resource not found |
| `500` | Internal server error |

## Pricing

| Endpoint | Price |
|---|---|
| `POST /v1/images/generate` | $0.05 USDC |
| `POST /v1/videos/generate` | $0.25 USDC |
| `GET /v1/generations/{id}` | Free |

## Available Models

### Image Models

| Model | Description |
|---|---|
| `nano-banana-2` | Fast image generation |
| `nano-banana-pro` | High quality image generation |
| `seedream-4.0` | Seedream v4.0 |
| `seedream-4.6` | Seedream v4.6 |

### Video Models

| Model | Description |
|---|---|
| `veo-3.1-fast` | Fast video generation |
| `veo-3.1-lite` | Lightweight video generation |
