Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,36 @@
"description": "Hardware wallet connection",
"icon": "shield",
"pages": ["ledger/introduction"]
},
{
"dropdown": "@sei-js/x402",
"description": "HTTP micro payments",
"icon": "credit-card",
"pages": [
{
"group": "Introduction",
"pages": ["x402/introduction", "x402/overview", "x402/quickstart"]
},
{
"group": "Facilitators",
"pages": ["x402/facilitators/introduction", "x402/facilitators/example"]
},
{
"group": "Client Integration",
"pages": ["x402/clients/fetch"]
},
{
"group": "Packages",
"pages": [
"x402/packages/x402",
"x402/packages/x402-fetch",
"x402/packages/x402-axios",
"x402/packages/x402-express",
"x402/packages/x402-hono",
"x402/packages/x402-next"
]
}
]
}
]
},
Expand Down
83 changes: 83 additions & 0 deletions docs/x402/clients/fetch.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
title: "Fetch Client"
description: "Make paid HTTP requests with the native Fetch API and x402"
icon: "desktop"
---

## Fetch Client Integration

Use x402 with the standard Fetch API to make paid HTTP requests. Perfect for both browser and Node.js environments.

## Installation

```bash
npm install @sei-js/x402-fetch viem dotenv
```

## Basic Usage

```typescript
import { config } from "dotenv";
import { Hex } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import {
wrapFetchWithPayment,
decodeXPaymentResponse,
} from "@sei-js/x402-fetch";

config();

const privateKey = process.env.PRIVATE_KEY as Hex;
const baseURL = process.env.RESOURCE_SERVER_URL as string; // e.g. http://localhost:4021
const endpointPath = process.env.ENDPOINT_PATH as string; // e.g. /weather
const url = `${baseURL}${endpointPath}`;

if (!baseURL || !privateKey || !endpointPath) {
console.error("Missing required environment variables");
process.exit(1);
}

// Create account from private key
const account = privateKeyToAccount(privateKey);

// Wrap fetch with payment handling
const fetchWithPayment = wrapFetchWithPayment(fetch, account);

// Make a paid request
fetchWithPayment(url, {
method: "GET",
})
.then(async (response) => {
const body = await response.json();
console.log("Response:", body);

// Decode the payment response
const paymentResponse = decodeXPaymentResponse(
response.headers.get("x-payment-response")!
);
console.log("Payment details:", paymentResponse);
})
.catch((error) => {
console.error("Error:", error.response?.data?.error);
});
```

## Environment Setup

Create a `.env` file with the required configuration:

```env
# Required: Your private key for making payments
PRIVATE_KEY=0xYourPrivateKeyHere

# Required: The server URL hosting the paid API
RESOURCE_SERVER_URL=http://localhost:4021

# Required: The endpoint path to access
ENDPOINT_PATH=/weather
```

<Warning>
**Security Note**: Never commit private keys to version control. Use
environment variables or secure key management services in production.
</Warning>
211 changes: 211 additions & 0 deletions docs/x402/facilitators/example.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
---
title: "Example"
description: "Complete setup guide for x402 facilitators"
icon: "code"
---

<Warning>
This example is for learning purposes only. Do not use it for production.
</Warning>
## Prerequisites

Before setting up a facilitator, ensure you have:

- **Node.js 18+** installed
- **Sei wallet** with some SEI for gas fees
- **Private key** for your facilitator wallet (testnet recommended for development)

## Quick Setup

### 1. Install Dependencies

```bash
npm install @sei-js/x402 express dotenv
```

### 2. Environment Configuration

Create a `.env` file:

```env
# Required: Your facilitator private key
PRIVATE_KEY=0xYourPrivateKeyHere

# Optional: Server port (defaults to 3000)
PORT=3002
```

<Warning>
**Security Note**: Never commit private keys to version control. Use
environment variables or secure key management services in production.
</Warning>

### 3. Basic Facilitator Implementation

Create `index.ts` with the following structure:

```typescript
import { config } from "dotenv";
import express from "express";
import { verify, settle } from "@sei-js/x402/facilitator";
import {
PaymentRequirementsSchema,
PaymentRequirements,
evm,
PaymentPayload,
PaymentPayloadSchema,
} from "@sei-js/x402/types";

config();

const PRIVATE_KEY = process.env.PRIVATE_KEY;

if (!PRIVATE_KEY) {
console.error("Missing required environment variables");
process.exit(1);
}

const { createConnectedClient, createSigner } = evm;

const app = express();
app.use(express.json());

type VerifyRequest = {
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};

type SettleRequest = {
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};

const client = createConnectedClient("sei-testnet");

// Verification endpoint
app.post("/verify", async (req, res) => {
try {
const body: VerifyRequest = req.body;
const paymentRequirements = PaymentRequirementsSchema.parse(
body.paymentRequirements
);
const paymentPayload = PaymentPayloadSchema.parse(body.paymentPayload);
const valid = await verify(client, paymentPayload, paymentRequirements);
res.json(valid);
} catch {
res.status(400).json({ error: "Invalid request" });
}
});

// Settlement endpoint
app.post("/settle", async (req, res) => {
try {
const signer = createSigner("sei-testnet", PRIVATE_KEY as `0x${string}`);
const body: SettleRequest = req.body;
const paymentRequirements = PaymentRequirementsSchema.parse(
body.paymentRequirements
);
const paymentPayload = PaymentPayloadSchema.parse(body.paymentPayload);
const response = await settle(signer, paymentPayload, paymentRequirements);
res.json(response);
} catch (error) {
res.status(400).json({ error: `Invalid request: ${error}` });
}
});

// Supported schemes endpoint
app.get("/supported", (req, res) => {
res.json({
kinds: [
{
x402Version: 1,
scheme: "exact",
network: "sei-testnet",
},
],
});
});

app.listen(process.env.PORT || 3000, () => {
console.log(
`Server listening at http://localhost:${process.env.PORT || 3000}`
);
});
```

### 4. Run Your Facilitator

```bash
npx tsx index.ts
```

<Check>
Your facilitator server should start and display: `Server listening at
http://localhost:3002`
</Check>

## API Endpoints

Your facilitator exposes three main endpoints:

### POST /verify

Verifies x402 payment payloads without executing transactions.

**Request Body:**

```typescript
{
paymentPayload: PaymentPayload; // x402 payment data
paymentRequirements: PaymentRequirements; // Payment requirements
}
```

**Response:**

```json
{
"valid": true,
"reason": "Payment payload is valid"
}
```

### POST /settle

Settles verified payments by signing and broadcasting transactions to Sei testnet.

**Request Body:**

```typescript
{
paymentPayload: PaymentPayload; // x402 payment data
paymentRequirements: PaymentRequirements; // Payment requirements
}
```

**Response:**

```json
{
"transactionHash": "0x...",
"status": "success"
}
```

### GET /supported

Returns supported payment schemes and networks.

**Response:**

```json
{
"kinds": [
{
"x402Version": 1,
"scheme": "exact",
"network": "sei-testnet"
}
]
}
```
Loading