npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

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-fetch

Quick 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 (typically globalThis.fetch)
  • stellarKeypair: The Stellar Keypair used to sign payment transactions
  • maxValue: 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 response
  • config: Optional X402 configuration (e.g., custom Stellar RPC URLs)

Returns

A wrapped fetch function that automatically handles 402 responses by:

  1. Making the initial request
  2. If a 402 response is received, parsing the payment requirements
  3. Verifying the payment amount is within the allowed maximum
  4. Creating a Stellar payment transaction using the provided keypair
  5. Retrying the request with the payment header

How It Works

When your wrapped fetch encounters a 402 Payment Required response:

  1. 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)
  2. 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
  3. Retry Request: The payment header is added and the request is retried

  4. 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 development
  • stellar: 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