Dexter
Dexter
Docs

@dexterai/x402

@dexterai/x402 is Dexter's full-stack x402 SDK.

It is the package you use when you want to:

  • protect an API endpoint with x402 payments
  • make x402 payments from Node.js scripts (Solana or EVM)
  • make x402 payments from browser apps
  • add payment-aware React UI flows
  • use Access Pass instead of signing every request
  • implement dynamic or token-based pricing
  • receive and display sponsored recommendations (Ads for Agents)

When To Use It

Use @dexterai/x402 when you are building:

  • a paid API
  • a wallet-connected browser app
  • a React application that needs payment state
  • a client that should handle 402 Payment Required automatically
  • an endpoint that needs dynamic or usage-based pricing
  • a publisher that wants to earn from sponsored recommendations

Do not use this package when your main goal is:

  • OpenClaw-native agent payments: use @dexterai/clawdexter
  • local stdio discovery/payment for editor or CLI agents: use @dexterai/opendexter

Install

npm install @dexterai/x402

Optional peer dependencies (install only what you need):

npm install viem          # EVM wallet support (Base, Polygon, Arbitrum, BSC, etc.)
npm install tiktoken      # Token pricing (LLM endpoints)
npm install stripe        # Stripe machine payments
npm install react         # React hooks

What It Exports

The published package exports five entry points:

  • @dexterai/x402/client
  • @dexterai/x402/server
  • @dexterai/x402/react
  • @dexterai/x402/adapters
  • @dexterai/x402/utils

Which Surface To Use

client

Use @dexterai/x402/client when you need payment-aware fetch behavior.

ExportPurpose
wrapFetchOne-liner for Node.js scripts — supports walletPrivateKey (Solana) and evmPrivateKey (EVM)
createX402ClientFull client for browser or wallet-connected environments
createKeypairWalletCreate a Solana wallet from a private key
createEvmKeypairWalletCreate an EVM wallet from a private key (requires viem)
getPaymentReceiptExtract typed payment receipt from a response
getSponsoredRecommendationsExtract sponsored recommendations from a payment response
getSponsoredAccessInfoExtract full sponsored-access extension data
fireImpressionBeaconConfirm recommendation delivery to the ad network
KEYPAIR_SYMBOLSymbol key for safe access to the underlying Solana Keypair
X402ErrorTyped error class with machine-readable error codes

server

Use @dexterai/x402/server when you are protecting endpoints or building seller infrastructure.

ExportPurpose
x402MiddlewareOne-liner Express middleware with onSettlement and onVerifyFailed callbacks
x402AccessPassTime-limited access pass middleware
createX402ServerLow-level server for manual 402 flows
createDynamicPricingPrice by payload size with HMAC-signed quotes
createTokenPricingPrice by token count (async, requires tiktoken)
stripePayToStripe machine payments provider (Base only)
x402BrowserSupportHTML paywall for browser 402 responses
escapeHtmlHTML escape function for rendering payment data safely
FacilitatorClientDirect facilitator API client with retry and caching
SponsoredRecommendationTyped recommendation interface (re-exported from @dexterai/x402-ads-types)
SPONSORED_ACCESS_EXTENSION_KEYExtension key constant ("sponsored-access")

react

Use @dexterai/x402/react when you want hook-based payment state in a React app.

ExportPurpose
useX402PaymentMain hook — returns sponsoredRecommendations, balances, transaction state
useAccessPassDedicated hook for access pass lifecycle (tier discovery, purchase, caching)
getSponsoredRecommendationsAlso available from react entry point
fireImpressionBeaconAlso available from react entry point

adapters

Use @dexterai/x402/adapters for lower-level chain adapter control.

  • createSolanaAdapter / createEvmAdapter
  • isKnownUSDC — check if an asset address is a known USDC contract (any chain)
  • USDC_ADDRESSES — registry of USDC addresses per EVM chain
  • Chain constants: BASE_MAINNET, POLYGON, ARBITRUM_ONE, OPTIMISM, AVALANCHE, BSC_MAINNET, SKALE_BASE

utils

Use @dexterai/x402/utils for amount conversion and network detection.

  • toAtomicUnits / fromAtomicUnits — convert between human-readable and atomic amounts
  • isSolanaNetwork / isEvmNetwork — check network type from CAIP-2 identifiers
  • getChainFamily / getChainName / getExplorerUrl — network utilities
  • encodeBase64Json / decodeBase64Json — unicode-safe base64 encoding

Minimal Paths

Fastest buyer path: Node.js (Solana)

import { wrapFetch } from '@dexterai/x402/client';
 
const x402Fetch = wrapFetch(fetch, {
  walletPrivateKey: process.env.SOLANA_PRIVATE_KEY,
});
 
const response = await x402Fetch('https://api.example.com/protected');

Fastest buyer path: Node.js (EVM)

import { wrapFetch } from '@dexterai/x402/client';
 
const x402Fetch = wrapFetch(fetch, {
  evmPrivateKey: process.env.EVM_PRIVATE_KEY,
});
 
const response = await x402Fetch('https://api.example.com/protected');

Fastest browser path

import { createX402Client } from '@dexterai/x402/client';
 
const client = createX402Client({
  wallets: {
    solana: solanaWallet,
    evm: evmWallet,
  },
});
 
const response = await client.fetch('https://api.example.com/protected');

Fastest seller path

import express from 'express';
import { x402Middleware } from '@dexterai/x402/server';
 
const app = express();
 
app.get('/api/protected',
  x402Middleware({
    payTo: 'YourSolanaAddress...',
    amount: '0.01',
    onSettlement: (info) => {
      console.log(`Paid: ${info.transaction} from ${info.payer}`);
    },
  }),
  (req, res) => {
    res.json({ data: 'protected content' });
  },
);

Supported Networks

The SDK supports all networks available on the Dexter facilitator:

  • Solana Mainnet
  • Base Mainnet
  • Polygon
  • Arbitrum
  • Optimism
  • Avalanche
  • BNB Smart Chain
  • SKALE

For exact current chain support and facilitator behavior, see Supported Networks.

What The SDK Covers

  • automatic 402 handling with pre-payment inspection (onPaymentRequired)
  • client fetch wrappers (Solana + EVM)
  • browser wallet flows
  • React hooks with sponsored recommendation delivery
  • Express middleware with settlement/verification callbacks
  • Access Pass (JWT-based time-limited access)
  • dynamic pricing (HMAC-signed, time-bounded quotes)
  • token pricing (async, tiktoken-based)
  • Stripe machine payments (Base)
  • sponsored access (Ads for Agents)

Common Failure Modes

Wrong wallet context

The client needs a compatible wallet for a chain the endpoint accepts. Use isSolanaNetwork() or isEvmNetwork() to check.

Missing funds

The payment flow cannot complete if the configured wallet is not funded with USDC on the accepted chain. Balance checks now throw on RPC errors instead of silently returning zero — the client skips the pre-check and lets the chain reject if the RPC is unavailable.

Choosing the wrong surface

GoalUse
Node.js scriptwrapFetch
Browser appcreateX402Client
React UIuseX402Payment
Protected endpointx402Middleware
Repeated readsx402AccessPass
Budget controlsonPaymentRequired callback