From a24038fe70e06c13a697b4a29c83b64fe3c12648 Mon Sep 17 00:00:00 2001 From: Eiman Date: Mon, 22 Sep 2025 09:36:35 -0500 Subject: [PATCH 1/5] Fix typo in facilitator configuration function Corrected a typo in the configuration function description. Signed-off-by: Eiman --- apps/portal/src/app/payments/x402/page.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/portal/src/app/payments/x402/page.mdx b/apps/portal/src/app/payments/x402/page.mdx index 935a5853955..3b5639600cb 100644 --- a/apps/portal/src/app/payments/x402/page.mdx +++ b/apps/portal/src/app/payments/x402/page.mdx @@ -43,7 +43,7 @@ const response = await fetchWithPay('https://api.example.com/paid-endpoint'); To make your API calls payable, you can use any x402 middleware library like x402-hono, x402-next, x402-express, etc. -Then, use the `facilitator` configuratino function settle transactions with your thirdweb server wallet gaslessly and pass it to the middleware. +Then, use the `facilitator` configuration function to settle transactions with your thirdweb server wallet gaslessly and pass it to the middleware. Here's an example with Next.js: From f0fac5a7e4a89d83ee4033ab08428e7c7c60ea79 Mon Sep 17 00:00:00 2001 From: Eiman Date: Mon, 22 Sep 2025 14:10:48 -0500 Subject: [PATCH 2/5] added explanation to x402 pages --- apps/portal/src/app/payments/x402/page.mdx | 241 ++++++++++++++++++++- 1 file changed, 233 insertions(+), 8 deletions(-) diff --git a/apps/portal/src/app/payments/x402/page.mdx b/apps/portal/src/app/payments/x402/page.mdx index 3b5639600cb..f922fa3052c 100644 --- a/apps/portal/src/app/payments/x402/page.mdx +++ b/apps/portal/src/app/payments/x402/page.mdx @@ -12,18 +12,110 @@ Implement paid API calls using the x402 protocol. Every request is paid for by t href="https://playground.thirdweb.com/payments/x402" /> -## Client Side +## Introduction & Core Concepts + +The **x402 payment protocol** enables micropayments for API access, allowing developers to monetize their APIs with per-request pricing. Instead of traditional subscription models or API keys, users pay small amounts (typically $0.01-$0.10) for each API call using cryptocurrency. + +### How it works +When a user makes a request to a paid API: +1. The API returns a `402 Payment Required` response with payment details +2. The user's wallet signs a payment authorization +3. The request is retried with a payment header +4. The API validates the payment and returns the requested data +5. The payment is settled on-chain to the API provider + +### Benefits +- **No subscriptions**: Users only pay for what they use +- **Global access**: Works with any web3 wallet worldwide +- **Instant monetization**: Start earning from your APIs immediately +- **Micropayment friendly**: Perfect for small, frequent transactions + +## X402 Protocol Fundamentals + +### Payment Flow +The x402 protocol follows a simple request-retry pattern: + +1. **Initial request**: Client makes normal API call +2. **402 response**: Server responds with payment requirements if payment needed +3. **Payment authorization**: User signs payment message in their wallet +4. **Retry with payment**: Request is retried with payment header +5. **Content delivery**: Server validates payment and returns content + +### Facilitators +A **facilitator** is a service that handles payment verification and settlement for x402 payments. Think of it as the payment processor that: +- Validates payment signatures from users +- Executes on-chain transfers to collect payments +- Provides payment infrastructure to API providers + +### Payment Schemes +Currently, x402 supports: +- **"exact"**: Fixed price payments (e.g., exactly $0.01 USDC) +- Additional schemes (percentage-based, auction-style) are planned for future versions + +### Security Model +- **Signature-based**: Users sign payment authorizations, no direct token transfers from client +- **Replay protection**: Each payment includes unique identifiers to prevent reuse +- **Amount validation**: Clients can set maximum payment limits for protection + +## Supported Payment Networks & Tokens + +### Supported Networks +thirdweb's x402 facilitator currently supports payments on: +- **Base** (mainnet) +- **Base Sepolia** (testnet) +- **Avalanche** (C-Chain) +- **Avalanche Fuji** (testnet) +- **IoTeX** (mainnet) +- **Sei** (mainnet) +- **Sei Testnet** + +### Payment Tokens +- **Primary**: USDC on all supported networks +- **Stablecoins**: Other USD-pegged tokens as available per network +- **Network selection**: Client and server automatically negotiate the best payment network + +### Chain Switching +If your wallet is connected to a different network than required for payment, the client will automatically: +1. Detect the payment network requirement +2. Prompt you to switch to the correct network +3. Proceed with payment once switched + +## thirdweb as X402 Facilitator + +thirdweb provides a complete x402 facilitator service that handles all the payment infrastructure for your APIs. + +### What thirdweb Provides +- **Payment verification**: Validates user payment signatures and wallet balances +- **Multi-chain settlement**: Supports payments across multiple blockchain networks +- **Server wallet integration**: Uses your configured server wallet to receive payments +- **Gasless transactions**: Handles all gas costs for payment settlement +- **Automatic execution**: Payments are settled without manual intervention + +### Server Wallet Concept +Your **server wallet** is the blockchain address where all API payments are collected. When users pay for API access: +1. They sign a payment authorization to your server wallet address +2. thirdweb validates the payment signature and user's token balance +3. thirdweb executes the token transfer to your server wallet +4. You receive the payment automatically without gas costs + +### Integration Benefits +- **Simple setup**: Just provide your server wallet address and thirdweb secret key +- **No blockchain complexity**: thirdweb handles all on-chain interactions +- **Reliable settlement**: Payments are automatically executed when valid +- **Multi-chain support**: Accept payments on multiple networks simultaneously + +## Client-Side Implementation + +### Basic Usage `wrapFetchWithPayment` wraps the native fetch API to automatically handle `402 Payment Required` responses from any API call. It will: 1. Make the initial request 2. If a 402 response is received, parse the payment requirements 3. Verify the payment amount is within the allowed maximum -4. Sign a payment authorization +4. Sign a payment authorization 5. Create a payment header using the provided wallet signature 6. Retry the request with the payment header -Here's an example: - ```typescript import { wrapFetchWithPayment } from "thirdweb/x402"; import { createThirdwebClient } from "thirdweb"; @@ -39,9 +131,82 @@ const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet); const response = await fetchWithPay('https://api.example.com/paid-endpoint'); ``` -## Server Side +### Advanced Configuration + +You can configure payment limits and behavior: + +```typescript +// Set maximum payment amount (default: 1 USDC) +const fetchWithPay = wrapFetchWithPayment( + fetch, + client, + wallet, + BigInt(5 * 10 ** 6) // Maximum 5 USDC +); +``` + +### Error Handling + +Handle different payment scenarios: + +```typescript +try { + const response = await fetchWithPay('/api/paid-endpoint'); + const data = await response.json(); +} catch (error) { + if (error.message.includes("Payment amount exceeds maximum")) { + // Handle payment too expensive + console.error("Payment required exceeds your limit"); + } else if (error.message.includes("Wallet not connected")) { + // Handle wallet connection issues + console.error("Please connect your wallet"); + } else if (error.message.includes("Payment already attempted")) { + // Handle retry scenarios + console.error("Payment was already processed"); + } else { + // Handle other errors (user rejected, insufficient funds, etc.) + console.error("Payment failed:", error.message); + } +} +``` + +### React Integration + +Use with React hooks for better UX: + +```typescript +import { useActiveWallet } from "thirdweb/react"; +import { useMutation } from "@tanstack/react-query"; + +function PayableAPICall() { + const wallet = useActiveWallet(); -To make your API calls payable, you can use any x402 middleware library like x402-hono, x402-next, x402-express, etc. + const paidApiCall = useMutation({ + mutationFn: async () => { + if (!wallet) throw new Error("Wallet not connected"); + + const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet); + const response = await fetchWithPay('/api/paid-endpoint'); + return response.json(); + }, + }); + + return ( + + ); +} +``` + +## Server-Side Implementation + +### Basic Middleware Setup + +To make your API calls payable, you can use any x402 middleware library like `x402-hono`, `x402-next`, `x402-express`, etc. Then, use the `facilitator` configuration function to settle transactions with your thirdweb server wallet gaslessly and pass it to the middleware. @@ -57,7 +222,7 @@ const client = createThirdwebClient({ }); export const middleware = paymentMiddleware( - "0xdd99b75f095d0c4d5112aCe938e4e6ed962fb024", + "0xdd99b75f095d0c4d5112aCe938e4e6ed962fb024", // Your server wallet address { "/api/paid-endpoint": { price: "$0.01", @@ -69,7 +234,7 @@ export const middleware = paymentMiddleware( }, facilitator({ client, - serverWalletAddress: "0x1234567890123456789012345678901234567890", + serverWalletAddress: process.env.SERVER_WALLET_ADDRESS, }), ); @@ -78,3 +243,63 @@ export const config = { matcher: ["/api/paid-endpoint"], }; ``` + +### Facilitator Configuration Deep-Dive + +The `facilitator` function accepts several configuration options: + +```typescript +facilitator({ + client: thirdwebClient, // Your thirdweb client with secret key + serverWalletAddress: "0x..." // Where payments are collected +}) +``` + +### Multiple Endpoint Configuration + +Configure different pricing for multiple API endpoints: + +```typescript +export const middleware = paymentMiddleware( + serverWalletAddress, + { + "/api/basic-data": { + price: "$0.01", + network: "base-sepolia", + config: { description: "Basic data access" }, + }, + "/api/premium-analytics": { + price: "$0.05", + network: "base", // Use mainnet for higher-value endpoints + config: { description: "Premium analytics data" }, + }, + "/api/ai-processing": { + price: "$0.10", + network: "base", + config: { description: "AI-powered data processing" }, + }, + }, + facilitator({ client, serverWalletAddress }), +); + +export const config = { + matcher: ["/api/basic-data", "/api/premium-analytics", "/api/ai-processing"], +}; +``` + +### Environment Variables + +Set up the required environment variables: + +```bash +# .env.local +THIRDWEB_SECRET_KEY=your_thirdweb_secret_key +SERVER_WALLET_ADDRESS=0x1234567890123456789012345678901234567890 +``` + +### Security Considerations + +- **Never expose your secret key**: Keep `THIRDWEB_SECRET_KEY` in server environment only +- **Server wallet security**: Use a dedicated wallet for collecting payments, separate from development wallets +- **Network selection**: Use testnets for development, mainnets for production +- **Price validation**: Set appropriate prices to prevent abuse while maintaining accessibility From de1547f53e0c060ec124f0104fda96726bfb780f Mon Sep 17 00:00:00 2001 From: Eiman Date: Mon, 22 Sep 2025 15:35:54 -0500 Subject: [PATCH 3/5] changed x402 to 402 Gated Payments --- apps/portal/src/app/payments/x402/page.mdx | 44 +++++++++++----------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/apps/portal/src/app/payments/x402/page.mdx b/apps/portal/src/app/payments/x402/page.mdx index f922fa3052c..fac709e2651 100644 --- a/apps/portal/src/app/payments/x402/page.mdx +++ b/apps/portal/src/app/payments/x402/page.mdx @@ -1,20 +1,20 @@ import { ArticleIconCard } from "@doc"; import { ReactIcon } from "@/icons"; -# x402 payments +# 402 Gated Payments -Implement paid API calls using the x402 protocol. Every request is paid for by the user with a micro payment onchain. +Implement gated API access with pay-per-request pricing. Users pay small amounts for each API call using cryptocurrency through the HTTP 402 Payment Required protocol. ## Introduction & Core Concepts -The **x402 payment protocol** enables micropayments for API access, allowing developers to monetize their APIs with per-request pricing. Instead of traditional subscription models or API keys, users pay small amounts (typically $0.01-$0.10) for each API call using cryptocurrency. +**402 gated payments** enable micropayments for API access using the HTTP 402 Payment Required status code, allowing developers to monetize their APIs with per-request pricing. Instead of traditional subscription models or API keys, users pay small amounts (typically $0.01-$0.10) for each API call using cryptocurrency. ### How it works When a user makes a request to a paid API: @@ -30,10 +30,10 @@ When a user makes a request to a paid API: - **Instant monetization**: Start earning from your APIs immediately - **Micropayment friendly**: Perfect for small, frequent transactions -## X402 Protocol Fundamentals +## 402 Payment Protocol Fundamentals ### Payment Flow -The x402 protocol follows a simple request-retry pattern: +The 402 payment protocol follows a simple request-retry pattern: 1. **Initial request**: Client makes normal API call 2. **402 response**: Server responds with payment requirements if payment needed @@ -41,16 +41,16 @@ The x402 protocol follows a simple request-retry pattern: 4. **Retry with payment**: Request is retried with payment header 5. **Content delivery**: Server validates payment and returns content -### Facilitators -A **facilitator** is a service that handles payment verification and settlement for x402 payments. Think of it as the payment processor that: +### Payment Processors +A **payment processor** is a service that handles payment verification and settlement for 402 payments. Think of it as the backend service that: - Validates payment signatures from users - Executes on-chain transfers to collect payments - Provides payment infrastructure to API providers ### Payment Schemes -Currently, x402 supports: -- **"exact"**: Fixed price payments (e.g., exactly $0.01 USDC) -- Additional schemes (percentage-based, auction-style) are planned for future versions +thirdweb's 402 payment implementation currently supports: +- **"exact"**: Fixed price payments (e.g., exactly $0.01 USDC) - our first supported scheme +- Additional schemes (percentage-based, auction-style, variable pricing) are planned for future versions ### Security Model - **Signature-based**: Users sign payment authorizations, no direct token transfers from client @@ -60,7 +60,7 @@ Currently, x402 supports: ## Supported Payment Networks & Tokens ### Supported Networks -thirdweb's x402 facilitator currently supports payments on: +thirdweb's 402 payment processor currently supports payments on: - **Base** (mainnet) - **Base Sepolia** (testnet) - **Avalanche** (C-Chain) @@ -80,9 +80,9 @@ If your wallet is connected to a different network than required for payment, th 2. Prompt you to switch to the correct network 3. Proceed with payment once switched -## thirdweb as X402 Facilitator +## thirdweb as 402 Payment Processor -thirdweb provides a complete x402 facilitator service that handles all the payment infrastructure for your APIs. +thirdweb provides a complete 402 payment processing service that handles all the payment infrastructure for your APIs. ### What thirdweb Provides - **Payment verification**: Validates user payment signatures and wallet balances @@ -108,7 +108,7 @@ Your **server wallet** is the blockchain address where all API payments are coll ### Basic Usage -`wrapFetchWithPayment` wraps the native fetch API to automatically handle `402 Payment Required` responses from any API call. It will: +`wrapFetchWithPayment` wraps the native fetch API to automatically handle `402 Payment Required` responses, implementing thirdweb's "exact" payment scheme. It will: 1. Make the initial request 2. If a 402 response is received, parse the payment requirements 3. Verify the payment amount is within the allowed maximum @@ -206,9 +206,9 @@ function PayableAPICall() { ### Basic Middleware Setup -To make your API calls payable, you can use any x402 middleware library like `x402-hono`, `x402-next`, `x402-express`, etc. +To make your API calls payable, you can use any 402 payment middleware library. thirdweb provides payment processor integration for popular frameworks like `x402-next`, `x402-hono`, `x402-express`, etc. -Then, use the `facilitator` configuration function to settle transactions with your thirdweb server wallet gaslessly and pass it to the middleware. +Then, use the thirdweb payment processor configuration to settle transactions with your server wallet gaslessly and pass it to the middleware. Here's an example with Next.js: @@ -235,7 +235,7 @@ export const middleware = paymentMiddleware( facilitator({ client, serverWalletAddress: process.env.SERVER_WALLET_ADDRESS, - }), + }), // thirdweb payment processor configuration ); // Configure which paths the middleware should run on @@ -244,9 +244,9 @@ export const config = { }; ``` -### Facilitator Configuration Deep-Dive +### Payment Processor Configuration Deep-Dive -The `facilitator` function accepts several configuration options: +The `facilitator` function configures thirdweb's payment processor and accepts several options: ```typescript facilitator({ @@ -279,7 +279,7 @@ export const middleware = paymentMiddleware( config: { description: "AI-powered data processing" }, }, }, - facilitator({ client, serverWalletAddress }), + facilitator({ client, serverWalletAddress }), // thirdweb payment processor ); export const config = { From b5965b0726c8adef56c8f91e041ea140c3153932 Mon Sep 17 00:00:00 2001 From: Eiman Date: Mon, 22 Sep 2025 16:47:50 -0500 Subject: [PATCH 4/5] cleaned up text --- apps/portal/src/app/payments/x402/page.mdx | 81 +++++++--------------- 1 file changed, 25 insertions(+), 56 deletions(-) diff --git a/apps/portal/src/app/payments/x402/page.mdx b/apps/portal/src/app/payments/x402/page.mdx index fac709e2651..e3cc2510724 100644 --- a/apps/portal/src/app/payments/x402/page.mdx +++ b/apps/portal/src/app/payments/x402/page.mdx @@ -32,15 +32,6 @@ When a user makes a request to a paid API: ## 402 Payment Protocol Fundamentals -### Payment Flow -The 402 payment protocol follows a simple request-retry pattern: - -1. **Initial request**: Client makes normal API call -2. **402 response**: Server responds with payment requirements if payment needed -3. **Payment authorization**: User signs payment message in their wallet -4. **Retry with payment**: Request is retried with payment header -5. **Content delivery**: Server validates payment and returns content - ### Payment Processors A **payment processor** is a service that handles payment verification and settlement for 402 payments. Think of it as the backend service that: - Validates payment signatures from users @@ -52,11 +43,6 @@ thirdweb's 402 payment implementation currently supports: - **"exact"**: Fixed price payments (e.g., exactly $0.01 USDC) - our first supported scheme - Additional schemes (percentage-based, auction-style, variable pricing) are planned for future versions -### Security Model -- **Signature-based**: Users sign payment authorizations, no direct token transfers from client -- **Replay protection**: Each payment includes unique identifiers to prevent reuse -- **Amount validation**: Clients can set maximum payment limits for protection - ## Supported Payment Networks & Tokens ### Supported Networks @@ -68,41 +54,41 @@ thirdweb's 402 payment processor currently supports payments on: - **IoTeX** (mainnet) - **Sei** (mainnet) - **Sei Testnet** +- **Solana (coming soon)** +- **Solana Devnet (coming soon)** ### Payment Tokens - **Primary**: USDC on all supported networks - **Stablecoins**: Other USD-pegged tokens as available per network - **Network selection**: Client and server automatically negotiate the best payment network -### Chain Switching -If your wallet is connected to a different network than required for payment, the client will automatically: -1. Detect the payment network requirement -2. Prompt you to switch to the correct network -3. Proceed with payment once switched +## thirdweb 402 Payment Components -## thirdweb as 402 Payment Processor +thirdweb provides a complete 402 payment system with components for both client and server sides, plus backend payment processing infrastructure. -thirdweb provides a complete 402 payment processing service that handles all the payment infrastructure for your APIs. +### Client-Side Components +**For app developers integrating payment functionality:** +- **`wrapFetchWithPayment`**: Automatically handles 402 responses and payment flows +- **Wallet integration**: Works with any thirdweb-supported wallet (inapp, MetaMask, WalletConnect, etc.) +- **Payment authorization**: Prompts users to sign payment messages when needed +- **Chain switching**: Automatically switches to the required payment network +- **Error handling**: Manages payment failures, insufficient funds, and user rejections -### What thirdweb Provides +### Server-Side Components +**For API providers implementing gated endpoints:** +- **Middleware libraries**: Integration with popular frameworks (`x402-next`, `x402-hono`, `x402-express`) - **Payment verification**: Validates user payment signatures and wallet balances -- **Multi-chain settlement**: Supports payments across multiple blockchain networks -- **Server wallet integration**: Uses your configured server wallet to receive payments -- **Gasless transactions**: Handles all gas costs for payment settlement -- **Automatic execution**: Payments are settled without manual intervention - -### Server Wallet Concept -Your **server wallet** is the blockchain address where all API payments are collected. When users pay for API access: -1. They sign a payment authorization to your server wallet address -2. thirdweb validates the payment signature and user's token balance -3. thirdweb executes the token transfer to your server wallet -4. You receive the payment automatically without gas costs - -### Integration Benefits -- **Simple setup**: Just provide your server wallet address and thirdweb secret key -- **No blockchain complexity**: thirdweb handles all on-chain interactions -- **Reliable settlement**: Payments are automatically executed when valid -- **Multi-chain support**: Accept payments on multiple networks simultaneously +- **Multi-chain support**: Accepts payments across multiple blockchain networks +- **Automatic settlement**: Executes token transfers to your server wallet +- **Gasless transactions**: thirdweb covers all gas costs for payment processing + +### Server Wallet +Your **Server Wallet** is the blockchain address where all API payments are collected: +- **Payment destination**: Users authorize payments to this specific wallet address +- **Multi-network**: Same wallet can receive payments across different supported chains +- **Automatic collection**: thirdweb handles the transfer execution without manual intervention +- **Gasless payments**: Payment transfers are performed in gasless fashion to reduce friction +- **Real-time settlement**: Payments arrive in your wallet immediately after validation ## Client-Side Implementation @@ -286,20 +272,3 @@ export const config = { matcher: ["/api/basic-data", "/api/premium-analytics", "/api/ai-processing"], }; ``` - -### Environment Variables - -Set up the required environment variables: - -```bash -# .env.local -THIRDWEB_SECRET_KEY=your_thirdweb_secret_key -SERVER_WALLET_ADDRESS=0x1234567890123456789012345678901234567890 -``` - -### Security Considerations - -- **Never expose your secret key**: Keep `THIRDWEB_SECRET_KEY` in server environment only -- **Server wallet security**: Use a dedicated wallet for collecting payments, separate from development wallets -- **Network selection**: Use testnets for development, mainnets for production -- **Price validation**: Set appropriate prices to prevent abuse while maintaining accessibility From d245b2e675968336d73e017e2b39db24d4a8d910 Mon Sep 17 00:00:00 2001 From: Eiman Date: Mon, 22 Sep 2025 16:50:47 -0500 Subject: [PATCH 5/5] took out react section --- apps/portal/src/app/payments/x402/page.mdx | 32 ---------------------- 1 file changed, 32 deletions(-) diff --git a/apps/portal/src/app/payments/x402/page.mdx b/apps/portal/src/app/payments/x402/page.mdx index e3cc2510724..ee8f467b16c 100644 --- a/apps/portal/src/app/payments/x402/page.mdx +++ b/apps/portal/src/app/payments/x402/page.mdx @@ -156,38 +156,6 @@ try { } ``` -### React Integration - -Use with React hooks for better UX: - -```typescript -import { useActiveWallet } from "thirdweb/react"; -import { useMutation } from "@tanstack/react-query"; - -function PayableAPICall() { - const wallet = useActiveWallet(); - - const paidApiCall = useMutation({ - mutationFn: async () => { - if (!wallet) throw new Error("Wallet not connected"); - - const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet); - const response = await fetchWithPay('/api/paid-endpoint'); - return response.json(); - }, - }); - - return ( - - ); -} -``` - ## Server-Side Implementation ### Basic Middleware Setup