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 🙏

© 2026 – Pkg Stats / Ryan Hefner

x402-error-handler

v0.1.0

Published

Production-ready, zero-runtime-dependency TypeScript library that transforms HTTP 402 Payment Required responses into structured, machine-actionable error events

Downloads

21

Readme

x402-error-handler

Production-ready, zero-runtime-dependency TypeScript library that transforms opaque HTTP 402 Payment Required responses into structured, machine-actionable error events suitable for autonomous agents, payment systems, and API integrators.

Features

  • Zero Dependencies: Pure TypeScript implementation
  • Machine-Actionable: Structured error codes with deterministic recovery paths
  • Cross-Platform: Works in Node.js ≥18, Bun, and modern browsers
  • Type-Safe: Full TypeScript support with strict type checking
  • Minimal Bundle: <3KB min+gzip
  • Telemetry Ready: Optional telemetry hooks for monitoring
  • Immutable Protocol: Fixed canonical error codes

Installation

npm install x402-error-handler

Quick Start

import { parseX402Error, formatError } from 'x402-error-handler';

const response = await fetch('https://api.example.com/paid-endpoint');

if (response.status === 402) {
  const errorContext = await parseX402Error(response);
  
  if (errorContext) {
    const formatted = formatError(errorContext);
    
    // Handle based on severity
    if (formatted.shouldStop) {
      console.log('Stop processing:', formatted.message);
    } else if (formatted.shouldRetry) {
      console.log('Retry with intent:', formatted.recoveryIntent);
    }
  }
}

Canonical Error Codes

| Code | Key | Message | Severity | Recovery Intent | |------|-----|---------|----------|-----------------| | X402-001 | INSUFFICIENT_FUNDS | USDC balance too low on Base | user | fund_wallet | | X402-002 | INVALID_SIGNATURE | Payment signature invalid or expired | fatal | — | | X402-003 | PAYMENT_TIMEOUT | Invoice expired. Retry with new nonce. | retryable | retry_with_nonce | | X402-004 | PAYMENT_CONFLICT | Concurrent payment attempt for same resource | retryable | retry_with_backoff | | X402-005 | NETWORK_CONGESTION | Base mempool congested. Auto-retry in progress. | retryable | retry_later | | X402-999 | UNKNOWN_402 | Unrecognized 402 response. Inspect raw headers/body. | debug | — |

API Reference

parseX402Error(response: ResponseLike): Promise<ErrorContext | null>

Parses an HTTP 402 response and extracts x402 error information.

formatError(context: ErrorContext): FormattedError

Formats an error context into a machine-actionable error with retry/stop logic.

createX402Handler(options?: HandlerOptions): X402Handler

Creates a handler instance with optional telemetry.

Severity-Based Behavior

| Severity | shouldRetry | shouldStop | Action | |----------|-------------|------------|---------| | fatal | false | true | Stop immediately | | retryable | true | false | Retry with backoff | | user | false | true | Wallet action required | | debug | false | false | Log and continue |

TypeScript Support

Full type definitions included:

interface ErrorContext {
  code: string;
  message: string;
  severity: 'fatal' | 'retryable' | 'user' | 'debug';
  recoveryIntent: 'fund_wallet' | 'retry_with_nonce' | 'retry_with_backoff' | 'retry_later' | null;
  raw?: any;
}

interface FormattedError {
  code: string;
  message: string;
  severity: Severity;
  recoveryIntent: RecoveryIntent;
  shouldRetry: boolean;
  shouldStop: boolean;
  metadata?: Record<string, any>;
}

Examples

See the examples directory for complete usage examples.

Development

# Install dependencies
npm install

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Build library
npm run build

# Type check
npm run typecheck

# Check bundle size
npm run size

Contact

License

MIT