# SDK

The X402 SDK enables developers to monetize their APIs with per-request micropayments. When a client calls your API without payment, they receive the payment requirements. Once they submit a valid payment, your function executes and settlement happens automatically on-chain.

**Key Benefits:**

* Simple one-function setup for payment-gated endpoints
* Automatic payment verification and settlement
* USDC stablecoin payments on Cronos
* Built on Hono for high performance

***

### Installation

```bash
npm install @axicov/x402-cronos-sdk
```

```bash
bun add @axicov/x402-cronos-sdk
```

```bash
yarn add @axicov/x402-cronos-sdk
```

***

### Quick Start

Create a paid API in under 10 lines of code:

```typescript
import { createx402Tool } from "@axicov/x402-cronos-sdk";

createx402Tool(
  async (input: { prompt: string }) => {
    const response = await generateText(input.prompt);
    return { result: response };
  },
  {
    price: 0.01,
    devWallet: "0xYourWalletAddress",
    port: 8000,
  }
);
```

Your API is now live at `http://localhost:8000/send` and requires 0.01 USDC per request.

***

### Configuration

#### X402Config

| Property      | Type     | Required | Description                                       |
| ------------- | -------- | -------- | ------------------------------------------------- |
| `price`       | `number` | Yes      | Price per request in USDC (e.g., `0.01` = 1 cent) |
| `devWallet`   | `string` | Yes      | Your wallet address to receive payments           |
| `port`        | `number` | No       | Server port (default: `3000`)                     |
| `description` | `string` | No       | Human-readable payment description                |

```typescript
interface X402Config {
  price: number;
  devWallet: string;
  port?: number;
  description?: string;
}
```

***

### API Reference

#### createx402Tool

Creates a payment-protected HTTP endpoint.

```typescript
function createx402Tool<TInput, TOutput>(
  fn: (input: TInput) => Promise<TOutput>,
  config: X402Config
): Hono
```

**Parameters:**

| Parameter | Description                                    |
| --------- | ---------------------------------------------- |
| `fn`      | Your async function that processes the request |
| `config`  | Payment configuration object                   |

**Returns:** A Hono application instance

**Example:**

```typescript
import { createx402Tool } from "@axicov/x402-cronos-sdk";

interface TranslationInput {
  text: string;
  targetLang: string;
}

interface TranslationOutput {
  translated: string;
}

const app = createx402Tool<TranslationInput, TranslationOutput>(
  async (input) => {
    const result = await translateText(input.text, input.targetLang);
    return { translated: result };
  },
  {
    price: 0.005,
    devWallet: "0x419E5aD68d2Ff4d1786FE4bB7ebe7b3563A5A6d7",
    port: 3000,
    description: "Translation service",
  }
);
```

***

#### x402Middleware

For custom Hono applications, use the middleware directly.

```typescript
import { x402Middleware } from "@axicov/x402-cronos-sdk";
```

**Usage:**

```typescript
import { Hono } from "hono";
import { x402Middleware } from "@axicov/x402-cronos-sdk";

const app = new Hono();

// Free endpoint
app.get("/health", (c) => c.json({ status: "ok" }));

// Paid endpoint
app.post(
  "/generate",
  x402Middleware({
    price: 0.02,
    devWallet: "0xYourWallet",
    description: "AI generation",
  }),
  async (c) => {
    const input = await c.req.json();
    const result = await generate(input);
    return c.json(result);
  }
);

export default app;
```

***

#### Facilitator

Access the underlying facilitator client for advanced use cases.

```typescript
import { facilitator, verify, settle } from "@axicov/x402-cronos-sdk";
```

**Generate Payment Requirements:**

```typescript
const requirements = facilitator.generatePaymentRequirements({
  payTo: "0xYourWallet",
  description: "API access",
  maxAmountRequired: "10000", // 0.01 USDC in base units
});
```

**Verify a Payment:**

```typescript
const result = await verify(paymentHeader, requirements);

if (result.isValid) {
  // Payment is valid, process the request
} else {
  // Payment invalid: result.invalidReason
}
```

**Settle a Payment:**

```typescript
await settle(paymentHeader, requirements);
// Payment transferred on-chain
```

***

### Payment Flow

#### How X402 Works

```
Client                          Your API                         Cronos
  │                                │                                │
  │  POST /send                    │                                │
  │  (no payment)                  │                                │
  │───────────────────────────────▶│                                │
  │                                │                                │
  │  HTTP 402                      │                                │
  │  X-PAYMENT-REQUIRED: {...}     │                                │
  │◀───────────────────────────────│                                │
  │                                │                                │
  │  POST /send                    │                                │
  │  X-PAYMENT: <signed>           │                                │
  │───────────────────────────────▶│                                │
  │                                │                                │
  │                                │  Verify payment                │
  │                                │───────────────────────────────▶│
  │                                │                                │
  │                                │  Execute your function         │
  │                                │                                │
  │                                │  Settle payment                │
  │                                │───────────────────────────────▶│
  │                                │                                │
  │  200 OK                        │                                │
  │  { result: ... }               │                                │
  │◀───────────────────────────────│                                │
```

#### HTTP Headers

| Header               | Direction | Description                         |
| -------------------- | --------- | ----------------------------------- |
| `X-PAYMENT-REQUIRED` | Response  | Base64-encoded payment requirements |
| `X-PAYMENT`          | Request   | Signed payment proof                |

#### Payment Requirements Format

```json
{
  "payTo": "0x...",
  "description": "Tool access",
  "maxAmountRequired": "10000"
}
```

> **Note:** `maxAmountRequired` is in USDC base units (6 decimals). 10000 = 0.01 USDC.

***

### Client Integration

#### Making Paid Requests

```typescript
async function callPaidAPI(url: string, input: any, signer: Signer) {
  // Step 1: Initial request
  const res = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(input),
  });

  // Step 2: Handle payment requirement
  if (res.status === 402) {
    const encoded = res.headers.get("X-PAYMENT-REQUIRED");
    const requirements = JSON.parse(Buffer.from(encoded, "base64").toString());

    // Step 3: Generate payment
    const payment = await facilitator.generatePaymentHeader({
      to: requirements.payTo,
      value: requirements.maxAmountRequired,
      signer,
      validBefore: Math.floor(Date.now() / 1000) + 600, // 10 min expiry
    });

    // Step 4: Retry with payment
    const paidRes = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-PAYMENT": payment,
      },
      body: JSON.stringify(input),
    });

    return paidRes.json();
  }

  return res.json();
}
```

#### Using ethers.js

```typescript
import { ethers } from "ethers";
import { facilitator } from "@axicov/x402-cronos-sdk";

const provider = new ethers.JsonRpcProvider("https://evm-t3.cronos.org");
const signer = new ethers.Wallet(PRIVATE_KEY, provider);

const payment = await facilitator.generatePaymentHeader({
  to: "0xDevWallet",
  value: "10000",
  signer,
  validBefore: Math.floor(Date.now() / 1000) + 600,
});
```

***

### Examples

#### Image Generation API

```typescript
import { createx402Tool } from "@axicov/x402-cronos-sdk";

interface ImageInput {
  prompt: string;
  size: "256" | "512" | "1024";
}

interface ImageOutput {
  url: string;
}

createx402Tool<ImageInput, ImageOutput>(
  async (input) => {
    const imageUrl = await generateImage(input.prompt, input.size);
    return { url: imageUrl };
  },
  {
    price: 0.05,
    devWallet: process.env.DEV_WALLET!,
    port: 8000,
    description: "AI image generation",
  }
);
```

#### Data Lookup Service

```typescript
import { createx402Tool } from "@axicov/x402-cronos-sdk";

createx402Tool(
  async (input: { address: string }) => {
    const data = await fetchBlockchainData(input.address);
    return {
      balance: data.balance,
      transactions: data.txCount,
      lastActive: data.lastSeen,
    };
  },
  {
    price: 0.001,
    devWallet: process.env.DEV_WALLET!,
    description: "Blockchain data lookup",
  }
);
```

#### Multi-Endpoint API with Middleware

```typescript
import { Hono } from "hono";
import { x402Middleware } from "@axicov/x402-cronos-sdk";

const app = new Hono();
const walletConfig = {
  devWallet: process.env.DEV_WALLET!,
};

// Free tier
app.get("/status", (c) => c.json({ online: true }));

// Basic tier - $0.01
app.post(
  "/basic",
  x402Middleware({ ...walletConfig, price: 0.01 }),
  async (c) => {
    return c.json({ tier: "basic", data: "..." });
  }
);

// Premium tier - $0.10
app.post(
  "/premium",
  x402Middleware({ ...walletConfig, price: 0.1 }),
  async (c) => {
    return c.json({ tier: "premium", data: "..." });
  }
);

export default app;
```

***

### Network

#### Cronos Testnet

The SDK operates on Cronos Testnet by default.

| Property | Value                           |
| -------- | ------------------------------- |
| Chain ID | 338                             |
| RPC URL  | `https://evm-t3.cronos.org`     |
| Currency | TCRO                            |
| Explorer | <https://testnet.cronoscan.com> |

#### Getting Test Tokens

1. Get TCRO from the [Cronos Testnet Faucet](https://cronos.org/faucet)
2. Acquire test USDC for payment testing

***

### Environment Variables

```bash
# Required for receiving payments
DEV_WALLET=0xYourWalletAddress

# Optional
PORT=3000
```

For client-side payment signing:

```bash
PRIVATE_KEY=your_private_key
```

***

### TypeScript Support

The SDK is written in TypeScript and exports full type definitions.

```typescript
import type { X402Config } from "@axicov/x402-cronos-sdk";

const config: X402Config = {
  price: 0.01,
  devWallet: "0x...",
};
```

Generic type inference works automatically:

```typescript
// Input and output types are inferred
createx402Tool(
  async (input: { name: string }) => {
    return { greeting: `Hello ${input.name}` };
  },
  config
);
```

***

### Error Handling

#### Common Errors

| Status              | Meaning          | Solution                           |
| ------------------- | ---------------- | ---------------------------------- |
| 402                 | Payment required | Include valid `X-PAYMENT` header   |
| 402 + error message | Payment invalid  | Check payment signature and expiry |
| 500                 | Server error     | Check your function implementation |

#### Handling in Middleware

```typescript
app.post(
  "/api",
  x402Middleware(config),
  async (c) => {
    try {
      const result = await riskyOperation();
      return c.json(result);
    } catch (error) {
      // Payment already verified, handle gracefully
      return c.json({ error: "Processing failed" }, 500);
    }
  }
);
```
