### Install @payai/x402-solana Package Source: https://www.npmjs.com/package/@payai/x402-solana/index_activeTab=code Instructions for installing the @payai/x402-solana package using popular package managers like pnpm, npm, and yarn. ```bash pnpm add @payai/x402-solana ``` ```bash npm install @payai/x402-solana ``` ```bash yarn add @payai/x402-solana ``` -------------------------------- ### Example: Create Payment Requirements with Environment Variables Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=versions Demonstrates how to dynamically create payment requirements using environment variables for network and base URL, and selecting the appropriate USDC mint address. ```javascript import { createPaymentRequirements } from '@payai/x402-solana'; const USDC_MINT = process.env.NODE_ENV === 'production' ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // mainnet : '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'; // devnet const paymentRequirements = await createPaymentRequirements({ price: { amount: "1000000", // $1.00 USDC asset: { address: USDC_MINT } }, network: process.env.NODE_ENV === 'production' ? 'solana' : 'solana-devnet', config: { description: 'Payment', resource: `${process.env.NEXT_PUBLIC_BASE_URL}/api/endpoint`, } }); ``` -------------------------------- ### Example: Creating Payment Requirements Dynamically Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependents Demonstrates how to dynamically create payment requirements using environment variables to select the correct network and USDC mint address, along with a base URL for the resource. ```javascript import { createPaymentRequirements } from '@payai/x402-solana/server'; const USDC_MINT = process.env.NODE_ENV === 'production' ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // mainnet : '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'; // devnet const paymentRequirements = await createPaymentRequirements({ price: { amount: "1000000", // $1.00 USDC asset: { address: USDC_MINT } }, network: process.env.NODE_ENV === 'production' ? 'solana' : 'solana-devnet', config: { description: 'Payment for API access', resource: `${process.env.NEXT_PUBLIC_BASE_URL}/api/protected-endpoint`, } }); ``` -------------------------------- ### Example: Create Payment Requirements with Environment Variables Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code Demonstrates how to dynamically select the correct USDC mint address and Solana network based on the environment (production vs. development) and use these to create payment requirements. It also shows how to construct the resource URL using a base URL environment variable. ```javascript const USDC_MINT = process.env.NODE_ENV === 'production' ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // mainnet : '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'; // devnet const paymentRequirements = await x402.createPaymentRequirements({ price: { amount: "1000000", // $1.00 USDC asset: { address: USDC_MINT } }, network: process.env.NODE_ENV === 'production' ? 'solana' : 'solana-devnet', config: { description: 'Payment', resource: `${process.env.NEXT_PUBLIC_BASE_URL}/api/endpoint`, } }); ``` -------------------------------- ### Example: Create Payment Requirements Dynamically Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependencies Demonstrates how to dynamically create payment requirements using environment variables for network and base URL, and selecting the correct USDC mint address based on the environment. ```typescript const USDC_MINT = process.env.NODE_ENV === 'production' ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // mainnet : '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'; // devnet const paymentRequirements = await x402.createPaymentRequirements({ price: { amount: "1000000", // $1.00 USDC asset: { address: USDC_MINT } }, network: process.env.NODE_ENV === 'production' ? 'solana' : 'solana-devnet', config: { description: 'Payment', resource: `${process.env.BASE_URL}/api/endpoint`, } }); ``` -------------------------------- ### Server-Side Paid Endpoint in Express with @payai/x402-solana Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code This example illustrates how to implement a paid endpoint using Express.js. It follows a similar logic to the Next.js example, including extracting payment headers, setting up payment requirements, verifying payments, handling business logic, and settling payments. Ensure `process.env.TREASURY_WALLET_ADDRESS` and `process.env.BASE_URL` are configured. ```typescript import express from 'express'; import { X402PaymentHandler } from '@payai/x402-solana/server'; const app = express(); const x402 = new X402PaymentHandler({ network: 'solana-devnet', treasuryAddress: process.env.TREASURY_WALLET_ADDRESS!, facilitatorUrl: 'https://facilitator.payai.network', }); app.post('/api/paid-endpoint', async (req, res) => { const paymentHeader = x402.extractPayment(req.headers); const paymentRequirements = await x402.createPaymentRequirements({ price: { amount: "2500000", // $2.50 USDC asset: { address: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU" // USDC devnet } }, network: 'solana-devnet', config: { description: 'API Request', resource: `${process.env.BASE_URL}/api/paid-endpoint`, } }); if (!paymentHeader) { const response = x402.create402Response(paymentRequirements); return res.status(response.status).json(response.body); } const verified = await x402.verifyPayment(paymentHeader, paymentRequirements); if (!verified) { return res.status(402).json({ error: 'Invalid payment' }); } const result = await yourBusinessLogic(req); await x402.settlePayment(paymentHeader, paymentRequirements); res.json(result); }); ``` -------------------------------- ### USDC Mint Addresses and Example Usage (JavaScript) Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=readme Provides USDC token mint addresses for Solana devnet and mainnet, demonstrating how to dynamically select the correct address based on the environment and use it when creating payment requirements. ```javascript import { createPaymentRequirements } from '@payai/x402-solana/server'; // Assuming server import for example const USDC_MINT_DEVNET = '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'; const USDC_MINT_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; const isProduction = process.env.NODE_ENV === 'production'; const network = isProduction ? 'solana' : 'solana-devnet'; const usdcMint = isProduction ? USDC_MINT_MAINNET : USDC_MINT_DEVNET; const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000'; const paymentRequirements = await createPaymentRequirements({ price: { amount: "1000000", // $1.00 USDC asset: { address: usdcMint } }, network: network, config: { description: 'Premium API Access', resource: `${baseUrl}/api/protected-resource` } }); console.log(paymentRequirements); ``` -------------------------------- ### Client Initialization Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=versions How to create a new x402 client instance with the necessary configuration. ```APIDOC ## POST /api/client ### Description Creates a new x402 client instance. ### Method POST ### Endpoint /api/client ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the client. - **wallet** (WalletAdapter) - Required - Wallet with `signTransaction` method. - **network** ('solana' | 'solana-devnet') - Required - The network to use. - **rpcUrl** (string) - Optional - Custom RPC URL. - **maxPaymentAmount** (bigint) - Optional - Safety limit for payments. ### Request Example ```json { "config": { "wallet": "YOUR_WALLET_ADAPTER", "network": "solana-devnet", "rpcUrl": "https://api.devnet.solana.com", "maxPaymentAmount": "1000000000" } } ``` ### Response #### Success Response (200) - **client** (object) - The initialized x402 client instance. #### Response Example ```json { "client": "X402_CLIENT_INSTANCE" } ``` ``` -------------------------------- ### Client Creation Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=readme How to create a new x402 client instance with the necessary configuration. ```APIDOC ## POST /api/x402/client ### Description Creates a new x402 client instance. This client is used to interact with X402 payment functionalities. ### Method POST ### Endpoint /api/x402/client ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the client. - **wallet** (WalletAdapter) - Required - A wallet adapter instance with a `signTransaction` method. - **network** (string) - Required - The network to use, either 'solana' or 'solana-devnet'. - **rpcUrl** (string) - Optional - A custom RPC URL. - **maxPaymentAmount** (bigint) - Optional - A safety limit for payment amounts. ### Request Example ```json { "config": { "wallet": { "address": "YOUR_WALLET_ADDRESS", "signTransaction": "async (tx) => tx" }, "network": "solana-devnet", "rpcUrl": "https://api.devnet.solana.com", "maxPaymentAmount": "1000000000" } } ``` ### Response #### Success Response (200) - **client** (object) - The created x402 client instance. #### Response Example ```json { "client": { "fetch": "function" } } ``` ``` -------------------------------- ### Client Initialization Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code Creates a new x402 client instance for making fetch requests with automatic payment handling. ```APIDOC ## createX402Client(config) ### Description Creates a new x402 client instance. ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the client. - **wallet** (WalletAdapter) - Required - A wallet adapter with a `signTransaction` method. - **network** ('solana' | 'solana-devnet') - Required - The Solana network to use. - **rpcUrl** (string) - Optional - A custom RPC URL. - **maxPaymentAmount** (bigint) - Optional - A safety limit for payment amounts. ### Request Example ```javascript import { createX402Client } from '@payai/x402-solana'; const config = { wallet: yourWalletAdapter, network: 'solana-devnet', rpcUrl: 'https://api.devnet.solana.com', }; const client = createX402Client(config); ``` ### Methods - `client.fetch(input, init)` - Make a fetch request with automatic payment handling. ``` -------------------------------- ### Client Initialization Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependents This section details how to create a new x402 client instance for making payments. ```APIDOC ## POST /api/client ### Description Creates a new x402 client instance for handling payments. ### Method POST ### Endpoint /api/client ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the x402 client. - **wallet** (WalletAdapter) - Required - A wallet adapter with a `signTransaction` method. - **network** ('solana' | 'solana-devnet') - Required - The network to use. - **rpcUrl** (string) - Optional - A custom RPC URL. - **maxPaymentAmount** (bigint) - Optional - A safety limit for payment amounts. ### Request Example ```json { "config": { "wallet": { "address": "YOUR_WALLET_ADDRESS", "signTransaction": "async (tx) => tx" }, "network": "solana-devnet", "rpcUrl": "https://api.devnet.solana.com", "maxPaymentAmount": 1000000000n } } ``` ### Response #### Success Response (200) - **client** (object) - The initialized x402 client instance. #### Response Example ```json { "client": "" } ``` ``` -------------------------------- ### Create x402 Client (JavaScript) Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=readme Initializes a new x402 client instance. Requires a wallet adapter, network configuration, and optionally custom RPC URLs or a maximum payment amount. ```javascript import { createX402Client } from '@payai/x402-solana'; const config = { wallet: walletAdapter, // Your WalletAdapter instance network: 'solana-devnet', // or 'solana' rpcUrl: 'https://api.devnet.solana.com', maxPaymentAmount: 1000000n // Optional safety limit }; const client = createX402Client(config); // Example usage of fetch method: // const response = await client.fetch('/api/data'); ``` -------------------------------- ### Configuration Details Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependents Details on environment variables, USDC mint addresses, and the wallet adapter interface. ```APIDOC ## Configuration ### Environment Variables - `NEXT_PUBLIC_NETWORK`: Sets the network ('solana' or 'solana-devnet'), defaults to 'solana-devnet'. - `TREASURY_WALLET_ADDRESS`: Your wallet address for receiving payments. - `NEXT_PUBLIC_SOLANA_RPC_DEVNET`: Custom RPC URL for Solana devnet. - `NEXT_PUBLIC_SOLANA_RPC_MAINNET`: Custom RPC URL for Solana mainnet. - `NEXT_PUBLIC_BASE_URL`: Base URL for the `resource` field in route configuration. ### USDC Mint Addresses - **Devnet**: `4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU` - **Mainnet**: `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` ### Example RouteConfig with Environment Variables ```javascript const USDC_MINT = process.env.NODE_ENV === 'production' ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // mainnet : '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'; // devnet const paymentRequirements = await x402.createPaymentRequirements({ price: { amount: "1000000", // $1.00 USDC asset: { address: USDC_MINT } }, network: process.env.NODE_ENV === 'production' ? 'solana' : 'solana-devnet', config: { description: 'Payment', resource: `${process.env.NEXT_PUBLIC_BASE_URL}/api/endpoint`, } }); ``` ### Wallet Adapter Interface The package requires a wallet adapter conforming to the following interface: ```typescript interface WalletAdapter { address: string; signTransaction: (tx: VersionedTransaction) => Promise; } ``` This interface is compatible with popular wallet SDKs like Privy, Phantom, and Solflare. ``` -------------------------------- ### Create X402 Client Instance Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=versions Initializes a new x402 client with a provided configuration object. This client is used for making fetch requests with automatic payment handling. It requires a wallet adapter and network configuration. ```javascript import { createX402Client } from '@payai/x402-solana'; const client = createX402Client({ wallet: walletAdapter, // An object with signTransaction method network: 'solana' | 'solana-devnet', rpcUrl: 'optional_custom_rpc_url', maxPaymentAmount: 1000000n // Optional safety limit }); ``` -------------------------------- ### Client Creation Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependencies Creates a new x402 client instance with the provided configuration. ```APIDOC ## createX402Client(config) ### Description Creates a new x402 client instance. ### Method `createX402Client` ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the client. - **wallet** (WalletAdapter) - Required - Wallet with `signTransaction` method. - **network** ('solana' | 'solana-devnet') - Required - The Solana network to use. - **rpcUrl** (string) - Optional - Custom RPC URL. - **maxPaymentAmount** (bigint) - Optional - Safety limit for payments. ### Request Example ```javascript import { createX402Client } from '@payai/x402-solana'; const config = { wallet: yourWalletAdapter, network: 'solana-devnet', rpcUrl: 'https://api.devnet.solana.com', maxPaymentAmount: 1000000n }; const client = createX402Client(config); ``` ### Response #### Success Response (200) - **client** (object) - The initialized x402 client instance. ### Methods - `client.fetch(input, init)` - Make a fetch request with automatic payment handling. ``` -------------------------------- ### Create x402 Client Instance Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependencies Initializes a new x402 client with a provided configuration object. Requires a wallet adapter, network type, and optionally accepts a custom RPC URL and a maximum payment amount limit. ```typescript import { WalletAdapter } from '@solana/wallet-adapter-base'; interface X402ClientConfig { wallet: WalletAdapter; network: 'solana' | 'solana-devnet'; rpcUrl?: string; maxPaymentAmount?: bigint; } // Assuming x402 is imported elsewhere // const client = x402.createX402Client(config); // Example usage: const config: X402ClientConfig = { wallet: yourWalletAdapter, // Replace with your actual wallet adapter network: 'solana-devnet', rpcUrl: 'https://api.devnet.solana.com' }; // const client = createX402Client(config); ``` -------------------------------- ### Testing the Package Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependents Instructions on how to use the integrated testing route to verify package functionality. ```APIDOC ## Testing Navigate to the `/x402-test` route within your application to perform independent testing of the package. The test suite verifies the following functionalities: - Successful import of package components. - Correct instantiation of the client with a wallet adapter. - Proper functioning of automatic 402 payment handling. - Successful transaction signing and submission. - Completion of payment verification and settlement processes. ``` -------------------------------- ### Environment Variables for Configuration Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependencies Lists essential environment variables for configuring the x402-solana package. Includes network settings, treasury wallet address, RPC URLs for different networks, and the base URL for resources. ```bash # Network (optional, defaults to devnet) NEXT_PUBLIC_NETWORK=solana-devnet # Treasury wallet address (where payments are sent) TREASURY_WALLET_ADDRESS=your_treasury_address # Optional: Custom RPC URLs NEXT_PUBLIC_SOLANA_RPC_DEVNET=https://api.devnet.solana.com NEXT_PUBLIC_SOLANA_RPC_MAINNET=https://api.mainnet-beta.solana.com # Base URL for resource field NEXT_PUBLIC_BASE_URL=http://localhost:3000 ``` -------------------------------- ### Create x402 Client Instance Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependents Initializes a new x402 client for making fetch requests with automatic payment handling. Requires a wallet adapter, network configuration, and optionally custom RPC URLs and a maximum payment amount. ```typescript import { createX402Client } from '@payai/x402-solana'; import { WalletAdapter } from '@solana/wallet-adapter-base'; const config = { wallet: walletAdapter as WalletAdapter, // Replace with your actual wallet adapter network: 'solana' | 'solana-devnet', rpcUrl: 'https://api.devnet.solana.com', maxPaymentAmount: 10000000n }; const client = createX402Client(config); // Example usage of fetch with automatic payment handling // const response = await client.fetch('/api/protected-resource'); ``` -------------------------------- ### Create x402 Client Instance Source: https://www.npmjs.com/package/@payai/x402-solana/index_activeTab=code Instantiates a new x402 client for making fetch requests with automatic payment handling. Requires a wallet adapter, network configuration, and optionally custom RPC URLs or a maximum payment amount. ```javascript import { createX402Client } from '@payai/x402-solana'; const config = { wallet: walletAdapter, // Wallet with signTransaction method network: 'solana' | 'solana-devnet', rpcUrl: 'optional_custom_rpc_url', maxPaymentAmount: 1000000n // Optional safety limit }; const client = createX402Client(config); // Make a fetch request with automatic payment handling const response = await client.fetch('/api/resource', { method: 'GET' }); ``` -------------------------------- ### Client Fetch Method Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=readme How to use the `fetch` method on an x402 client to make authenticated requests. ```APIDOC ## POST /api/fetch ### Description Makes a fetch request with automatic X402 payment handling. The client will intercept the request, ensure payment is made if required, and return the response. ### Method POST ### Endpoint /api/fetch ### Parameters - **input** (string | Request) - Required - The URL or Request object for the fetch. - **init** (object) - Optional - Fetch options, similar to the standard Fetch API. ### Request Example ```javascript // Assuming 'client' is an initialized x402 client instance const response = await client.fetch('https://api.example.com/protected/resource', { method: 'GET', headers: { 'Authorization': 'Bearer YOUR_TOKEN' } }); const data = await response.json(); console.log(data); ``` ### Response #### Success Response (200) - **response** (Response) - The standard Fetch API Response object. #### Response Example ```json { "status": 200, "ok": true, "headers": { "content-type": "application/json" }, "body": { "data": "Protected resource data" } } ``` ``` -------------------------------- ### Payment Handler Initialization Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code Creates a new payment handler instance for the server-side. ```APIDOC ## new X402PaymentHandler(config) ### Description Creates a new payment handler instance for handling incoming payments. ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the payment handler. - **network** ('solana' | 'solana-devnet') - Required - The Solana network to use. - **treasuryAddress** (string) - Required - The Solana address where payments are sent. - **facilitatorUrl** (string) - Required - The URL of the facilitator service. - **rpcUrl** (string) - Optional - A custom RPC URL. - **defaultToken** (string) - Optional - The default token mint address (auto-detected if not provided). - **middlewareConfig** (object) - Optional - Configuration for middleware. ### Request Example ```javascript import { X402PaymentHandler } from '@payai/x402-solana'; const config = { network: 'solana-devnet', treasuryAddress: 'YOUR_TREASURY_ADDRESS', facilitatorUrl: 'https://your-facilitator.com', }; const paymentHandler = new X402PaymentHandler(config); ``` ### Methods - `paymentHandler.extractPayment(headers)` - Extract X-PAYMENT header from request. - `paymentHandler.createPaymentRequirements(routeConfig)` - Create payment requirements object. - `paymentHandler.create402Response(requirements)` - Create a 402 response body. - `paymentHandler.verifyPayment(header, requirements)` - Verify payment with the facilitator. - `paymentHandler.settlePayment(header, requirements)` - Settle payment with the facilitator. ``` -------------------------------- ### Server Payment Handler Initialization Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=versions How to create a new X402PaymentHandler instance for server-side payment processing. ```APIDOC ## POST /api/payment-handler ### Description Creates a new X402PaymentHandler instance. ### Method POST ### Endpoint /api/payment-handler ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the payment handler. - **network** ('solana' | 'solana-devnet') - Required - The network to use. - **treasuryAddress** (string) - Required - Where payments are sent. - **facilitatorUrl** (string) - Required - Facilitator service URL. - **rpcUrl** (string) - Optional - Custom RPC URL. - **defaultToken** (string) - Optional - Default token mint address. - **middlewareConfig** (object) - Optional - Middleware configuration. ### Request Example ```json { "config": { "network": "solana-devnet", "treasuryAddress": "TREASURY_WALLET_ADDRESS", "facilitatorUrl": "https://facilitator.example.com", "rpcUrl": "https://api.devnet.solana.com", "defaultToken": "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU" } } ``` ### Response #### Success Response (200) - **handler** (object) - The initialized X402PaymentHandler instance. #### Response Example ```json { "handler": "X402_PAYMENT_HANDLER_INSTANCE" } ``` ``` -------------------------------- ### Environment Variables Configuration Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code Lists the environment variables required for configuring the x402-solana package. ```APIDOC ## Environment Variables ### Network ``` NEXT_PUBLIC_NETWORK=solana-devnet ``` *Optional, defaults to `solana-devnet`.* ### Treasury Wallet Address ``` TREASURY_WALLET_ADDRESS=your_treasury_address ``` *Required. The Solana address where payments are sent.* ### RPC URLs ``` NEXT_PUBLIC_SOLANA_RPC_DEVNET=https://api.devnet.solana.com NEXT_PUBLIC_SOLANA_RPC_MAINNET=https://api.mainnet-beta.solana.com ``` *Optional. Custom RPC URLs for Devnet and Mainnet.* ### Base URL ``` NEXT_PUBLIC_BASE_URL=http://localhost:3000 ``` *Optional. Base URL used for the `resource` field in RouteConfig.* ``` -------------------------------- ### Client Fetch Method Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=versions Making fetch requests with automatic payment handling using the x402 client. ```APIDOC ## POST /api/fetch ### Description Make a fetch request with automatic payment handling. ### Method POST ### Endpoint /api/fetch ### Parameters #### Request Body - **input** (string | Request) - Required - The URL or Request object to fetch. - **init** (object) - Optional - Fetch request options. ### Request Example ```json { "input": "https://example.com/api/data", "init": { "method": "GET" } } ``` ### Response #### Success Response (200) - **response** (Response) - The response from the fetch request. #### Response Example ```json { "response": "FETCH_RESPONSE" } ``` ``` -------------------------------- ### Server Payment Handler Initialization Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependents This section details how to create a new x402 payment handler instance for the server. ```APIDOC ## POST /api/payment-handler ### Description Creates a new x402 payment handler instance on the server-side to manage incoming payments. ### Method POST ### Endpoint /api/payment-handler ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the x402 payment handler. - **network** ('solana' | 'solana-devnet') - Required - The network where payments will be processed. - **treasuryAddress** (string) - Required - The wallet address where payments are sent. - **facilitatorUrl** (string) - Required - The URL of the facilitator service. - **rpcUrl** (string) - Optional - A custom RPC URL. - **defaultToken** (string) - Optional - The default token mint address (auto-detected if not provided). - **middlewareConfig** (object) - Optional - Configuration for middleware processing. ### Request Example ```json { "config": { "network": "solana-devnet", "treasuryAddress": "TREASURY_WALLET_ADDRESS", "facilitatorUrl": "https://facilitator.example.com", "rpcUrl": "https://api.devnet.solana.com", "defaultToken": "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU" } } ``` ### Response #### Success Response (200) - **handler** (object) - The initialized x402 payment handler instance. #### Response Example ```json { "handler": "" } ``` ``` -------------------------------- ### Create x402 Solana Client Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code Instantiates a new x402 client for making fetch requests with automatic payment handling. Requires a wallet adapter, network configuration, and optionally custom RPC URLs and a maximum payment amount. ```javascript import { createX402Client } from '@payai/x402-solana'; const client = createX402Client({ wallet: walletAdapter, // An object with signTransaction method network: 'solana' | 'solana-devnet', rpcUrl: 'https://api.devnet.solana.com', maxPaymentAmount: 1000000000n }); // Use the client to make requests const response = await client.fetch('/api/protected-resource'); ``` -------------------------------- ### Create x402 Solana Payment Handler (Server) Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code Initializes an X402PaymentHandler for server-side payment processing. This handler manages extracting payment details, creating payment requirements, generating 402 responses, and verifying/settling payments with a facilitator service. It requires network configuration, treasury address, and facilitator URL. ```javascript import { X402PaymentHandler } from '@payai/x402-solana/server'; const paymentHandler = new X402PaymentHandler({ network: 'solana' | 'solana-devnet', treasuryAddress: 'YOUR_TREASURY_ADDRESS', facilitatorUrl: 'https://your-facilitator-service.com', rpcUrl: 'https://api.devnet.solana.com', defaultToken: 'USDC_MINT_ADDRESS' }); // Methods available on paymentHandler: // paymentHandler.extractPayment(headers) // paymentHandler.createPaymentRequirements(routeConfig) // paymentHandler.create402Response(requirements) // paymentHandler.verifyPayment(header, requirements) // paymentHandler.settlePayment(header, requirements) ``` -------------------------------- ### Testing Endpoint Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code Information about the testing utility provided by the package. ```APIDOC ## Testing To independently test the package's functionality within your application, navigate to the `/x402-test` endpoint in your browser. The test verifies the following: * Successful package imports. * Correct client creation with a wallet adapter. * Proper functioning of automatic 402 payment handling. * Successful transaction signing and submission. * Completion of payment verification and settlement processes. ``` -------------------------------- ### Create X402 Payment Handler (JavaScript) Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=readme Sets up a server-side payment handler for processing X-PAYMENT requests. Requires network, treasury address, facilitator URL, and optionally RPC URL, default token, or middleware configuration. ```javascript import { X402PaymentHandler } from '@payai/x402-solana/server'; const handlerConfig = { network: 'solana-devnet', // or 'solana' treasuryAddress: 'your_treasury_address', facilitatorUrl: 'https://your-facilitator.com', rpcUrl: 'https://api.devnet.solana.com', defaultToken: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU' // Example USDC devnet mint }; const paymentHandler = new X402PaymentHandler(handlerConfig); // Example usage of methods: // const paymentRequirements = paymentHandler.createPaymentRequirements(routeConfig); // const response = paymentHandler.create402Response(paymentRequirements); ``` -------------------------------- ### Testing Endpoint Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=versions Information about the `/x402-test` endpoint for package verification. ```APIDOC ## GET /x402-test ### Description Provides a testing interface to verify the functionality of the x402-solana package independently within your application. ### Method GET ### Endpoint /x402-test ### Verification Visiting this endpoint allows you to test the following: ✅ Package imports work correctly ✅ Client can be created with wallet adapter ✅ Automatic 402 payment handling works ✅ Transaction signing and submission succeed ✅ Payment verification and settlement complete ### Response #### Success Response (200) - **status** (string) - Indicates the success or failure of the tests. - **details** (object) - Provides specific results for each test case. #### Response Example ```json { "status": "All tests passed!", "details": { "imports": "passed", "clientCreation": "passed", "paymentHandling": "passed", "transactionSigning": "passed", "paymentVerification": "passed" } } ``` ``` -------------------------------- ### Configure Environment Variables for PayAI x402 Source: https://www.npmjs.com/package/@payai/x402-solana/index_activeTab=code Sets up necessary environment variables for the PayAI x402 Solana package, including network, treasury address, and RPC URLs. These variables configure the payment handling and client initialization. ```env # Network (optional, defaults to devnet) NEXT_PUBLIC_NETWORK=solana-devnet # Treasury wallet address (where payments are sent) TREASURY_WALLET_ADDRESS=your_treasury_address # Optional: Custom RPC URLs NEXT_PUBLIC_SOLANA_RPC_DEVNET=https://api.devnet.solana.com NEXT_PUBLIC_SOLANA_RPC_MAINNET=https://api.mainnet-beta.solana.com # Base URL for resource field NEXT_PUBLIC_BASE_URL=http://localhost:3000 ``` -------------------------------- ### Create X402 Payment Handler Instance (Server) Source: https://www.npmjs.com/package/@payai/x402-solana/index_activeTab=code Initializes a payment handler on the server-side for processing X-PAYMENT requests. Requires network, treasury address, and facilitator URL. Supports optional RPC URLs, default tokens, and middleware configurations. ```javascript import { X402PaymentHandler } from '@payai/x402-solana/server'; const handlerConfig = { network: 'solana' | 'solana-devnet', treasuryAddress: 'your_treasury_address', facilitatorUrl: 'https://your-facilitator.com', rpcUrl: 'optional_custom_rpc_url', defaultToken: 'optional_default_token_mint', middlewareConfig: {} }; const paymentHandler = new X402PaymentHandler(handlerConfig); ``` -------------------------------- ### Payment Handler Creation Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=readme How to create a new x402 payment handler instance for server-side payment processing. ```APIDOC ## POST /api/x402/payment-handler ### Description Creates a new x402 payment handler instance. This handler is used on the server to process incoming payments. ### Method POST ### Endpoint /api/x402/payment-handler ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the payment handler. - **network** (string) - Required - The network to use, either 'solana' or 'solana-devnet'. - **treasuryAddress** (string) - Required - The Solana address where payments are sent. - **facilitatorUrl** (string) - Required - The URL of the X402 facilitator service. - **rpcUrl** (string) - Optional - A custom RPC URL. - **defaultToken** (string) - Optional - The default token mint address (auto-detected if not provided). - **middlewareConfig** (object) - Optional - Configuration for middleware. ### Request Example ```json { "config": { "network": "solana-devnet", "treasuryAddress": "TREASURY_WALLET_ADDRESS", "facilitatorUrl": "https://facilitator.example.com", "rpcUrl": "https://api.devnet.solana.com", "defaultToken": "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU" } } ``` ### Response #### Success Response (200) - **handler** (object) - The created x402 payment handler instance. #### Response Example ```json { "handler": { "extractPayment": "function", "createPaymentRequirements": "function", "create402Response": "function", "verifyPayment": "function", "settlePayment": "function" } } ``` ``` -------------------------------- ### Environment Variables Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=versions Environment variables for configuring the x402-solana package. ```APIDOC ## Environment Variables ### Description Configuration settings managed through environment variables. ### Variables - **NEXT_PUBLIC_NETWORK** (string) - Optional - Network to use (defaults to 'solana-devnet'). - **TREASURY_WALLET_ADDRESS** (string) - Required - The Solana address where payments are sent. - **NEXT_PUBLIC_SOLANA_RPC_DEVNET** (string) - Optional - Custom RPC URL for Solana Devnet. - **NEXT_PUBLIC_SOLANA_RPC_MAINNET** (string) - Optional - Custom RPC URL for Solana Mainnet. - **NEXT_PUBLIC_BASE_URL** (string) - Optional - Base URL for resource fields in RouteConfig. ### Example ```bash NEXT_PUBLIC_NETWORK=solana-devnet TREASURY_WALLET_ADDRESS=your_treasury_address NEXT_PUBLIC_BASE_URL=http://localhost:3000 ``` ``` -------------------------------- ### Payment Amounts Formatting Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code Explains how payment amounts should be formatted (USDC micro-units). ```APIDOC ## Payment Amounts Payment amounts are specified in USDC micro-units (which have 6 decimal places) and should be represented as **strings**. * 1 USDC = `"1000000"` micro-units * $0.01 = `"10000"` micro-units * $2.50 = `"2500000"` micro-units **Helper functions** are available to assist with conversions: ```javascript import { usdToMicroUsdc, microUsdcToUsd } from '@payai/x402-solana/utils'; const microUnits = usdToMicroUsdc(2.5); // Returns "2500000" const usd = microUsdcToUsd("2500000"); // Returns 2.5 ``` ``` -------------------------------- ### Create Payment Requirements with Dynamic Configuration Source: https://www.npmjs.com/package/@payai/x402-solana/index_activeTab=code Generates the payment requirements object using environment variables for network and base URL, and dynamically determined USDC mint address. This is used for setting up payment requests. ```javascript const USDC_MINT = process.env.NODE_ENV === 'production' ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' : '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'; const paymentRequirements = await x402.createPaymentRequirements({ price: { amount: "1000000", // $1.00 USDC asset: { address: USDC_MINT } }, network: process.env.NODE_ENV === 'production' ? 'solana' : 'solana-devnet', config: { description: 'Payment', resource: `${process.env.NEXT_PUBLIC_BASE_URL}/api/endpoint`, } }); ``` -------------------------------- ### Payment Amount Formatting Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependents Information on how payment amounts are represented and helper functions for conversion. ```APIDOC ## Payment Amounts Payment amounts are specified in USDC micro-units (6 decimal places) as strings. - **1 USDC** = `"1000000"` micro-units - **$0.01** = `"10000"` micro-units - **$2.50** = `"2500000"` micro-units ### Helper Functions ```javascript import { usdToMicroUsdc, microUsdcToUsd } from '@payai/x402-solana/utils'; const microUnits = usdToMicroUsdc(2.5); // Result: "2500000" const usd = microUsdcToUsd("2500000"); // Result: 2.5 ``` ``` -------------------------------- ### Wallet Adapter Interface Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=code Specifies the required interface for wallet adapters used with the x402-solana package. ```APIDOC ## Wallet Adapter Interface The package is designed to work with any wallet that implements the following interface: ```typescript interface WalletAdapter { address: string; signTransaction: (tx: VersionedTransaction) => Promise; } ``` This interface is compatible with various Solana wallet SDKs, including: * Privy wallets (`useSolanaWallets()`) * Phantom SDK * Solflare SDK * Any wallet providing a `signTransaction` method. ``` -------------------------------- ### Payment Handling Methods (Server) Source: https://www.npmjs.com/package/@payai/x402-solana/package/%40payai/x402-solana_activetab=dependents This section outlines the methods available on the x402 payment handler for processing payments. ```APIDOC ## Payment Handler Methods ### Extract Payment Header #### Description Extracts the X-PAYMENT header from incoming request headers. #### Method `handler.extractPayment(headers)` #### Parameters - **headers** (object) - Required - The request headers object. #### Response - **paymentHeader** (string | undefined) - The extracted payment header value or undefined if not found. ### Create Payment Requirements #### Description Generates the requirements object needed for a specific payment route. #### Method `handler.createPaymentRequirements(routeConfig)` #### Parameters - **routeConfig** (object) - Required - Configuration for the route, including price and resource details. - **price** (object) - Required - The payment price details. - **amount** (string) - Required - Payment amount in token micro-units (e.g., "1000000" for 1 USDC). - **asset** (object) - Required - The asset details. - **address** (string) - Required - The token mint address (e.g., USDC). - **network** ('solana' | 'solana-devnet') - Required - The network for the transaction. - **config** (object) - Required - Additional configuration for the route. - **description** (string) - Required - A human-readable description of the resource. - **resource** (string) - Required - The URL of the API endpoint being protected. - **mimeType** (string) - Optional - The expected MIME type of the response (defaults to 'application/json'). - **maxTimeoutSeconds** (number) - Optional - Maximum allowed timeout in seconds (defaults to 300). - **outputSchema** (object) - Optional - Schema for the response output. #### Response - **requirements** (object) - The generated payment requirements object. ### Create 402 Response #### Description Creates a 402 Payment Required response body based on the provided requirements. #### Method `handler.create402Response(requirements)` #### Parameters - **requirements** (object) - Required - The payment requirements object obtained from `createPaymentRequirements`. #### Response - **responseBody** (object) - The JSON body for a 402 response. ### Verify Payment #### Description Verifies a payment using the facilitator service based on the header and requirements. #### Method `handler.verifyPayment(header, requirements)` #### Parameters - **header** (string) - Required - The payment header value. - **requirements** (object) - Required - The payment requirements object. #### Response - **verificationResult** (boolean) - True if the payment is verified, false otherwise. ### Settle Payment #### Description Settles a verified payment with the facilitator service. #### Method `handler.settlePayment(header, requirements)` #### Parameters - **header** (string) - Required - The payment header value. - **requirements** (object) - Required - The payment requirements object. #### Response - **settlementResult** (boolean) - True if the payment was settled successfully, false otherwise. ```