diff --git a/docs/docs.json b/docs/docs.json index ffb2fdcb0..f83be447c 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -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" + ] + } + ] } ] }, diff --git a/docs/x402/clients/fetch.mdx b/docs/x402/clients/fetch.mdx new file mode 100644 index 000000000..3238d8942 --- /dev/null +++ b/docs/x402/clients/fetch.mdx @@ -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 +``` + + + **Security Note**: Never commit private keys to version control. Use + environment variables or secure key management services in production. + diff --git a/docs/x402/facilitators/example.mdx b/docs/x402/facilitators/example.mdx new file mode 100644 index 000000000..d0de7e459 --- /dev/null +++ b/docs/x402/facilitators/example.mdx @@ -0,0 +1,211 @@ +--- +title: "Example" +description: "Complete setup guide for x402 facilitators" +icon: "code" +--- + + + This example is for learning purposes only. Do not use it for production. + +## 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 +``` + + + **Security Note**: Never commit private keys to version control. Use + environment variables or secure key management services in production. + + +### 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 +``` + + + Your facilitator server should start and display: `Server listening at + http://localhost:3002` + + +## 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" + } + ] +} +``` diff --git a/docs/x402/facilitators/introduction.mdx b/docs/x402/facilitators/introduction.mdx new file mode 100644 index 000000000..5c2ada093 --- /dev/null +++ b/docs/x402/facilitators/introduction.mdx @@ -0,0 +1,121 @@ +--- +title: "Facilitators" +description: "Understanding the role of facilitators in the x402 protocol" +icon: "server" +--- + +## What is a Facilitator? + +The facilitator is an optional but recommended service that simplifies the process of verifying and settling payments between clients (buyers) and servers (sellers). + +The facilitator is a service that: + +- **Verifies payment payloads** submitted by clients +- **Settles payments** on the blockchain on behalf of servers + +By using a facilitator, servers do not need to maintain direct blockchain connectivity or implement payment verification logic themselves. This reduces operational complexity and ensures accurate, real-time validation of transactions. + + + The facilitator does not hold funds or act as a custodian - it performs + verification and execution of onchain transactions based on signed payloads + provided by clients. + + +## Facilitator Responsibilities + + + + Confirm that the client's payment payload meets the server's declared + payment requirements + + + Submit validated payments to the blockchain and monitor for confirmation + + + Return verification and settlement results to the server, allowing the + server to decide whether to fulfill the client's request + + + Ensure standardized verification and settlement flows across services + + + +## Why Use a Facilitator? + +Using a facilitator provides several key benefits: + + + + Servers do not need to interact directly with blockchain nodes or implement + complex payment verification logic. + + +{" "} + + + Standardized verification and settlement flows across services ensure reliable + payment processing. + + +{" "} + + + Services can start accepting payments with minimal blockchain-specific + development required. + + + + Accurate, real-time validation of transactions without maintaining + blockchain infrastructure. + + + + + While it is possible to implement verification and settlement locally, using a + facilitator accelerates adoption and ensures correct protocol behavior. + + +## Interaction Flow + +The following diagram shows how clients, servers, and facilitators interact in the x402 protocol: + +```mermaid +sequenceDiagram + participant C as Client + participant S as Server + participant F as Facilitator + participant B as Blockchain + + C->>S: 1. HTTP Request + S->>C: 2. 402 Payment Required + Payment Details + C->>C: 3. Create Payment Payload + C->>S: 4. HTTP Request + X-PAYMENT header + S->>F: 5. POST /verify (Payment Payload + Details) + F->>S: 6. Verification Response + + alt Payment Valid + S->>S: 7. Fulfill Request + S->>F: 8. POST /settle (Payment Payload + Details) + F->>B: 9. Submit Payment Transaction + B->>F: 10. Transaction Confirmation + F->>S: 11. Payment Execution Response + S->>C: 12. 200 OK + Resource + X-PAYMENT-RESPONSE + else Payment Invalid + S->>C: 402 Payment Required + end +``` + +### Step-by-Step Breakdown + +1. **Client** makes an HTTP request to a **resource server** +2. **Resource server** responds with a `402 Payment Required` status and payment details +3. **Client** creates a payment payload based on the selected payment scheme +4. **Client** sends the request with `X-PAYMENT` header containing the payment payload +5. **Resource server** verifies the payment via the facilitator's `/verify` endpoint +6. **Facilitator** performs verification and returns a verification response +7. If valid, the **resource server** fulfills the request +8. **Resource server** settles payment via the facilitator's `/settle` endpoint +9. **Facilitator** submits the payment to the blockchain +10. **Facilitator** waits for blockchain confirmation +11. **Facilitator** returns execution response to the server +12. **Resource server** returns the requested resource with settlement details \ No newline at end of file diff --git a/docs/x402/introduction.mdx b/docs/x402/introduction.mdx new file mode 100644 index 000000000..1c45a07d6 --- /dev/null +++ b/docs/x402/introduction.mdx @@ -0,0 +1,65 @@ +--- +title: "x402 Introduction" +description: HTTP micro payments on Sei. Build paid APIs, premium content, and micro payment systems. +icon: "rocket" +--- + +## Build Paid APIs on Sei + +x402 Protocol brings HTTP micro payments to Sei, enabling you to monetize APIs, premium content, and digital +services with instant, low-cost payments. Whether you're building AI APIs, data feeds, or premium content platform, +x402 makes it simple to add payment gates to any HTTP endpoint. + +**Works with Sei's advantages:** Sei's fast finality, low gas fees, and EVM compatibility make it perfect for micro payments. X402 leverages these features to enable seamless payment flows that complete in milliseconds. + +## Why X402 on Sei? + + + + Sei's 400ms finality and low gas fees make micropayments practical. Perfect + for pay-per-request APIs and streaming content. + + + Use familiar tools like Viem, Ethers.js, and Hardhat. All existing Ethereum + tooling works seamlessly on Sei. + + + Integrates with Sei wallets, MetaMask, and any EIP-6963 compatible wallet + for smooth user experiences. + + + +## Use Cases on Sei + +The x402 protocol enables a wide range of monetization strategies for web services and APIs: + +### **AI & Machine Learning Services** +- **Per-inference pricing** for LLM APIs, image generation, and data processing +- **Usage-based billing** for compute-intensive AI workloads +- **Tiered access** to different model capabilities and response speeds + +### **Premium Content & Media** +- **Pay-per-view** articles, videos, and digital content +- **Subscription gates** with flexible billing periods +- **Time-based access** to premium features and content + +### **Real-Time Data & APIs** +- **Market data feeds** with per-request or streaming payments +- **Weather and IoT data** monetization +- **Financial APIs** with usage-based pricing models + +### **Infrastructure & CDN Services** +- **Bandwidth metering** for content delivery networks +- **Storage payments** on a per-GB or per-request basis +- **Compute resources** with granular usage tracking + +## Getting Started + + + + Learn about the architecture of x402 and how it works on Sei + + + Build your first paid API on Sei in under 10 minutes + + \ No newline at end of file diff --git a/docs/x402/overview.mdx b/docs/x402/overview.mdx new file mode 100644 index 000000000..8d46994f6 --- /dev/null +++ b/docs/x402/overview.mdx @@ -0,0 +1,79 @@ +--- +title: Protocol Overview +description: Understanding x402 HTTP micropayments and how they work on Sei Network +icon: "eye" +--- + +# x402 Protocol Overview + +x402 transforms any HTTP endpoint into a paid service using blockchain micropayments. Originally designed as an extension to HTTP status codes, X402 enables seamless monetization of APIs, content, and digital services. + +## Core Components + + + + **HTTP Payment Required** Standard HTTP status indicating payment is needed + to access the resource. + + + **X-402-Payment Headers** Cryptographic proof of payment embedded in HTTP + requests. + + + + + + **Payment Processors** Server-side components that handle payment + verification and enforcement. + + + **Payment Makers** Client libraries that automatically handle payment + creation and retry logic. + + + +## How x402 Works + +The protocol adds payment capabilities to standard HTTP by introducing payment headers and the `402 Payment Required` status code: + +```mermaid +graph TD + A[Client Request] --> B[Server Check] + B --> C{Payment Required?} + C -->|No| D[Return Content] + C -->|Yes| E[Return 402 + Payment Info] + E --> F[Client Creates Payment] + F --> G[Payment to Blockchain] + G --> H[Client Retries with Payment Header] + H --> I[Server Verifies Payment] + I --> J[Return Protected Content] +``` + +## Facilitators and Clients + +The x402 ecosystem consists of two main types of components that work together to enable seamless micropayments: + +**Facilitators** are server-side services that: +- Verify payment proofs from blockchain transactions +- Enforce payment requirements for protected resources +- Handle payment settlement and confirmation +- Provide APIs for payment status checking + +**Clients** are libraries and tools that: +- Automatically detect 402 Payment Required responses +- Create and submit blockchain payments +- Retry requests with payment headers +- Manage wallet connections and user interactions + +This separation allows developers to focus on their core business logic while the x402 infrastructure handles all payment complexity. + +## Learn More + + + + Learn how to set up and configure payment processors + + + Integrate x402 payments into your applications + + diff --git a/docs/x402/packages/x402-axios.mdx b/docs/x402/packages/x402-axios.mdx new file mode 100644 index 000000000..24440e179 --- /dev/null +++ b/docs/x402/packages/x402-axios.mdx @@ -0,0 +1,103 @@ +--- +title: "@sei-js/x402-axios" +description: Axios interceptor with automatic x402 payment handling +--- + +# @sei-js/x402-axios + +A utility package that extends Axios to automatically handle 402 Payment Required responses using the x402 payment protocol. This package enables seamless integration of payment functionality into your applications when making HTTP requests with Axios. + +## Installation + +```bash +npm install @sei-js/x402-axios +``` + +## Quick Start + +```typescript +import { createWalletClient, http } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { withPaymentInterceptor } from "@sei-js/x402-axios"; +import axios from "axios"; +import { seiTestnet } from "viem/chains"; + +// Create a wallet client +const account = privateKeyToAccount("0xYourPrivateKey"); +const client = createWalletClient({ + account, + transport: http(), + chain: seiTestnet, +}); + +// Create an Axios instance with payment handling +const api = withPaymentInterceptor( + axios.create({ + baseURL: "https://api.example.com", + }), + client +); + +// Make a request that may require payment +const response = await api.get("/paid-endpoint"); +console.log(response.data); +``` + +## Features + +- Automatic handling of 402 Payment Required responses +- Automatic retry of requests with payment headers +- Payment verification and header generation +- Exposes payment response headers + +## API + +### `withPaymentInterceptor(axiosClient, walletClient)` + +Adds payment handling interceptors to an existing Axios instance. + +#### Parameters + +- `axiosClient`: The Axios instance to add payment handling to +- `walletClient`: The wallet client used to sign payment messages (must implement the x402 wallet interface) + +#### Returns + +The same Axios instance with payment interceptors added. The interceptors will: +1. Catch 402 responses +2. Parse payment requirements from the response +3. Create payment headers using the wallet client +4. Retry the original request with payment headers + +## Example + +```typescript +import { createWalletClient, http } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { withPaymentInterceptor } from "@sei-js/x402-axios"; +import axios from "axios"; +import { seiTestnet } from "viem/chains"; + +const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); +const client = createWalletClient({ + account, + transport: http(), + chain: seiTestnet, +}); + +const api = withPaymentInterceptor( + axios.create({ + baseURL: "https://api.example.com", + timeout: 10000, + }), + client +); + +// Use the API client normally - payments are handled automatically +try { + const response = await api.get("/premium-data"); + console.log("Premium data:", response.data); +} catch (error) { + console.error("Request failed:", error); +} +``` diff --git a/docs/x402/packages/x402-express.mdx b/docs/x402/packages/x402-express.mdx new file mode 100644 index 000000000..523d55a6c --- /dev/null +++ b/docs/x402/packages/x402-express.mdx @@ -0,0 +1,163 @@ +--- +title: "@sei-js/x402-express" +description: Express middleware integration for x402 Payment Protocol +--- + +# @sei-js/x402-express + +Express middleware integration for the x402 Payment Protocol. This package allows you to easily add paywall functionality to your Express.js applications using the x402 protocol. + +## Installation + +```bash +npm install @sei-js/x402-express +``` + +## Quick Start + +```typescript +import express from "express"; +import { paymentMiddleware, Network } from "@sei-js/x402-express"; + +const app = express(); + +// Configure the payment middleware +app.use(paymentMiddleware( + "0xYourAddress", + { + "/protected-route": { + price: "$0.10", + network: "sei", + config: { + description: "Access to premium content", + } + } + } +)); + +// Implement your route +app.get("/protected-route", + (req, res) => { + res.json({ message: "This content is behind a paywall" }); + } +); + +app.listen(3000); +``` + +## Configuration + +The `paymentMiddleware` function accepts three parameters: + +1. `payTo`: Your receiving address (`0x${string}`) +2. `routes`: Route configurations for protected endpoints +3. `facilitator`: (Optional) Configuration for the x402 facilitator service +4. `paywall`: (Optional) Configuration for the built-in paywall + +See the Middleware Options section below for detailed configuration options. + +## Middleware Options + +The middleware supports various configuration options: + +### Route Configuration + +```typescript +type RoutesConfig = Record; + +interface RouteConfig { + price: Price; // Price in USD or token amount + network: Network; // "sei" or "seiTestnet" + config?: PaymentMiddlewareConfig; +} +``` + +### Payment Configuration + +```typescript +interface PaymentMiddlewareConfig { + description?: string; // Description of the payment + mimeType?: string; // MIME type of the resource + maxTimeoutSeconds?: number; // Maximum time for payment (default: 60) + outputSchema?: Record; // JSON schema for the response + customPaywallHtml?: string; // Custom HTML for the paywall + resource?: string; // Resource URL (defaults to request URL) +} +``` + +### Facilitator Configuration + +```typescript +type FacilitatorConfig = { + url: string; // URL of the x402 facilitator service + createAuthHeaders?: CreateHeaders; // Optional function to create authentication headers +}; +``` + +### Paywall Configuration + +For more on paywall configuration options, refer to the [paywall README](/docs/x402/src/paywall/README.md). + +```typescript +type PaywallConfig = { + cdpClientKey?: string; // Your CDP Client API Key + appName?: string; // Name displayed in the paywall wallet selection modal + appLogo?: string; // Logo for the paywall wallet selection modal +}; +``` + +## Example with Full Configuration + +```typescript +import express from "express"; +import { paymentMiddleware } from "@sei-js/x402-express"; +import { facilitator } from "@sei-js/x402"; + +const app = express(); + +app.use(paymentMiddleware( + "0xYourAddress", + { + "/premium-api": { + price: "$0.05", + network: "sei", + config: { + description: "Premium API access", + maxTimeoutSeconds: 120, + } + }, + "/data-feed": { + price: "$0.01", + network: "sei", + config: { + description: "Real-time data feed", + mimeType: "application/json", + } + } + }, + facilitator, // Use facilitator + { + appName: "My Premium API", + appLogo: "https://example.com/logo.png" + } +)); + +app.get("/premium-api", (req, res) => { + res.json({ + data: "This is premium content", + timestamp: new Date().toISOString() + }); +}); + +app.get("/data-feed", (req, res) => { + res.json({ + price: Math.random() * 100, + symbol: "BTC/USD", + timestamp: Date.now() + }); +}); + +app.listen(3000, () => { + console.log("Server running on port 3000"); +}); +``` diff --git a/docs/x402/packages/x402-fetch.mdx b/docs/x402/packages/x402-fetch.mdx new file mode 100644 index 000000000..c1d907a25 --- /dev/null +++ b/docs/x402/packages/x402-fetch.mdx @@ -0,0 +1,98 @@ +--- +title: "@sei-js/x402-fetch" +description: Fetch API wrapper with automatic x402 payment handling +--- + +# @sei-js/x402-fetch + +A utility package that extends the native `fetch` API to automatically handle 402 Payment Required responses using the x402 payment protocol. This package enables seamless integration of payment functionality into your applications when making HTTP requests. + +## Installation + +```bash +npm install @sei-js/x402-fetch +``` + +## Quick Start + +```typescript +import { createWalletClient, http } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { wrapFetchWithPayment } from "@sei-js/x402-fetch"; +import { seiTestnet } from "viem/chains"; + +// Create a wallet client +const account = privateKeyToAccount("0xYourPrivateKey"); +const client = createWalletClient({ + account, + transport: http(), + chain: seiTestnet, +}); + +// Wrap the fetch function with payment handling +const fetchWithPay = wrapFetchWithPayment(fetch, client); + +// Make a request that may require payment +const response = await fetchWithPay("https://api.example.com/paid-endpoint", { + method: "GET", +}); + +const data = await response.json(); +``` + +## API + +### `wrapFetchWithPayment(fetch, walletClient, maxValue?, paymentRequirementsSelector?)` + +Wraps the native fetch API to handle 402 Payment Required responses automatically. + +#### Parameters + +- `fetch`: The fetch function to wrap (typically `globalThis.fetch`) +- `walletClient`: The wallet client used to sign payment messages (must implement the x402 wallet interface) +- `maxValue`: Optional maximum allowed payment amount in base units (defaults to 0.1 USDC) +- `paymentRequirementsSelector`: Optional function to select payment requirements from the response (defaults to `selectPaymentRequirements`) + +#### Returns + +A wrapped fetch function that automatically handles 402 responses by: +1. Making the initial request +2. If a 402 response is received, parsing the payment requirements +3. Verifying the payment amount is within the allowed maximum +4. Creating a payment header using the provided wallet client +5. Retrying the request with the payment header + +## Example + +```typescript +import { config } from "dotenv"; +import { createWalletClient, http } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { wrapFetchWithPayment } from "@sei-js/x402-fetch"; +import { seiTestnet } from "viem/chains"; + +config(); + +const { PRIVATE_KEY, API_URL } = process.env; + +const account = privateKeyToAccount(PRIVATE_KEY as `0x${string}`); +const client = createWalletClient({ + account, + transport: http(), + chain: seiTestnet, +}); + +const fetchWithPay = wrapFetchWithPayment(fetch, client); + +// Make a request to a paid API endpoint +fetchWithPay(API_URL, { + method: "GET", +}) + .then(async response => { + const data = await response.json(); + console.log(data); + }) + .catch(error => { + console.error(error); + }); +``` diff --git a/docs/x402/packages/x402-hono.mdx b/docs/x402/packages/x402-hono.mdx new file mode 100644 index 000000000..79656ae6a --- /dev/null +++ b/docs/x402/packages/x402-hono.mdx @@ -0,0 +1,139 @@ +--- +title: "@sei-js/x402-hono" +description: Hono middleware integration for x402 Payment Protocol +--- + +# @sei-js/x402-hono + +Hono middleware integration for the x402 Payment Protocol. This package allows you to easily add paywall functionality to your Hono applications using the x402 protocol. + +## Installation + +```bash +npm install @sei-js/x402-hono +``` + +## Quick Start + +```typescript +import { Hono } from "hono"; +import { paymentMiddleware, Network } from "@sei-js/x402-hono"; + +const app = new Hono(); + +// Configure the payment middleware +app.use(paymentMiddleware( + "0xYourAddress", + { + "/protected-route": { + price: "$0.10", + network: "sei", + config: { + description: "Access to premium content", + } + } + } +)); + +// Implement your route +app.get("/protected-route", (c) => { + return c.json({ message: "This content is behind a paywall" }); +}); + +serve({ + fetch: app.fetch, + port: 3000 +}); +``` + +## Configuration + +The `paymentMiddleware` function accepts three parameters: + +1. `payTo`: Your receiving address (`0x${string}`) +2. `routes`: Route configurations for protected endpoints +3. `facilitator`: (Optional) Configuration for the x402 facilitator service +4. `paywall`: (Optional) Configuration for the built-in paywall + +## Middleware Options + +The middleware supports the same configuration options as the Express middleware: + +### Route Configuration + +```typescript +type RoutesConfig = Record; + +interface RouteConfig { + price: Price; // Price in USD or token amount + network: Network; // "sei" or "seiTestnet" + config?: PaymentMiddlewareConfig; +} +``` + +### Payment Configuration + +```typescript +interface PaymentMiddlewareConfig { + description?: string; // Description of the payment + mimeType?: string; // MIME type of the resource + maxTimeoutSeconds?: number; // Maximum time for payment (default: 60) + outputSchema?: Record; // JSON schema for the response + customPaywallHtml?: string; // Custom HTML for the paywall + resource?: string; // Resource URL (defaults to request URL) +} +``` + +## Example with Cloudflare Workers + +```typescript +import { Hono } from "hono"; +import { paymentMiddleware } from "@sei-js/x402-hono"; + +const app = new Hono(); + +app.use(paymentMiddleware( + "0xYourAddress", + { + "/api/premium": { + price: "$0.02", + network: "sei", + config: { + description: "Premium API endpoint", + maxTimeoutSeconds: 60, + } + } + } +)); + +app.get("/api/premium", (c) => { + return c.json({ + message: "This is premium content", + data: { + timestamp: Date.now(), + premium: true + } + }); +}); + +app.get("/", (c) => { + return c.text("Hono x402 API Server"); +}); + +export default app; +``` + +## Edge Runtime Support + +Hono's lightweight design makes it perfect for edge computing environments. The x402-hono middleware works seamlessly with: + +- Cloudflare Workers +- Vercel Edge Functions +- Deno Deploy +- Bun runtime + +## Performance Benefits + +- **Minimal overhead**: Hono's fast routing combined with x402's efficient payment protocol +- **Edge-optimized**: Perfect for serverless and edge computing environments +- **TypeScript-first**: Full type safety for payment configurations and responses diff --git a/docs/x402/packages/x402-next.mdx b/docs/x402/packages/x402-next.mdx new file mode 100644 index 000000000..8be8d6eac --- /dev/null +++ b/docs/x402/packages/x402-next.mdx @@ -0,0 +1,214 @@ +--- +title: "@sei-js/x402-next" +description: Next.js middleware integration for x402 Payment Protocol +--- + +# @sei-js/x402-next + +Next.js middleware integration for the x402 Payment Protocol. This package allows you to easily add paywall functionality to your Next.js applications using the x402 protocol. + +## Installation + +```bash +npm install @sei-js/x402-next +``` + +## Quick Start + +Create a middleware file in your Next.js project (e.g., `middleware.ts`): + +```typescript +import { paymentMiddleware } from '@sei-js/x402-next'; + +export const middleware = paymentMiddleware( + "0xYourAddress", + { + '/protected': { + price: '$0.01', + network: "sei", + config: { + description: 'Access to protected content' + } + }, + } +); + +// Configure which paths the middleware should run on +export const config = { + matcher: [ + '/protected/:path*', + ] +}; +``` + +## Configuration + +The `paymentMiddleware` function accepts three parameters: + +1. `payTo`: Your receiving address (`0x${string}`) +2. `routes`: Route configurations for protected endpoints +3. `facilitator`: (Optional) Configuration for the x402 facilitator service +4. `paywall`: (Optional) Configuration for the built-in paywall + +See the Middleware Options section below for detailed configuration options. + +## Middleware Options + +### Route Configuration + +```typescript +type RoutesConfig = Record; + +interface RouteConfig { + price: Price; // Price in USD or token amount + network: Network; // "sei" or "seiTestnet" + config?: PaymentMiddlewareConfig; +} +``` + +### Payment Configuration + +```typescript +interface PaymentMiddlewareConfig { + description?: string; // Description of the payment + mimeType?: string; // MIME type of the resource + maxTimeoutSeconds?: number; // Maximum time for payment (default: 60) + outputSchema?: Record; // JSON schema for the response + customPaywallHtml?: string; // Custom HTML for the paywall + resource?: string; // Resource URL (defaults to request URL) +} +``` + +## Example with API Routes + +Create protected API routes in your Next.js application: + +```typescript +// middleware.ts +import { paymentMiddleware } from '@sei-js/x402-next'; +import { facilitator } from '@sei-js/x402'; + +export const middleware = paymentMiddleware( + "0xYourAddress", + { + '/api/premium': { + price: '$0.05', + network: "sei", + config: { + description: 'Premium API access', + maxTimeoutSeconds: 120, + } + }, + '/api/data-feed': { + price: '$0.01', + network: "sei", + config: { + description: 'Real-time data feed', + mimeType: 'application/json', + } + } + }, + facilitator, + { + appName: 'My Next.js App', + appLogo: '/logo.png' + } +); + +export const config = { + matcher: [ + '/api/premium/:path*', + '/api/data-feed/:path*', + ] +}; +``` + +```typescript +// pages/api/premium/index.ts or app/api/premium/route.ts +export async function GET() { + return Response.json({ + message: "This is premium content", + data: { + timestamp: new Date().toISOString(), + premium: true + } + }); +} +``` + +## App Router Support + +The middleware works with both Pages Router and App Router: + +### App Router (app directory) + +```typescript +// middleware.ts +import { paymentMiddleware } from '@sei-js/x402-next'; + +export const middleware = paymentMiddleware( + "0xYourAddress", + { + '/dashboard': { + price: '$0.10', + network: "sei", + config: { + description: 'Premium dashboard access' + } + } + } +); + +export const config = { + matcher: ['/dashboard/:path*'] +}; +``` + +### Pages Router (pages directory) + +```typescript +// middleware.ts +import { paymentMiddleware } from '@sei-js/x402-next'; + +export const middleware = paymentMiddleware( + "0xYourAddress", + { + '/premium': { + price: '$0.05', + network: "sei", + config: { + description: 'Premium page access' + } + } + } +); + +export const config = { + matcher: ['/premium/:path*'] +}; +``` + +## Deployment Considerations + +### Vercel + +The middleware works seamlessly with Vercel's Edge Runtime: + +```typescript +// middleware.ts +export const config = { + matcher: [ + '/api/premium/:path*', + '/protected/:path*' + ], + runtime: 'edge' // Optional: explicitly use Edge Runtime +}; +``` + +### Other Platforms + +The middleware is compatible with any platform that supports Next.js middleware: +- Netlify +- AWS Amplify +- Railway +- Self-hosted deployments diff --git a/docs/x402/packages/x402.mdx b/docs/x402/packages/x402.mdx new file mode 100644 index 000000000..32826d99b --- /dev/null +++ b/docs/x402/packages/x402.mdx @@ -0,0 +1,58 @@ +--- +title: "@sei-js/x402" +description: Core TypeScript implementation of the x402 Payment Protocol +--- + +# @sei-js/x402 + +Core TypeScript implementation of the x402 Payment Protocol. This package provides the foundational types, schemas, and utilities that power all x402 integrations. + +## Installation + +```bash +npm install @sei-js/x402 +``` + +## Overview + +The @sei-js/x402 package provides the core building blocks for implementing the x402 Payment Protocol in TypeScript. It's designed to be used by: + +- Middleware implementations (Express, Hono, Next.js) +- Client-side payment handlers (fetch wrapper) +- Facilitator services +- Custom integrations + +## Integration Packages + +This core package is used by the following integration packages: + +- `@sei-js/x402-express`: Express.js middleware +- `@sei-js/x402-hono`: Hono middleware +- `@sei-js/x402-next`: Next.js middleware +- `@sei-js/x402-fetch`: Fetch API wrapper +- `@sei-js/x402-axios`: Axios interceptor + +## Manual Server Integration + +If you're not using one of our server middleware packages, you can implement the x402 protocol manually. Here's what you'll need to handle: + +1. Return 402 error responses with the appropriate response body +2. Use the facilitator to validate payments +3. Use the facilitator to settle payments +4. Return the appropriate response header to the caller + +## Manual Client Integration + +If you're not using our `@sei-js/x402-fetch` or `@sei-js/x402-axios` packages, you can manually integrate the x402 protocol in your client application. Here's how: + +1. Make a request to a x402-protected endpoint. The server will respond with a 402 status code and a JSON object containing: + - `x402Version`: The version of the x402 protocol being used + - `accepts`: An array of payment requirements you can fulfill + +2. Select the payment requirement you wish to fulfill from the `accepts` array + +3. Create the payment header using the selected payment requirement + +4. Retry your network call with: + - The payment header assigned to the `X-PAYMENT` field + - The `Access-Control-Expose-Headers` field set to `"X-PAYMENT-RESPONSE"` to receive the server's transaction response \ No newline at end of file diff --git a/docs/x402/quickstart.mdx b/docs/x402/quickstart.mdx new file mode 100644 index 000000000..5c2e8741f --- /dev/null +++ b/docs/x402/quickstart.mdx @@ -0,0 +1,163 @@ +--- +title: Quickstart Guide +description: Build your first paid API on Sei in under 10 minutes by using @sei-js/x402 +icon: "bolt" +--- + +## Prerequisites + +Before you begin, ensure you have the following: + + + + **Required for running x402 applications:** + - **Node.js** (v18 or higher) - Required for running x402 packages + - **npm, yarn, or pnpm** - For package management + + + Verify your installation: `node --version` should output v18.0.0 or higher + + + + + **Required for testing payments:** + - **MetaMask** or **Compass Wallet** - For signing transactions + - **Sei Testnet configured** - Add Sei testnet to your wallet + - **Test SEI tokens** - Get from [Sei Faucet](https://docs.sei.io/learn/faucet) + + + Sei testnet details: Chain ID `1328`, RPC `https://evm-rpc-testnet.sei-apis.com` + + + + + **Required configuration for your paid API:** + - **`FACILITATOR_URL`** - URL of your x402 facilitator service + - **`ADDRESS`** - Your Sei wallet address (0x format) to receive payments + + + Keep your environment variables secure and never commit them to version control + + + + + +## Create Your First Paid API + + + + Create a new project and install the required packages: + + + ```bash npm + mkdir my-paid-api && cd my-paid-api + npm init -y + npm install @sei-js/x402-express express dotenv + ``` + + ```bash yarn + mkdir my-paid-api && cd my-paid-api + yarn init -y + yarn add @sei-js/x402-express express dotenv + ``` + + ```bash pnpm + mkdir my-paid-api && cd my-paid-api + pnpm init -y + pnpm add @sei-js/x402-express express dotenv + ``` + + + + **Expected outcome:** Project directory created with x402 dependencies installed. + + + + + + **Facilitator Might be Required**: The code references `facilitatorUrl` environment variable that need to be configured. You'll need to set up a facilitator to process payments or use a public facilitator. See the [Facilitator Example](/facilitators/example) here. + + Create `server.js` with a protected API endpoint: + + ```javascript + import {config} from "dotenv"; + import express from "express"; + import {paymentMiddleware, Resource} from "@sei-js/x402-express"; + config(); + + const facilitatorUrl = process.env.FACILITATOR_URL as Resource; + const payTo = process.env.ADDRESS as `0x${string}`; + + if (!facilitatorUrl || !payTo) { + console.error("Missing required environment variables"); + process.exit(1); + } + + const app = express(); + + app.use( + paymentMiddleware( + payTo, + { + "GET /weather": { + // USDC amount in dollars + price: "$0.001", + network: "sei-testnet", + } + }, + { + url: facilitatorUrl, + }, + ), + ); + + app.get("/weather", (req, res) => { + res.send({ + report: { + weather: "sunny", + temperature: 70, + }, + }); + }); + + app.listen(4021, () => { + console.log(`Server listening at http://localhost:${4021}`); + }); + + ``` + + + **Expected outcome:** Express server configured with x402 payment middleware. + + + + + Start your server and test the payment requirement: + + ```bash + node server.js + ``` + + In another terminal, try accessing the protected endpoint: + + ```bash + curl http://localhost:4021/weather + ``` + + + **Expected outcome:** You should receive a `402 Payment Required` response with payment details. + + + Example response: + ```json + { + "error": "Payment Required", + "amount": "0.01", + "currency": "SEI", + "recipient": "YOUR_WALLET_ADDRESS", + "network": "sei-testnet" + } + ``` + + +