Overview
Thex402-fetch package wraps the native fetch API to automatically handle x402 payment protocol. When a server responds with 402 Payment Required, the wrapper automatically signs the payment and retries the request.
Installation
Basic Usage
API Reference
wrapFetchWithPayment(fetchFn, signer)
Wraps a fetch function to automatically handle x402 payments.
Parameters
fetchFn(typeof fetch) - The fetch function to wrap (usually globalfetch)signer(Signer) - An x402-compatible signer for creating payment signatures
Returns
A wrapped fetch function with the same signature as the nativefetch API.
Signer Interface
The signer must implement:Examples
Cloudflare Worker Agent
From thecloudflare-agents demo (source):
Creating x402-Compatible Signer
From the Crossmint wallet adapter (source):Checking Wallet Deployment
Before making payments, you may need to check if a smart wallet is deployed:Deploying Pre-deployed Wallets
If using Crossmint smart wallets with ERC-6492, you may need to deploy them:How It Works
- Initial Request: You call the wrapped fetch with a URL
- Intercept 402: If server responds with
402 Payment Required, the wrapper intercepts it - Parse Requirements: Extract payment details from the 402 response body
- Sign Payment: Use the provided signer to create an EIP-712 signature
- Retry with Payment: Automatically retry the request with
X-PAYMENTheader - Return Response: Return the successful response to your code
Payment Headers
The wrapper automatically manages these headers:- Request:
Accept: application/vnd.x402+json(indicates x402 support) - Retry:
X-PAYMENT: <signature>(contains payment authorization) - Response:
X-PAYMENT-RESPONSE: <receipt>(payment confirmation)
Error Handling
The wrapper preserves standard fetch error behavior:- Payment signature failed: Check wallet balance and deployment status
- Network errors: Standard fetch network issues
- 402 persists: Signature verification failed on server
TypeScript Types
Related
- x402-axios - Axios interceptor for x402
- x402-hono - Server-side middleware for Hono
- Crossmint Wallets - Creating x402-compatible wallets