stellar-x402-fetch
v0.2.1
Published
Stellar x402 Payment Protocol
Readme
stellar-x402-fetch
A utility package that extends the native fetch API to automatically handle 402 Payment Required responses using the x402 payment protocol for the Stellar network. This package enables seamless integration of Stellar payment functionality into your applications when making HTTP requests.
Installation
npm install stellar-x402-fetchQuick Start
import { Keypair } from "@stellar/stellar-sdk";
import { wrapFetchWithPayment } from "stellar-x402-fetch";
// Create a Stellar keypair (or load from secret key)
const keypair = Keypair.fromSecret("SXXX..."); // Your Stellar secret key
// Wrap the fetch function with payment handling
const fetchWithPay = wrapFetchWithPayment(fetch, keypair);
// Make a request that may require payment
const response = await fetchWithPay("https://api.example.com/paid-endpoint", {
method: "GET",
});
const data = await response.json();API
wrapFetchWithPayment(fetch, stellarKeypair, maxValue?, paymentRequirementsSelector?, config?)
Wraps the native fetch API to handle 402 Payment Required responses automatically using Stellar transactions.
Parameters
fetch: The fetch function to wrap (typicallyglobalThis.fetch)stellarKeypair: The Stellar Keypair used to sign payment transactionsmaxValue: Optional maximum allowed payment amount in stroops (defaults to 1,000,000 stroops = 0.1 USDC)paymentRequirementsSelector: Optional function to select payment requirements from the responseconfig: Optional X402 configuration (e.g., custom Stellar RPC URLs)
Returns
A wrapped fetch function that automatically handles 402 responses by:
- Making the initial request
- If a 402 response is received, parsing the payment requirements
- Verifying the payment amount is within the allowed maximum
- Creating a Stellar payment transaction using the provided keypair
- Retrying the request with the payment header
How It Works
When your wrapped fetch encounters a 402 Payment Required response:
Parse Requirements: The server responds with payment requirements including:
- Amount in USDC (Stellar asset)
- Recipient Stellar address
- Network (stellar-testnet or stellar)
- Payment scheme (exact)
Create Payment: Your Stellar keypair signs a transaction that:
- Sends the required USDC amount
- Includes the fee sponsor signature from the facilitator
- Is ready for settlement
Retry Request: The payment header is added and the request is retried
Access Content: If payment is valid, you get the protected content
Example
import { Keypair } from "@stellar/stellar-sdk";
import { wrapFetchWithPayment } from "stellar-x402-fetch";
// Load your Stellar keypair from environment
const keypair = Keypair.fromSecret(process.env.STELLAR_SECRET_KEY);
// Wrap fetch with payment handling
const fetchWithPay = wrapFetchWithPayment(fetch, keypair);
// Make a request to a paid API endpoint
fetchWithPay("https://api.example.com/premium-data", {
method: "GET",
})
.then(async response => {
const data = await response.json();
console.log("Premium data:", data);
})
.catch(error => {
console.error("Payment or request failed:", error);
});Advanced Configuration
Custom Maximum Payment
// Allow payments up to 1 USDC (10,000,000 stroops)
const fetchWithPay = wrapFetchWithPayment(
fetch,
keypair,
BigInt(10_000_000)
);Custom Stellar RPC
const fetchWithPay = wrapFetchWithPayment(
fetch,
keypair,
undefined,
undefined,
{
stellarConfig: {
rpcUrl: "https://soroban-testnet.stellar.org"
}
}
);Stellar Networks
The package supports:
stellar-testnet: Stellar testnet for developmentstellar: Stellar mainnet for production
USDC issuers:
- Testnet:
GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5 - Mainnet:
GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN
Error Handling
try {
const response = await fetchWithPay(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
} catch (error) {
if (error.message.includes("Payment amount exceeds maximum")) {
console.error("Payment too expensive!");
} else if (error.message.includes("Payment already attempted")) {
console.error("Payment was already tried for this request");
} else {
console.error("Request failed:", error);
}
}Type Exports
export { decodeXPaymentResponse } from "stellar-x402/shared";
export type { X402Config, Network } from "stellar-x402/types";
export type { Keypair } from "@stellar/stellar-sdk";License
Apache 2.0
