Set up the x402 facilitator

The x402 facilitator is a lightweight library that bridges your backend with the blockchain. It handles the heavy lifting: verifying USDC payments, managing nonces, and ensuring that only authenticated requests reach your analytics endpoints. Think of it as a bouncer at a club—it checks the ID (payment) before letting anyone in.

For chain analytics APIs, this setup is critical. You want to ensure that data queries are paid for before computation begins, preventing abuse and ensuring sustainable service. We will use Thirdweb’s official x402 facilitator, which supports both Node.js and Python environments.

Install the facilitator library

First, install the package in your project directory. This adds the necessary dependencies to handle HTTP 402 responses and payment verification logic.

Shell
npm install @thirdweb-dev/extension-x402

For Python users, you can use the corresponding pip package:

Shell
pip install x402-facilitator

Initialize the facilitator

Once installed, initialize the facilitator with your chain configuration. You’ll need your wallet private key (for signing transactions) and the contract address of the USDC token on your chosen network.

JavaScript
import { X402Facilitator } from '@thirdweb-dev/extension-x402';

const facilitator = new X402Facilitator({
  privateKey: process.env.WALLET_PRIVATE_KEY,
  chainId: 1, // Ethereum Mainnet
  tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
});

Create a payment-gated endpoint

Wrap your analytics endpoint with the facilitator’s middleware. This ensures that every request includes a valid payment proof before your code executes.

JavaScript
app.get('/api/analytics', facilitator.middleware(async (req, res) => {
  // Your analytics logic here
  const data = await fetchChainData(req.query);
  res.json(data);
}));

With the facilitator in place, your API is now ready to accept USDC payments. The next step is to test the integration and ensure payments are correctly verified.

Connect to chain analytics providers

Replacing API keys with x402 payment logic transforms how you access chain data. Instead of managing subscriptions or exposing static credentials, your analytics queries become self-sovereign transactions. Providers like Bitquery and QuickNode now support this standard, allowing you to pay per query or via pre-funded wallets using stablecoins like USDC.

Follow these steps to integrate x402 endpoints into your existing analytics workflow.

x402 Endpoints for Chain Analytics APIs
1
Choose your analytics provider

Select a provider that explicitly supports x402. Bitquery offers a comprehensive guide for accessing payment transactions and real-time server activity via their documentation. QuickNode provides a similar path for blockchain infrastructure access, removing the need for traditional account setups as outlined here. Verify that the specific endpoint you need supports the x402 header requirement.

x402 Endpoints for Chain Analytics APIs
2
Set up a USDC-compatible wallet

You need a wallet capable of holding and spending USDC on the network supported by your provider. Most x402 integrations operate on EVM-compatible chains like Ethereum, Polygon, or Base. Ensure your wallet has sufficient USDC balance to cover the query costs. Unlike API keys, there is no recurring subscription; you pay only for the data you retrieve.

x402 Endpoints for Chain Analytics APIs
3
Configure the x402 payment header

When making your API request, replace the standard Authorization or X-API-Key header with the x402 payment logic. This typically involves generating a signed payment intent or including a specific payment token in the request headers. The provider’s gateway intercepts this header, verifies the USDC transfer or allowance, and then processes your query. If the payment is insufficient or invalid, the request is rejected before hitting the data layer.

x402 Endpoints for Chain Analytics APIs
4
Test the integration with a sample query

Start with a lightweight query to confirm the payment flow works. For example, request basic chain stats or a small transaction history. Check the response for both the data payload and any payment confirmation metadata. If you receive a 200 OK, your wallet was debited correctly, and the data was delivered. If you get an error, verify your USDC balance and the correct network ID in your payment header.

FeatureTraditional API Keyx402 Payment Gateway
AuthenticationStatic API KeySigned Payment Intent
Billing ModelMonthly SubscriptionPay-Per-Query or Wallet Balance
User OnboardingAccount Creation RequiredWallet Connection Only
Data AccessTiered by PlanDirect Payment for Access

Handle USDC micropayments

To make analytics queries cost-effective, we use USDC on low-fee networks like Solana. This keeps transaction costs near zero, allowing you to charge fractions of a cent per API call without the friction of high gas fees.

Set up the payment facilitator

The facilitator acts as the gatekeeper. It intercepts the API request, checks for a valid USDC payment on-chain, and only proceeds if the transaction is confirmed. You can use libraries like @x402/solana to handle this validation efficiently.

Validate the transaction

Once the client sends a payment, your endpoint must verify it. Check the transaction hash against the blockchain to ensure the USDC transfer is complete and irreversible. This step prevents replay attacks and ensures the data is released only after payment.

Return the data

After confirmation, the endpoint returns the requested analytics data. This creates a seamless loop where users pay only for what they consume, making it viable for high-frequency queries.

Code example

Here is a simplified flow using Hono and Solana:

TypeScript
import { Hono } from 'hono';
import { x402 } from '@x402/solana';

const app = new Hono();

app.get('/analytics', async (c) => {
  // Check for payment
  const isValid = await x402.verifyPayment(c.req.raw);
  
  if (!isValid) {
    return c.json({ error: 'Payment required' }, 402);
  }

  // Return data
  return c.json({ data: 'Analytics results' });
});

This setup ensures that every query is backed by a verified transaction, creating a secure and automated payment model for your API.

Test the payment flow

Before you push these x402 endpoints to production, you need to prove that the payment gate is working. The goal is simple: verify that unpaid requests are blocked and that data only flows after a successful USDC transaction. This verification protects your analytics infrastructure from free-riding and ensures your billing logic is sound.

Start by setting up a local payment facilitator or using a testnet environment that supports x402. You will need a wallet with a small amount of USDC to simulate real-world conditions. The following checklist guides you through the essential verification steps.

x402 Endpoints for Chain Analytics APIs

Verification Checklist

  • Verify the 402 Response: Send a request without a payment proof. The endpoint must return an HTTP 402 status code with a Payment-Required header. This header should contain the payment URI or instructions for the client.
  • Test Unpaid Access: Ensure that sending a request with an empty or invalid Authorization header is rejected. The endpoint should not leak any data, not even an error message that reveals internal structure.
  • Validate USDC Payment: Execute a transaction using a test wallet. Confirm that the payment facilitator acknowledges the USDC transfer and issues a valid payment proof token.
  • Check Data Delivery: Send the same request with the valid payment proof. The endpoint should return the full analytics payload (e.g., chain data, transaction history) with a 200 OK status.
  • Test Token Expiration: If your implementation uses time-bound tokens, verify that the endpoint rejects requests after the token's validity period expires, returning a 402 or 401 error.
  • Audit Log Accuracy: Confirm that your server logs record the payment event, linking the transaction hash to the specific API request for auditing and reconciliation.

Once these steps pass, your x402 endpoint is ready for integration. This rigorous testing ensures that your API remains secure, billable, and reliable for AI agents and human developers alike.

Common x402 integration: what to check next

Before wiring x402 into your chain analytics pipeline, it helps to understand how payment flows interact with API latency and network constraints. The standard is designed for machine-to-machine transactions, but real-world implementation requires careful handling of gas fees and endpoint availability.

Integrating x402 means shifting from token-based access to value-based access. For chain analytics, this allows you to charge per-query or per-block-height accurately. Always test with a small USDC amount first to ensure your gateway routes the payment correctly before scaling to production workloads.