X402 Tutorial

Example Code: The complete working example for this tutorial is available at sb-on-demand-examples/solana/x402arrow-up-right

This tutorial walks you through implementing Switchboard with X402 micropayments to access paywalled data sources on Solana.

Prerequisites

  • Solana CLIarrow-up-right installed and configured

  • Node.js 18+

  • A Solana keypair with USDC on mainnet-beta (for micropayments)

Installation

Clone the examples repository and install dependencies:

git clone https://github.com/switchboard-xyz/sb-on-demand-examples.git
cd sb-on-demand-examples/solana/x402
npm install

Dependencies

The example uses these X402-specific packages:

{
  "@faremeter/payment-solana": "^0.8.0",
  "@faremeter/wallet-solana": "^0.8.0",
  "@switchboard-xyz/x402-utils": "0.3.0"
}

Understanding the Flow

The X402 integration follows these steps:

  1. Initialize Faremeter wallet - Create a local wallet for USDC micropayments

  2. Derive X402 headers - Generate authentication headers for the paywalled endpoint

  3. Define oracle feed inline - Create feed definition with placeholder variables

  4. Fetch managed update - Pass X402 headers as variable overrides

  5. Read oracle data - Access verified data from the quote account

Implementation

Step 1: Set Up Imports and Constants

Step 2: Define the Oracle Feed with Placeholders

The feed is defined inline with placeholder variables that will be replaced at runtime:

Note the ${X402_PAYMENT_HEADER} and ${X402_SWITCHBOARD_PAYMENT_HEADER} placeholders - these get replaced with actual authentication headers at runtime.

Step 3: Initialize Payment Infrastructure

Step 4: Check USDC Balance

Before making payments, verify you have sufficient USDC:

Step 5: Derive X402 Payment Headers

The X402FetchManager derives authentication headers for the paywalled endpoint:

Step 6: Fetch Managed Update with Variable Overrides

Pass the X402 headers as variable overrides when fetching oracle instructions:

Step 7: Build and Send Transaction

Key Points

numSignatures Must Be 1

When using X402, you must set numSignatures: 1 in the managed update options. This is a critical requirement for X402 requests to work correctly.

Don't Reuse Payment Headers

Each X402 payment header is valid for a single request. If you simulate a transaction with an X402 header and then send the actual transaction, you may be charged twice. Either:

  • Skip simulation for X402 transactions, or

  • Generate separate headers for simulation and execution

Inline Feed Definition

Unlike standard managed updates (which use feed IDs from IPFS), X402 feeds are defined inline in your code. This allows for dynamic configuration without on-chain or IPFS storage.

Running the Example

Expected output:

Next Steps

Last updated