### EVM RPC Calls with Authentication and Payment Handling (TypeScript) Source: https://x402.quicknode.com/llms.txt This example demonstrates how to make RPC calls to an EVM network using the X402 QuickNode API. It covers setting up a wallet client, authenticating with Sign-In with Ethereum (SIWE), creating an x402-enabled fetch function that handles automatic payments, and making a sample RPC call to get the block number. Dependencies include 'viem', 'siwe', and '@x402/fetch'. ```typescript import { createWalletClient, http } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; import { baseSepolia } from 'viem/chains'; import { SiweMessage, generateNonce } from 'siwe'; import { wrapFetchWithPayment, x402Client } from '@x402/fetch'; import { ExactEvmScheme, toClientEvmSigner } from '@x402/evm'; const BASE_URL = 'https://x402.quicknode.com'; // 1. Set up wallet const walletClient = createWalletClient({ account: privateKeyToAccount('0xYOUR_PRIVATE_KEY'), chain: baseSepolia, transport: http(), }); // 2. Authenticate with SIWE const siweMessage = new SiweMessage({ domain: 'x402.quicknode.com', address: walletClient.account.address, statement: 'I accept the Quicknode Terms of Service: https://www.quicknode.com/terms', uri: BASE_URL, version: '1', chainId: 84532, nonce: generateNonce(), issuedAt: new Date().toISOString(), }); const message = siweMessage.prepareMessage(); const signature = await walletClient.signMessage({ message }); const authResponse = await fetch(`${BASE_URL}/auth`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message, signature }), }); const { token } = await authResponse.json(); // 3. Create x402-enabled fetch (handles payments automatically) const evmSigner = toClientEvmSigner({ address: walletClient.account.address, signTypedData: (params) => walletClient.signTypedData(params), }); const client = new x402Client() .register('eip155:84532', new ExactEvmScheme(evmSigner)); // IMPORTANT: @x402/fetch passes a Request object (not url+init) on payment // retries, so the inner fetch must handle both calling conventions. const authedFetch = async (input: RequestInfo | URL, init?: RequestInit) => { if (input instanceof Request) { const req = input.clone(); req.headers.set('Authorization', `Bearer ${token}`); return fetch(req); } const headers = new Headers(init?.headers); headers.set('Authorization', `Bearer ${token}`); return fetch(input, { ...init, headers }); }; const x402Fetch = wrapFetchWithPayment(authedFetch, client); // 4. Make RPC calls — payment is automatic on 402 const response = await x402Fetch(`${BASE_URL}/base-sepolia`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: [], }), }); const { result } = await response.json(); console.log('Block number:', BigInt(result)); // 5. Check remaining credits const creditsResponse = await fetch(`${BASE_URL}/credits`, { headers: { Authorization: `Bearer ${token}` }, }); const { credits } = await creditsResponse.json(); console.log('Credits remaining:', credits); ``` -------------------------------- ### Client Setup - Solana Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments Demonstrates how to create an x402 client configured for Solana Devnet using a Base58 encoded private key. ```APIDOC ## Client Setup - Solana ### Description This section details the configuration required to initialize the QuickNode x402 client for interacting with Solana Devnet. It emphasizes the use of a Base58 encoded secret key for the `svmPrivateKey` parameter. ### Method `createQuicknodeX402Client` ### Endpoint N/A (Client Initialization) ### Parameters #### Request Body - **baseUrl** (string) - Optional - The x402 gateway URL. Defaults to `https://x402.quicknode.com`. - **network** (string) - Required - The CAIP-2 chain identifier for the payment network. For Solana Devnet, use `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`. - **svmPrivateKey** (string) - Required - The Base58-encoded secret key for your Solana wallet. - **preAuth** (boolean) - Optional - If `true`, the client pre-authenticates by signing a SIWX message and acquiring a JWT before the first request, speeding up subsequent payments. ### Request Example ```javascript import { createQuicknodeX402Client } from '@quicknode/x402'; const client = await createQuicknodeX402Client({ baseUrl: 'https://x402.quicknode.com', network: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', // Solana Devnet svmPrivateKey: '', preAuth: true, }); ``` ### Response #### Success Response (200) - **client** (object) - An initialized x402 client instance. #### Response Example N/A (Client initialization does not return a JSON response in this context.) ``` -------------------------------- ### Client Setup - EVM Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments Illustrates how to set up the x402 client for EVM-compatible chains using a hex-encoded private key. ```APIDOC ## Client Setup - EVM ### Description This section explains how to configure the QuickNode x402 client for EVM-compatible networks, such as Base Sepolia. It requires a hex-encoded private key for the `evmPrivateKey` parameter. ### Method `createQuicknodeX402Client` ### Endpoint N/A (Client Initialization) ### Parameters #### Request Body - **baseUrl** (string) - Optional - The x402 gateway URL. Defaults to `https://x402.quicknode.com`. - **network** (string) - Required - The CAIP-2 chain identifier for the payment network. For example, `eip155:84532` for Base Sepolia. - **evmPrivateKey** (string) - Required - The hex-encoded private key for your EVM wallet. - **preAuth** (boolean) - Optional - If `true`, the client pre-authenticates by signing a SIWX message and acquiring a JWT before the first request, speeding up subsequent payments. ### Request Example ```javascript import { createQuicknodeX402Client } from '@quicknode/x402'; const client = await createQuicknodeX402Client({ baseUrl: 'https://x402.quicknode.com', network: 'eip155:84532', // Base Sepolia evmPrivateKey: '0xYOUR_PRIVATE_KEY', preAuth: true, }); ``` ### Response #### Success Response (200) - **client** (object) - An initialized x402 client instance. #### Response Example N/A (Client initialization does not return a JSON response in this context.) ``` -------------------------------- ### Set Up Project for x402 Payments with Quicknode (Node.js) Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This snippet demonstrates the initial project setup for interacting with Quicknode endpoints using x402 payments. It involves creating a project directory and initializing it with npm. ```bash mkdir x402-quicknode-example cd x402-quicknode-example npm init -y ``` -------------------------------- ### Automated Handling with @x402/fetch (Solana) Source: https://x402.quicknode.com/llms.txt This section explains how to use the `@x402/fetch` package for automated payment handling on Solana networks, including installation and a TypeScript example. ```APIDOC ## Automatic handling with @x402/fetch (Solana) ### Description Automate x402 payments for Solana networks using the `@x402/fetch` package. This involves registering a Solana signer and wrapping a fetch function. ### Installation ```bash npm install @x402/fetch @x402/svm @solana/kit tweetnacl bs58 ``` ### Usage ```typescript import { createKeyPairSignerFromBytes } from '@solana/kit'; import { wrapFetchWithPayment, x402Client } from '@x402/fetch'; import { ExactSvmScheme } from '@x402/svm'; // Create a Solana signer from your secret key (64 bytes) const signer = await createKeyPairSignerFromBytes(secretKey); // Register the signer for Solana Devnet const client = new x402Client() .register('solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', new ExactSvmScheme(signer)); const x402Fetch = wrapFetchWithPayment(authedFetch, client); const response = await x402Fetch('https://x402.quicknode.com/solana-devnet', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getBlockHeight', params: [] }), }); ``` ### Parameters #### Signer Creation - **secretKey** (Uint8Array) - Required - The 64-byte secret key for Solana signing. #### Client Registration - **network** (string) - Required - The CAIP-2 chain ID of the network. - **scheme** (object) - Required - An instance of `ExactSvmScheme`. #### `x402Fetch` Usage - **input** (RequestInfo | URL) - Required - The URL or Request object to fetch. - **init** (RequestInit) - Optional - The fetch options. ### Response Example (Success) ```json { "jsonrpc": "2.0", "id": 1, "result": 123456789 } ``` ``` -------------------------------- ### Install Quicknode MCP Server Source: https://blog.quicknode.com/x402-micropayments-quicknode-rpc-endpoints Installs the Quicknode MCP server, which enables AI assistants to manage Quicknode infrastructure through natural language. This tool helps in provisioning endpoints, monitoring usage, and managing billing. ```bash npx -y @quicknode/mcp ``` -------------------------------- ### Automated Handling with @x402/fetch (EVM) Source: https://x402.quicknode.com/llms.txt This section covers automated payment handling for EVM using the `@x402/fetch` package, including installation and a TypeScript example. ```APIDOC ## Automatic handling with @x402/fetch (EVM) ### Description Automate x402 payments for EVM networks using the `@x402/fetch` package. This involves wrapping a fetch function that can handle payment retries. ### Installation ```bash npm install @x402/fetch @x402/evm viem siwe ``` ### Usage ```typescript import { wrapFetchWithPayment, x402Client } from '@x402/fetch'; import { ExactEvmScheme, toClientEvmSigner } from '@x402/evm'; // Create an EVM signer from your wallet const evmSigner = toClientEvmSigner({ address: walletClient.account.address, signTypedData: (params) => walletClient.signTypedData(params), }); // Register the signer for Base Sepolia const client = new x402Client() .register('eip155:84532', new ExactEvmScheme(evmSigner)); // IMPORTANT: @x402/fetch passes a Request object (not url+init) on payment // retries. The inner fetch must handle both calling conventions or the JWT // will be silently dropped on the retry and the request will fail with 401. const authedFetch = async (input: RequestInfo | URL, init?: RequestInit) => { if (input instanceof Request) { const req = input.clone(); req.headers.set('Authorization', `Bearer ${jwtToken}`); return fetch(req); } const headers = new Headers(init?.headers); headers.set('Authorization', `Bearer ${jwtToken}`); return fetch(input, { ...init, headers }); }; const x402Fetch = wrapFetchWithPayment(authedFetch, client); // Use x402Fetch like normal fetch — payments happen transparently const response = await x402Fetch('https://x402.quicknode.com/base-sepolia', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: [] }), }); ``` ### Parameters #### Signer Creation - **address** (string) - Required - The wallet address. - **signTypedData** (function) - Required - A function to sign typed data. #### Client Registration - **network** (string) - Required - The CAIP-2 chain ID of the network. - **scheme** (object) - Required - An instance of `ExactEvmScheme`. #### `authedFetch` Function - **input** (RequestInfo | URL) - Required - The request input. - **init** (RequestInit) - Optional - The request initialization. #### `x402Fetch` Usage - **input** (RequestInfo | URL) - Required - The URL or Request object to fetch. - **init** (RequestInit) - Optional - The fetch options. ### Response Example (Success) ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1234567890abcdef" } ``` ``` -------------------------------- ### Install HyperCore CLI Tool Source: https://blog.quicknode.com/x402-micropayments-quicknode-rpc-endpoints This command installs the Quicknode HyperCore CLI tool globally using npm. This tool allows developers to stream and backfill Hyperliquid datasets directly from the terminal on a pay-per-request basis. ```bash npm install -g @quicknode/hypercore-cli ``` -------------------------------- ### Automated Payment Handling with @quicknode/x402 Source: https://x402.quicknode.com/llms.txt This section details how to use the `@quicknode/x402` npm package for automated payment handling, including installation and a TypeScript example. ```APIDOC ## Automated Payment Handling with @quicknode/x402 ### Description Automate the entire x402 payment flow using the `@quicknode/x402` npm package. This client handles authentication, SIWX, payment, and session management automatically. ### Installation ```bash npm install @quicknode/x402 ``` ### Usage ```typescript import { createQuicknodeX402Client } from '@quicknode/x402'; const client = await createQuicknodeX402Client({ baseUrl: 'https://x402.quicknode.com', network: 'eip155:84532', evmPrivateKey: '0xYOUR_PRIVATE_KEY', preAuth: true, }); // client.fetch handles auth, SIWX, payment, and session management automatically const response = await client.fetch('https://x402.quicknode.com/base-sepolia', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: [] }), }); ``` ### Parameters #### Client Initialization - **baseUrl** (string) - Required - The base URL for the x402 service. - **network** (string) - Required - The CAIP-2 chain ID of the network. - **evmPrivateKey** (string) - Required - The private key for EVM signing. - **preAuth** (boolean) - Optional - Whether to pre-authenticate the client. #### Client Fetch Method - **input** (RequestInfo | URL) - Required - The URL or Request object to fetch. - **init** (RequestInit) - Optional - The fetch options, including method, headers, and body. ### Response Example (Success) ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1234567890abcdef" } ``` ``` -------------------------------- ### Making JSON-RPC Calls (HTTP Request Example) Source: https://x402.quicknode.com/llms.txt This example demonstrates how to make a JSON-RPC call to the QuickNode LLM Text API using an HTTP POST request. It includes the necessary Authorization header and the JSON-RPC payload for querying the block number. ```http POST /ethereum-mainnet HTTP/1.1 Authorization: Bearer Content-Type: application/json {"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]} ``` -------------------------------- ### Make Authenticated API Requests with x402 Client Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This example shows how to use the `client.fetch` method, which mirrors the standard Fetch API, to make requests to different blockchain networks. It demonstrates fetching the latest block number for EVM (Base Sepolia) and the current slot for Solana Devnet, with authentication and payments handled automatically by the x402 client. ```javascript const X402_BASE_URL = 'https://x402.quicknode.com'; // Example for EVM (Base Sepolia) const evmResponse = await client.fetch(`${X402_BASE_URL}/base-sepolia`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: [], }), }); const evmData = await evmResponse.json(); const block = BigInt(evmData.result); console.log(`EVM Block: ${block}`); // Example for Solana Devnet const solanaResponse = await client.fetch( 'https://x402.quicknode.com/solana-devnet', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getSlot', params: [], }), } ); const solanaData = await solanaResponse.json(); const slot = solanaData.result; console.log(`Solana Slot: ${slot}`); ``` -------------------------------- ### Create QuickNode x402 Client for EVM (Base Sepolia) Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This code snippet illustrates initializing the QuickNode x402 client for an EVM network, specifically Base Sepolia. It uses a hex-encoded EVM private key and the corresponding CAIP-2 network identifier. Similar to the Solana setup, `preAuth: true` optimizes the authentication flow. ```javascript import { createQuicknodeX402Client } from '@quicknode/x402' const client = await createQuicknodeX402Client({ baseUrl: 'https://x402.quicknode.com', network: 'eip155:84532', evmPrivateKey: '0xYOUR_PRIVATE_KEY', preAuth: true, }) ``` -------------------------------- ### Run Quicknode JSON-RPC Script (Node.js) Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This command executes the Node.js script created to interact with Quicknode endpoints. Ensure you have Node.js installed and the script file saved. ```bash node your_script_name.js ``` -------------------------------- ### Automated Payment Handling with @x402/fetch for EVM (TypeScript) Source: https://x402.quicknode.com/llms.txt This example demonstrates automated payment handling for EVM networks using the @x402/fetch package. It involves creating an EVM signer, registering it with the x402 client, and then using the wrapped fetch function for transparent payment processing. The authedFetch function is crucial for correctly passing JWT tokens during payment retries. ```typescript import { wrapFetchWithPayment, x402Client } from '@x402/fetch'; import { ExactEvmScheme, toClientEvmSigner } from '@x402/evm'; // Create an EVM signer from your wallet const evmSigner = toClientEvmSigner({ address: walletClient.account.address, signTypedData: (params) => walletClient.signTypedData(params), }); // Register the signer for Base Sepolia const client = new x402Client() .register('eip155:84532', new ExactEvmScheme(evmSigner)); // IMPORTANT: @x402/fetch passes a Request object (not url+init) on payment // retries. The inner fetch must handle both calling conventions or the JWT // will be silently dropped on the retry and the request will fail with 401. const authedFetch = async (input: RequestInfo | URL, init?: RequestInit) => { if (input instanceof Request) { const req = input.clone(); req.headers.set('Authorization', `Bearer ${jwtToken}`); return fetch(req); } const headers = new Headers(init?.headers); headers.set('Authorization', `Bearer ${jwtToken}`); return fetch(input, { ...init, headers }); }; const x402Fetch = wrapFetchWithPayment(authedFetch, client); // Use x402Fetch like normal fetch — payments happen transparently const response = await x402Fetch('https://x402.quicknode.com/base-sepolia', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: [] }), }); ``` -------------------------------- ### Automated Payment Handling with @x402/fetch for Solana (TypeScript) Source: https://x402.quicknode.com/llms.txt This example demonstrates automated payment handling for Solana networks using the @x402/fetch package. It involves creating a Solana signer from a secret key, registering it with the x402 client, and then using the wrapped fetch function for transparent payment processing. The authedFetch function is essential for correctly passing JWT tokens during payment retries. ```typescript import { createKeyPairSignerFromBytes } from '@solana/kit'; import { wrapFetchWithPayment, x402Client } from '@x402/fetch'; import { ExactSvmScheme } from '@x402/svm'; // Create a Solana signer from your secret key (64 bytes) const signer = await createKeyPairSignerFromBytes(secretKey); // Register the signer for Solana Devnet const client = new x402Client() .register('solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', new ExactSvmScheme(signer)); const x402Fetch = wrapFetchWithPayment(authedFetch, client); const response = await x402Fetch('https://x402.quicknode.com/solana-devnet', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getBlockHeight', params: [] }), }); ``` -------------------------------- ### GET /discovery/resources - Network Catalog Source: https://x402.quicknode.com/llms.txt A public endpoint that returns a paginated Bazaar-compatible catalog of all supported network endpoints, including pricing and JSON-RPC schema. No authentication is required. ```APIDOC ## GET /discovery/resources ### Description Bazaar-compatible catalog of all supported network endpoints with pricing and JSON-RPC schema. Public, no authentication required. Returns paginated results. ### Method GET ### Endpoint `/discovery/resources` ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of results to return per page (default 50, max 200). - **offset** (integer) - Optional - The number of results to skip (default 0). ### Response #### Success Response (200) - A paginated list of network endpoint resources, each containing details like pricing and JSON-RPC schema. #### Response Example ```json { "total": 137, "limit": 50, "offset": 0, "resources": [ { "network": "ethereum-mainnet", "pricing": { "json_rpc": { "per_request": "0.0001 USDC" } }, "json_rpc_schema": { "methods": { "eth_getBlockByNumber": { "params": [ "blockTag", "boolean" ] } } } } // ... more network resources ] } ``` ``` -------------------------------- ### Check Account Credits Source: https://x402.quicknode.com/llms.txt An example HTTP request to check the remaining credits for an authenticated account. Requires a JWT in the Authorization header and returns the account ID and credit balance. ```http GET /credits HTTP/1.1 Authorization: Bearer ``` -------------------------------- ### Create and Use QuickNode x402 Client in TypeScript Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This script initializes a QuickNode x402 client, makes concurrent RPC calls to different networks (Base Sepolia and Solana Devnet), and logs the block number or slot along with the remaining credits. It demonstrates how the client handles credit consumption and potential automatic payments. ```typescript import { createQuicknodeX402Client } from '@quicknode/x402' const X402_BASE_URL = 'https://x402.quicknode.com' const NETWORK = 'eip155:84532' // Base Sepolia async function main() { // Create client — preAuth speeds up payment by authenticating (SIWX + JWT) upfront const client = await createQuicknodeX402Client({ baseUrl: X402_BASE_URL, network: NETWORK, evmPrivateKey: process.env.PRIVATE_KEY || undefined, preAuth: true, }) console.log('Client ready. USDC payment will be made on Base Sepolia.') console.log( 'Making calls: eth_blockNumber on Base Sepolia and getSlot on Solana Devnet...\n' ) // Make requests in a loop to see credit consumption for (let i = 1; i <= 10; i++) { const evmResponse = await client.fetch(`${X402_BASE_URL}/base-sepolia`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: i, method: 'eth_blockNumber', params: [], }), }) const evmData = await evmResponse.json() const block = BigInt(evmData.result) console.log(`Request #${i}: Block ${block}`) console.log( 'Credits:', (await fetch('https://x402.quicknode.com/credits', { headers: { Authorization: `Bearer ${client.getToken()}` }, }).then(r => r.json())).credits ) const solanaResponse = await client.fetch( 'https://x402.quicknode.com/solana-devnet', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getSlot', params: [], }), } ) const solanaData = await solanaResponse.json() const slot = solanaData.result console.log(`Request #${i}: Solana Slot ${slot}`) console.log( 'Credits:', (await fetch('https://x402.quicknode.com/credits', { headers: { Authorization: `Bearer ${client.getToken()}` }, }).then(r => r.json())).credits ) console.log('\n') } } main().catch(console.error) ``` -------------------------------- ### Create QuickNode x402 Client for Solana Devnet Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This code demonstrates how to initialize the QuickNode x402 client for the Solana Devnet. It requires a Base58-encoded SVM private key and specifies the Solana Devnet network identifier. The `preAuth: true` option enables pre-authentication for faster subsequent requests. ```javascript import { createQuicknodeX402Client } from '@quicknode/x402' const client = await createQuicknodeX402Client({ baseUrl: 'https://x402.quicknode.com', network: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', // Solana Devnet svmPrivateKey: '', preAuth: true, }) ``` -------------------------------- ### GET /credits - Check Credit Balance Source: https://x402.quicknode.com/llms.txt Retrieves the current credit balance for the authenticated account. Requires a valid JWT in the Authorization header. ```APIDOC ## GET /credits ### Description Checks the current credit balance for the authenticated account. Requires a valid JWT in the `Authorization` header. ### Method GET ### Endpoint `/credits` ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token with the JWT. ### Response #### Success Response (200) - **accountId** (string) - The CAIP-10 identifier of the account. - **credits** (integer) - The remaining credit balance. #### Response Example ```json { "accountId": "eip155:1:0x123...", "credits": 95 } ``` ``` -------------------------------- ### Access Quicknode Endpoints via REST API Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This snippet illustrates how to make a REST API call to a Quicknode endpoint. It demonstrates sending a GET request to retrieve data, often used for simpler queries. ```javascript fetch('YOUR_QUICKNODE_REST_ENDPOINT', { method: 'GET', headers: { 'x-api-key': 'YOUR_API_KEY' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` -------------------------------- ### GET /:network/ws - WebSocket Proxy Source: https://x402.quicknode.com/llms.txt Provides a WebSocket proxy for persistent JSON-RPC connections. Requires a valid JWT and sufficient credits. The network parameter specifies the target network. ```APIDOC ## GET /:network/ws ### Description WebSocket proxy for persistent JSON-RPC connections. Requires a valid JWT and sufficient credits. The `network` parameter specifies the target network. ### Method GET ### Endpoint `/:network/ws` ### Parameters #### Path Parameters - **network** (string) - Required - The network identifier (e.g., `ethereum-mainnet`). #### Headers - **Authorization** (string) - Required - Bearer token with the JWT. ### Response #### Success Response (101) - WebSocket Connection - A WebSocket connection is established for JSON-RPC communication. #### Error Response - Standard JSON error object: `{ "error": "", "message": "" }` #### Error Response Example ```json { "error": "missing_token", "message": "Authorization token is missing." } ``` ``` -------------------------------- ### Use Cases for x402 Source: https://blog.quicknode.com/x402-micropayments-quicknode-rpc-endpoints Explores various applications and use cases for Quicknode's x402 protocol, including AI agents and development prototyping. ```APIDOC ## Use Cases for x402 ### Description This section outlines potential applications and benefits of using Quicknode's x402 protocol. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Use Cases: 1. **AI Agents with Autonomous Blockchain Access:** * Query token prices and portfolio balances. * Monitor wallet activity and transaction history. * Execute blockchain reads for DeFi protocols. * Access historical block data for analysis. * Enables AI agents to interact with blockchain data without pre-provisioned API keys. 2. **MCP Server for AI-Assisted Infrastructure Management:** * Use `@quicknode/mcp` to manage Quicknode endpoints across multiple networks via natural language. * Monitor usage and billing. * Pairs well with x402 for lightweight, wallet-authenticated endpoint access. * Installation: `npx -y @quicknode/mcp` 3. **Blockchain Skills for AI Coding Agents:** * Provides AI coding agents with knowledge of the Quicknode product suite. * Adds skills via: `npx skills add quiknode-labs/blockchain-skills` * Offers accurate endpoints, parameters, and best practices. * Open source at: `github.com/quiknode/blockchain-skills` 4. **Pay-Per-Request Development and Prototyping:** * Allows developers to test ideas across multiple chains without plan commitment. * Pay only for the RPC calls made using USDC. ``` -------------------------------- ### Request Testnet Faucet Funds Source: https://x402.quicknode.com/llms.txt An example HTTP POST request to the /drip endpoint to request free testnet USDC. This is a one-time request per account and is only available for Base Sepolia. Requires a JWT for authentication. ```http POST /drip HTTP/1.1 Authorization: Bearer ``` -------------------------------- ### Solana Prerequisites for Quicknode Integration Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This section outlines the necessary prerequisites for integrating Solana with Quicknode endpoints. It typically involves having a Solana wallet and sufficient SOL for transaction fees. ```markdown * A Solana wallet (e.g., Phantom, Solflare). * Some SOL in your wallet to cover transaction fees. ``` -------------------------------- ### Making Requests with client.fetch Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments Shows how to use the `client.fetch` method to make requests to different blockchain networks, with authentication and payments handled automatically. ```APIDOC ## Making Requests with client.fetch ### Description The `client.fetch` method provides a familiar interface, mirroring the standard Fetch API, to interact with blockchain networks. The x402 SDK transparently manages authentication and payment negotiation for these requests. ### Method `client.fetch(url, options)` ### Endpoint `https://x402.quicknode.com/{network}` ### Parameters #### Path Parameters - **network** (string) - Required - The network identifier to target (e.g., `base-sepolia`, `solana-devnet`). This can be different from the network configured during client initialization. #### Query Parameters None #### Request Body - **options** (object) - Standard Fetch API options, including `method`, `headers`, and `body`. ### Request Example ```javascript // Assuming 'client' is an initialized x402 client const X402_BASE_URL = 'https://x402.quicknode.com'; // Example for EVM (Base Sepolia) const evmResponse = await client.fetch(`${X402_BASE_URL}/base-sepolia`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: [], }), }); const evmData = await evmResponse.json(); const block = BigInt(evmData.result); console.log(`EVM Block Number: ${block}`); // Example for Solana (Devnet) const solanaResponse = await client.fetch(`${X402_BASE_URL}/solana-devnet`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getSlot', params: [], }), }); const solanaData = await solanaResponse.json(); const slot = solanaData.result; console.log(`Solana Slot: ${slot}`); ``` ### Response #### Success Response (200) - **response** (object) - The raw response object from the target API, typically JSON. #### Response Example ```json // Example for eth_blockNumber { "jsonrpc": "2.0", "id": 1, "result": "0x1234567890abcdef" } // Example for getSlot { "jsonrpc": "2.0", "result": 123456789 } ``` ``` -------------------------------- ### Configure Environment Variables for Quicknode Access (Node.js) Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This snippet shows how to set up the .env file to store sensitive information like API keys and endpoint URLs required for accessing Quicknode services via x402. ```env NODE_ENV=development QUICKNODE_RPC_URL="YOUR_QUICKNODE_ENDPOINT_URL" PAYMENT_GATEWAY_URL="YOUR_X402_PAYMENT_GATEWAY_URL" API_KEY="YOUR_API_KEY" ``` -------------------------------- ### Drip Faucet (Base Sepolia Only) Source: https://x402.quicknode.com/llms.txt Provides free testnet USDC for Base Sepolia network to facilitate development. ```APIDOC ## POST /drip ### Description Requests testnet USDC to be sent to the authenticated user's wallet on the Base Sepolia network. This is a one-time faucet. ### Method POST ### Endpoint /drip ### Headers - **Authorization** (string) - Required - Bearer token obtained from the /auth endpoint (e.g., `Bearer `). ### Request Body (No request body required for this endpoint) ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating USDC has been sent. #### Response Example ```json { "message": "USDC sent to your wallet on Base Sepolia. Please allow a few seconds for confirmation." } ``` ``` -------------------------------- ### Manual Payment Handling Source: https://x402.quicknode.com/llms.txt Instructions for manually handling HTTP 402 responses to negotiate payment, including details on signing and constructing payment headers. ```APIDOC ## Manual handling ### Description When an HTTP 402 response is received, the response body contains payment options. You need to construct and sign a payment according to the network's requirements and include it in the `PAYMENT-SIGNATURE` header on your retry request. ### Process 1. **Receive HTTP 402:** The server responds with a 402 status code. 2. **Inspect Response Body:** The body contains an `accepts` array with payment details (`network`, `amount`, `payTo`, `asset`). 3. **Construct Payment:** - **EVM:** Sign an EIP-712 typed data payment. - **Solana:** Construct a partially-signed USDC transfer using the `feePayer` from the `extra` field. 4. **Include Signature:** Add the base64-encoded payment signature to the `PAYMENT-SIGNATURE` header on your retry request. ``` -------------------------------- ### Create JSON-RPC Request Script for Quicknode (Node.js) Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This JavaScript snippet demonstrates how to create a JSON-RPC request to a Quicknode endpoint using x402 for payment. It includes fetching data from the environment and making a POST request. ```javascript require('dotenv').config(); const fetch = require('node-fetch'); async function getBlockNumber() { const url = process.env.QUICKNODE_RPC_URL; const payload = { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }; try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': process.env.API_KEY }, body: JSON.stringify(payload) }); const data = await response.json(); if (data.error) { console.error('Error:', data.error); return null; } console.log('Current Block Number:', data.result); return data.result; } catch (error) { console.error('Network or fetch error:', error); return null; } } getBlockNumber(); ``` -------------------------------- ### Establish WebSocket Connection to Quicknode Source: https://www.quicknode.com/guides/x402/access-quicknode-endpoints-with-x402-payments This snippet shows how to establish a WebSocket connection to a Quicknode endpoint. WebSockets are ideal for real-time data streams and notifications. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('YOUR_QUICKNODE_WEBSOCKET_URL'); ws.on('open', function open() { console.log('Connected to WebSocket'); // Send a message, e.g., subscribe to new blocks ws.send(JSON.stringify({ jsonrpc: '2.0', method: 'eth_subscribe', params: ['newHeads'], id: 1 })); }); ws.on('message', function incoming(data) { console.log('Received:', JSON.parse(data)); }); ws.on('error', function error(err) { console.error('WebSocket error:', err); }); ws.on('close', function close() { console.log('Disconnected from WebSocket'); }); ``` -------------------------------- ### Generate EVM Wallet with Viem Source: https://x402.quicknode.com/llms.txt Generates a new Ethereum private key and account using the 'viem' library. This is useful for bootstrapping an EVM wallet without an existing one, particularly for development on testnets. The generated private key should be stored securely for future use. ```typescript import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; // No existing key needed — generate one on the fly const privateKey = generatePrivateKey(); const account = privateKeyToAccount(privateKey); // Store privateKey securely — you will need it for future sessions ``` -------------------------------- ### Automated Payment Handling with @quicknode/x402 (TypeScript) Source: https://x402.quicknode.com/llms.txt This snippet shows how to use the createQuicknodeX402Client function from the @quicknode/x402 package to automatically handle authentication, SIWX, payment, and session management for API requests. It requires network, EVM private key, and base URL configuration. ```typescript import { createQuicknodeX402Client } from '@quicknode/x402'; const client = await createQuicknodeX402Client({ baseUrl: 'https://x402.quicknode.com', network: 'eip155:84532', evmPrivateKey: '0xYOUR_PRIVATE_KEY', preAuth: true, }); // client.fetch handles auth, SIWX, payment, and session management automatically const response = await client.fetch('https://x402.quicknode.com/base-sepolia', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: [] }), }); ``` -------------------------------- ### x402 Extension-Based Authentication Flow Source: https://x402.quicknode.com/llms.txt This section outlines the step-by-step process for authenticating with x402-native agents using the SIWX header, including handling 402 responses and obtaining a JWT. ```APIDOC ## x402 Extension-Based Authentication (SIWX Header) For x402-native agents, a fully self-describing flow is available — no out-of-band knowledge of the `/auth` endpoint needed: 1. **Hit any endpoint with no auth** — The server returns HTTP 402 with `extensions` in the response body and `PAYMENT-REQUIRED` header. 2. **Read the `sign-in-with-x` extension** — Contains a SIWX challenge with `domain`, `uri`, `nonce`, `issuedAt`, `expirationTime`, and `supportedChains` (all EVM + Solana chains). 3. **Sign the SIWX challenge** — Construct a SIWX message from the challenge params, sign with your wallet, and encode as a `SIGN-IN-WITH-X` header (Base64-encoded JSON). 4. **Pay** — Include `PAYMENT-SIGNATURE` header with the x402 payment. The settlement response contains a `quicknode-session` extension with a JWT. 5. **Extract JWT from settlement** — Read `extensions['quicknode-session'].info.token` from the `PAYMENT-RESPONSE` header and use as `Authorization: Bearer ` for subsequent requests. ### `SIGN-IN-WITH-X` header format The header value is Base64-encoded JSON matching the `SIWxPayload` schema: ```json { "type": "eip191", "domain": "x402.quicknode.com", "address": "0xYourAddress", "uri": "https://x402.quicknode.com/ethereum-mainnet", "version": "1", "chainId": "eip155:8453", "nonce": "abc123...", "issuedAt": "2026-01-01T00:00:00.000Z", "signature": "0x..." } ``` For Solana, use `"type": "ed25519"` and Base58 signature. Smart wallets (EIP-1271/6492) are supported on EVM chains. ### 402 Response Extensions Every 402 response includes these extensions: - **`sign-in-with-x`**: SIWX challenge with `info` (domain, uri, nonce, issuedAt, expirationTime, resources) and `supportedChains` array. Nonce expires in 5 minutes. - **`bazaar`**: JSON-RPC POST input schema (`jsonrpc`, `method`, `params`, `id`) and example output (`{ jsonrpc: "2.0", result: "0x1234567", id: 1 }`). - **`quicknode-session`**: Declares that a JWT will be issued in the settlement response at `extensions.quicknode-session.info.token`. Includes `expirySeconds`, `authEndpoint` (`/auth`), and `usage` (`Authorization: Bearer `). All fields are nested under `info` per x402 extension convention. ``` -------------------------------- ### Mixpanel Initialization (JavaScript) Source: https://blog.quicknode.com/x402-micropayments-quicknode-rpc-endpoints This JavaScript code initializes Mixpanel, a product analytics service. It sets up the Mixpanel object and defines methods for tracking events and user properties. This is a common pattern for integrating Mixpanel into web applications for user behavior analysis. ```javascript (function(f,b){if(!b.__SV){var e,g,i,h;window.mixpanel=b;b._i=[];b.init=function(e,f,c){function g(a,d){var b=d.split(".");2==b.length&&(a=a[b[0]],d=b[1]);a[d]=function(){a.push([d].concat(Array.prototype.slice.call(arguments,0)))}}var a=b; ```