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

@x402x/core

v0.3.0

Published

Core utilities for x402x settlement framework

Downloads

170

Readme

@x402x/core

Core utilities for the x402x settlement framework - a lightweight library that extends x402 with programmable settlement capabilities.

Features

  • 🔐 Commitment Calculation: Cryptographically bind settlement parameters to user signatures
  • 🌐 Network Configuration: Pre-configured settings for all supported networks
  • 🔌 Builtin Hooks: Easy integration with TransferHook and other builtin hooks
  • 🚀 Middleware: Drop-in Express and Hono middleware for resource servers
  • 🛡️ Type-Safe: Full TypeScript support with comprehensive type definitions

Installation

npm install @x402x/core
# or
pnpm add @x402x/core
# or
yarn add @x402x/core

Quick Start

Resource Server (Generating PaymentRequirements)

import { addSettlementExtra, TransferHook, getNetworkConfig } from "@x402x/core";

// Base PaymentRequirements (standard x402)
const baseRequirements = {
  scheme: "exact",
  network: "base-sepolia",
  maxAmountRequired: "100000", // 0.1 USDC
  asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
  payTo: merchantAddress,
  resource: "/api/payment",
};

// Add settlement extension
const requirements = addSettlementExtra(baseRequirements, {
  hook: TransferHook.getAddress("base-sepolia"),
  hookData: TransferHook.encode(),
  facilitatorFee: "10000", // 0.01 USDC
  payTo: merchantAddress,
});

// Return 402 response
res.status(402).json({
  accepts: [requirements],
  x402Version: 1,
});

Using Express Middleware

import express from "express";
import { x402Middleware } from "@x402x/core/middleware/express";

const app = express();

app.post(
  "/api/payment",
  x402Middleware({
    network: "base-sepolia",
    amount: "100000",
    resource: "/api/payment",
    facilitatorFee: "10000",
  }),
  (req, res) => {
    // Only runs after successful payment
    res.json({ success: true });
  },
);

Facilitator Integration

import { settle } from "x402/facilitator";
import { isSettlementMode, settleWithRouter, getNetworkConfig } from "@x402x/core/facilitator";

// Detect settlement mode
if (isSettlementMode(paymentRequirements)) {
  // x402x settlement
  const config = getNetworkConfig(paymentRequirements.network);
  const result = await settleWithRouter(signer, paymentPayload, paymentRequirements, {
    allowedRouters: {
      [paymentRequirements.network]: [config.settlementRouter],
    },
  });
} else {
  // Standard x402
  const result = await settle(signer, paymentPayload, paymentRequirements);
}

API Reference

Core Functions

calculateCommitment(params: CommitmentParams): string

Calculate commitment hash that binds all settlement parameters.

const commitment = calculateCommitment({
  chainId: 84532,
  hub: "0x...",
  asset: "0x...",
  from: "0x...",
  value: "100000",
  validAfter: "0",
  validBefore: "1234567890",
  salt: "0x...",
  payTo: "0x...",
  facilitatorFee: "10000",
  hook: "0x...",
  hookData: "0x",
});

generateSalt(): string

Generate a random 32-byte salt for settlement uniqueness.

const salt = generateSalt();
// => '0x1234567890abcdef...'

addSettlementExtra(requirements, params): PaymentRequirements

Add settlement extension to PaymentRequirements.

Network Functions

getNetworkConfig(network: string): NetworkConfig

Get configuration for a specific network.

const config = getNetworkConfig("base-sepolia");
// => { chainId: 84532, settlementRouter: '0x...', ... }

getSupportedNetworks(): string[]

Get list of all supported networks.

const networks = getSupportedNetworks();
// => ['base-sepolia', 'x-layer-testnet']

Builtin Hooks

TransferHook.encode(): string

Encode hookData for TransferHook (always returns '0x').

TransferHook.getAddress(network: string): string

Get TransferHook address for a specific network.

Facilitator API

The core package provides client-side functions to interact with facilitator HTTP APIs, following the x402 protocol standard.

verify(facilitatorUrl, paymentPayload, paymentRequirements): Promise<VerifyResponse>

Verify a payment payload with the facilitator without executing it. This calls the facilitator's /verify endpoint.

import { verify } from "@x402x/core";

const result = await verify("https://facilitator.x402x.dev", paymentPayload, paymentRequirements);

if (result.isValid) {
  console.log("Payment is valid, payer:", result.payer);
} else {
  console.error("Invalid payment:", result.invalidReason);
}

Response type:

interface VerifyResponse {
  isValid: boolean;
  invalidReason?: string;
  payer: string;
}

settle(facilitatorUrl, paymentPayload, paymentRequirements, timeout?): Promise<SettleResponse>

Settle a payment with the facilitator. This calls the facilitator's /settle endpoint to execute the payment on-chain.

import { settle } from "@x402x/core";

const result = await settle(
  "https://facilitator.x402x.dev",
  paymentPayload,
  paymentRequirements,
  30000, // optional timeout in ms
);

if (result.success) {
  console.log("Settlement successful!");
  console.log("Transaction:", result.transaction);
  console.log("Network:", result.network);
} else {
  console.error("Settlement failed:", result.errorReason);
}

Response type:

interface SettleResponse {
  success: boolean;
  transaction: string; // Transaction hash
  network: string;
  payer: string;
  errorReason?: string;
}

calculateFacilitatorFee(facilitatorUrl, network, hook, hookData?): Promise<FeeCalculationResult>

Calculate recommended facilitator fee for a specific hook.

import { calculateFacilitatorFee } from "@x402x/core";

const feeResult = await calculateFacilitatorFee(
  "https://facilitator.x402x.dev",
  "base-sepolia",
  "0x1234...",
  "0x",
);

console.log(`Fee: ${feeResult.facilitatorFee} (${feeResult.facilitatorFeeUSD} USD)`);

Other Facilitator Utilities

  • isSettlementMode(paymentRequirements) - Check if SettlementRouter mode is required
  • parseSettlementExtra(extra) - Parse and validate settlement extra parameters
  • clearFeeCache() - Clear the fee calculation cache

Facilitator Functions

See @x402x/core/facilitator for detailed facilitator utilities.

Supported Networks

  • base-sepolia (Testnet): Base Sepolia testnet
  • x-layer-testnet (Testnet): X-Layer testnet

Mainnet support coming after security audit.

License

Apache-2.0

Links