Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@x402/core

Package Overview
Dependencies
Maintainers
2
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@x402/core - npm Package Compare versions

Comparing version
2.8.0
to
2.9.0
+786
dist/cjs/mechanisms-Djgn2ixv.d.ts
type PaymentRequirementsV1 = {
scheme: string;
network: Network;
maxAmountRequired: string;
resource: string;
description: string;
mimeType: string;
outputSchema: Record<string, unknown>;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
extra: Record<string, unknown>;
};
type PaymentRequiredV1 = {
x402Version: 1;
error?: string;
accepts: PaymentRequirementsV1[];
};
type PaymentPayloadV1 = {
x402Version: 1;
scheme: string;
network: Network;
payload: Record<string, unknown>;
};
type VerifyRequestV1 = {
x402Version: number;
paymentPayload: PaymentPayloadV1;
paymentRequirements: PaymentRequirementsV1;
};
type SettleRequestV1 = {
x402Version: number;
paymentPayload: PaymentPayloadV1;
paymentRequirements: PaymentRequirementsV1;
};
type SettleResponseV1 = {
success: boolean;
errorReason?: string;
errorMessage?: string;
payer?: string;
transaction: string;
network: Network;
};
type SupportedResponseV1 = {
kinds: {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
}[];
};
interface FacilitatorConfig {
url?: string;
createAuthHeaders?: () => Promise<{
verify: Record<string, string>;
settle: Record<string, string>;
supported: Record<string, string>;
}>;
}
/**
* Interface for facilitator clients
* Can be implemented for HTTP-based or local facilitators
*/
interface FacilitatorClient {
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
/**
* Get supported payment kinds and extensions from the facilitator
*
* @returns Supported payment kinds and extensions
*/
getSupported(): Promise<SupportedResponse>;
}
/**
* HTTP-based client for interacting with x402 facilitator services
* Handles HTTP communication with facilitator endpoints
*/
declare class HTTPFacilitatorClient implements FacilitatorClient {
readonly url: string;
private readonly _createAuthHeaders?;
/**
* Creates a new HTTPFacilitatorClient instance.
*
* @param config - Configuration options for the facilitator client
*/
constructor(config?: FacilitatorConfig);
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
/**
* Get supported payment kinds and extensions from the facilitator.
* Retries with exponential backoff on 429 rate limit errors.
*
* @returns Supported payment kinds and extensions
*/
getSupported(): Promise<SupportedResponse>;
/**
* Creates authentication headers for a specific path.
*
* @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
* @returns An object containing the authentication headers for the specified path
*/
createAuthHeaders(path: string): Promise<{
headers: Record<string, string>;
}>;
/**
* Helper to convert objects to JSON-safe format.
* Handles BigInt and other non-JSON types.
*
* @param obj - The object to convert
* @returns The JSON-safe representation of the object
*/
private toJsonSafe;
}
/**
* Configuration for a protected resource
* Only contains payment-specific configuration, not resource metadata
*/
interface ResourceConfig {
scheme: string;
payTo: string;
price: Price;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Lifecycle Hook Context Interfaces
*/
interface PaymentRequiredContext {
requirements: PaymentRequirements[];
resourceInfo: ResourceInfo;
error?: string;
paymentRequiredResponse: PaymentRequired;
transportContext?: unknown;
}
interface VerifyContext {
paymentPayload: PaymentPayload;
requirements: PaymentRequirements;
}
interface VerifyResultContext extends VerifyContext {
result: VerifyResponse;
}
interface VerifyFailureContext extends VerifyContext {
error: Error;
}
interface SettleContext {
paymentPayload: PaymentPayload;
requirements: PaymentRequirements;
}
interface SettleResultContext extends SettleContext {
result: SettleResponse;
transportContext?: unknown;
}
interface SettleFailureContext extends SettleContext {
error: Error;
}
/**
* Lifecycle Hook Type Definitions
*/
type BeforeVerifyHook = (context: VerifyContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
type AfterVerifyHook = (context: VerifyResultContext) => Promise<void>;
type OnVerifyFailureHook = (context: VerifyFailureContext) => Promise<void | {
recovered: true;
result: VerifyResponse;
}>;
type BeforeSettleHook = (context: SettleContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
type AfterSettleHook = (context: SettleResultContext) => Promise<void>;
type OnSettleFailureHook = (context: SettleFailureContext) => Promise<void | {
recovered: true;
result: SettleResponse;
}>;
/**
* Optional overrides for settlement parameters.
* Used to support partial settlement (e.g., upto scheme billing by actual usage).
*
* Note: Overriding the amount to a value different from the agreed-upon
* `PaymentRequirements.amount` is only valid in schemes that explicitly support
* partial settlement, such as the `upto` scheme. Using this with standard
* x402 schemes (e.g., `exact`) will likely cause settlement verification to fail.
*/
interface SettlementOverrides {
/**
* Amount to settle. Supports three formats:
*
* - **Raw atomic units** — e.g., `"1000"` settles exactly 1000 atomic units.
* - **Percent** — e.g., `"50%"` settles 50% of `PaymentRequirements.amount`.
* Supports up to two decimal places (e.g., `"33.33%"`). The result is floored
* to the nearest atomic unit.
* - **Dollar price** — e.g., `"$0.05"` converts a USD-denominated price to
* atomic units. Decimals are determined from the registered scheme's
* `getAssetDecimals` method, falling back to 6 (standard for USDC stablecoins).
* The result is rounded to the nearest atomic unit.
*
* The resolved amount must be <= the authorized maximum in `PaymentRequirements`.
*
* Note: Setting this to an amount other than `PaymentRequirements.amount` is
* only valid in schemes that support partial settlement, such as `upto`.
*/
amount?: string;
}
/**
* Core x402 protocol server for resource protection
* Transport-agnostic implementation of the x402 payment protocol
*/
declare class x402ResourceServer {
private facilitatorClients;
private registeredServerSchemes;
private supportedResponsesMap;
private facilitatorClientsMap;
private registeredExtensions;
private beforeVerifyHooks;
private afterVerifyHooks;
private onVerifyFailureHooks;
private beforeSettleHooks;
private afterSettleHooks;
private onSettleFailureHooks;
/**
* Creates a new x402ResourceServer instance.
*
* @param facilitatorClients - Optional facilitator client(s) for payment processing
*/
constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]);
/**
* Register a scheme/network server implementation.
*
* @param network - The network identifier
* @param server - The scheme/network server implementation
* @returns The x402ResourceServer instance for chaining
*/
register(network: Network, server: SchemeNetworkServer): x402ResourceServer;
/**
* Check if a scheme is registered for a given network.
*
* @param network - The network identifier
* @param scheme - The payment scheme name
* @returns True if the scheme is registered for the network, false otherwise
*/
hasRegisteredScheme(network: Network, scheme: string): boolean;
/**
* Registers a resource service extension that can enrich extension declarations.
*
* @param extension - The extension to register
* @returns The x402ResourceServer instance for chaining
*/
registerExtension(extension: ResourceServerExtension): this;
/**
* Check if an extension is registered.
*
* @param key - The extension key
* @returns True if the extension is registered
*/
hasExtension(key: string): boolean;
/**
* Get all registered extensions.
*
* @returns Array of registered extensions
*/
getExtensions(): ResourceServerExtension[];
/**
* Enriches declared extensions using registered extension hooks.
*
* @param declaredExtensions - Extensions declared on the route
* @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
* @returns Enriched extensions map
*/
enrichExtensions(declaredExtensions: Record<string, unknown>, transportContext: unknown): Record<string, unknown>;
/**
* Register a hook to execute before payment verification.
* Can abort verification by returning { abort: true, reason: string }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer;
/**
* Register a hook to execute after successful payment verification.
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onAfterVerify(hook: AfterVerifyHook): x402ResourceServer;
/**
* Register a hook to execute when payment verification fails.
* Can recover from failure by returning { recovered: true, result: VerifyResponse }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer;
/**
* Register a hook to execute before payment settlement.
* Can abort settlement by returning { abort: true, reason: string }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer;
/**
* Register a hook to execute after successful payment settlement.
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onAfterSettle(hook: AfterSettleHook): x402ResourceServer;
/**
* Register a hook to execute when payment settlement fails.
* Can recover from failure by returning { recovered: true, result: SettleResponse }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer;
/**
* Initialize by fetching supported kinds from all facilitators
* Creates mappings for supported responses and facilitator clients
* Earlier facilitators in the array get precedence
*/
initialize(): Promise<void>;
/**
* Get supported kind for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The supported kind or undefined if not found
*/
getSupportedKind(x402Version: number, network: Network, scheme: string): SupportedKind | undefined;
/**
* Get facilitator extensions for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The facilitator extensions or empty array if not found
*/
getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[];
/**
* Build payment requirements for a protected resource
*
* @param resourceConfig - Configuration for the protected resource
* @returns Array of payment requirements
*/
buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]>;
/**
* Build payment requirements from multiple payment options
* This method handles resolving dynamic payTo/price functions and builds requirements for each option
*
* @param paymentOptions - Array of payment options to convert
* @param context - HTTP request context for resolving dynamic functions
* @returns Array of payment requirements (one per option)
*/
buildPaymentRequirementsFromOptions<TContext = unknown>(paymentOptions: Array<{
scheme: string;
payTo: string | ((context: TContext) => string | Promise<string>);
price: Price | ((context: TContext) => Price | Promise<Price>);
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}>, context: TContext): Promise<PaymentRequirements[]>;
/**
* Create a payment required response
*
* @param requirements - Payment requirements
* @param resourceInfo - Resource information
* @param error - Error message
* @param extensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional transport-specific context (e.g., HTTP request, MCP tool context)
* @returns Payment required response object
*/
createPaymentRequiredResponse(requirements: PaymentRequirements[], resourceInfo: ResourceInfo, error?: string, extensions?: Record<string, unknown>, transportContext?: unknown): Promise<PaymentRequired>;
/**
* Verify a payment against requirements
*
* @param paymentPayload - The payment payload to verify
* @param requirements - The payment requirements
* @returns Verification response
*/
verifyPayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a verified payment
*
* @param paymentPayload - The payment payload to settle
* @param requirements - The payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)
* @param settlementOverrides - Optional overrides for settlement parameters (e.g., partial settlement amount)
* @returns Settlement response
*/
settlePayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown, settlementOverrides?: SettlementOverrides): Promise<SettleResponse>;
/**
* Find matching payment requirements for a payment
*
* @param availableRequirements - Array of available payment requirements
* @param paymentPayload - The payment payload
* @returns Matching payment requirements or undefined
*/
findMatchingRequirements(availableRequirements: PaymentRequirements[], paymentPayload: PaymentPayload): PaymentRequirements | undefined;
/**
* Process a payment request
*
* @param paymentPayload - Optional payment payload if provided
* @param resourceConfig - Configuration for the protected resource
* @param resourceInfo - Information about the resource being accessed
* @param extensions - Optional extensions to include in the response
* @returns Processing result
*/
processPaymentRequest(paymentPayload: PaymentPayload | null, resourceConfig: ResourceConfig, resourceInfo: ResourceInfo, extensions?: Record<string, unknown>): Promise<{
success: boolean;
requiresPayment?: PaymentRequired;
verificationResult?: VerifyResponse;
settlementResult?: SettleResponse;
error?: string;
}>;
/**
* Get facilitator client for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The facilitator client or undefined if not found
*/
private getFacilitatorClient;
}
/**
* Base interface for facilitator extensions.
* Extensions registered with x402Facilitator are stored by key and made
* available to mechanism implementations via FacilitatorContext.
*
* Specific extensions extend this with additional capabilities:
*
* @example
* interface Erc20GasSponsoringExtension extends FacilitatorExtension {
* batchSigner: SmartWalletBatchSigner;
* }
*/
interface FacilitatorExtension {
key: string;
}
interface ResourceServerExtension {
key: string;
/**
* Enrich extension declaration with extension-specific data.
*
* @param declaration - Extension declaration from route config
* @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
* @returns Enriched extension declaration
*/
enrichDeclaration?: (declaration: unknown, transportContext: unknown) => unknown;
/**
* Called when generating a 402 PaymentRequired response.
* Return extension data to add to extensions[key], or undefined to skip.
*
* @param declaration - Extension declaration from route config
* @param context - PaymentRequired context containing response, requirements, and optional transportContext
* @returns Extension data to add to response.extensions[key]
*/
enrichPaymentRequiredResponse?: (declaration: unknown, context: PaymentRequiredContext) => Promise<unknown>;
/**
* Called after successful payment settlement.
* Return extension data to add to response.extensions[key], or undefined to skip.
*
* @param declaration - Extension declaration from route config
* @param context - Settlement result context containing payment payload, requirements, result and optional transportContext
* @returns Extension data to add to response.extensions[key]
*/
enrichSettlementResponse?: (declaration: unknown, context: SettleResultContext) => Promise<unknown>;
}
type Network = `${string}:${string}`;
type Money = string | number;
type AssetAmount = {
asset: string;
amount: string;
extra?: Record<string, unknown>;
};
type Price = Money | AssetAmount;
interface ResourceInfo {
url: string;
description?: string;
mimeType?: string;
}
type PaymentRequirements = {
scheme: string;
network: Network;
asset: string;
amount: string;
payTo: string;
maxTimeoutSeconds: number;
extra: Record<string, unknown>;
};
type PaymentRequired = {
x402Version: number;
error?: string;
resource: ResourceInfo;
accepts: PaymentRequirements[];
extensions?: Record<string, unknown>;
};
type PaymentPayload = {
x402Version: number;
resource?: ResourceInfo;
accepted: PaymentRequirements;
payload: Record<string, unknown>;
extensions?: Record<string, unknown>;
};
type VerifyRequest = {
x402Version: number;
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};
type VerifyResponse = {
isValid: boolean;
invalidReason?: string;
invalidMessage?: string;
payer?: string;
extensions?: Record<string, unknown>;
};
type SettleRequest = {
x402Version: number;
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};
type SettleResponse = {
success: boolean;
errorReason?: string;
errorMessage?: string;
payer?: string;
transaction: string;
network: Network;
/** Actual amount settled in atomic token units. Present for schemes like `upto` where settlement amount may differ from the authorized maximum. */
amount?: string;
extensions?: Record<string, unknown>;
};
type SupportedKind = {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
};
type SupportedResponse = {
kinds: SupportedKind[];
extensions: string[];
signers: Record<string, string[]>;
};
/**
* Error thrown when payment verification fails.
*/
declare class VerifyError extends Error {
readonly invalidReason?: string;
readonly invalidMessage?: string;
readonly payer?: string;
readonly statusCode: number;
/**
* Creates a VerifyError from a failed verification response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The verify response containing error details
*/
constructor(statusCode: number, response: VerifyResponse);
}
/**
* Error thrown when payment settlement fails.
*/
declare class SettleError extends Error {
readonly errorReason?: string;
readonly errorMessage?: string;
readonly payer?: string;
readonly transaction: string;
readonly network: Network;
readonly statusCode: number;
/**
* Creates a SettleError from a failed settlement response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The settle response containing error details
*/
constructor(statusCode: number, response: SettleResponse);
}
/**
* Error thrown when a facilitator returns malformed success payload data.
*/
declare class FacilitatorResponseError extends Error {
/**
* Creates a FacilitatorResponseError for malformed facilitator responses.
*
* @param message - The boundary error message
*/
constructor(message: string);
}
/**
* Walks an error cause chain to find the first facilitator response error.
*
* @param error - The thrown value to inspect
* @returns The nested facilitator response error, if present
*/
declare function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null;
/**
* Money parser function that converts a numeric amount to an AssetAmount
* Receives the amount as a decimal number (e.g., 1.50 for $1.50)
* Returns null to indicate "cannot handle this amount", causing fallback to next parser
* Always returns a Promise for consistency - use async/await
*
* @param amount - The decimal amount (e.g., 1.50)
* @param network - The network identifier for context
* @returns AssetAmount or null to try next parser
*/
type MoneyParser = (amount: number, network: Network) => Promise<AssetAmount | null>;
/**
* Result of createPaymentPayload - the core payload fields.
* Contains the x402 version, scheme-specific payload data, and optional extension data.
* Schemes may return extensions (e.g., EIP-2612 gas sponsoring) that get merged
* with server-declared extensions in the final PaymentPayload.
*/
type PaymentPayloadResult = Pick<PaymentPayload, "x402Version" | "payload"> & {
extensions?: Record<string, unknown>;
};
/**
* Context passed to scheme's createPaymentPayload for extensions awareness.
* Contains the server-declared extensions from PaymentRequired so the scheme
* can check which extensions are advertised and respond accordingly.
*/
interface PaymentPayloadContext {
extensions?: Record<string, unknown>;
}
interface SchemeNetworkClient {
readonly scheme: string;
createPaymentPayload(x402Version: number, paymentRequirements: PaymentRequirements, context?: PaymentPayloadContext): Promise<PaymentPayloadResult>;
}
/**
* Context passed to SchemeNetworkFacilitator.verify/settle, providing
* access to registered facilitator extensions. Mechanism implementations
* use this to retrieve extension-provided capabilities (e.g., a batch signer).
*/
interface FacilitatorContext {
getExtension<T extends FacilitatorExtension = FacilitatorExtension>(key: string): T | undefined;
}
interface SchemeNetworkFacilitator {
readonly scheme: string;
/**
* CAIP family pattern that this facilitator supports.
* Used to group signers by blockchain family in the supported response.
*
* @example
* // EVM facilitators
* readonly caipFamily = "eip155:*";
*
* @example
* // SVM facilitators
* readonly caipFamily = "solana:*";
*/
readonly caipFamily: string;
/**
* Get mechanism-specific extra data needed for the supported kinds endpoint.
* This method is called when building the facilitator's supported response.
*
* @param network - The network identifier for context
* @returns Extra data object or undefined if no extra data is needed
*
* @example
* // EVM schemes return undefined (no extra data needed)
* getExtra(network: Network): undefined {
* return undefined;
* }
*
* @example
* // SVM schemes return feePayer address
* getExtra(network: Network): Record<string, unknown> | undefined {
* return { feePayer: this.signer.address };
* }
*/
getExtra(network: Network): Record<string, unknown> | undefined;
/**
* Get signer addresses used by this facilitator for a given network.
* These are included in the supported response to help clients understand
* which addresses might sign/pay for transactions.
*
* Supports multiple addresses for load balancing, key rotation, and high availability.
*
* @param network - The network identifier
* @returns Array of signer addresses (wallet addresses, fee payer addresses, etc.)
*
* @example
* // EVM facilitator
* getSigners(network: string): string[] {
* return [...this.signer.getAddresses()];
* }
*
* @example
* // SVM facilitator
* getSigners(network: string): string[] {
* return [...this.signer.getAddresses()];
* }
*/
getSigners(network: string): string[];
verify(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<VerifyResponse>;
settle(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<SettleResponse>;
}
interface SchemeNetworkServer {
readonly scheme: string;
/**
* Convert a user-friendly price to the scheme's specific amount and asset format
* Always returns a Promise for consistency
*
* @param price - User-friendly price (e.g., "$0.10", "0.10", { amount: "100000", asset: "USDC" })
* @param network - The network identifier for context
* @returns Promise that resolves to the converted amount, asset identifier, and any extra metadata
*
* @example
* // For EVM networks with USDC:
* await parsePrice("$0.10", "eip155:8453") => { amount: "100000", asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }
*
* // For custom schemes:
* await parsePrice("10 points", "custom:network") => { amount: "10", asset: "points" }
*/
parsePrice(price: Price, network: Network): Promise<AssetAmount>;
/**
* Optional: Return the decimal precision of the asset for a given network.
* Used by `resolveSettlementOverrideAmount` to convert dollar-format overrides to atomic units.
* Defaults to 6 when not implemented.
*
* @param asset - The asset address or symbol
* @param network - The network identifier
* @returns Number of decimal places for the asset
*/
getAssetDecimals?(asset: string, network: Network): number;
/**
* Build payment requirements for this scheme/network combination
*
* @param paymentRequirements - Base payment requirements with amount/asset already set
* @param supportedKind - The supported kind from facilitator's /supported endpoint
* @param supportedKind.x402Version - The x402 version
* @param supportedKind.scheme - The payment scheme
* @param supportedKind.network - The network identifier
* @param supportedKind.extra - Optional extra metadata
* @param facilitatorExtensions - Extensions supported by the facilitator
* @returns Enhanced payment requirements ready to be sent to clients
*/
enhancePaymentRequirements(paymentRequirements: PaymentRequirements, supportedKind: {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
}, facilitatorExtensions: string[]): Promise<PaymentRequirements>;
}
export { type AfterVerifyHook as A, type BeforeVerifyHook as B, type SettleResponseV1 as C, type SupportedResponseV1 as D, type AssetAmount as E, type FacilitatorExtension as F, type VerifyRequest as G, HTTPFacilitatorClient as H, type SettleRequest as I, type SupportedResponse as J, VerifyError as K, SettleError as L, type Money as M, type Network as N, type OnVerifyFailureHook as O, type PaymentPayload as P, type ResourceInfo as Q, type ResourceConfig as R, type SettleResponse as S, type SchemeNetworkServer as T, type MoneyParser as U, type VerifyResponse as V, type PaymentPayloadResult as W, type PaymentPayloadContext as X, type FacilitatorContext as Y, type ResourceServerExtension as Z, type PaymentRequirements as a, type SchemeNetworkFacilitator as b, type PaymentRequired as c, type FacilitatorClient as d, type FacilitatorConfig as e, FacilitatorResponseError as f, getFacilitatorResponseError as g, type SchemeNetworkClient as h, type PaymentRequiredContext as i, type VerifyContext as j, type VerifyResultContext as k, type VerifyFailureContext as l, type SettleContext as m, type SettleResultContext as n, type SettleFailureContext as o, type SettlementOverrides as p, type BeforeSettleHook as q, type AfterSettleHook as r, type OnSettleFailureHook as s, type Price as t, type PaymentRequirementsV1 as u, type PaymentRequiredV1 as v, type PaymentPayloadV1 as w, x402ResourceServer as x, type VerifyRequestV1 as y, type SettleRequestV1 as z };
import { x as x402ResourceServer, t as Price, N as Network, S as SettleResponse, c as PaymentRequired, P as PaymentPayload, a as PaymentRequirements, p as SettlementOverrides } from './mechanisms-Djgn2ixv.js';
declare const SETTLEMENT_OVERRIDES_HEADER = "Settlement-Overrides";
/**
* Framework-agnostic HTTP adapter interface
* Implementations provide framework-specific HTTP operations
*/
interface HTTPAdapter {
getHeader(name: string): string | undefined;
getMethod(): string;
getPath(): string;
getUrl(): string;
getAcceptHeader(): string;
getUserAgent(): string;
/**
* Get query parameters from the request URL
*
* @returns Record of query parameter key-value pairs
*/
getQueryParams?(): Record<string, string | string[]>;
/**
* Get a specific query parameter by name
*
* @param name - The query parameter name
* @returns The query parameter value(s) or undefined
*/
getQueryParam?(name: string): string | string[] | undefined;
/**
* Get the parsed request body
* Framework adapters should parse JSON/form data appropriately
*
* @returns The parsed request body
*/
getBody?(): unknown;
}
/**
* Paywall configuration for HTML responses
*/
interface PaywallConfig {
appName?: string;
appLogo?: string;
sessionTokenEndpoint?: string;
currentUrl?: string;
testnet?: boolean;
}
/**
* Paywall provider interface for generating HTML
*/
interface PaywallProvider {
generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;
}
/**
* Dynamic payTo function that receives HTTP request context
*/
type DynamicPayTo = (context: HTTPRequestContext) => string | Promise<string>;
/**
* Dynamic price function that receives HTTP request context
*/
type DynamicPrice = (context: HTTPRequestContext) => Price | Promise<Price>;
/**
* Result of response body callbacks containing content type and body.
*/
interface HTTPResponseBody {
/**
* The content type for the response (e.g., 'application/json', 'text/plain').
*/
contentType: string;
/**
* The response body to include in the 402 response.
*/
body: unknown;
}
/**
* Dynamic function to generate a custom response for unpaid requests.
* Receives the HTTP request context and returns the content type and body to include in the 402 response.
*/
type UnpaidResponseBody = (context: HTTPRequestContext) => HTTPResponseBody | Promise<HTTPResponseBody>;
/**
* Dynamic function to generate a custom response for settlement failures.
* Receives the HTTP request context and settle failure result, returns the content type and body.
*/
type SettlementFailedResponseBody = (context: HTTPRequestContext, settleResult: Omit<ProcessSettleFailureResponse, "response">) => HTTPResponseBody | Promise<HTTPResponseBody>;
/**
* A single payment option for a route
* Represents one way a client can pay for access to the resource
*/
interface PaymentOption {
scheme: string;
payTo: string | DynamicPayTo;
price: Price | DynamicPrice;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Route configuration for HTTP endpoints
*
* The 'accepts' field defines payment options for the route.
* Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.
*/
interface RouteConfig {
accepts: PaymentOption | PaymentOption[];
resource?: string;
description?: string;
mimeType?: string;
customPaywallHtml?: string;
/**
* Optional callback to generate a custom response for unpaid API requests.
* This allows servers to return preview data, error messages, or other content
* when a request lacks payment.
*
* For browser requests (Accept: text/html), the paywall HTML takes precedence.
* This callback is only used for API clients.
*
* If not provided, defaults to { contentType: 'application/json', body: {} }.
*
* @param context - The HTTP request context
* @returns An object containing both contentType and body for the 402 response
*/
unpaidResponseBody?: UnpaidResponseBody;
/**
* Optional callback to generate a custom response for settlement failures.
* If not provided, defaults to { contentType: 'application/json', body: {} }.
*
* @param context - The HTTP request context
* @param settleResult - The settlement failure result
* @returns An object containing both contentType and body for the 402 response
*/
settlementFailedResponseBody?: SettlementFailedResponseBody;
extensions?: Record<string, unknown>;
}
/**
* Routes configuration - maps path patterns to route configs
*/
type RoutesConfig = Record<string, RouteConfig> | RouteConfig;
/**
* Hook that runs on every request to a protected route, before payment processing.
* Can grant access without payment, deny the request, or continue to payment flow.
*
* @returns
* - `void` - Continue to payment processing (default behavior)
* - `{ grantAccess: true }` - Grant access without requiring payment
* - `{ abort: true; reason: string }` - Deny the request (returns 403)
*/
type ProtectedRequestHook = (context: HTTPRequestContext, routeConfig: RouteConfig) => Promise<void | {
grantAccess: true;
} | {
abort: true;
reason: string;
}>;
/**
* Compiled route for efficient matching
*/
interface CompiledRoute {
verb: string;
regex: RegExp;
config: RouteConfig;
pattern: string;
}
/**
* HTTP request context that encapsulates all request data
*/
interface HTTPRequestContext {
adapter: HTTPAdapter;
path: string;
method: string;
paymentHeader?: string;
routePattern?: string;
}
/**
* HTTP transport context contains both request context and optional response data.
*/
interface HTTPTransportContext {
/** The HTTP request context */
request: HTTPRequestContext;
/** The response body buffer */
responseBody?: Buffer;
/** Response headers set by the route handler (used for settlement overrides) */
responseHeaders?: Record<string, string>;
}
/**
* HTTP response instructions for the framework middleware
*/
interface HTTPResponseInstructions {
status: number;
headers: Record<string, string>;
body?: unknown;
isHtml?: boolean;
}
/**
* Result of processing an HTTP request for payment
*/
type HTTPProcessResult = {
type: "no-payment-required";
} | {
type: "payment-verified";
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
declaredExtensions?: Record<string, unknown>;
} | {
type: "payment-error";
response: HTTPResponseInstructions;
};
/**
* Result of processSettlement
*/
type ProcessSettleSuccessResponse = SettleResponse & {
success: true;
headers: Record<string, string>;
requirements: PaymentRequirements;
};
type ProcessSettleFailureResponse = SettleResponse & {
success: false;
errorReason: string;
errorMessage?: string;
headers: Record<string, string>;
response: HTTPResponseInstructions;
};
type ProcessSettleResultResponse = ProcessSettleSuccessResponse | ProcessSettleFailureResponse;
/**
* Represents a validation error for a specific route's payment configuration.
*/
interface RouteValidationError {
/** The route pattern (e.g., "GET /api/weather") */
routePattern: string;
/** The payment scheme that failed validation */
scheme: string;
/** The network that failed validation */
network: Network;
/** The type of validation failure */
reason: "missing_scheme" | "missing_facilitator";
/** Human-readable error message */
message: string;
}
/**
* Error thrown when route configuration validation fails.
*/
declare class RouteConfigurationError extends Error {
/** The validation errors that caused this exception */
readonly errors: RouteValidationError[];
/**
* Creates a new RouteConfigurationError with the given validation errors.
*
* @param errors - The validation errors that caused this exception.
*/
constructor(errors: RouteValidationError[]);
}
/**
* HTTP-enhanced x402 resource server
* Provides framework-agnostic HTTP protocol handling
*/
declare class x402HTTPResourceServer {
private ResourceServer;
private compiledRoutes;
private routesConfig;
private paywallProvider?;
private protectedRequestHooks;
/**
* Creates a new x402HTTPResourceServer instance.
*
* @param ResourceServer - The core x402ResourceServer instance to use
* @param routes - Route configuration for payment-protected endpoints
*/
constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig);
/**
* Get the underlying x402ResourceServer instance.
*
* @returns The underlying x402ResourceServer instance
*/
get server(): x402ResourceServer;
/**
* Get the routes configuration.
*
* @returns The routes configuration
*/
get routes(): RoutesConfig;
/**
* Initialize the HTTP resource server.
*
* This method initializes the underlying resource server (fetching facilitator support)
* and then validates that all route payment configurations have corresponding
* registered schemes and facilitator support.
*
* @throws RouteConfigurationError if any route's payment options don't have
* corresponding registered schemes or facilitator support
*
* @example
* ```typescript
* const httpServer = new x402HTTPResourceServer(server, routes);
* await httpServer.initialize();
* ```
*/
initialize(): Promise<void>;
/**
* Register a custom paywall provider for generating HTML
*
* @param provider - PaywallProvider instance
* @returns This service instance for chaining
*/
registerPaywallProvider(provider: PaywallProvider): this;
/**
* Register a hook that runs on every request to a protected route, before payment processing.
* Hooks are executed in order of registration. The first hook to return a non-void result wins.
*
* @param hook - The request hook function
* @returns The x402HTTPResourceServer instance for chaining
*/
onProtectedRequest(hook: ProtectedRequestHook): this;
/**
* Process HTTP request and return response instructions
* This is the main entry point for framework middleware
*
* @param context - HTTP request context
* @param paywallConfig - Optional paywall configuration
* @returns Process result indicating next action for middleware
*/
processHTTPRequest(context: HTTPRequestContext, paywallConfig?: PaywallConfig): Promise<HTTPProcessResult>;
/**
* Process settlement after successful response
*
* @param paymentPayload - The verified payment payload
* @param requirements - The matching payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional HTTP transport context
* @param settlementOverrides - Optional settlement overrides (e.g., partial settlement amount)
* @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
*/
processSettlement(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: HTTPTransportContext, settlementOverrides?: SettlementOverrides): Promise<ProcessSettleResultResponse>;
/**
* Check if a request requires payment based on route configuration
*
* @param context - HTTP request context
* @returns True if the route requires payment, false otherwise
*/
requiresPayment(context: HTTPRequestContext): boolean;
/**
* Build HTTPResponseInstructions for settlement failure.
* Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.
*
* @param failure - Settlement failure result with headers
* @param transportContext - Optional HTTP transport context for the request
* @returns HTTP response instructions for the 402 settlement failure response
*/
private buildSettlementFailureResponse;
/**
* Normalizes a RouteConfig's accepts field into an array of PaymentOptions
* Handles both single PaymentOption and array formats
*
* @param routeConfig - Route configuration
* @returns Array of payment options
*/
private normalizePaymentOptions;
/**
* Validates that all payment options in routes have corresponding registered schemes
* and facilitator support.
*
* @returns Array of validation errors (empty if all routes are valid)
*/
private validateRouteConfiguration;
/**
* Get route configuration for a request
*
* @param path - Request path
* @param method - HTTP method
* @returns Route configuration and pattern, or undefined if no match
*/
private getRouteConfig;
/**
* Extract payment from HTTP headers (handles v1 and v2)
*
* @param adapter - HTTP adapter
* @returns Decoded payment payload or null
*/
private extractPayment;
/**
* Check if request is from a web browser
*
* @param adapter - HTTP adapter
* @returns True if request appears to be from a browser
*/
private isWebBrowser;
/**
* Create HTTP response instructions from payment required
*
* @param paymentRequired - Payment requirements
* @param isWebBrowser - Whether request is from browser
* @param paywallConfig - Paywall configuration
* @param customHtml - Custom HTML template
* @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
* @returns Response instructions
*/
private createHTTPResponse;
/**
* Create HTTP payment required response (v1 puts in body, v2 puts in header)
*
* @param paymentRequired - Payment required object
* @returns Headers and body for the HTTP response
*/
private createHTTPPaymentRequiredResponse;
/**
* Create settlement response headers
*
* @param settleResponse - Settlement response
* @returns Headers to add to response
*/
private createSettlementHeaders;
/**
* Parse route pattern into verb and regex
*
* @param pattern - Route pattern like "GET /api/*", "/api/[id]", or "/api/:id"
* @returns Parsed pattern with verb and regex
*/
private parseRoutePattern;
/**
* Normalize path for matching
*
* @param path - Raw path from request
* @returns Normalized path
*/
private normalizePath;
/**
* Generate paywall HTML for browser requests
*
* @param paymentRequired - Payment required response
* @param paywallConfig - Optional paywall configuration
* @param customHtml - Optional custom HTML template
* @returns HTML string
*/
private generatePaywallHTML;
/**
* Extract display amount from payment requirements.
*
* @param paymentRequired - The payment required object
* @returns The display amount in decimal format
*/
private getDisplayAmount;
}
export { type CompiledRoute as C, type DynamicPayTo as D, type HTTPAdapter as H, type PaywallConfig as P, type RouteConfig as R, type SettlementFailedResponseBody as S, type UnpaidResponseBody as U, type HTTPRequestContext as a, type HTTPTransportContext as b, type HTTPResponseInstructions as c, type HTTPProcessResult as d, type PaywallProvider as e, type PaymentOption as f, type RoutesConfig as g, type DynamicPrice as h, type HTTPResponseBody as i, type ProcessSettleResultResponse as j, type ProcessSettleSuccessResponse as k, type ProcessSettleFailureResponse as l, type RouteValidationError as m, RouteConfigurationError as n, type ProtectedRequestHook as o, SETTLEMENT_OVERRIDES_HEADER as p, x402HTTPResourceServer as x };
import {
z
} from "./chunk-KMQH4MQI.mjs";
import {
x402Version
} from "./chunk-VE37GDG2.mjs";
import {
FacilitatorResponseError,
SettleError,
VerifyError
} from "./chunk-JUGE6MAI.mjs";
import {
Base64EncodedRegex,
safeBase64Decode,
safeBase64Encode
} from "./chunk-TDLQZ6MP.mjs";
import {
__require
} from "./chunk-BJTO5JO5.mjs";
// src/http/x402HTTPResourceServer.ts
var SETTLEMENT_OVERRIDES_HEADER = "Settlement-Overrides";
var RouteConfigurationError = class extends Error {
/**
* Creates a new RouteConfigurationError with the given validation errors.
*
* @param errors - The validation errors that caused this exception.
*/
constructor(errors) {
const message = `x402 Route Configuration Errors:
${errors.map((e) => ` - ${e.message}`).join("\n")}`;
super(message);
this.name = "RouteConfigurationError";
this.errors = errors;
}
};
var x402HTTPResourceServer = class {
/**
* Creates a new x402HTTPResourceServer instance.
*
* @param ResourceServer - The core x402ResourceServer instance to use
* @param routes - Route configuration for payment-protected endpoints
*/
constructor(ResourceServer, routes) {
this.compiledRoutes = [];
this.protectedRequestHooks = [];
this.ResourceServer = ResourceServer;
this.routesConfig = routes;
const normalizedRoutes = typeof routes === "object" && !("accepts" in routes) ? routes : { "*": routes };
for (const [pattern, config] of Object.entries(normalizedRoutes)) {
const parsed = this.parseRoutePattern(pattern);
this.compiledRoutes.push({
verb: parsed.verb,
regex: parsed.regex,
config,
pattern: parsed.path
});
}
}
/**
* Get the underlying x402ResourceServer instance.
*
* @returns The underlying x402ResourceServer instance
*/
get server() {
return this.ResourceServer;
}
/**
* Get the routes configuration.
*
* @returns The routes configuration
*/
get routes() {
return this.routesConfig;
}
/**
* Initialize the HTTP resource server.
*
* This method initializes the underlying resource server (fetching facilitator support)
* and then validates that all route payment configurations have corresponding
* registered schemes and facilitator support.
*
* @throws RouteConfigurationError if any route's payment options don't have
* corresponding registered schemes or facilitator support
*
* @example
* ```typescript
* const httpServer = new x402HTTPResourceServer(server, routes);
* await httpServer.initialize();
* ```
*/
async initialize() {
await this.ResourceServer.initialize();
const errors = this.validateRouteConfiguration();
if (errors.length > 0) {
throw new RouteConfigurationError(errors);
}
}
/**
* Register a custom paywall provider for generating HTML
*
* @param provider - PaywallProvider instance
* @returns This service instance for chaining
*/
registerPaywallProvider(provider) {
this.paywallProvider = provider;
return this;
}
/**
* Register a hook that runs on every request to a protected route, before payment processing.
* Hooks are executed in order of registration. The first hook to return a non-void result wins.
*
* @param hook - The request hook function
* @returns The x402HTTPResourceServer instance for chaining
*/
onProtectedRequest(hook) {
this.protectedRequestHooks.push(hook);
return this;
}
/**
* Process HTTP request and return response instructions
* This is the main entry point for framework middleware
*
* @param context - HTTP request context
* @param paywallConfig - Optional paywall configuration
* @returns Process result indicating next action for middleware
*/
async processHTTPRequest(context, paywallConfig) {
const method = context.method || context.adapter.getMethod();
context = { ...context, method };
const { adapter, path } = context;
const routeMatch = this.getRouteConfig(path, method);
if (!routeMatch) {
return { type: "no-payment-required" };
}
const { config: routeConfig, pattern: routePattern } = routeMatch;
const enrichedContext = { ...context, routePattern };
for (const hook of this.protectedRequestHooks) {
const result = await hook(enrichedContext, routeConfig);
if (result && "grantAccess" in result) {
return { type: "no-payment-required" };
}
if (result && "abort" in result) {
return {
type: "payment-error",
response: {
status: 403,
headers: { "Content-Type": "application/json" },
body: { error: result.reason }
}
};
}
}
const paymentOptions = this.normalizePaymentOptions(routeConfig);
const paymentPayload = this.extractPayment(adapter);
const resourceInfo = {
url: routeConfig.resource || enrichedContext.adapter.getUrl(),
description: routeConfig.description || "",
mimeType: routeConfig.mimeType || ""
};
let requirements = await this.ResourceServer.buildPaymentRequirementsFromOptions(
paymentOptions,
enrichedContext
);
let extensions = routeConfig.extensions;
if (extensions) {
extensions = this.ResourceServer.enrichExtensions(extensions, enrichedContext);
}
const transportContext = { request: enrichedContext };
const paymentRequired = await this.ResourceServer.createPaymentRequiredResponse(
requirements,
resourceInfo,
!paymentPayload ? "Payment required" : void 0,
extensions,
transportContext
);
if (!paymentPayload) {
const unpaidBody = routeConfig.unpaidResponseBody ? await routeConfig.unpaidResponseBody(enrichedContext) : void 0;
return {
type: "payment-error",
response: this.createHTTPResponse(
paymentRequired,
this.isWebBrowser(adapter),
paywallConfig,
routeConfig.customPaywallHtml,
unpaidBody
)
};
}
try {
const matchingRequirements = this.ResourceServer.findMatchingRequirements(
paymentRequired.accepts,
paymentPayload
);
if (!matchingRequirements) {
const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(
requirements,
resourceInfo,
"No matching payment requirements",
routeConfig.extensions,
transportContext
);
return {
type: "payment-error",
response: this.createHTTPResponse(errorResponse, false, paywallConfig)
};
}
const verifyResult = await this.ResourceServer.verifyPayment(
paymentPayload,
matchingRequirements
);
if (!verifyResult.isValid) {
const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(
requirements,
resourceInfo,
verifyResult.invalidReason,
routeConfig.extensions,
transportContext
);
return {
type: "payment-error",
response: this.createHTTPResponse(errorResponse, false, paywallConfig)
};
}
return {
type: "payment-verified",
paymentPayload,
paymentRequirements: matchingRequirements,
declaredExtensions: routeConfig.extensions
};
} catch (error) {
if (error instanceof FacilitatorResponseError) {
throw error;
}
const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(
requirements,
resourceInfo,
error instanceof Error ? error.message : "Payment verification failed",
routeConfig.extensions,
transportContext
);
return {
type: "payment-error",
response: this.createHTTPResponse(errorResponse, false, paywallConfig)
};
}
}
/**
* Process settlement after successful response
*
* @param paymentPayload - The verified payment payload
* @param requirements - The matching payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional HTTP transport context
* @param settlementOverrides - Optional settlement overrides (e.g., partial settlement amount)
* @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
*/
async processSettlement(paymentPayload, requirements, declaredExtensions, transportContext, settlementOverrides) {
if (transportContext?.request && !transportContext.request.method) {
transportContext = {
...transportContext,
request: {
...transportContext.request,
method: transportContext.request.adapter.getMethod()
}
};
}
try {
let resolvedOverrides = settlementOverrides;
if (!resolvedOverrides && transportContext?.responseHeaders) {
const overridesKey = SETTLEMENT_OVERRIDES_HEADER.toLowerCase();
const rawValue = Object.entries(transportContext.responseHeaders).find(
([key]) => key.toLowerCase() === overridesKey
)?.[1];
if (rawValue) {
try {
resolvedOverrides = JSON.parse(rawValue);
} catch {
}
}
}
const settleResponse = await this.ResourceServer.settlePayment(
paymentPayload,
requirements,
declaredExtensions,
transportContext,
resolvedOverrides
);
if (!settleResponse.success) {
const failure = {
...settleResponse,
success: false,
errorReason: settleResponse.errorReason || "Settlement failed",
errorMessage: settleResponse.errorMessage || settleResponse.errorReason || "Settlement failed",
headers: this.createSettlementHeaders(settleResponse)
};
const response = await this.buildSettlementFailureResponse(failure, transportContext);
return { ...failure, response };
}
return {
...settleResponse,
success: true,
headers: this.createSettlementHeaders(settleResponse),
requirements
};
} catch (error) {
if (error instanceof FacilitatorResponseError) {
throw error;
}
if (error instanceof SettleError) {
const errorReason2 = error.errorReason || error.message;
const settleResponse2 = {
success: false,
errorReason: errorReason2,
errorMessage: error.errorMessage || errorReason2,
payer: error.payer,
network: error.network,
transaction: error.transaction
};
const failure2 = {
...settleResponse2,
success: false,
errorReason: errorReason2,
headers: this.createSettlementHeaders(settleResponse2)
};
const response2 = await this.buildSettlementFailureResponse(failure2, transportContext);
return { ...failure2, response: response2 };
}
const errorReason = error instanceof Error ? error.message : "Settlement failed";
const settleResponse = {
success: false,
errorReason,
errorMessage: errorReason,
network: requirements.network,
transaction: ""
};
const failure = {
...settleResponse,
success: false,
errorReason,
headers: this.createSettlementHeaders(settleResponse)
};
const response = await this.buildSettlementFailureResponse(failure, transportContext);
return { ...failure, response };
}
}
/**
* Check if a request requires payment based on route configuration
*
* @param context - HTTP request context
* @returns True if the route requires payment, false otherwise
*/
requiresPayment(context) {
const method = context.method || context.adapter.getMethod();
return this.getRouteConfig(context.path, method) !== void 0;
}
/**
* Build HTTPResponseInstructions for settlement failure.
* Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.
*
* @param failure - Settlement failure result with headers
* @param transportContext - Optional HTTP transport context for the request
* @returns HTTP response instructions for the 402 settlement failure response
*/
async buildSettlementFailureResponse(failure, transportContext) {
const settlementHeaders = failure.headers;
const routeConfig = transportContext ? this.getRouteConfig(transportContext.request.path, transportContext.request.method) : void 0;
const customBody = routeConfig?.config.settlementFailedResponseBody ? await routeConfig.config.settlementFailedResponseBody(transportContext.request, failure) : void 0;
const contentType = customBody ? customBody.contentType : "application/json";
const body = customBody ? customBody.body : {};
return {
status: 402,
headers: {
"Content-Type": contentType,
...settlementHeaders
},
body,
isHtml: contentType.includes("text/html")
};
}
/**
* Normalizes a RouteConfig's accepts field into an array of PaymentOptions
* Handles both single PaymentOption and array formats
*
* @param routeConfig - Route configuration
* @returns Array of payment options
*/
normalizePaymentOptions(routeConfig) {
return Array.isArray(routeConfig.accepts) ? routeConfig.accepts : [routeConfig.accepts];
}
/**
* Validates that all payment options in routes have corresponding registered schemes
* and facilitator support.
*
* @returns Array of validation errors (empty if all routes are valid)
*/
validateRouteConfiguration() {
const errors = [];
const normalizedRoutes = typeof this.routesConfig === "object" && !("accepts" in this.routesConfig) ? Object.entries(this.routesConfig) : [["*", this.routesConfig]];
for (const [pattern, config] of normalizedRoutes) {
const pathPart = pattern.includes(" ") ? pattern.split(/\s+/)[1] : pattern;
if (pathPart && pathPart.includes("*") && config.extensions && "bazaar" in config.extensions) {
console.warn(
`[x402] Route "${pattern}": Wildcard (*) patterns with bazaar discovery extensions will auto-generate parameter names (var1, var2, ...). Consider using named parameters instead (e.g. /weather/:city) for better discovery metadata.`
);
}
const paymentOptions = this.normalizePaymentOptions(config);
for (const option of paymentOptions) {
if (!this.ResourceServer.hasRegisteredScheme(option.network, option.scheme)) {
errors.push({
routePattern: pattern,
scheme: option.scheme,
network: option.network,
reason: "missing_scheme",
message: `Route "${pattern}": No scheme implementation registered for "${option.scheme}" on network "${option.network}"`
});
continue;
}
const supportedKind = this.ResourceServer.getSupportedKind(
x402Version,
option.network,
option.scheme
);
if (!supportedKind) {
errors.push({
routePattern: pattern,
scheme: option.scheme,
network: option.network,
reason: "missing_facilitator",
message: `Route "${pattern}": Facilitator does not support scheme "${option.scheme}" on network "${option.network}"`
});
}
}
}
return errors;
}
/**
* Get route configuration for a request
*
* @param path - Request path
* @param method - HTTP method
* @returns Route configuration and pattern, or undefined if no match
*/
getRouteConfig(path, method) {
const normalizedPath = this.normalizePath(path);
const upperMethod = method.toUpperCase();
const matchingRoute = this.compiledRoutes.find(
(route) => route.regex.test(normalizedPath) && (route.verb === "*" || route.verb === upperMethod)
);
if (!matchingRoute) return void 0;
return { config: matchingRoute.config, pattern: matchingRoute.pattern };
}
/**
* Extract payment from HTTP headers (handles v1 and v2)
*
* @param adapter - HTTP adapter
* @returns Decoded payment payload or null
*/
extractPayment(adapter) {
const header = adapter.getHeader("payment-signature") || adapter.getHeader("PAYMENT-SIGNATURE");
if (header) {
try {
return decodePaymentSignatureHeader(header);
} catch (error) {
console.warn("Failed to decode PAYMENT-SIGNATURE header:", error);
}
}
return null;
}
/**
* Check if request is from a web browser
*
* @param adapter - HTTP adapter
* @returns True if request appears to be from a browser
*/
isWebBrowser(adapter) {
const accept = adapter.getAcceptHeader();
const userAgent = adapter.getUserAgent();
return accept.includes("text/html") && userAgent.includes("Mozilla");
}
/**
* Create HTTP response instructions from payment required
*
* @param paymentRequired - Payment requirements
* @param isWebBrowser - Whether request is from browser
* @param paywallConfig - Paywall configuration
* @param customHtml - Custom HTML template
* @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
* @returns Response instructions
*/
createHTTPResponse(paymentRequired, isWebBrowser, paywallConfig, customHtml, unpaidResponse) {
const status = paymentRequired.error === "permit2_allowance_required" ? 412 : 402;
if (isWebBrowser) {
const html = this.generatePaywallHTML(paymentRequired, paywallConfig, customHtml);
return {
status,
headers: { "Content-Type": "text/html" },
body: html,
isHtml: true
};
}
const response = this.createHTTPPaymentRequiredResponse(paymentRequired);
const contentType = unpaidResponse ? unpaidResponse.contentType : "application/json";
const body = unpaidResponse ? unpaidResponse.body : {};
return {
status,
headers: {
"Content-Type": contentType,
...response.headers
},
body
};
}
/**
* Create HTTP payment required response (v1 puts in body, v2 puts in header)
*
* @param paymentRequired - Payment required object
* @returns Headers and body for the HTTP response
*/
createHTTPPaymentRequiredResponse(paymentRequired) {
return {
headers: {
"PAYMENT-REQUIRED": encodePaymentRequiredHeader(paymentRequired)
}
};
}
/**
* Create settlement response headers
*
* @param settleResponse - Settlement response
* @returns Headers to add to response
*/
createSettlementHeaders(settleResponse) {
const encoded = encodePaymentResponseHeader(settleResponse);
return { "PAYMENT-RESPONSE": encoded };
}
/**
* Parse route pattern into verb and regex
*
* @param pattern - Route pattern like "GET /api/*", "/api/[id]", or "/api/:id"
* @returns Parsed pattern with verb and regex
*/
parseRoutePattern(pattern) {
const [verb, path] = pattern.includes(" ") ? pattern.split(/\s+/) : ["*", pattern];
const regex = new RegExp(
`^${path.replace(/\\/g, "\\\\").replace(/[$()+.?^{|}]/g, "\\$&").replace(/\*/g, ".*?").replace(/\[([^\]]+)\]/g, "[^/]+").replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, "[^/]+").replace(/\//g, "\\/")}$`,
"i"
);
return { verb: verb.toUpperCase(), regex, path };
}
/**
* Normalize path for matching
*
* @param path - Raw path from request
* @returns Normalized path
*/
normalizePath(path) {
const pathWithoutQuery = path.split(/[?#]/)[0];
let decodedOrRawPath;
try {
decodedOrRawPath = decodeURIComponent(pathWithoutQuery);
} catch {
decodedOrRawPath = pathWithoutQuery;
}
return decodedOrRawPath.replace(/\\/g, "/").replace(/\/+/g, "/").replace(/(.+?)\/+$/, "$1");
}
/**
* Generate paywall HTML for browser requests
*
* @param paymentRequired - Payment required response
* @param paywallConfig - Optional paywall configuration
* @param customHtml - Optional custom HTML template
* @returns HTML string
*/
generatePaywallHTML(paymentRequired, paywallConfig, customHtml) {
if (customHtml) {
return customHtml;
}
if (this.paywallProvider) {
return this.paywallProvider.generateHtml(paymentRequired, paywallConfig);
}
try {
const paywall = __require("@x402/paywall");
const displayAmount2 = this.getDisplayAmount(paymentRequired);
const resource2 = paymentRequired.resource;
return paywall.getPaywallHtml({
amount: displayAmount2,
paymentRequired,
currentUrl: resource2?.url || paywallConfig?.currentUrl || "",
testnet: paywallConfig?.testnet ?? true,
appName: paywallConfig?.appName,
appLogo: paywallConfig?.appLogo,
sessionTokenEndpoint: paywallConfig?.sessionTokenEndpoint
});
} catch {
}
const resource = paymentRequired.resource;
const displayAmount = this.getDisplayAmount(paymentRequired);
return `
<!DOCTYPE html>
<html>
<head>
<title>Payment Required</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div style="max-width: 600px; margin: 50px auto; padding: 20px; font-family: system-ui, -apple-system, sans-serif;">
${paywallConfig?.appLogo ? `<img src="${paywallConfig.appLogo}" alt="${paywallConfig.appName || "App"}" style="max-width: 200px; margin-bottom: 20px;">` : ""}
<h1>Payment Required</h1>
${resource ? `<p><strong>Resource:</strong> ${resource.description || resource.url}</p>` : ""}
<p><strong>Amount:</strong> $${displayAmount.toFixed(2)} USDC</p>
<div id="payment-widget"
data-requirements='${JSON.stringify(paymentRequired)}'
data-app-name="${paywallConfig?.appName || ""}"
data-testnet="${paywallConfig?.testnet || false}">
<!-- Install @x402/paywall for full wallet integration -->
<p style="margin-top: 2rem; padding: 1rem; background: #fef3c7; border-radius: 0.5rem;">
<strong>Note:</strong> Install <code>@x402/paywall</code> for full wallet connection and payment UI.
</p>
</div>
</div>
</body>
</html>
`;
}
/**
* Extract display amount from payment requirements.
*
* @param paymentRequired - The payment required object
* @returns The display amount in decimal format
*/
getDisplayAmount(paymentRequired) {
const accepts = paymentRequired.accepts;
if (accepts && accepts.length > 0) {
const firstReq = accepts[0];
if ("amount" in firstReq) {
return parseFloat(firstReq.amount) / 1e6;
}
}
return 0;
}
};
// src/http/httpFacilitatorClient.ts
var DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
var GET_SUPPORTED_RETRIES = 3;
var GET_SUPPORTED_RETRY_DELAY_MS = 1e3;
var verifyResponseSchema = z.object({
isValid: z.boolean(),
invalidReason: z.string().nullish().transform((v) => v ?? void 0),
invalidMessage: z.string().nullish().transform((v) => v ?? void 0),
payer: z.string().nullish().transform((v) => v ?? void 0),
extensions: z.record(z.string(), z.unknown()).nullish().transform((v) => v ?? void 0)
});
var settleResponseSchema = z.object({
success: z.boolean(),
errorReason: z.string().nullish().transform((v) => v ?? void 0),
errorMessage: z.string().nullish().transform((v) => v ?? void 0),
payer: z.string().nullish().transform((v) => v ?? void 0),
transaction: z.string(),
network: z.custom((value) => typeof value === "string"),
extensions: z.record(z.string(), z.unknown()).nullish().transform((v) => v ?? void 0)
});
var supportedKindSchema = z.object({
x402Version: z.number(),
scheme: z.string(),
network: z.custom(
(value) => typeof value === "string"
),
extra: z.record(z.string(), z.unknown()).nullish().transform((v) => v ?? void 0)
});
var supportedResponseSchema = z.object({
kinds: z.array(supportedKindSchema),
extensions: z.array(z.string()).default([]),
signers: z.record(z.string(), z.array(z.string())).default({})
});
function responseExcerpt(text, limit = 200) {
const compact = text.trim().replace(/\s+/g, " ");
if (!compact) {
return "<empty response>";
}
if (compact.length <= limit) {
return compact;
}
return `${compact.slice(0, limit - 3)}...`;
}
async function parseSuccessResponse(response, schema, operation) {
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
throw new FacilitatorResponseError(
`Facilitator ${operation} returned invalid JSON: ${responseExcerpt(text)}`
);
}
const parsed = schema.safeParse(data);
if (!parsed.success) {
throw new FacilitatorResponseError(
`Facilitator ${operation} returned invalid data: ${responseExcerpt(text)}`
);
}
return parsed.data;
}
var HTTPFacilitatorClient = class {
/**
* Creates a new HTTPFacilitatorClient instance.
*
* @param config - Configuration options for the facilitator client
*/
constructor(config) {
this.url = (config?.url || DEFAULT_FACILITATOR_URL).replace(/\/+$/, "");
this._createAuthHeaders = config?.createAuthHeaders;
}
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
async verify(paymentPayload, paymentRequirements) {
let headers = {
"Content-Type": "application/json"
};
if (this._createAuthHeaders) {
const authHeaders = await this.createAuthHeaders("verify");
headers = { ...headers, ...authHeaders.headers };
}
const response = await fetch(`${this.url}/verify`, {
method: "POST",
headers,
redirect: "follow",
body: JSON.stringify({
x402Version: paymentPayload.x402Version,
paymentPayload: this.toJsonSafe(paymentPayload),
paymentRequirements: this.toJsonSafe(paymentRequirements)
})
});
if (!response.ok) {
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
throw new Error(`Facilitator verify failed (${response.status}): ${responseExcerpt(text)}`);
}
if (typeof data === "object" && data !== null && "isValid" in data) {
throw new VerifyError(response.status, data);
}
throw new Error(
`Facilitator verify failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`
);
}
return parseSuccessResponse(response, verifyResponseSchema, "verify");
}
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
async settle(paymentPayload, paymentRequirements) {
let headers = {
"Content-Type": "application/json"
};
if (this._createAuthHeaders) {
const authHeaders = await this.createAuthHeaders("settle");
headers = { ...headers, ...authHeaders.headers };
}
const response = await fetch(`${this.url}/settle`, {
method: "POST",
headers,
redirect: "follow",
body: JSON.stringify({
x402Version: paymentPayload.x402Version,
paymentPayload: this.toJsonSafe(paymentPayload),
paymentRequirements: this.toJsonSafe(paymentRequirements)
})
});
if (!response.ok) {
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
throw new Error(`Facilitator settle failed (${response.status}): ${responseExcerpt(text)}`);
}
if (typeof data === "object" && data !== null && "success" in data) {
throw new SettleError(response.status, data);
}
throw new Error(
`Facilitator settle failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`
);
}
return parseSuccessResponse(response, settleResponseSchema, "settle");
}
/**
* Get supported payment kinds and extensions from the facilitator.
* Retries with exponential backoff on 429 rate limit errors.
*
* @returns Supported payment kinds and extensions
*/
async getSupported() {
let headers = {
"Content-Type": "application/json"
};
if (this._createAuthHeaders) {
const authHeaders = await this.createAuthHeaders("supported");
headers = { ...headers, ...authHeaders.headers };
}
let lastError = null;
for (let attempt = 0; attempt < GET_SUPPORTED_RETRIES; attempt++) {
const response = await fetch(`${this.url}/supported`, {
method: "GET",
headers,
redirect: "follow"
});
if (response.ok) {
return parseSuccessResponse(response, supportedResponseSchema, "supported");
}
const errorText = await response.text().catch(() => response.statusText);
lastError = new Error(
`Facilitator getSupported failed (${response.status}): ${responseExcerpt(errorText)}`
);
if (response.status === 429 && attempt < GET_SUPPORTED_RETRIES - 1) {
const delay = GET_SUPPORTED_RETRY_DELAY_MS * Math.pow(2, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
throw lastError;
}
throw lastError ?? new Error("Facilitator getSupported failed after retries");
}
/**
* Creates authentication headers for a specific path.
*
* @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
* @returns An object containing the authentication headers for the specified path
*/
async createAuthHeaders(path) {
if (this._createAuthHeaders) {
const authHeaders = await this._createAuthHeaders();
return {
headers: authHeaders[path] ?? {}
};
}
return {
headers: {}
};
}
/**
* Helper to convert objects to JSON-safe format.
* Handles BigInt and other non-JSON types.
*
* @param obj - The object to convert
* @returns The JSON-safe representation of the object
*/
toJsonSafe(obj) {
return JSON.parse(
JSON.stringify(obj, (_, value) => typeof value === "bigint" ? value.toString() : value)
);
}
};
// src/http/x402HTTPClient.ts
var x402HTTPClient = class {
/**
* Creates a new x402HTTPClient instance.
*
* @param client - The underlying x402Client for payment logic
*/
constructor(client) {
this.client = client;
this.paymentRequiredHooks = [];
}
/**
* Register a hook to handle 402 responses before payment.
* Hooks run in order; first to return headers wins.
*
* @param hook - The hook function to register
* @returns This instance for chaining
*/
onPaymentRequired(hook) {
this.paymentRequiredHooks.push(hook);
return this;
}
/**
* Run hooks and return headers if any hook provides them.
*
* @param paymentRequired - The payment required response from the server
* @returns Headers to use for retry, or null to proceed to payment
*/
async handlePaymentRequired(paymentRequired) {
for (const hook of this.paymentRequiredHooks) {
const result = await hook({ paymentRequired });
if (result?.headers) {
return result.headers;
}
}
return null;
}
/**
* Encodes a payment payload into appropriate HTTP headers based on version.
*
* @param paymentPayload - The payment payload to encode
* @returns HTTP headers containing the encoded payment signature
*/
encodePaymentSignatureHeader(paymentPayload) {
switch (paymentPayload.x402Version) {
case 2:
return {
"PAYMENT-SIGNATURE": encodePaymentSignatureHeader(paymentPayload)
};
case 1:
return {
"X-PAYMENT": encodePaymentSignatureHeader(paymentPayload)
};
default:
throw new Error(
`Unsupported x402 version: ${paymentPayload.x402Version}`
);
}
}
/**
* Extracts payment required information from HTTP response.
*
* @param getHeader - Function to retrieve header value by name (case-insensitive)
* @param body - Optional response body for v1 compatibility
* @returns The payment required object
*/
getPaymentRequiredResponse(getHeader, body) {
const paymentRequired = getHeader("PAYMENT-REQUIRED");
if (paymentRequired) {
return decodePaymentRequiredHeader(paymentRequired);
}
if (body && body instanceof Object && "x402Version" in body && body.x402Version === 1) {
return body;
}
throw new Error("Invalid payment required response");
}
/**
* Extracts payment settlement response from HTTP headers.
*
* @param getHeader - Function to retrieve header value by name (case-insensitive)
* @returns The settlement response object
*/
getPaymentSettleResponse(getHeader) {
const paymentResponse = getHeader("PAYMENT-RESPONSE");
if (paymentResponse) {
return decodePaymentResponseHeader(paymentResponse);
}
const xPaymentResponse = getHeader("X-PAYMENT-RESPONSE");
if (xPaymentResponse) {
return decodePaymentResponseHeader(xPaymentResponse);
}
throw new Error("Payment response header not found");
}
/**
* Creates a payment payload for the given payment requirements.
* Delegates to the underlying x402Client.
*
* @param paymentRequired - The payment required response from the server
* @returns Promise resolving to the payment payload
*/
async createPaymentPayload(paymentRequired) {
return this.client.createPaymentPayload(paymentRequired);
}
};
// src/http/index.ts
function encodePaymentSignatureHeader(paymentPayload) {
return safeBase64Encode(JSON.stringify(paymentPayload));
}
function decodePaymentSignatureHeader(paymentSignatureHeader) {
if (!Base64EncodedRegex.test(paymentSignatureHeader)) {
throw new Error("Invalid payment signature header");
}
return JSON.parse(safeBase64Decode(paymentSignatureHeader));
}
function encodePaymentRequiredHeader(paymentRequired) {
return safeBase64Encode(JSON.stringify(paymentRequired));
}
function decodePaymentRequiredHeader(paymentRequiredHeader) {
if (!Base64EncodedRegex.test(paymentRequiredHeader)) {
throw new Error("Invalid payment required header");
}
return JSON.parse(safeBase64Decode(paymentRequiredHeader));
}
function encodePaymentResponseHeader(paymentResponse) {
return safeBase64Encode(JSON.stringify(paymentResponse));
}
function decodePaymentResponseHeader(paymentResponseHeader) {
if (!Base64EncodedRegex.test(paymentResponseHeader)) {
throw new Error("Invalid payment response header");
}
return JSON.parse(safeBase64Decode(paymentResponseHeader));
}
export {
SETTLEMENT_OVERRIDES_HEADER,
RouteConfigurationError,
x402HTTPResourceServer,
HTTPFacilitatorClient,
encodePaymentSignatureHeader,
decodePaymentSignatureHeader,
encodePaymentRequiredHeader,
decodePaymentRequiredHeader,
encodePaymentResponseHeader,
decodePaymentResponseHeader,
x402HTTPClient
};
//# sourceMappingURL=chunk-JFGRL3BL.mjs.map

Sorry, the diff of this file is too big to display

// src/types/facilitator.ts
var VerifyError = class extends Error {
/**
* Creates a VerifyError from a failed verification response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The verify response containing error details
*/
constructor(statusCode, response) {
const reason = response.invalidReason || "unknown reason";
const message = response.invalidMessage;
super(message ? `${reason}: ${message}` : reason);
this.name = "VerifyError";
this.statusCode = statusCode;
this.invalidReason = response.invalidReason;
this.invalidMessage = response.invalidMessage;
this.payer = response.payer;
}
};
var SettleError = class extends Error {
/**
* Creates a SettleError from a failed settlement response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The settle response containing error details
*/
constructor(statusCode, response) {
const reason = response.errorReason || "unknown reason";
const message = response.errorMessage;
super(message ? `${reason}: ${message}` : reason);
this.name = "SettleError";
this.statusCode = statusCode;
this.errorReason = response.errorReason;
this.errorMessage = response.errorMessage;
this.payer = response.payer;
this.transaction = response.transaction;
this.network = response.network;
}
};
var FacilitatorResponseError = class extends Error {
/**
* Creates a FacilitatorResponseError for malformed facilitator responses.
*
* @param message - The boundary error message
*/
constructor(message) {
super(message);
this.name = "FacilitatorResponseError";
}
};
function getFacilitatorResponseError(error) {
let current = error;
while (current instanceof Error) {
if (current instanceof FacilitatorResponseError) {
return current;
}
current = current.cause;
}
return null;
}
export {
VerifyError,
SettleError,
FacilitatorResponseError,
getFacilitatorResponseError
};
//# sourceMappingURL=chunk-JUGE6MAI.mjs.map
{"version":3,"sources":["../../src/types/facilitator.ts"],"sourcesContent":["import { PaymentPayload, PaymentRequirements } from \"./payments\";\nimport { Network } from \"./\";\n\nexport type VerifyRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type VerifyResponse = {\n isValid: boolean;\n invalidReason?: string;\n invalidMessage?: string;\n payer?: string;\n extensions?: Record<string, unknown>;\n};\n\nexport type SettleRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type SettleResponse = {\n success: boolean;\n errorReason?: string;\n errorMessage?: string;\n payer?: string;\n transaction: string;\n network: Network;\n /** Actual amount settled in atomic token units. Present for schemes like `upto` where settlement amount may differ from the authorized maximum. */\n amount?: string;\n extensions?: Record<string, unknown>;\n};\n\nexport type SupportedKind = {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n};\n\nexport type SupportedResponse = {\n kinds: SupportedKind[];\n extensions: string[];\n signers: Record<string, string[]>; // CAIP family pattern → Signer addresses\n};\n\n/**\n * Error thrown when payment verification fails.\n */\nexport class VerifyError extends Error {\n readonly invalidReason?: string;\n readonly invalidMessage?: string;\n readonly payer?: string;\n readonly statusCode: number;\n\n /**\n * Creates a VerifyError from a failed verification response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The verify response containing error details\n */\n constructor(statusCode: number, response: VerifyResponse) {\n const reason = response.invalidReason || \"unknown reason\";\n const message = response.invalidMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"VerifyError\";\n this.statusCode = statusCode;\n this.invalidReason = response.invalidReason;\n this.invalidMessage = response.invalidMessage;\n this.payer = response.payer;\n }\n}\n\n/**\n * Error thrown when payment settlement fails.\n */\nexport class SettleError extends Error {\n readonly errorReason?: string;\n readonly errorMessage?: string;\n readonly payer?: string;\n readonly transaction: string;\n readonly network: Network;\n readonly statusCode: number;\n\n /**\n * Creates a SettleError from a failed settlement response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The settle response containing error details\n */\n constructor(statusCode: number, response: SettleResponse) {\n const reason = response.errorReason || \"unknown reason\";\n const message = response.errorMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"SettleError\";\n this.statusCode = statusCode;\n this.errorReason = response.errorReason;\n this.errorMessage = response.errorMessage;\n this.payer = response.payer;\n this.transaction = response.transaction;\n this.network = response.network;\n }\n}\n\n/**\n * Error thrown when a facilitator returns malformed success payload data.\n */\nexport class FacilitatorResponseError extends Error {\n /**\n * Creates a FacilitatorResponseError for malformed facilitator responses.\n *\n * @param message - The boundary error message\n */\n constructor(message: string) {\n super(message);\n this.name = \"FacilitatorResponseError\";\n }\n}\n\n/**\n * Walks an error cause chain to find the first facilitator response error.\n *\n * @param error - The thrown value to inspect\n * @returns The nested facilitator response error, if present\n */\nexport function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null {\n let current = error;\n\n while (current instanceof Error) {\n if (current instanceof FacilitatorResponseError) {\n return current;\n }\n current = current.cause;\n }\n\n return null;\n}\n"],"mappings":";AAmDO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,iBAAiB;AACzC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,gBAAgB,SAAS;AAC9B,SAAK,iBAAiB,SAAS;AAC/B,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAKO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,eAAe;AACvC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,cAAc,SAAS;AAC5B,SAAK,eAAe,SAAS;AAC7B,SAAK,QAAQ,SAAS;AACtB,SAAK,cAAc,SAAS;AAC5B,SAAK,UAAU,SAAS;AAAA,EAC1B;AACF;AAKO,IAAM,2BAAN,cAAuC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMlD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAQO,SAAS,4BAA4B,OAAiD;AAC3F,MAAI,UAAU;AAEd,SAAO,mBAAmB,OAAO;AAC/B,QAAI,mBAAmB,0BAA0B;AAC/C,aAAO;AAAA,IACT;AACA,cAAU,QAAQ;AAAA,EACpB;AAEA,SAAO;AACT;","names":[]}
type PaymentRequirementsV1 = {
scheme: string;
network: Network;
maxAmountRequired: string;
resource: string;
description: string;
mimeType: string;
outputSchema: Record<string, unknown>;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
extra: Record<string, unknown>;
};
type PaymentRequiredV1 = {
x402Version: 1;
error?: string;
accepts: PaymentRequirementsV1[];
};
type PaymentPayloadV1 = {
x402Version: 1;
scheme: string;
network: Network;
payload: Record<string, unknown>;
};
type VerifyRequestV1 = {
x402Version: number;
paymentPayload: PaymentPayloadV1;
paymentRequirements: PaymentRequirementsV1;
};
type SettleRequestV1 = {
x402Version: number;
paymentPayload: PaymentPayloadV1;
paymentRequirements: PaymentRequirementsV1;
};
type SettleResponseV1 = {
success: boolean;
errorReason?: string;
errorMessage?: string;
payer?: string;
transaction: string;
network: Network;
};
type SupportedResponseV1 = {
kinds: {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
}[];
};
interface FacilitatorConfig {
url?: string;
createAuthHeaders?: () => Promise<{
verify: Record<string, string>;
settle: Record<string, string>;
supported: Record<string, string>;
}>;
}
/**
* Interface for facilitator clients
* Can be implemented for HTTP-based or local facilitators
*/
interface FacilitatorClient {
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
/**
* Get supported payment kinds and extensions from the facilitator
*
* @returns Supported payment kinds and extensions
*/
getSupported(): Promise<SupportedResponse>;
}
/**
* HTTP-based client for interacting with x402 facilitator services
* Handles HTTP communication with facilitator endpoints
*/
declare class HTTPFacilitatorClient implements FacilitatorClient {
readonly url: string;
private readonly _createAuthHeaders?;
/**
* Creates a new HTTPFacilitatorClient instance.
*
* @param config - Configuration options for the facilitator client
*/
constructor(config?: FacilitatorConfig);
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
/**
* Get supported payment kinds and extensions from the facilitator.
* Retries with exponential backoff on 429 rate limit errors.
*
* @returns Supported payment kinds and extensions
*/
getSupported(): Promise<SupportedResponse>;
/**
* Creates authentication headers for a specific path.
*
* @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
* @returns An object containing the authentication headers for the specified path
*/
createAuthHeaders(path: string): Promise<{
headers: Record<string, string>;
}>;
/**
* Helper to convert objects to JSON-safe format.
* Handles BigInt and other non-JSON types.
*
* @param obj - The object to convert
* @returns The JSON-safe representation of the object
*/
private toJsonSafe;
}
/**
* Configuration for a protected resource
* Only contains payment-specific configuration, not resource metadata
*/
interface ResourceConfig {
scheme: string;
payTo: string;
price: Price;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Lifecycle Hook Context Interfaces
*/
interface PaymentRequiredContext {
requirements: PaymentRequirements[];
resourceInfo: ResourceInfo;
error?: string;
paymentRequiredResponse: PaymentRequired;
transportContext?: unknown;
}
interface VerifyContext {
paymentPayload: PaymentPayload;
requirements: PaymentRequirements;
}
interface VerifyResultContext extends VerifyContext {
result: VerifyResponse;
}
interface VerifyFailureContext extends VerifyContext {
error: Error;
}
interface SettleContext {
paymentPayload: PaymentPayload;
requirements: PaymentRequirements;
}
interface SettleResultContext extends SettleContext {
result: SettleResponse;
transportContext?: unknown;
}
interface SettleFailureContext extends SettleContext {
error: Error;
}
/**
* Lifecycle Hook Type Definitions
*/
type BeforeVerifyHook = (context: VerifyContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
type AfterVerifyHook = (context: VerifyResultContext) => Promise<void>;
type OnVerifyFailureHook = (context: VerifyFailureContext) => Promise<void | {
recovered: true;
result: VerifyResponse;
}>;
type BeforeSettleHook = (context: SettleContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
type AfterSettleHook = (context: SettleResultContext) => Promise<void>;
type OnSettleFailureHook = (context: SettleFailureContext) => Promise<void | {
recovered: true;
result: SettleResponse;
}>;
/**
* Optional overrides for settlement parameters.
* Used to support partial settlement (e.g., upto scheme billing by actual usage).
*
* Note: Overriding the amount to a value different from the agreed-upon
* `PaymentRequirements.amount` is only valid in schemes that explicitly support
* partial settlement, such as the `upto` scheme. Using this with standard
* x402 schemes (e.g., `exact`) will likely cause settlement verification to fail.
*/
interface SettlementOverrides {
/**
* Amount to settle. Supports three formats:
*
* - **Raw atomic units** — e.g., `"1000"` settles exactly 1000 atomic units.
* - **Percent** — e.g., `"50%"` settles 50% of `PaymentRequirements.amount`.
* Supports up to two decimal places (e.g., `"33.33%"`). The result is floored
* to the nearest atomic unit.
* - **Dollar price** — e.g., `"$0.05"` converts a USD-denominated price to
* atomic units. Decimals are determined from the registered scheme's
* `getAssetDecimals` method, falling back to 6 (standard for USDC stablecoins).
* The result is rounded to the nearest atomic unit.
*
* The resolved amount must be <= the authorized maximum in `PaymentRequirements`.
*
* Note: Setting this to an amount other than `PaymentRequirements.amount` is
* only valid in schemes that support partial settlement, such as `upto`.
*/
amount?: string;
}
/**
* Core x402 protocol server for resource protection
* Transport-agnostic implementation of the x402 payment protocol
*/
declare class x402ResourceServer {
private facilitatorClients;
private registeredServerSchemes;
private supportedResponsesMap;
private facilitatorClientsMap;
private registeredExtensions;
private beforeVerifyHooks;
private afterVerifyHooks;
private onVerifyFailureHooks;
private beforeSettleHooks;
private afterSettleHooks;
private onSettleFailureHooks;
/**
* Creates a new x402ResourceServer instance.
*
* @param facilitatorClients - Optional facilitator client(s) for payment processing
*/
constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]);
/**
* Register a scheme/network server implementation.
*
* @param network - The network identifier
* @param server - The scheme/network server implementation
* @returns The x402ResourceServer instance for chaining
*/
register(network: Network, server: SchemeNetworkServer): x402ResourceServer;
/**
* Check if a scheme is registered for a given network.
*
* @param network - The network identifier
* @param scheme - The payment scheme name
* @returns True if the scheme is registered for the network, false otherwise
*/
hasRegisteredScheme(network: Network, scheme: string): boolean;
/**
* Registers a resource service extension that can enrich extension declarations.
*
* @param extension - The extension to register
* @returns The x402ResourceServer instance for chaining
*/
registerExtension(extension: ResourceServerExtension): this;
/**
* Check if an extension is registered.
*
* @param key - The extension key
* @returns True if the extension is registered
*/
hasExtension(key: string): boolean;
/**
* Get all registered extensions.
*
* @returns Array of registered extensions
*/
getExtensions(): ResourceServerExtension[];
/**
* Enriches declared extensions using registered extension hooks.
*
* @param declaredExtensions - Extensions declared on the route
* @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
* @returns Enriched extensions map
*/
enrichExtensions(declaredExtensions: Record<string, unknown>, transportContext: unknown): Record<string, unknown>;
/**
* Register a hook to execute before payment verification.
* Can abort verification by returning { abort: true, reason: string }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer;
/**
* Register a hook to execute after successful payment verification.
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onAfterVerify(hook: AfterVerifyHook): x402ResourceServer;
/**
* Register a hook to execute when payment verification fails.
* Can recover from failure by returning { recovered: true, result: VerifyResponse }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer;
/**
* Register a hook to execute before payment settlement.
* Can abort settlement by returning { abort: true, reason: string }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer;
/**
* Register a hook to execute after successful payment settlement.
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onAfterSettle(hook: AfterSettleHook): x402ResourceServer;
/**
* Register a hook to execute when payment settlement fails.
* Can recover from failure by returning { recovered: true, result: SettleResponse }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer;
/**
* Initialize by fetching supported kinds from all facilitators
* Creates mappings for supported responses and facilitator clients
* Earlier facilitators in the array get precedence
*/
initialize(): Promise<void>;
/**
* Get supported kind for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The supported kind or undefined if not found
*/
getSupportedKind(x402Version: number, network: Network, scheme: string): SupportedKind | undefined;
/**
* Get facilitator extensions for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The facilitator extensions or empty array if not found
*/
getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[];
/**
* Build payment requirements for a protected resource
*
* @param resourceConfig - Configuration for the protected resource
* @returns Array of payment requirements
*/
buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]>;
/**
* Build payment requirements from multiple payment options
* This method handles resolving dynamic payTo/price functions and builds requirements for each option
*
* @param paymentOptions - Array of payment options to convert
* @param context - HTTP request context for resolving dynamic functions
* @returns Array of payment requirements (one per option)
*/
buildPaymentRequirementsFromOptions<TContext = unknown>(paymentOptions: Array<{
scheme: string;
payTo: string | ((context: TContext) => string | Promise<string>);
price: Price | ((context: TContext) => Price | Promise<Price>);
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}>, context: TContext): Promise<PaymentRequirements[]>;
/**
* Create a payment required response
*
* @param requirements - Payment requirements
* @param resourceInfo - Resource information
* @param error - Error message
* @param extensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional transport-specific context (e.g., HTTP request, MCP tool context)
* @returns Payment required response object
*/
createPaymentRequiredResponse(requirements: PaymentRequirements[], resourceInfo: ResourceInfo, error?: string, extensions?: Record<string, unknown>, transportContext?: unknown): Promise<PaymentRequired>;
/**
* Verify a payment against requirements
*
* @param paymentPayload - The payment payload to verify
* @param requirements - The payment requirements
* @returns Verification response
*/
verifyPayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a verified payment
*
* @param paymentPayload - The payment payload to settle
* @param requirements - The payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)
* @param settlementOverrides - Optional overrides for settlement parameters (e.g., partial settlement amount)
* @returns Settlement response
*/
settlePayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown, settlementOverrides?: SettlementOverrides): Promise<SettleResponse>;
/**
* Find matching payment requirements for a payment
*
* @param availableRequirements - Array of available payment requirements
* @param paymentPayload - The payment payload
* @returns Matching payment requirements or undefined
*/
findMatchingRequirements(availableRequirements: PaymentRequirements[], paymentPayload: PaymentPayload): PaymentRequirements | undefined;
/**
* Process a payment request
*
* @param paymentPayload - Optional payment payload if provided
* @param resourceConfig - Configuration for the protected resource
* @param resourceInfo - Information about the resource being accessed
* @param extensions - Optional extensions to include in the response
* @returns Processing result
*/
processPaymentRequest(paymentPayload: PaymentPayload | null, resourceConfig: ResourceConfig, resourceInfo: ResourceInfo, extensions?: Record<string, unknown>): Promise<{
success: boolean;
requiresPayment?: PaymentRequired;
verificationResult?: VerifyResponse;
settlementResult?: SettleResponse;
error?: string;
}>;
/**
* Get facilitator client for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The facilitator client or undefined if not found
*/
private getFacilitatorClient;
}
/**
* Base interface for facilitator extensions.
* Extensions registered with x402Facilitator are stored by key and made
* available to mechanism implementations via FacilitatorContext.
*
* Specific extensions extend this with additional capabilities:
*
* @example
* interface Erc20GasSponsoringExtension extends FacilitatorExtension {
* batchSigner: SmartWalletBatchSigner;
* }
*/
interface FacilitatorExtension {
key: string;
}
interface ResourceServerExtension {
key: string;
/**
* Enrich extension declaration with extension-specific data.
*
* @param declaration - Extension declaration from route config
* @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
* @returns Enriched extension declaration
*/
enrichDeclaration?: (declaration: unknown, transportContext: unknown) => unknown;
/**
* Called when generating a 402 PaymentRequired response.
* Return extension data to add to extensions[key], or undefined to skip.
*
* @param declaration - Extension declaration from route config
* @param context - PaymentRequired context containing response, requirements, and optional transportContext
* @returns Extension data to add to response.extensions[key]
*/
enrichPaymentRequiredResponse?: (declaration: unknown, context: PaymentRequiredContext) => Promise<unknown>;
/**
* Called after successful payment settlement.
* Return extension data to add to response.extensions[key], or undefined to skip.
*
* @param declaration - Extension declaration from route config
* @param context - Settlement result context containing payment payload, requirements, result and optional transportContext
* @returns Extension data to add to response.extensions[key]
*/
enrichSettlementResponse?: (declaration: unknown, context: SettleResultContext) => Promise<unknown>;
}
type Network = `${string}:${string}`;
type Money = string | number;
type AssetAmount = {
asset: string;
amount: string;
extra?: Record<string, unknown>;
};
type Price = Money | AssetAmount;
interface ResourceInfo {
url: string;
description?: string;
mimeType?: string;
}
type PaymentRequirements = {
scheme: string;
network: Network;
asset: string;
amount: string;
payTo: string;
maxTimeoutSeconds: number;
extra: Record<string, unknown>;
};
type PaymentRequired = {
x402Version: number;
error?: string;
resource: ResourceInfo;
accepts: PaymentRequirements[];
extensions?: Record<string, unknown>;
};
type PaymentPayload = {
x402Version: number;
resource?: ResourceInfo;
accepted: PaymentRequirements;
payload: Record<string, unknown>;
extensions?: Record<string, unknown>;
};
type VerifyRequest = {
x402Version: number;
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};
type VerifyResponse = {
isValid: boolean;
invalidReason?: string;
invalidMessage?: string;
payer?: string;
extensions?: Record<string, unknown>;
};
type SettleRequest = {
x402Version: number;
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};
type SettleResponse = {
success: boolean;
errorReason?: string;
errorMessage?: string;
payer?: string;
transaction: string;
network: Network;
/** Actual amount settled in atomic token units. Present for schemes like `upto` where settlement amount may differ from the authorized maximum. */
amount?: string;
extensions?: Record<string, unknown>;
};
type SupportedKind = {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
};
type SupportedResponse = {
kinds: SupportedKind[];
extensions: string[];
signers: Record<string, string[]>;
};
/**
* Error thrown when payment verification fails.
*/
declare class VerifyError extends Error {
readonly invalidReason?: string;
readonly invalidMessage?: string;
readonly payer?: string;
readonly statusCode: number;
/**
* Creates a VerifyError from a failed verification response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The verify response containing error details
*/
constructor(statusCode: number, response: VerifyResponse);
}
/**
* Error thrown when payment settlement fails.
*/
declare class SettleError extends Error {
readonly errorReason?: string;
readonly errorMessage?: string;
readonly payer?: string;
readonly transaction: string;
readonly network: Network;
readonly statusCode: number;
/**
* Creates a SettleError from a failed settlement response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The settle response containing error details
*/
constructor(statusCode: number, response: SettleResponse);
}
/**
* Error thrown when a facilitator returns malformed success payload data.
*/
declare class FacilitatorResponseError extends Error {
/**
* Creates a FacilitatorResponseError for malformed facilitator responses.
*
* @param message - The boundary error message
*/
constructor(message: string);
}
/**
* Walks an error cause chain to find the first facilitator response error.
*
* @param error - The thrown value to inspect
* @returns The nested facilitator response error, if present
*/
declare function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null;
/**
* Money parser function that converts a numeric amount to an AssetAmount
* Receives the amount as a decimal number (e.g., 1.50 for $1.50)
* Returns null to indicate "cannot handle this amount", causing fallback to next parser
* Always returns a Promise for consistency - use async/await
*
* @param amount - The decimal amount (e.g., 1.50)
* @param network - The network identifier for context
* @returns AssetAmount or null to try next parser
*/
type MoneyParser = (amount: number, network: Network) => Promise<AssetAmount | null>;
/**
* Result of createPaymentPayload - the core payload fields.
* Contains the x402 version, scheme-specific payload data, and optional extension data.
* Schemes may return extensions (e.g., EIP-2612 gas sponsoring) that get merged
* with server-declared extensions in the final PaymentPayload.
*/
type PaymentPayloadResult = Pick<PaymentPayload, "x402Version" | "payload"> & {
extensions?: Record<string, unknown>;
};
/**
* Context passed to scheme's createPaymentPayload for extensions awareness.
* Contains the server-declared extensions from PaymentRequired so the scheme
* can check which extensions are advertised and respond accordingly.
*/
interface PaymentPayloadContext {
extensions?: Record<string, unknown>;
}
interface SchemeNetworkClient {
readonly scheme: string;
createPaymentPayload(x402Version: number, paymentRequirements: PaymentRequirements, context?: PaymentPayloadContext): Promise<PaymentPayloadResult>;
}
/**
* Context passed to SchemeNetworkFacilitator.verify/settle, providing
* access to registered facilitator extensions. Mechanism implementations
* use this to retrieve extension-provided capabilities (e.g., a batch signer).
*/
interface FacilitatorContext {
getExtension<T extends FacilitatorExtension = FacilitatorExtension>(key: string): T | undefined;
}
interface SchemeNetworkFacilitator {
readonly scheme: string;
/**
* CAIP family pattern that this facilitator supports.
* Used to group signers by blockchain family in the supported response.
*
* @example
* // EVM facilitators
* readonly caipFamily = "eip155:*";
*
* @example
* // SVM facilitators
* readonly caipFamily = "solana:*";
*/
readonly caipFamily: string;
/**
* Get mechanism-specific extra data needed for the supported kinds endpoint.
* This method is called when building the facilitator's supported response.
*
* @param network - The network identifier for context
* @returns Extra data object or undefined if no extra data is needed
*
* @example
* // EVM schemes return undefined (no extra data needed)
* getExtra(network: Network): undefined {
* return undefined;
* }
*
* @example
* // SVM schemes return feePayer address
* getExtra(network: Network): Record<string, unknown> | undefined {
* return { feePayer: this.signer.address };
* }
*/
getExtra(network: Network): Record<string, unknown> | undefined;
/**
* Get signer addresses used by this facilitator for a given network.
* These are included in the supported response to help clients understand
* which addresses might sign/pay for transactions.
*
* Supports multiple addresses for load balancing, key rotation, and high availability.
*
* @param network - The network identifier
* @returns Array of signer addresses (wallet addresses, fee payer addresses, etc.)
*
* @example
* // EVM facilitator
* getSigners(network: string): string[] {
* return [...this.signer.getAddresses()];
* }
*
* @example
* // SVM facilitator
* getSigners(network: string): string[] {
* return [...this.signer.getAddresses()];
* }
*/
getSigners(network: string): string[];
verify(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<VerifyResponse>;
settle(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<SettleResponse>;
}
interface SchemeNetworkServer {
readonly scheme: string;
/**
* Convert a user-friendly price to the scheme's specific amount and asset format
* Always returns a Promise for consistency
*
* @param price - User-friendly price (e.g., "$0.10", "0.10", { amount: "100000", asset: "USDC" })
* @param network - The network identifier for context
* @returns Promise that resolves to the converted amount, asset identifier, and any extra metadata
*
* @example
* // For EVM networks with USDC:
* await parsePrice("$0.10", "eip155:8453") => { amount: "100000", asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }
*
* // For custom schemes:
* await parsePrice("10 points", "custom:network") => { amount: "10", asset: "points" }
*/
parsePrice(price: Price, network: Network): Promise<AssetAmount>;
/**
* Optional: Return the decimal precision of the asset for a given network.
* Used by `resolveSettlementOverrideAmount` to convert dollar-format overrides to atomic units.
* Defaults to 6 when not implemented.
*
* @param asset - The asset address or symbol
* @param network - The network identifier
* @returns Number of decimal places for the asset
*/
getAssetDecimals?(asset: string, network: Network): number;
/**
* Build payment requirements for this scheme/network combination
*
* @param paymentRequirements - Base payment requirements with amount/asset already set
* @param supportedKind - The supported kind from facilitator's /supported endpoint
* @param supportedKind.x402Version - The x402 version
* @param supportedKind.scheme - The payment scheme
* @param supportedKind.network - The network identifier
* @param supportedKind.extra - Optional extra metadata
* @param facilitatorExtensions - Extensions supported by the facilitator
* @returns Enhanced payment requirements ready to be sent to clients
*/
enhancePaymentRequirements(paymentRequirements: PaymentRequirements, supportedKind: {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
}, facilitatorExtensions: string[]): Promise<PaymentRequirements>;
}
export { type AfterVerifyHook as A, type BeforeVerifyHook as B, type SettleResponseV1 as C, type SupportedResponseV1 as D, type AssetAmount as E, type FacilitatorExtension as F, type VerifyRequest as G, HTTPFacilitatorClient as H, type SettleRequest as I, type SupportedResponse as J, VerifyError as K, SettleError as L, type Money as M, type Network as N, type OnVerifyFailureHook as O, type PaymentPayload as P, type ResourceInfo as Q, type ResourceConfig as R, type SettleResponse as S, type SchemeNetworkServer as T, type MoneyParser as U, type VerifyResponse as V, type PaymentPayloadResult as W, type PaymentPayloadContext as X, type FacilitatorContext as Y, type ResourceServerExtension as Z, type PaymentRequirements as a, type SchemeNetworkFacilitator as b, type PaymentRequired as c, type FacilitatorClient as d, type FacilitatorConfig as e, FacilitatorResponseError as f, getFacilitatorResponseError as g, type SchemeNetworkClient as h, type PaymentRequiredContext as i, type VerifyContext as j, type VerifyResultContext as k, type VerifyFailureContext as l, type SettleContext as m, type SettleResultContext as n, type SettleFailureContext as o, type SettlementOverrides as p, type BeforeSettleHook as q, type AfterSettleHook as r, type OnSettleFailureHook as s, type Price as t, type PaymentRequirementsV1 as u, type PaymentRequiredV1 as v, type PaymentPayloadV1 as w, x402ResourceServer as x, type VerifyRequestV1 as y, type SettleRequestV1 as z };
import { x as x402ResourceServer, t as Price, N as Network, S as SettleResponse, c as PaymentRequired, P as PaymentPayload, a as PaymentRequirements, p as SettlementOverrides } from './mechanisms-Djgn2ixv.mjs';
declare const SETTLEMENT_OVERRIDES_HEADER = "Settlement-Overrides";
/**
* Framework-agnostic HTTP adapter interface
* Implementations provide framework-specific HTTP operations
*/
interface HTTPAdapter {
getHeader(name: string): string | undefined;
getMethod(): string;
getPath(): string;
getUrl(): string;
getAcceptHeader(): string;
getUserAgent(): string;
/**
* Get query parameters from the request URL
*
* @returns Record of query parameter key-value pairs
*/
getQueryParams?(): Record<string, string | string[]>;
/**
* Get a specific query parameter by name
*
* @param name - The query parameter name
* @returns The query parameter value(s) or undefined
*/
getQueryParam?(name: string): string | string[] | undefined;
/**
* Get the parsed request body
* Framework adapters should parse JSON/form data appropriately
*
* @returns The parsed request body
*/
getBody?(): unknown;
}
/**
* Paywall configuration for HTML responses
*/
interface PaywallConfig {
appName?: string;
appLogo?: string;
sessionTokenEndpoint?: string;
currentUrl?: string;
testnet?: boolean;
}
/**
* Paywall provider interface for generating HTML
*/
interface PaywallProvider {
generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;
}
/**
* Dynamic payTo function that receives HTTP request context
*/
type DynamicPayTo = (context: HTTPRequestContext) => string | Promise<string>;
/**
* Dynamic price function that receives HTTP request context
*/
type DynamicPrice = (context: HTTPRequestContext) => Price | Promise<Price>;
/**
* Result of response body callbacks containing content type and body.
*/
interface HTTPResponseBody {
/**
* The content type for the response (e.g., 'application/json', 'text/plain').
*/
contentType: string;
/**
* The response body to include in the 402 response.
*/
body: unknown;
}
/**
* Dynamic function to generate a custom response for unpaid requests.
* Receives the HTTP request context and returns the content type and body to include in the 402 response.
*/
type UnpaidResponseBody = (context: HTTPRequestContext) => HTTPResponseBody | Promise<HTTPResponseBody>;
/**
* Dynamic function to generate a custom response for settlement failures.
* Receives the HTTP request context and settle failure result, returns the content type and body.
*/
type SettlementFailedResponseBody = (context: HTTPRequestContext, settleResult: Omit<ProcessSettleFailureResponse, "response">) => HTTPResponseBody | Promise<HTTPResponseBody>;
/**
* A single payment option for a route
* Represents one way a client can pay for access to the resource
*/
interface PaymentOption {
scheme: string;
payTo: string | DynamicPayTo;
price: Price | DynamicPrice;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Route configuration for HTTP endpoints
*
* The 'accepts' field defines payment options for the route.
* Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.
*/
interface RouteConfig {
accepts: PaymentOption | PaymentOption[];
resource?: string;
description?: string;
mimeType?: string;
customPaywallHtml?: string;
/**
* Optional callback to generate a custom response for unpaid API requests.
* This allows servers to return preview data, error messages, or other content
* when a request lacks payment.
*
* For browser requests (Accept: text/html), the paywall HTML takes precedence.
* This callback is only used for API clients.
*
* If not provided, defaults to { contentType: 'application/json', body: {} }.
*
* @param context - The HTTP request context
* @returns An object containing both contentType and body for the 402 response
*/
unpaidResponseBody?: UnpaidResponseBody;
/**
* Optional callback to generate a custom response for settlement failures.
* If not provided, defaults to { contentType: 'application/json', body: {} }.
*
* @param context - The HTTP request context
* @param settleResult - The settlement failure result
* @returns An object containing both contentType and body for the 402 response
*/
settlementFailedResponseBody?: SettlementFailedResponseBody;
extensions?: Record<string, unknown>;
}
/**
* Routes configuration - maps path patterns to route configs
*/
type RoutesConfig = Record<string, RouteConfig> | RouteConfig;
/**
* Hook that runs on every request to a protected route, before payment processing.
* Can grant access without payment, deny the request, or continue to payment flow.
*
* @returns
* - `void` - Continue to payment processing (default behavior)
* - `{ grantAccess: true }` - Grant access without requiring payment
* - `{ abort: true; reason: string }` - Deny the request (returns 403)
*/
type ProtectedRequestHook = (context: HTTPRequestContext, routeConfig: RouteConfig) => Promise<void | {
grantAccess: true;
} | {
abort: true;
reason: string;
}>;
/**
* Compiled route for efficient matching
*/
interface CompiledRoute {
verb: string;
regex: RegExp;
config: RouteConfig;
pattern: string;
}
/**
* HTTP request context that encapsulates all request data
*/
interface HTTPRequestContext {
adapter: HTTPAdapter;
path: string;
method: string;
paymentHeader?: string;
routePattern?: string;
}
/**
* HTTP transport context contains both request context and optional response data.
*/
interface HTTPTransportContext {
/** The HTTP request context */
request: HTTPRequestContext;
/** The response body buffer */
responseBody?: Buffer;
/** Response headers set by the route handler (used for settlement overrides) */
responseHeaders?: Record<string, string>;
}
/**
* HTTP response instructions for the framework middleware
*/
interface HTTPResponseInstructions {
status: number;
headers: Record<string, string>;
body?: unknown;
isHtml?: boolean;
}
/**
* Result of processing an HTTP request for payment
*/
type HTTPProcessResult = {
type: "no-payment-required";
} | {
type: "payment-verified";
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
declaredExtensions?: Record<string, unknown>;
} | {
type: "payment-error";
response: HTTPResponseInstructions;
};
/**
* Result of processSettlement
*/
type ProcessSettleSuccessResponse = SettleResponse & {
success: true;
headers: Record<string, string>;
requirements: PaymentRequirements;
};
type ProcessSettleFailureResponse = SettleResponse & {
success: false;
errorReason: string;
errorMessage?: string;
headers: Record<string, string>;
response: HTTPResponseInstructions;
};
type ProcessSettleResultResponse = ProcessSettleSuccessResponse | ProcessSettleFailureResponse;
/**
* Represents a validation error for a specific route's payment configuration.
*/
interface RouteValidationError {
/** The route pattern (e.g., "GET /api/weather") */
routePattern: string;
/** The payment scheme that failed validation */
scheme: string;
/** The network that failed validation */
network: Network;
/** The type of validation failure */
reason: "missing_scheme" | "missing_facilitator";
/** Human-readable error message */
message: string;
}
/**
* Error thrown when route configuration validation fails.
*/
declare class RouteConfigurationError extends Error {
/** The validation errors that caused this exception */
readonly errors: RouteValidationError[];
/**
* Creates a new RouteConfigurationError with the given validation errors.
*
* @param errors - The validation errors that caused this exception.
*/
constructor(errors: RouteValidationError[]);
}
/**
* HTTP-enhanced x402 resource server
* Provides framework-agnostic HTTP protocol handling
*/
declare class x402HTTPResourceServer {
private ResourceServer;
private compiledRoutes;
private routesConfig;
private paywallProvider?;
private protectedRequestHooks;
/**
* Creates a new x402HTTPResourceServer instance.
*
* @param ResourceServer - The core x402ResourceServer instance to use
* @param routes - Route configuration for payment-protected endpoints
*/
constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig);
/**
* Get the underlying x402ResourceServer instance.
*
* @returns The underlying x402ResourceServer instance
*/
get server(): x402ResourceServer;
/**
* Get the routes configuration.
*
* @returns The routes configuration
*/
get routes(): RoutesConfig;
/**
* Initialize the HTTP resource server.
*
* This method initializes the underlying resource server (fetching facilitator support)
* and then validates that all route payment configurations have corresponding
* registered schemes and facilitator support.
*
* @throws RouteConfigurationError if any route's payment options don't have
* corresponding registered schemes or facilitator support
*
* @example
* ```typescript
* const httpServer = new x402HTTPResourceServer(server, routes);
* await httpServer.initialize();
* ```
*/
initialize(): Promise<void>;
/**
* Register a custom paywall provider for generating HTML
*
* @param provider - PaywallProvider instance
* @returns This service instance for chaining
*/
registerPaywallProvider(provider: PaywallProvider): this;
/**
* Register a hook that runs on every request to a protected route, before payment processing.
* Hooks are executed in order of registration. The first hook to return a non-void result wins.
*
* @param hook - The request hook function
* @returns The x402HTTPResourceServer instance for chaining
*/
onProtectedRequest(hook: ProtectedRequestHook): this;
/**
* Process HTTP request and return response instructions
* This is the main entry point for framework middleware
*
* @param context - HTTP request context
* @param paywallConfig - Optional paywall configuration
* @returns Process result indicating next action for middleware
*/
processHTTPRequest(context: HTTPRequestContext, paywallConfig?: PaywallConfig): Promise<HTTPProcessResult>;
/**
* Process settlement after successful response
*
* @param paymentPayload - The verified payment payload
* @param requirements - The matching payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional HTTP transport context
* @param settlementOverrides - Optional settlement overrides (e.g., partial settlement amount)
* @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
*/
processSettlement(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: HTTPTransportContext, settlementOverrides?: SettlementOverrides): Promise<ProcessSettleResultResponse>;
/**
* Check if a request requires payment based on route configuration
*
* @param context - HTTP request context
* @returns True if the route requires payment, false otherwise
*/
requiresPayment(context: HTTPRequestContext): boolean;
/**
* Build HTTPResponseInstructions for settlement failure.
* Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.
*
* @param failure - Settlement failure result with headers
* @param transportContext - Optional HTTP transport context for the request
* @returns HTTP response instructions for the 402 settlement failure response
*/
private buildSettlementFailureResponse;
/**
* Normalizes a RouteConfig's accepts field into an array of PaymentOptions
* Handles both single PaymentOption and array formats
*
* @param routeConfig - Route configuration
* @returns Array of payment options
*/
private normalizePaymentOptions;
/**
* Validates that all payment options in routes have corresponding registered schemes
* and facilitator support.
*
* @returns Array of validation errors (empty if all routes are valid)
*/
private validateRouteConfiguration;
/**
* Get route configuration for a request
*
* @param path - Request path
* @param method - HTTP method
* @returns Route configuration and pattern, or undefined if no match
*/
private getRouteConfig;
/**
* Extract payment from HTTP headers (handles v1 and v2)
*
* @param adapter - HTTP adapter
* @returns Decoded payment payload or null
*/
private extractPayment;
/**
* Check if request is from a web browser
*
* @param adapter - HTTP adapter
* @returns True if request appears to be from a browser
*/
private isWebBrowser;
/**
* Create HTTP response instructions from payment required
*
* @param paymentRequired - Payment requirements
* @param isWebBrowser - Whether request is from browser
* @param paywallConfig - Paywall configuration
* @param customHtml - Custom HTML template
* @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
* @returns Response instructions
*/
private createHTTPResponse;
/**
* Create HTTP payment required response (v1 puts in body, v2 puts in header)
*
* @param paymentRequired - Payment required object
* @returns Headers and body for the HTTP response
*/
private createHTTPPaymentRequiredResponse;
/**
* Create settlement response headers
*
* @param settleResponse - Settlement response
* @returns Headers to add to response
*/
private createSettlementHeaders;
/**
* Parse route pattern into verb and regex
*
* @param pattern - Route pattern like "GET /api/*", "/api/[id]", or "/api/:id"
* @returns Parsed pattern with verb and regex
*/
private parseRoutePattern;
/**
* Normalize path for matching
*
* @param path - Raw path from request
* @returns Normalized path
*/
private normalizePath;
/**
* Generate paywall HTML for browser requests
*
* @param paymentRequired - Payment required response
* @param paywallConfig - Optional paywall configuration
* @param customHtml - Optional custom HTML template
* @returns HTML string
*/
private generatePaywallHTML;
/**
* Extract display amount from payment requirements.
*
* @param paymentRequired - The payment required object
* @returns The display amount in decimal format
*/
private getDisplayAmount;
}
export { type CompiledRoute as C, type DynamicPayTo as D, type HTTPAdapter as H, type PaywallConfig as P, type RouteConfig as R, type SettlementFailedResponseBody as S, type UnpaidResponseBody as U, type HTTPRequestContext as a, type HTTPTransportContext as b, type HTTPResponseInstructions as c, type HTTPProcessResult as d, type PaywallProvider as e, type PaymentOption as f, type RoutesConfig as g, type DynamicPrice as h, type HTTPResponseBody as i, type ProcessSettleResultResponse as j, type ProcessSettleSuccessResponse as k, type ProcessSettleFailureResponse as l, type RouteValidationError as m, RouteConfigurationError as n, type ProtectedRequestHook as o, SETTLEMENT_OVERRIDES_HEADER as p, x402HTTPResourceServer as x };
+1
-1

@@ -1,2 +0,2 @@

import { c as PaymentRequired, a as PaymentRequirements, P as PaymentPayload, N as Network, h as SchemeNetworkClient, S as SettleResponse } from '../mechanisms-B3SXtgLV.js';
import { c as PaymentRequired, a as PaymentRequirements, P as PaymentPayload, N as Network, h as SchemeNetworkClient, S as SettleResponse } from '../mechanisms-Djgn2ixv.js';

@@ -3,0 +3,0 @@ /**

@@ -1,2 +0,2 @@

import { P as PaymentPayload, a as PaymentRequirements, V as VerifyResponse, S as SettleResponse, N as Network, b as SchemeNetworkFacilitator, F as FacilitatorExtension } from '../mechanisms-B3SXtgLV.js';
import { P as PaymentPayload, a as PaymentRequirements, V as VerifyResponse, S as SettleResponse, N as Network, b as SchemeNetworkFacilitator, F as FacilitatorExtension } from '../mechanisms-Djgn2ixv.js';

@@ -3,0 +3,0 @@ /**

@@ -1,4 +0,4 @@

import { P as PaymentPayload, c as PaymentRequired, S as SettleResponse } from '../mechanisms-B3SXtgLV.js';
export { d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, g as getFacilitatorResponseError } from '../mechanisms-B3SXtgLV.js';
export { C as CompiledRoute, D as DynamicPayTo, h as DynamicPrice, H as HTTPAdapter, d as HTTPProcessResult, a as HTTPRequestContext, i as HTTPResponseBody, c as HTTPResponseInstructions, b as HTTPTransportContext, f as PaymentOption, P as PaywallConfig, e as PaywallProvider, l as ProcessSettleFailureResponse, j as ProcessSettleResultResponse, k as ProcessSettleSuccessResponse, o as ProtectedRequestHook, R as RouteConfig, n as RouteConfigurationError, m as RouteValidationError, g as RoutesConfig, S as SettlementFailedResponseBody, U as UnpaidResponseBody, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-DMq04DQi.js';
import { P as PaymentPayload, c as PaymentRequired, S as SettleResponse } from '../mechanisms-Djgn2ixv.js';
export { d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, g as getFacilitatorResponseError } from '../mechanisms-Djgn2ixv.js';
export { C as CompiledRoute, D as DynamicPayTo, h as DynamicPrice, H as HTTPAdapter, d as HTTPProcessResult, a as HTTPRequestContext, i as HTTPResponseBody, c as HTTPResponseInstructions, b as HTTPTransportContext, f as PaymentOption, P as PaywallConfig, e as PaywallProvider, l as ProcessSettleFailureResponse, j as ProcessSettleResultResponse, k as ProcessSettleSuccessResponse, o as ProtectedRequestHook, R as RouteConfig, n as RouteConfigurationError, m as RouteValidationError, g as RoutesConfig, S as SettlementFailedResponseBody, U as UnpaidResponseBody, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-C517OLKe.js';
export { PaymentRequiredContext, PaymentRequiredHook, x402HTTPClient } from '../client/index.js';

@@ -5,0 +5,0 @@

@@ -126,2 +126,3 @@ "use strict";

// src/http/x402HTTPResourceServer.ts
var SETTLEMENT_OVERRIDES_HEADER = "Settlement-Overrides";
var RouteConfigurationError = class extends Error {

@@ -233,3 +234,5 @@ /**

async processHTTPRequest(context, paywallConfig) {
const { adapter, path, method } = context;
const method = context.method || context.adapter.getMethod();
context = { ...context, method };
const { adapter, path } = context;
const routeMatch = this.getRouteConfig(path, method);

@@ -358,6 +361,29 @@ if (!routeMatch) {

* @param transportContext - Optional HTTP transport context
* @param settlementOverrides - Optional settlement overrides (e.g., partial settlement amount)
* @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
*/
async processSettlement(paymentPayload, requirements, declaredExtensions, transportContext) {
async processSettlement(paymentPayload, requirements, declaredExtensions, transportContext, settlementOverrides) {
if (transportContext?.request && !transportContext.request.method) {
transportContext = {
...transportContext,
request: {
...transportContext.request,
method: transportContext.request.adapter.getMethod()
}
};
}
try {
let resolvedOverrides = settlementOverrides;
if (!resolvedOverrides && transportContext?.responseHeaders) {
const overridesKey = SETTLEMENT_OVERRIDES_HEADER.toLowerCase();
const rawValue = Object.entries(transportContext.responseHeaders).find(
([key]) => key.toLowerCase() === overridesKey
)?.[1];
if (rawValue) {
try {
resolvedOverrides = JSON.parse(rawValue);
} catch {
}
}
}
const settleResponse = await this.ResourceServer.settlePayment(

@@ -367,3 +393,4 @@ paymentPayload,

declaredExtensions,
transportContext
transportContext,
resolvedOverrides
);

@@ -435,3 +462,4 @@ if (!settleResponse.success) {

requiresPayment(context) {
return this.getRouteConfig(context.path, context.method) !== void 0;
const method = context.method || context.adapter.getMethod();
return this.getRouteConfig(context.path, method) !== void 0;
}

@@ -627,3 +655,3 @@ /**

const regex = new RegExp(
`^${path.replace(/[$()+.?^{|}]/g, "\\$&").replace(/\*/g, ".*?").replace(/\[([^\]]+)\]/g, "[^/]+").replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, "[^/]+").replace(/\//g, "\\/")}$`,
`^${path.replace(/\\/g, "\\\\").replace(/[$()+.?^{|}]/g, "\\$&").replace(/\*/g, ".*?").replace(/\[([^\]]+)\]/g, "[^/]+").replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, "[^/]+").replace(/\//g, "\\/")}$`,
"i"

@@ -872,3 +900,3 @@ );

constructor(config) {
this.url = config?.url || DEFAULT_FACILITATOR_URL;
this.url = (config?.url || DEFAULT_FACILITATOR_URL).replace(/\/+$/, "");
this._createAuthHeaders = config?.createAuthHeaders;

@@ -894,2 +922,3 @@ }

headers,
redirect: "follow",
body: JSON.stringify({

@@ -936,2 +965,3 @@ x402Version: paymentPayload.x402Version,

headers,
redirect: "follow",
body: JSON.stringify({

@@ -978,3 +1008,4 @@ x402Version: paymentPayload.x402Version,

method: "GET",
headers
headers,
redirect: "follow"
});

@@ -981,0 +1012,0 @@ if (response.ok) {

@@ -1,2 +0,2 @@

export { d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, R as ResourceConfig, i as SettleResultContext, g as getFacilitatorResponseError, x as x402ResourceServer } from '../mechanisms-B3SXtgLV.js';
export { C as CompiledRoute, H as HTTPAdapter, d as HTTPProcessResult, a as HTTPRequestContext, i as HTTPResponseBody, c as HTTPResponseInstructions, b as HTTPTransportContext, P as PaywallConfig, e as PaywallProvider, l as ProcessSettleFailureResponse, j as ProcessSettleResultResponse, k as ProcessSettleSuccessResponse, R as RouteConfig, n as RouteConfigurationError, m as RouteValidationError, g as RoutesConfig, S as SettlementFailedResponseBody, U as UnpaidResponseBody, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-DMq04DQi.js';
export { r as AfterSettleHook, A as AfterVerifyHook, q as BeforeSettleHook, B as BeforeVerifyHook, d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, s as OnSettleFailureHook, O as OnVerifyFailureHook, i as PaymentRequiredContext, R as ResourceConfig, m as SettleContext, o as SettleFailureContext, n as SettleResultContext, p as SettlementOverrides, j as VerifyContext, l as VerifyFailureContext, k as VerifyResultContext, g as getFacilitatorResponseError, x as x402ResourceServer } from '../mechanisms-Djgn2ixv.js';
export { C as CompiledRoute, H as HTTPAdapter, d as HTTPProcessResult, a as HTTPRequestContext, i as HTTPResponseBody, c as HTTPResponseInstructions, b as HTTPTransportContext, P as PaywallConfig, e as PaywallProvider, l as ProcessSettleFailureResponse, j as ProcessSettleResultResponse, k as ProcessSettleSuccessResponse, o as ProtectedRequestHook, R as RouteConfig, n as RouteConfigurationError, m as RouteValidationError, g as RoutesConfig, p as SETTLEMENT_OVERRIDES_HEADER, S as SettlementFailedResponseBody, U as UnpaidResponseBody, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-C517OLKe.js';

@@ -26,2 +26,3 @@ "use strict";

RouteConfigurationError: () => RouteConfigurationError,
SETTLEMENT_OVERRIDES_HEADER: () => SETTLEMENT_OVERRIDES_HEADER,
getFacilitatorResponseError: () => getFacilitatorResponseError,

@@ -303,3 +304,3 @@ x402HTTPResourceServer: () => x402HTTPResourceServer,

constructor(config) {
this.url = config?.url || DEFAULT_FACILITATOR_URL;
this.url = (config?.url || DEFAULT_FACILITATOR_URL).replace(/\/+$/, "");
this._createAuthHeaders = config?.createAuthHeaders;

@@ -325,2 +326,3 @@ }

headers,
redirect: "follow",
body: JSON.stringify({

@@ -367,2 +369,3 @@ x402Version: paymentPayload.x402Version,

headers,
redirect: "follow",
body: JSON.stringify({

@@ -409,3 +412,4 @@ x402Version: paymentPayload.x402Version,

method: "GET",
headers
headers,
redirect: "follow"
});

@@ -463,2 +467,17 @@ if (response.ok) {

// src/server/x402ResourceServer.ts
function resolveSettlementOverrideAmount(rawAmount, requirements, decimals = 6) {
const percentMatch = rawAmount.match(/^(\d+(?:\.\d{0,2})?)%$/);
if (percentMatch) {
const [intPart, decPart = ""] = percentMatch[1].split(".");
const scaledPercent = BigInt(intPart) * 100n + BigInt(decPart.padEnd(2, "0").slice(0, 2));
const base = BigInt(requirements.amount);
return (base * scaledPercent / 10000n).toString();
}
const dollarMatch = rawAmount.match(/^\$(\d+(?:\.\d+)?)$/);
if (dollarMatch) {
const dollars = parseFloat(dollarMatch[1]);
return Math.round(dollars * 10 ** decimals).toString();
}
return rawAmount;
}
var x402ResourceServer = class {

@@ -935,8 +954,22 @@ /**

* @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)
* @param settlementOverrides - Optional overrides for settlement parameters (e.g., partial settlement amount)
* @returns Settlement response
*/
async settlePayment(paymentPayload, requirements, declaredExtensions, transportContext) {
async settlePayment(paymentPayload, requirements, declaredExtensions, transportContext, settlementOverrides) {
let effectiveRequirements = requirements;
if (settlementOverrides?.amount !== void 0) {
const scheme = findByNetworkAndScheme(
this.registeredServerSchemes,
requirements.scheme,
requirements.network
);
const decimals = scheme?.getAssetDecimals?.(requirements.asset ?? "", requirements.network) ?? 6;
effectiveRequirements = {
...requirements,
amount: resolveSettlementOverrideAmount(settlementOverrides.amount, requirements, decimals)
};
}
const context = {
paymentPayload,
requirements
requirements: effectiveRequirements
};

@@ -971,4 +1004,4 @@ for (const hook of this.beforeSettleHooks) {

paymentPayload.x402Version,
requirements.network,
requirements.scheme
effectiveRequirements.network,
effectiveRequirements.scheme
);

@@ -980,3 +1013,3 @@ let settleResult;

try {
settleResult = await client.settle(paymentPayload, requirements);
settleResult = await client.settle(paymentPayload, effectiveRequirements);
break;

@@ -989,7 +1022,7 @@ } catch (error) {

throw lastError || new Error(
`No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`
`No facilitator supports ${effectiveRequirements.scheme} on ${effectiveRequirements.network} for v${paymentPayload.x402Version}`
);
}
} else {
settleResult = await facilitatorClient.settle(paymentPayload, requirements);
settleResult = await facilitatorClient.settle(paymentPayload, effectiveRequirements);
}

@@ -1140,2 +1173,3 @@ const resultContext = {

// src/http/x402HTTPResourceServer.ts
var SETTLEMENT_OVERRIDES_HEADER = "Settlement-Overrides";
var RouteConfigurationError = class extends Error {

@@ -1247,3 +1281,5 @@ /**

async processHTTPRequest(context, paywallConfig) {
const { adapter, path, method } = context;
const method = context.method || context.adapter.getMethod();
context = { ...context, method };
const { adapter, path } = context;
const routeMatch = this.getRouteConfig(path, method);

@@ -1372,6 +1408,29 @@ if (!routeMatch) {

* @param transportContext - Optional HTTP transport context
* @param settlementOverrides - Optional settlement overrides (e.g., partial settlement amount)
* @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
*/
async processSettlement(paymentPayload, requirements, declaredExtensions, transportContext) {
async processSettlement(paymentPayload, requirements, declaredExtensions, transportContext, settlementOverrides) {
if (transportContext?.request && !transportContext.request.method) {
transportContext = {
...transportContext,
request: {
...transportContext.request,
method: transportContext.request.adapter.getMethod()
}
};
}
try {
let resolvedOverrides = settlementOverrides;
if (!resolvedOverrides && transportContext?.responseHeaders) {
const overridesKey = SETTLEMENT_OVERRIDES_HEADER.toLowerCase();
const rawValue = Object.entries(transportContext.responseHeaders).find(
([key]) => key.toLowerCase() === overridesKey
)?.[1];
if (rawValue) {
try {
resolvedOverrides = JSON.parse(rawValue);
} catch {
}
}
}
const settleResponse = await this.ResourceServer.settlePayment(

@@ -1381,3 +1440,4 @@ paymentPayload,

declaredExtensions,
transportContext
transportContext,
resolvedOverrides
);

@@ -1449,3 +1509,4 @@ if (!settleResponse.success) {

requiresPayment(context) {
return this.getRouteConfig(context.path, context.method) !== void 0;
const method = context.method || context.adapter.getMethod();
return this.getRouteConfig(context.path, method) !== void 0;
}

@@ -1641,3 +1702,3 @@ /**

const regex = new RegExp(
`^${path.replace(/[$()+.?^{|}]/g, "\\$&").replace(/\*/g, ".*?").replace(/\[([^\]]+)\]/g, "[^/]+").replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, "[^/]+").replace(/\//g, "\\/")}$`,
`^${path.replace(/\\/g, "\\\\").replace(/[$()+.?^{|}]/g, "\\$&").replace(/\*/g, ".*?").replace(/\[([^\]]+)\]/g, "[^/]+").replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, "[^/]+").replace(/\//g, "\\/")}$`,
"i"

@@ -1745,2 +1806,3 @@ );

RouteConfigurationError,
SETTLEMENT_OVERRIDES_HEADER,
getFacilitatorResponseError,

@@ -1747,0 +1809,0 @@ x402HTTPResourceServer,

@@ -1,1 +0,1 @@

export { A as AssetAmount, D as FacilitatorContext, F as FacilitatorExtension, f as FacilitatorResponseError, M as Money, z as MoneyParser, N as Network, P as PaymentPayload, C as PaymentPayloadContext, B as PaymentPayloadResult, m as PaymentPayloadV1, c as PaymentRequired, G as PaymentRequiredContext, l as PaymentRequiredV1, a as PaymentRequirements, k as PaymentRequirementsV1, j as Price, w as ResourceInfo, E as ResourceServerExtension, h as SchemeNetworkClient, b as SchemeNetworkFacilitator, y as SchemeNetworkServer, v as SettleError, s as SettleRequest, S as SettleResponse, i as SettleResultContext, t as SupportedResponse, u as VerifyError, r as VerifyRequest, V as VerifyResponse, g as getFacilitatorResponseError } from '../mechanisms-B3SXtgLV.js';
export { E as AssetAmount, Y as FacilitatorContext, F as FacilitatorExtension, f as FacilitatorResponseError, M as Money, U as MoneyParser, N as Network, P as PaymentPayload, X as PaymentPayloadContext, W as PaymentPayloadResult, w as PaymentPayloadV1, c as PaymentRequired, i as PaymentRequiredContext, v as PaymentRequiredV1, a as PaymentRequirements, u as PaymentRequirementsV1, t as Price, Q as ResourceInfo, Z as ResourceServerExtension, h as SchemeNetworkClient, b as SchemeNetworkFacilitator, T as SchemeNetworkServer, L as SettleError, I as SettleRequest, S as SettleResponse, n as SettleResultContext, J as SupportedResponse, K as VerifyError, G as VerifyRequest, V as VerifyResponse, g as getFacilitatorResponseError } from '../mechanisms-Djgn2ixv.js';

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/types/index.ts","../../../src/types/facilitator.ts"],"sourcesContent":["export type {\n VerifyRequest,\n VerifyResponse,\n SettleRequest,\n SettleResponse,\n SupportedResponse,\n} from \"./facilitator\";\nexport {\n VerifyError,\n SettleError,\n FacilitatorResponseError,\n getFacilitatorResponseError,\n} from \"./facilitator\";\nexport type {\n PaymentRequirements,\n PaymentPayload,\n PaymentRequired,\n ResourceInfo,\n} from \"./payments\";\nexport type {\n SchemeNetworkClient,\n SchemeNetworkFacilitator,\n SchemeNetworkServer,\n MoneyParser,\n PaymentPayloadResult,\n PaymentPayloadContext,\n FacilitatorContext,\n} from \"./mechanisms\";\nexport type { PaymentRequirementsV1, PaymentRequiredV1, PaymentPayloadV1 } from \"./v1\";\nexport type {\n FacilitatorExtension,\n ResourceServerExtension,\n PaymentRequiredContext,\n SettleResultContext,\n} from \"./extensions\";\n\nexport type Network = `${string}:${string}`;\n\nexport type Money = string | number;\nexport type AssetAmount = {\n asset: string;\n amount: string;\n extra?: Record<string, unknown>;\n};\nexport type Price = Money | AssetAmount;\n","import { PaymentPayload, PaymentRequirements } from \"./payments\";\nimport { Network } from \"./\";\n\nexport type VerifyRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type VerifyResponse = {\n isValid: boolean;\n invalidReason?: string;\n invalidMessage?: string;\n payer?: string;\n extensions?: Record<string, unknown>;\n};\n\nexport type SettleRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type SettleResponse = {\n success: boolean;\n errorReason?: string;\n errorMessage?: string;\n payer?: string;\n transaction: string;\n network: Network;\n extensions?: Record<string, unknown>;\n};\n\nexport type SupportedKind = {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n};\n\nexport type SupportedResponse = {\n kinds: SupportedKind[];\n extensions: string[];\n signers: Record<string, string[]>; // CAIP family pattern → Signer addresses\n};\n\n/**\n * Error thrown when payment verification fails.\n */\nexport class VerifyError extends Error {\n readonly invalidReason?: string;\n readonly invalidMessage?: string;\n readonly payer?: string;\n readonly statusCode: number;\n\n /**\n * Creates a VerifyError from a failed verification response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The verify response containing error details\n */\n constructor(statusCode: number, response: VerifyResponse) {\n const reason = response.invalidReason || \"unknown reason\";\n const message = response.invalidMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"VerifyError\";\n this.statusCode = statusCode;\n this.invalidReason = response.invalidReason;\n this.invalidMessage = response.invalidMessage;\n this.payer = response.payer;\n }\n}\n\n/**\n * Error thrown when payment settlement fails.\n */\nexport class SettleError extends Error {\n readonly errorReason?: string;\n readonly errorMessage?: string;\n readonly payer?: string;\n readonly transaction: string;\n readonly network: Network;\n readonly statusCode: number;\n\n /**\n * Creates a SettleError from a failed settlement response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The settle response containing error details\n */\n constructor(statusCode: number, response: SettleResponse) {\n const reason = response.errorReason || \"unknown reason\";\n const message = response.errorMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"SettleError\";\n this.statusCode = statusCode;\n this.errorReason = response.errorReason;\n this.errorMessage = response.errorMessage;\n this.payer = response.payer;\n this.transaction = response.transaction;\n this.network = response.network;\n }\n}\n\n/**\n * Error thrown when a facilitator returns malformed success payload data.\n */\nexport class FacilitatorResponseError extends Error {\n /**\n * Creates a FacilitatorResponseError for malformed facilitator responses.\n *\n * @param message - The boundary error message\n */\n constructor(message: string) {\n super(message);\n this.name = \"FacilitatorResponseError\";\n }\n}\n\n/**\n * Walks an error cause chain to find the first facilitator response error.\n *\n * @param error - The thrown value to inspect\n * @returns The nested facilitator response error, if present\n */\nexport function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null {\n let current = error;\n\n while (current instanceof Error) {\n if (current instanceof FacilitatorResponseError) {\n return current;\n }\n current = current.cause;\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiDO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,iBAAiB;AACzC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,gBAAgB,SAAS;AAC9B,SAAK,iBAAiB,SAAS;AAC/B,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAKO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,eAAe;AACvC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,cAAc,SAAS;AAC5B,SAAK,eAAe,SAAS;AAC7B,SAAK,QAAQ,SAAS;AACtB,SAAK,cAAc,SAAS;AAC5B,SAAK,UAAU,SAAS;AAAA,EAC1B;AACF;AAKO,IAAM,2BAAN,cAAuC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMlD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAQO,SAAS,4BAA4B,OAAiD;AAC3F,MAAI,UAAU;AAEd,SAAO,mBAAmB,OAAO;AAC/B,QAAI,mBAAmB,0BAA0B;AAC/C,aAAO;AAAA,IACT;AACA,cAAU,QAAQ;AAAA,EACpB;AAEA,SAAO;AACT;","names":[]}
{"version":3,"sources":["../../../src/types/index.ts","../../../src/types/facilitator.ts"],"sourcesContent":["export type {\n VerifyRequest,\n VerifyResponse,\n SettleRequest,\n SettleResponse,\n SupportedResponse,\n} from \"./facilitator\";\nexport {\n VerifyError,\n SettleError,\n FacilitatorResponseError,\n getFacilitatorResponseError,\n} from \"./facilitator\";\nexport type {\n PaymentRequirements,\n PaymentPayload,\n PaymentRequired,\n ResourceInfo,\n} from \"./payments\";\nexport type {\n SchemeNetworkClient,\n SchemeNetworkFacilitator,\n SchemeNetworkServer,\n MoneyParser,\n PaymentPayloadResult,\n PaymentPayloadContext,\n FacilitatorContext,\n} from \"./mechanisms\";\nexport type { PaymentRequirementsV1, PaymentRequiredV1, PaymentPayloadV1 } from \"./v1\";\nexport type {\n FacilitatorExtension,\n ResourceServerExtension,\n PaymentRequiredContext,\n SettleResultContext,\n} from \"./extensions\";\n\nexport type Network = `${string}:${string}`;\n\nexport type Money = string | number;\nexport type AssetAmount = {\n asset: string;\n amount: string;\n extra?: Record<string, unknown>;\n};\nexport type Price = Money | AssetAmount;\n","import { PaymentPayload, PaymentRequirements } from \"./payments\";\nimport { Network } from \"./\";\n\nexport type VerifyRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type VerifyResponse = {\n isValid: boolean;\n invalidReason?: string;\n invalidMessage?: string;\n payer?: string;\n extensions?: Record<string, unknown>;\n};\n\nexport type SettleRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type SettleResponse = {\n success: boolean;\n errorReason?: string;\n errorMessage?: string;\n payer?: string;\n transaction: string;\n network: Network;\n /** Actual amount settled in atomic token units. Present for schemes like `upto` where settlement amount may differ from the authorized maximum. */\n amount?: string;\n extensions?: Record<string, unknown>;\n};\n\nexport type SupportedKind = {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n};\n\nexport type SupportedResponse = {\n kinds: SupportedKind[];\n extensions: string[];\n signers: Record<string, string[]>; // CAIP family pattern → Signer addresses\n};\n\n/**\n * Error thrown when payment verification fails.\n */\nexport class VerifyError extends Error {\n readonly invalidReason?: string;\n readonly invalidMessage?: string;\n readonly payer?: string;\n readonly statusCode: number;\n\n /**\n * Creates a VerifyError from a failed verification response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The verify response containing error details\n */\n constructor(statusCode: number, response: VerifyResponse) {\n const reason = response.invalidReason || \"unknown reason\";\n const message = response.invalidMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"VerifyError\";\n this.statusCode = statusCode;\n this.invalidReason = response.invalidReason;\n this.invalidMessage = response.invalidMessage;\n this.payer = response.payer;\n }\n}\n\n/**\n * Error thrown when payment settlement fails.\n */\nexport class SettleError extends Error {\n readonly errorReason?: string;\n readonly errorMessage?: string;\n readonly payer?: string;\n readonly transaction: string;\n readonly network: Network;\n readonly statusCode: number;\n\n /**\n * Creates a SettleError from a failed settlement response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The settle response containing error details\n */\n constructor(statusCode: number, response: SettleResponse) {\n const reason = response.errorReason || \"unknown reason\";\n const message = response.errorMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"SettleError\";\n this.statusCode = statusCode;\n this.errorReason = response.errorReason;\n this.errorMessage = response.errorMessage;\n this.payer = response.payer;\n this.transaction = response.transaction;\n this.network = response.network;\n }\n}\n\n/**\n * Error thrown when a facilitator returns malformed success payload data.\n */\nexport class FacilitatorResponseError extends Error {\n /**\n * Creates a FacilitatorResponseError for malformed facilitator responses.\n *\n * @param message - The boundary error message\n */\n constructor(message: string) {\n super(message);\n this.name = \"FacilitatorResponseError\";\n }\n}\n\n/**\n * Walks an error cause chain to find the first facilitator response error.\n *\n * @param error - The thrown value to inspect\n * @returns The nested facilitator response error, if present\n */\nexport function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null {\n let current = error;\n\n while (current instanceof Error) {\n if (current instanceof FacilitatorResponseError) {\n return current;\n }\n current = current.cause;\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmDO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,iBAAiB;AACzC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,gBAAgB,SAAS;AAC9B,SAAK,iBAAiB,SAAS;AAC/B,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAKO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,eAAe;AACvC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,cAAc,SAAS;AAC5B,SAAK,eAAe,SAAS;AAC7B,SAAK,QAAQ,SAAS;AACtB,SAAK,cAAc,SAAS;AAC5B,SAAK,UAAU,SAAS;AAAA,EAC1B;AACF;AAKO,IAAM,2BAAN,cAAuC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMlD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAQO,SAAS,4BAA4B,OAAiD;AAC3F,MAAI,UAAU;AAEd,SAAO,mBAAmB,OAAO;AAC/B,QAAI,mBAAmB,0BAA0B;AAC/C,aAAO;AAAA,IACT;AACA,cAAU,QAAQ;AAAA,EACpB;AAEA,SAAO;AACT;","names":[]}

@@ -1,1 +0,1 @@

export { m as PaymentPayloadV1, l as PaymentRequiredV1, k as PaymentRequirementsV1, o as SettleRequestV1, p as SettleResponseV1, q as SupportedResponseV1, n as VerifyRequestV1 } from '../../mechanisms-B3SXtgLV.js';
export { w as PaymentPayloadV1, v as PaymentRequiredV1, u as PaymentRequirementsV1, z as SettleRequestV1, C as SettleResponseV1, D as SupportedResponseV1, y as VerifyRequestV1 } from '../../mechanisms-Djgn2ixv.js';

@@ -1,2 +0,2 @@

import { N as Network } from '../mechanisms-B3SXtgLV.js';
import { N as Network } from '../mechanisms-Djgn2ixv.js';

@@ -3,0 +3,0 @@ /**

@@ -1,2 +0,2 @@

import { c as PaymentRequired, a as PaymentRequirements, P as PaymentPayload, N as Network, h as SchemeNetworkClient, S as SettleResponse } from '../mechanisms-B3SXtgLV.mjs';
import { c as PaymentRequired, a as PaymentRequirements, P as PaymentPayload, N as Network, h as SchemeNetworkClient, S as SettleResponse } from '../mechanisms-Djgn2ixv.mjs';

@@ -3,0 +3,0 @@ /**

import {
x402HTTPClient
} from "../chunk-ACVTKVCM.mjs";
} from "../chunk-JFGRL3BL.mjs";
import "../chunk-KMQH4MQI.mjs";

@@ -8,3 +8,3 @@ import {

} from "../chunk-VE37GDG2.mjs";
import "../chunk-VY72CEUI.mjs";
import "../chunk-JUGE6MAI.mjs";
import {

@@ -11,0 +11,0 @@ findByNetworkAndScheme,

@@ -1,2 +0,2 @@

import { P as PaymentPayload, a as PaymentRequirements, V as VerifyResponse, S as SettleResponse, N as Network, b as SchemeNetworkFacilitator, F as FacilitatorExtension } from '../mechanisms-B3SXtgLV.mjs';
import { P as PaymentPayload, a as PaymentRequirements, V as VerifyResponse, S as SettleResponse, N as Network, b as SchemeNetworkFacilitator, F as FacilitatorExtension } from '../mechanisms-Djgn2ixv.mjs';

@@ -3,0 +3,0 @@ /**

@@ -1,4 +0,4 @@

import { P as PaymentPayload, c as PaymentRequired, S as SettleResponse } from '../mechanisms-B3SXtgLV.mjs';
export { d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, g as getFacilitatorResponseError } from '../mechanisms-B3SXtgLV.mjs';
export { C as CompiledRoute, D as DynamicPayTo, h as DynamicPrice, H as HTTPAdapter, d as HTTPProcessResult, a as HTTPRequestContext, i as HTTPResponseBody, c as HTTPResponseInstructions, b as HTTPTransportContext, f as PaymentOption, P as PaywallConfig, e as PaywallProvider, l as ProcessSettleFailureResponse, j as ProcessSettleResultResponse, k as ProcessSettleSuccessResponse, o as ProtectedRequestHook, R as RouteConfig, n as RouteConfigurationError, m as RouteValidationError, g as RoutesConfig, S as SettlementFailedResponseBody, U as UnpaidResponseBody, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-Czgtr1xC.mjs';
import { P as PaymentPayload, c as PaymentRequired, S as SettleResponse } from '../mechanisms-Djgn2ixv.mjs';
export { d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, g as getFacilitatorResponseError } from '../mechanisms-Djgn2ixv.mjs';
export { C as CompiledRoute, D as DynamicPayTo, h as DynamicPrice, H as HTTPAdapter, d as HTTPProcessResult, a as HTTPRequestContext, i as HTTPResponseBody, c as HTTPResponseInstructions, b as HTTPTransportContext, f as PaymentOption, P as PaywallConfig, e as PaywallProvider, l as ProcessSettleFailureResponse, j as ProcessSettleResultResponse, k as ProcessSettleSuccessResponse, o as ProtectedRequestHook, R as RouteConfig, n as RouteConfigurationError, m as RouteValidationError, g as RoutesConfig, S as SettlementFailedResponseBody, U as UnpaidResponseBody, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-D9iYGDlY.mjs';
export { PaymentRequiredContext, PaymentRequiredHook, x402HTTPClient } from '../client/index.mjs';

@@ -5,0 +5,0 @@

@@ -12,3 +12,3 @@ import {

x402HTTPResourceServer
} from "../chunk-ACVTKVCM.mjs";
} from "../chunk-JFGRL3BL.mjs";
import "../chunk-KMQH4MQI.mjs";

@@ -19,3 +19,3 @@ import "../chunk-VE37GDG2.mjs";

getFacilitatorResponseError
} from "../chunk-VY72CEUI.mjs";
} from "../chunk-JUGE6MAI.mjs";
import "../chunk-TDLQZ6MP.mjs";

@@ -22,0 +22,0 @@ import "../chunk-BJTO5JO5.mjs";

@@ -1,2 +0,2 @@

export { d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, R as ResourceConfig, i as SettleResultContext, g as getFacilitatorResponseError, x as x402ResourceServer } from '../mechanisms-B3SXtgLV.mjs';
export { C as CompiledRoute, H as HTTPAdapter, d as HTTPProcessResult, a as HTTPRequestContext, i as HTTPResponseBody, c as HTTPResponseInstructions, b as HTTPTransportContext, P as PaywallConfig, e as PaywallProvider, l as ProcessSettleFailureResponse, j as ProcessSettleResultResponse, k as ProcessSettleSuccessResponse, R as RouteConfig, n as RouteConfigurationError, m as RouteValidationError, g as RoutesConfig, S as SettlementFailedResponseBody, U as UnpaidResponseBody, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-Czgtr1xC.mjs';
export { r as AfterSettleHook, A as AfterVerifyHook, q as BeforeSettleHook, B as BeforeVerifyHook, d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, s as OnSettleFailureHook, O as OnVerifyFailureHook, i as PaymentRequiredContext, R as ResourceConfig, m as SettleContext, o as SettleFailureContext, n as SettleResultContext, p as SettlementOverrides, j as VerifyContext, l as VerifyFailureContext, k as VerifyResultContext, g as getFacilitatorResponseError, x as x402ResourceServer } from '../mechanisms-Djgn2ixv.mjs';
export { C as CompiledRoute, H as HTTPAdapter, d as HTTPProcessResult, a as HTTPRequestContext, i as HTTPResponseBody, c as HTTPResponseInstructions, b as HTTPTransportContext, P as PaywallConfig, e as PaywallProvider, l as ProcessSettleFailureResponse, j as ProcessSettleResultResponse, k as ProcessSettleSuccessResponse, o as ProtectedRequestHook, R as RouteConfig, n as RouteConfigurationError, m as RouteValidationError, g as RoutesConfig, p as SETTLEMENT_OVERRIDES_HEADER, S as SettlementFailedResponseBody, U as UnpaidResponseBody, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-D9iYGDlY.mjs';
import {
HTTPFacilitatorClient,
RouteConfigurationError,
SETTLEMENT_OVERRIDES_HEADER,
x402HTTPResourceServer
} from "../chunk-ACVTKVCM.mjs";
} from "../chunk-JFGRL3BL.mjs";
import "../chunk-KMQH4MQI.mjs";

@@ -15,3 +16,3 @@ import {

getFacilitatorResponseError
} from "../chunk-VY72CEUI.mjs";
} from "../chunk-JUGE6MAI.mjs";
import {

@@ -24,2 +25,17 @@ deepEqual,

// src/server/x402ResourceServer.ts
function resolveSettlementOverrideAmount(rawAmount, requirements, decimals = 6) {
const percentMatch = rawAmount.match(/^(\d+(?:\.\d{0,2})?)%$/);
if (percentMatch) {
const [intPart, decPart = ""] = percentMatch[1].split(".");
const scaledPercent = BigInt(intPart) * 100n + BigInt(decPart.padEnd(2, "0").slice(0, 2));
const base = BigInt(requirements.amount);
return (base * scaledPercent / 10000n).toString();
}
const dollarMatch = rawAmount.match(/^\$(\d+(?:\.\d+)?)$/);
if (dollarMatch) {
const dollars = parseFloat(dollarMatch[1]);
return Math.round(dollars * 10 ** decimals).toString();
}
return rawAmount;
}
var x402ResourceServer = class {

@@ -496,8 +512,22 @@ /**

* @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)
* @param settlementOverrides - Optional overrides for settlement parameters (e.g., partial settlement amount)
* @returns Settlement response
*/
async settlePayment(paymentPayload, requirements, declaredExtensions, transportContext) {
async settlePayment(paymentPayload, requirements, declaredExtensions, transportContext, settlementOverrides) {
let effectiveRequirements = requirements;
if (settlementOverrides?.amount !== void 0) {
const scheme = findByNetworkAndScheme(
this.registeredServerSchemes,
requirements.scheme,
requirements.network
);
const decimals = scheme?.getAssetDecimals?.(requirements.asset ?? "", requirements.network) ?? 6;
effectiveRequirements = {
...requirements,
amount: resolveSettlementOverrideAmount(settlementOverrides.amount, requirements, decimals)
};
}
const context = {
paymentPayload,
requirements
requirements: effectiveRequirements
};

@@ -532,4 +562,4 @@ for (const hook of this.beforeSettleHooks) {

paymentPayload.x402Version,
requirements.network,
requirements.scheme
effectiveRequirements.network,
effectiveRequirements.scheme
);

@@ -541,3 +571,3 @@ let settleResult;

try {
settleResult = await client.settle(paymentPayload, requirements);
settleResult = await client.settle(paymentPayload, effectiveRequirements);
break;

@@ -550,7 +580,7 @@ } catch (error) {

throw lastError || new Error(
`No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`
`No facilitator supports ${effectiveRequirements.scheme} on ${effectiveRequirements.network} for v${paymentPayload.x402Version}`
);
}
} else {
settleResult = await facilitatorClient.settle(paymentPayload, requirements);
settleResult = await facilitatorClient.settle(paymentPayload, effectiveRequirements);
}

@@ -689,2 +719,3 @@ const resultContext = {

RouteConfigurationError,
SETTLEMENT_OVERRIDES_HEADER,
getFacilitatorResponseError,

@@ -691,0 +722,0 @@ x402HTTPResourceServer,

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/x402ResourceServer.ts"],"sourcesContent":["import {\n SettleError,\n SettleResponse,\n VerifyResponse,\n SupportedResponse,\n SupportedKind,\n} from \"../types/facilitator\";\nimport {\n PaymentPayload,\n PaymentRequirements,\n PaymentRequired,\n ResourceInfo,\n} from \"../types/payments\";\nimport { SchemeNetworkServer } from \"../types/mechanisms\";\nimport { Price, Network, ResourceServerExtension, VerifyError } from \"../types\";\nimport { deepEqual, findByNetworkAndScheme } from \"../utils\";\nimport { FacilitatorClient, HTTPFacilitatorClient } from \"../http/httpFacilitatorClient\";\nimport { x402Version } from \"..\";\n\n/**\n * Configuration for a protected resource\n * Only contains payment-specific configuration, not resource metadata\n */\nexport interface ResourceConfig {\n scheme: string;\n payTo: string; // Payment recipient address\n price: Price;\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>; // Scheme-specific additional data\n}\n\n/**\n * Lifecycle Hook Context Interfaces\n */\n\nexport interface PaymentRequiredContext {\n requirements: PaymentRequirements[];\n resourceInfo: ResourceInfo;\n error?: string;\n paymentRequiredResponse: PaymentRequired;\n transportContext?: unknown;\n}\n\nexport interface VerifyContext {\n paymentPayload: PaymentPayload;\n requirements: PaymentRequirements;\n}\n\nexport interface VerifyResultContext extends VerifyContext {\n result: VerifyResponse;\n}\n\nexport interface VerifyFailureContext extends VerifyContext {\n error: Error;\n}\n\nexport interface SettleContext {\n paymentPayload: PaymentPayload;\n requirements: PaymentRequirements;\n}\n\nexport interface SettleResultContext extends SettleContext {\n result: SettleResponse;\n transportContext?: unknown;\n}\n\nexport interface SettleFailureContext extends SettleContext {\n error: Error;\n}\n\n/**\n * Lifecycle Hook Type Definitions\n */\n\nexport type BeforeVerifyHook = (\n context: VerifyContext,\n) => Promise<void | { abort: true; reason: string; message?: string }>;\n\nexport type AfterVerifyHook = (context: VerifyResultContext) => Promise<void>;\n\nexport type OnVerifyFailureHook = (\n context: VerifyFailureContext,\n) => Promise<void | { recovered: true; result: VerifyResponse }>;\n\nexport type BeforeSettleHook = (\n context: SettleContext,\n) => Promise<void | { abort: true; reason: string; message?: string }>;\n\nexport type AfterSettleHook = (context: SettleResultContext) => Promise<void>;\n\nexport type OnSettleFailureHook = (\n context: SettleFailureContext,\n) => Promise<void | { recovered: true; result: SettleResponse }>;\n\n/**\n * Core x402 protocol server for resource protection\n * Transport-agnostic implementation of the x402 payment protocol\n */\nexport class x402ResourceServer {\n private facilitatorClients: FacilitatorClient[];\n private registeredServerSchemes: Map<string, Map<string, SchemeNetworkServer>> = new Map();\n private supportedResponsesMap: Map<number, Map<string, Map<string, SupportedResponse>>> =\n new Map();\n private facilitatorClientsMap: Map<number, Map<string, Map<string, FacilitatorClient>>> =\n new Map();\n private registeredExtensions: Map<string, ResourceServerExtension> = new Map();\n\n private beforeVerifyHooks: BeforeVerifyHook[] = [];\n private afterVerifyHooks: AfterVerifyHook[] = [];\n private onVerifyFailureHooks: OnVerifyFailureHook[] = [];\n private beforeSettleHooks: BeforeSettleHook[] = [];\n private afterSettleHooks: AfterSettleHook[] = [];\n private onSettleFailureHooks: OnSettleFailureHook[] = [];\n\n /**\n * Creates a new x402ResourceServer instance.\n *\n * @param facilitatorClients - Optional facilitator client(s) for payment processing\n */\n constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]) {\n // Normalize facilitator clients to array\n if (!facilitatorClients) {\n // No clients provided, create a default HTTP client\n this.facilitatorClients = [new HTTPFacilitatorClient()];\n } else if (Array.isArray(facilitatorClients)) {\n // Array of clients provided\n this.facilitatorClients =\n facilitatorClients.length > 0 ? facilitatorClients : [new HTTPFacilitatorClient()];\n } else {\n // Single client provided\n this.facilitatorClients = [facilitatorClients];\n }\n }\n\n /**\n * Register a scheme/network server implementation.\n *\n * @param network - The network identifier\n * @param server - The scheme/network server implementation\n * @returns The x402ResourceServer instance for chaining\n */\n register(network: Network, server: SchemeNetworkServer): x402ResourceServer {\n if (!this.registeredServerSchemes.has(network)) {\n this.registeredServerSchemes.set(network, new Map());\n }\n\n const serverByScheme = this.registeredServerSchemes.get(network)!;\n if (!serverByScheme.has(server.scheme)) {\n serverByScheme.set(server.scheme, server);\n }\n\n return this;\n }\n\n /**\n * Check if a scheme is registered for a given network.\n *\n * @param network - The network identifier\n * @param scheme - The payment scheme name\n * @returns True if the scheme is registered for the network, false otherwise\n */\n hasRegisteredScheme(network: Network, scheme: string): boolean {\n return !!findByNetworkAndScheme(this.registeredServerSchemes, scheme, network);\n }\n\n /**\n * Registers a resource service extension that can enrich extension declarations.\n *\n * @param extension - The extension to register\n * @returns The x402ResourceServer instance for chaining\n */\n registerExtension(extension: ResourceServerExtension): this {\n this.registeredExtensions.set(extension.key, extension);\n return this;\n }\n\n /**\n * Check if an extension is registered.\n *\n * @param key - The extension key\n * @returns True if the extension is registered\n */\n hasExtension(key: string): boolean {\n return this.registeredExtensions.has(key);\n }\n\n /**\n * Get all registered extensions.\n *\n * @returns Array of registered extensions\n */\n getExtensions(): ResourceServerExtension[] {\n return Array.from(this.registeredExtensions.values());\n }\n\n /**\n * Enriches declared extensions using registered extension hooks.\n *\n * @param declaredExtensions - Extensions declared on the route\n * @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)\n * @returns Enriched extensions map\n */\n enrichExtensions(\n declaredExtensions: Record<string, unknown>,\n transportContext: unknown,\n ): Record<string, unknown> {\n const enriched: Record<string, unknown> = {};\n\n for (const [key, declaration] of Object.entries(declaredExtensions)) {\n const extension = this.registeredExtensions.get(key);\n\n if (extension?.enrichDeclaration) {\n enriched[key] = extension.enrichDeclaration(declaration, transportContext);\n } else {\n enriched[key] = declaration;\n }\n }\n\n return enriched;\n }\n\n /**\n * Register a hook to execute before payment verification.\n * Can abort verification by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer {\n this.beforeVerifyHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment verification.\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onAfterVerify(hook: AfterVerifyHook): x402ResourceServer {\n this.afterVerifyHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment verification fails.\n * Can recover from failure by returning { recovered: true, result: VerifyResponse }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer {\n this.onVerifyFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute before payment settlement.\n * Can abort settlement by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer {\n this.beforeSettleHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment settlement.\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onAfterSettle(hook: AfterSettleHook): x402ResourceServer {\n this.afterSettleHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment settlement fails.\n * Can recover from failure by returning { recovered: true, result: SettleResponse }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer {\n this.onSettleFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Initialize by fetching supported kinds from all facilitators\n * Creates mappings for supported responses and facilitator clients\n * Earlier facilitators in the array get precedence\n */\n async initialize(): Promise<void> {\n // Clear existing mappings\n this.supportedResponsesMap.clear();\n this.facilitatorClientsMap.clear();\n let lastError: Error | undefined;\n\n // Fetch supported kinds from all facilitator clients\n // Process in order to give precedence to earlier facilitators\n for (const facilitatorClient of this.facilitatorClients) {\n try {\n const supported = await facilitatorClient.getSupported();\n\n // Process each supported kind (now flat array with version in each element)\n for (const kind of supported.kinds) {\n const x402Version = kind.x402Version;\n\n // Get or create version map for supported responses\n if (!this.supportedResponsesMap.has(x402Version)) {\n this.supportedResponsesMap.set(x402Version, new Map());\n }\n const responseVersionMap = this.supportedResponsesMap.get(x402Version)!;\n\n // Get or create version map for facilitator clients\n if (!this.facilitatorClientsMap.has(x402Version)) {\n this.facilitatorClientsMap.set(x402Version, new Map());\n }\n const clientVersionMap = this.facilitatorClientsMap.get(x402Version)!;\n\n // Get or create network map for responses\n if (!responseVersionMap.has(kind.network)) {\n responseVersionMap.set(kind.network, new Map());\n }\n const responseNetworkMap = responseVersionMap.get(kind.network)!;\n\n // Get or create network map for clients\n if (!clientVersionMap.has(kind.network)) {\n clientVersionMap.set(kind.network, new Map());\n }\n const clientNetworkMap = clientVersionMap.get(kind.network)!;\n\n // Only store if not already present (gives precedence to earlier facilitators)\n if (!responseNetworkMap.has(kind.scheme)) {\n responseNetworkMap.set(kind.scheme, supported);\n clientNetworkMap.set(kind.scheme, facilitatorClient);\n }\n }\n } catch (error) {\n lastError = error as Error;\n // Log error but continue with other facilitators\n console.warn(`Failed to fetch supported kinds from facilitator: ${error}`);\n }\n }\n\n if (this.supportedResponsesMap.size === 0) {\n throw lastError\n ? new Error(\n \"Failed to initialize: no supported payment kinds loaded from any facilitator.\",\n {\n cause: lastError,\n },\n )\n : new Error(\n \"Failed to initialize: no supported payment kinds loaded from any facilitator.\",\n );\n }\n }\n\n /**\n * Get supported kind for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The supported kind or undefined if not found\n */\n getSupportedKind(\n x402Version: number,\n network: Network,\n scheme: string,\n ): SupportedKind | undefined {\n const versionMap = this.supportedResponsesMap.get(x402Version);\n if (!versionMap) return undefined;\n\n const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);\n if (!supportedResponse) return undefined;\n\n // Find the specific kind from the response (kinds are flat array with version in each element)\n return supportedResponse.kinds.find(\n kind =>\n kind.x402Version === x402Version && kind.network === network && kind.scheme === scheme,\n );\n }\n\n /**\n * Get facilitator extensions for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The facilitator extensions or empty array if not found\n */\n getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[] {\n const versionMap = this.supportedResponsesMap.get(x402Version);\n if (!versionMap) return [];\n\n const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);\n return supportedResponse?.extensions || [];\n }\n\n /**\n * Build payment requirements for a protected resource\n *\n * @param resourceConfig - Configuration for the protected resource\n * @returns Array of payment requirements\n */\n async buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]> {\n const requirements: PaymentRequirements[] = [];\n\n // Find the matching server implementation\n const scheme = resourceConfig.scheme;\n const SchemeNetworkServer = findByNetworkAndScheme(\n this.registeredServerSchemes,\n scheme,\n resourceConfig.network,\n );\n\n if (!SchemeNetworkServer) {\n // Fallback to placeholder implementation if no server registered\n // TODO: Remove this fallback once implementations are registered\n console.warn(\n `No server implementation registered for scheme: ${scheme}, network: ${resourceConfig.network}`,\n );\n return requirements;\n }\n\n // Find the matching supported kind from facilitator\n const supportedKind = this.getSupportedKind(\n x402Version,\n resourceConfig.network,\n SchemeNetworkServer.scheme,\n );\n\n if (!supportedKind) {\n throw new Error(\n `Facilitator does not support ${SchemeNetworkServer.scheme} on ${resourceConfig.network}. ` +\n `Make sure to call initialize() to fetch supported kinds from facilitators.`,\n );\n }\n\n // Get facilitator extensions for this combination\n const facilitatorExtensions = this.getFacilitatorExtensions(\n x402Version,\n resourceConfig.network,\n SchemeNetworkServer.scheme,\n );\n\n // Parse the price using the scheme's price parser\n const parsedPrice = await SchemeNetworkServer.parsePrice(\n resourceConfig.price,\n resourceConfig.network,\n );\n\n // Build base payment requirements from resource config\n const baseRequirements: PaymentRequirements = {\n scheme: SchemeNetworkServer.scheme,\n network: resourceConfig.network,\n amount: parsedPrice.amount,\n asset: parsedPrice.asset,\n payTo: resourceConfig.payTo,\n maxTimeoutSeconds: resourceConfig.maxTimeoutSeconds || 300, // Default 5 minutes\n extra: {\n ...parsedPrice.extra,\n ...resourceConfig.extra, // Merge user-provided extra\n },\n };\n\n // Delegate to the implementation for scheme-specific enhancements\n // Note: enhancePaymentRequirements expects x402Version in the kind, so we add it back\n const requirement = await SchemeNetworkServer.enhancePaymentRequirements(\n baseRequirements,\n {\n ...supportedKind,\n x402Version,\n },\n facilitatorExtensions,\n );\n\n requirements.push(requirement);\n return requirements;\n }\n\n /**\n * Build payment requirements from multiple payment options\n * This method handles resolving dynamic payTo/price functions and builds requirements for each option\n *\n * @param paymentOptions - Array of payment options to convert\n * @param context - HTTP request context for resolving dynamic functions\n * @returns Array of payment requirements (one per option)\n */\n async buildPaymentRequirementsFromOptions<TContext = unknown>(\n paymentOptions: Array<{\n scheme: string;\n payTo: string | ((context: TContext) => string | Promise<string>);\n price: Price | ((context: TContext) => Price | Promise<Price>);\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>;\n }>,\n context: TContext,\n ): Promise<PaymentRequirements[]> {\n const allRequirements: PaymentRequirements[] = [];\n\n for (const option of paymentOptions) {\n // Resolve dynamic payTo and price if they are functions\n const resolvedPayTo =\n typeof option.payTo === \"function\" ? await option.payTo(context) : option.payTo;\n const resolvedPrice =\n typeof option.price === \"function\" ? await option.price(context) : option.price;\n\n const resourceConfig: ResourceConfig = {\n scheme: option.scheme,\n payTo: resolvedPayTo,\n price: resolvedPrice,\n network: option.network,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n extra: option.extra,\n };\n\n // Use existing buildPaymentRequirements for each option\n const requirements = await this.buildPaymentRequirements(resourceConfig);\n allRequirements.push(...requirements);\n }\n\n return allRequirements;\n }\n\n /**\n * Create a payment required response\n *\n * @param requirements - Payment requirements\n * @param resourceInfo - Resource information\n * @param error - Error message\n * @param extensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional transport-specific context (e.g., HTTP request, MCP tool context)\n * @returns Payment required response object\n */\n async createPaymentRequiredResponse(\n requirements: PaymentRequirements[],\n resourceInfo: ResourceInfo,\n error?: string,\n extensions?: Record<string, unknown>,\n transportContext?: unknown,\n ): Promise<PaymentRequired> {\n // V2 response with resource at top level\n let response: PaymentRequired = {\n x402Version: 2,\n error,\n resource: resourceInfo,\n accepts: requirements as PaymentRequirements[],\n };\n\n // Add extensions if provided\n if (extensions && Object.keys(extensions).length > 0) {\n response.extensions = extensions;\n }\n\n // Let declared extensions add data to PaymentRequired response\n if (extensions) {\n for (const [key, declaration] of Object.entries(extensions)) {\n const extension = this.registeredExtensions.get(key);\n if (extension?.enrichPaymentRequiredResponse) {\n try {\n const context: PaymentRequiredContext = {\n requirements,\n resourceInfo,\n error,\n paymentRequiredResponse: response,\n transportContext,\n };\n const extensionData = await extension.enrichPaymentRequiredResponse(\n declaration,\n context,\n );\n if (extensionData !== undefined) {\n if (!response.extensions) {\n response.extensions = {};\n }\n response.extensions[key] = extensionData;\n }\n } catch (error) {\n console.error(\n `Error in enrichPaymentRequiredResponse hook for extension ${key}:`,\n error,\n );\n }\n }\n }\n }\n\n return response;\n }\n\n /**\n * Verify a payment against requirements\n *\n * @param paymentPayload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Verification response\n */\n async verifyPayment(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const context: VerifyContext = {\n paymentPayload,\n requirements,\n };\n\n // Execute beforeVerify hooks\n for (const hook of this.beforeVerifyHooks) {\n try {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n return {\n isValid: false,\n invalidReason: result.reason,\n invalidMessage: result.message,\n };\n }\n } catch (error) {\n throw new VerifyError(400, {\n isValid: false,\n invalidReason: \"before_verify_hook_error\",\n invalidMessage: error instanceof Error ? error.message : \"\",\n });\n }\n }\n\n try {\n // Find the facilitator that supports this payment type\n const facilitatorClient = this.getFacilitatorClient(\n paymentPayload.x402Version,\n requirements.network,\n requirements.scheme,\n );\n\n let verifyResult: VerifyResponse;\n\n if (!facilitatorClient) {\n // Fallback: try all facilitators if no specific support found\n let lastError: Error | undefined;\n\n for (const client of this.facilitatorClients) {\n try {\n verifyResult = await client.verify(paymentPayload, requirements);\n break;\n } catch (error) {\n lastError = error as Error;\n }\n }\n\n if (!verifyResult!) {\n throw (\n lastError ||\n new Error(\n `No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`,\n )\n );\n }\n } else {\n // Use the specific facilitator that supports this payment\n verifyResult = await facilitatorClient.verify(paymentPayload, requirements);\n }\n\n // Execute afterVerify hooks\n const resultContext: VerifyResultContext = {\n ...context,\n result: verifyResult,\n };\n\n for (const hook of this.afterVerifyHooks) {\n await hook(resultContext);\n }\n\n return verifyResult;\n } catch (error) {\n const failureContext: VerifyFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onVerifyFailure hooks\n for (const hook of this.onVerifyFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.result;\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Settle a verified payment\n *\n * @param paymentPayload - The payment payload to settle\n * @param requirements - The payment requirements\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)\n * @returns Settlement response\n */\n async settlePayment(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n transportContext?: unknown,\n ): Promise<SettleResponse> {\n const context: SettleContext = {\n paymentPayload,\n requirements,\n };\n\n // Execute beforeSettle hooks\n for (const hook of this.beforeSettleHooks) {\n try {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new SettleError(400, {\n success: false,\n errorReason: result.reason,\n errorMessage: result.message,\n transaction: \"\",\n network: requirements.network,\n });\n }\n } catch (error) {\n if (error instanceof SettleError) {\n throw error;\n }\n throw new SettleError(400, {\n success: false,\n errorReason: \"before_settle_hook_error\",\n errorMessage: error instanceof Error ? error.message : \"\",\n transaction: \"\",\n network: requirements.network,\n });\n }\n }\n\n try {\n // Find the facilitator that supports this payment type\n const facilitatorClient = this.getFacilitatorClient(\n paymentPayload.x402Version,\n requirements.network,\n requirements.scheme,\n );\n\n let settleResult: SettleResponse;\n\n if (!facilitatorClient) {\n // Fallback: try all facilitators if no specific support found\n let lastError: Error | undefined;\n\n for (const client of this.facilitatorClients) {\n try {\n settleResult = await client.settle(paymentPayload, requirements);\n break;\n } catch (error) {\n lastError = error as Error;\n }\n }\n\n if (!settleResult!) {\n throw (\n lastError ||\n new Error(\n `No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`,\n )\n );\n }\n } else {\n // Use the specific facilitator that supports this payment\n settleResult = await facilitatorClient.settle(paymentPayload, requirements);\n }\n\n // Execute afterSettle hooks\n const resultContext: SettleResultContext = {\n ...context,\n result: settleResult,\n transportContext,\n };\n\n for (const hook of this.afterSettleHooks) {\n await hook(resultContext);\n }\n\n // Let declared extensions add data to settlement response\n if (declaredExtensions) {\n for (const [key, declaration] of Object.entries(declaredExtensions)) {\n const extension = this.registeredExtensions.get(key);\n if (extension?.enrichSettlementResponse) {\n try {\n const extensionData = await extension.enrichSettlementResponse(\n declaration,\n resultContext,\n );\n if (extensionData !== undefined) {\n if (!settleResult.extensions) {\n settleResult.extensions = {};\n }\n settleResult.extensions[key] = extensionData;\n }\n } catch (error) {\n console.error(`Error in enrichSettlementResponse hook for extension ${key}:`, error);\n }\n }\n }\n }\n\n return settleResult;\n } catch (error) {\n const failureContext: SettleFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onSettleFailure hooks\n for (const hook of this.onSettleFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.result;\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Find matching payment requirements for a payment\n *\n * @param availableRequirements - Array of available payment requirements\n * @param paymentPayload - The payment payload\n * @returns Matching payment requirements or undefined\n */\n findMatchingRequirements(\n availableRequirements: PaymentRequirements[],\n paymentPayload: PaymentPayload,\n ): PaymentRequirements | undefined {\n switch (paymentPayload.x402Version) {\n case 2:\n // For v2, match by accepted requirements\n return availableRequirements.find(paymentRequirements =>\n deepEqual(paymentRequirements, paymentPayload.accepted),\n );\n case 1:\n // For v1, match by scheme and network\n return availableRequirements.find(\n req =>\n req.scheme === paymentPayload.accepted.scheme &&\n req.network === paymentPayload.accepted.network,\n );\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Process a payment request\n *\n * @param paymentPayload - Optional payment payload if provided\n * @param resourceConfig - Configuration for the protected resource\n * @param resourceInfo - Information about the resource being accessed\n * @param extensions - Optional extensions to include in the response\n * @returns Processing result\n */\n async processPaymentRequest(\n paymentPayload: PaymentPayload | null,\n resourceConfig: ResourceConfig,\n resourceInfo: ResourceInfo,\n extensions?: Record<string, unknown>,\n ): Promise<{\n success: boolean;\n requiresPayment?: PaymentRequired;\n verificationResult?: VerifyResponse;\n settlementResult?: SettleResponse;\n error?: string;\n }> {\n const requirements = await this.buildPaymentRequirements(resourceConfig);\n\n if (!paymentPayload) {\n return {\n success: false,\n requiresPayment: await this.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"Payment required\",\n extensions,\n ),\n };\n }\n\n // Find matching requirements\n const matchingRequirements = this.findMatchingRequirements(requirements, paymentPayload);\n if (!matchingRequirements) {\n return {\n success: false,\n requiresPayment: await this.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"No matching payment requirements found\",\n extensions,\n ),\n };\n }\n\n // Verify payment\n const verificationResult = await this.verifyPayment(paymentPayload, matchingRequirements);\n if (!verificationResult.isValid) {\n return {\n success: false,\n error: verificationResult.invalidReason,\n verificationResult,\n };\n }\n\n // Payment verified, ready for settlement\n return {\n success: true,\n verificationResult,\n };\n }\n\n /**\n * Get facilitator client for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The facilitator client or undefined if not found\n */\n private getFacilitatorClient(\n x402Version: number,\n network: Network,\n scheme: string,\n ): FacilitatorClient | undefined {\n const versionMap = this.facilitatorClientsMap.get(x402Version);\n if (!versionMap) return undefined;\n\n // Use findByNetworkAndScheme for pattern matching\n return findByNetworkAndScheme(versionMap, scheme, network);\n }\n}\n\nexport default x402ResourceServer;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmGO,IAAM,qBAAN,MAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqB9B,YAAY,oBAA8D;AAnB1E,SAAQ,0BAAyE,oBAAI,IAAI;AACzF,SAAQ,wBACN,oBAAI,IAAI;AACV,SAAQ,wBACN,oBAAI,IAAI;AACV,SAAQ,uBA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AAkC,WAAW;AAAA,QAC7E;AAAA,IACJ;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,sBACJ,gBACA,gBACA,cACA,YAOC;AACD,UAAM,eAAe,MAAM,KAAK,yBAAyB,cAAc;AAEvE,QAAI,CAAC,gBAAgB;AACnB,aAAO;AAAA,QACL,SAAS;AAAA,QACT,iBAAiB,MAAM,KAAK;AAAA,UAC1B;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,UAAM,uBAAuB,KAAK,yBAAyB,cAAc,cAAc;AACvF,QAAI,CAAC,sBAAsB;AACzB,aAAO;AAAA,QACL,SAAS;AAAA,QACT,iBAAiB,MAAM,KAAK;AAAA,UAC1B;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,UAAM,qBAAqB,MAAM,KAAK,cAAc,gBAAgB,oBAAoB;AACxF,QAAI,CAAC,mBAAmB,SAAS;AAC/B,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,mBAAmB;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAGA,WAAO;AAAA,MACL,SAAS;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,qBACND,cACA,SACA,QAC+B;AAC/B,UAAM,aAAa,KAAK,sBAAsB,IAAIA,YAAW;AAC7D,QAAI,CAAC,WAAY,QAAO;AAGxB,WAAO,uBAAuB,YAAY,QAAQ,OAAO;AAAA,EAC3D;AACF;","names":["x402Version","error"]}
{"version":3,"sources":["../../../src/server/x402ResourceServer.ts"],"sourcesContent":["import {\n SettleError,\n SettleResponse,\n VerifyResponse,\n SupportedResponse,\n SupportedKind,\n} from \"../types/facilitator\";\nimport {\n PaymentPayload,\n PaymentRequirements,\n PaymentRequired,\n ResourceInfo,\n} from \"../types/payments\";\nimport { SchemeNetworkServer } from \"../types/mechanisms\";\nimport { Price, Network, ResourceServerExtension, VerifyError } from \"../types\";\nimport { deepEqual, findByNetworkAndScheme } from \"../utils\";\nimport { FacilitatorClient, HTTPFacilitatorClient } from \"../http/httpFacilitatorClient\";\nimport { x402Version } from \"..\";\n\n/**\n * Configuration for a protected resource\n * Only contains payment-specific configuration, not resource metadata\n */\nexport interface ResourceConfig {\n scheme: string;\n payTo: string; // Payment recipient address\n price: Price;\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>; // Scheme-specific additional data\n}\n\n/**\n * Lifecycle Hook Context Interfaces\n */\n\nexport interface PaymentRequiredContext {\n requirements: PaymentRequirements[];\n resourceInfo: ResourceInfo;\n error?: string;\n paymentRequiredResponse: PaymentRequired;\n transportContext?: unknown;\n}\n\nexport interface VerifyContext {\n paymentPayload: PaymentPayload;\n requirements: PaymentRequirements;\n}\n\nexport interface VerifyResultContext extends VerifyContext {\n result: VerifyResponse;\n}\n\nexport interface VerifyFailureContext extends VerifyContext {\n error: Error;\n}\n\nexport interface SettleContext {\n paymentPayload: PaymentPayload;\n requirements: PaymentRequirements;\n}\n\nexport interface SettleResultContext extends SettleContext {\n result: SettleResponse;\n transportContext?: unknown;\n}\n\nexport interface SettleFailureContext extends SettleContext {\n error: Error;\n}\n\n/**\n * Lifecycle Hook Type Definitions\n */\n\nexport type BeforeVerifyHook = (\n context: VerifyContext,\n) => Promise<void | { abort: true; reason: string; message?: string }>;\n\nexport type AfterVerifyHook = (context: VerifyResultContext) => Promise<void>;\n\nexport type OnVerifyFailureHook = (\n context: VerifyFailureContext,\n) => Promise<void | { recovered: true; result: VerifyResponse }>;\n\nexport type BeforeSettleHook = (\n context: SettleContext,\n) => Promise<void | { abort: true; reason: string; message?: string }>;\n\nexport type AfterSettleHook = (context: SettleResultContext) => Promise<void>;\n\nexport type OnSettleFailureHook = (\n context: SettleFailureContext,\n) => Promise<void | { recovered: true; result: SettleResponse }>;\n\n/**\n * Optional overrides for settlement parameters.\n * Used to support partial settlement (e.g., upto scheme billing by actual usage).\n *\n * Note: Overriding the amount to a value different from the agreed-upon\n * `PaymentRequirements.amount` is only valid in schemes that explicitly support\n * partial settlement, such as the `upto` scheme. Using this with standard\n * x402 schemes (e.g., `exact`) will likely cause settlement verification to fail.\n */\nexport interface SettlementOverrides {\n /**\n * Amount to settle. Supports three formats:\n *\n * - **Raw atomic units** — e.g., `\"1000\"` settles exactly 1000 atomic units.\n * - **Percent** — e.g., `\"50%\"` settles 50% of `PaymentRequirements.amount`.\n * Supports up to two decimal places (e.g., `\"33.33%\"`). The result is floored\n * to the nearest atomic unit.\n * - **Dollar price** — e.g., `\"$0.05\"` converts a USD-denominated price to\n * atomic units. Decimals are determined from the registered scheme's\n * `getAssetDecimals` method, falling back to 6 (standard for USDC stablecoins).\n * The result is rounded to the nearest atomic unit.\n *\n * The resolved amount must be <= the authorized maximum in `PaymentRequirements`.\n *\n * Note: Setting this to an amount other than `PaymentRequirements.amount` is\n * only valid in schemes that support partial settlement, such as `upto`.\n */\n amount?: string;\n}\n\n/**\n * Resolves a settlement override amount string to a final atomic-unit string.\n *\n * Supports three input formats (see {@link SettlementOverrides.amount}):\n * - Raw atomic units: `\"1000\"`\n * - Percent of `PaymentRequirements.amount`: `\"50%\"`\n * - Dollar price: `\"$0.05\"` (converted using the provided decimals)\n *\n * @param rawAmount - The override amount string (e.g., `\"1000\"`, `\"50%\"`, `\"$0.05\"`)\n * @param requirements - The payment requirements containing the base amount\n * @param decimals - Decimal precision to use for dollar-format conversion (default 6)\n * @returns The resolved amount as an atomic-unit string\n */\nexport function resolveSettlementOverrideAmount(\n rawAmount: string,\n requirements: PaymentRequirements,\n decimals: number = 6,\n): string {\n // Percent format: \"50%\" or \"33.33%\"\n const percentMatch = rawAmount.match(/^(\\d+(?:\\.\\d{0,2})?)%$/);\n if (percentMatch) {\n const [intPart, decPart = \"\"] = percentMatch[1].split(\".\");\n const scaledPercent = BigInt(intPart) * 100n + BigInt(decPart.padEnd(2, \"0\").slice(0, 2));\n const base = BigInt(requirements.amount);\n return ((base * scaledPercent) / 10000n).toString();\n }\n\n // Dollar price format: \"$0.05\"\n const dollarMatch = rawAmount.match(/^\\$(\\d+(?:\\.\\d+)?)$/);\n if (dollarMatch) {\n const dollars = parseFloat(dollarMatch[1]);\n return Math.round(dollars * 10 ** decimals).toString();\n }\n\n // Raw atomic units (existing behavior)\n return rawAmount;\n}\n\n/**\n * Core x402 protocol server for resource protection\n * Transport-agnostic implementation of the x402 payment protocol\n */\nexport class x402ResourceServer {\n private facilitatorClients: FacilitatorClient[];\n private registeredServerSchemes: Map<string, Map<string, SchemeNetworkServer>> = new Map();\n private supportedResponsesMap: Map<number, Map<string, Map<string, SupportedResponse>>> =\n new Map();\n private facilitatorClientsMap: Map<number, Map<string, Map<string, FacilitatorClient>>> =\n new Map();\n private registeredExtensions: Map<string, ResourceServerExtension> = new Map();\n\n private beforeVerifyHooks: BeforeVerifyHook[] = [];\n private afterVerifyHooks: AfterVerifyHook[] = [];\n private onVerifyFailureHooks: OnVerifyFailureHook[] = [];\n private beforeSettleHooks: BeforeSettleHook[] = [];\n private afterSettleHooks: AfterSettleHook[] = [];\n private onSettleFailureHooks: OnSettleFailureHook[] = [];\n\n /**\n * Creates a new x402ResourceServer instance.\n *\n * @param facilitatorClients - Optional facilitator client(s) for payment processing\n */\n constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]) {\n // Normalize facilitator clients to array\n if (!facilitatorClients) {\n // No clients provided, create a default HTTP client\n this.facilitatorClients = [new HTTPFacilitatorClient()];\n } else if (Array.isArray(facilitatorClients)) {\n // Array of clients provided\n this.facilitatorClients =\n facilitatorClients.length > 0 ? facilitatorClients : [new HTTPFacilitatorClient()];\n } else {\n // Single client provided\n this.facilitatorClients = [facilitatorClients];\n }\n }\n\n /**\n * Register a scheme/network server implementation.\n *\n * @param network - The network identifier\n * @param server - The scheme/network server implementation\n * @returns The x402ResourceServer instance for chaining\n */\n register(network: Network, server: SchemeNetworkServer): x402ResourceServer {\n if (!this.registeredServerSchemes.has(network)) {\n this.registeredServerSchemes.set(network, new Map());\n }\n\n const serverByScheme = this.registeredServerSchemes.get(network)!;\n if (!serverByScheme.has(server.scheme)) {\n serverByScheme.set(server.scheme, server);\n }\n\n return this;\n }\n\n /**\n * Check if a scheme is registered for a given network.\n *\n * @param network - The network identifier\n * @param scheme - The payment scheme name\n * @returns True if the scheme is registered for the network, false otherwise\n */\n hasRegisteredScheme(network: Network, scheme: string): boolean {\n return !!findByNetworkAndScheme(this.registeredServerSchemes, scheme, network);\n }\n\n /**\n * Registers a resource service extension that can enrich extension declarations.\n *\n * @param extension - The extension to register\n * @returns The x402ResourceServer instance for chaining\n */\n registerExtension(extension: ResourceServerExtension): this {\n this.registeredExtensions.set(extension.key, extension);\n return this;\n }\n\n /**\n * Check if an extension is registered.\n *\n * @param key - The extension key\n * @returns True if the extension is registered\n */\n hasExtension(key: string): boolean {\n return this.registeredExtensions.has(key);\n }\n\n /**\n * Get all registered extensions.\n *\n * @returns Array of registered extensions\n */\n getExtensions(): ResourceServerExtension[] {\n return Array.from(this.registeredExtensions.values());\n }\n\n /**\n * Enriches declared extensions using registered extension hooks.\n *\n * @param declaredExtensions - Extensions declared on the route\n * @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)\n * @returns Enriched extensions map\n */\n enrichExtensions(\n declaredExtensions: Record<string, unknown>,\n transportContext: unknown,\n ): Record<string, unknown> {\n const enriched: Record<string, unknown> = {};\n\n for (const [key, declaration] of Object.entries(declaredExtensions)) {\n const extension = this.registeredExtensions.get(key);\n\n if (extension?.enrichDeclaration) {\n enriched[key] = extension.enrichDeclaration(declaration, transportContext);\n } else {\n enriched[key] = declaration;\n }\n }\n\n return enriched;\n }\n\n /**\n * Register a hook to execute before payment verification.\n * Can abort verification by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer {\n this.beforeVerifyHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment verification.\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onAfterVerify(hook: AfterVerifyHook): x402ResourceServer {\n this.afterVerifyHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment verification fails.\n * Can recover from failure by returning { recovered: true, result: VerifyResponse }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer {\n this.onVerifyFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute before payment settlement.\n * Can abort settlement by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer {\n this.beforeSettleHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment settlement.\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onAfterSettle(hook: AfterSettleHook): x402ResourceServer {\n this.afterSettleHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment settlement fails.\n * Can recover from failure by returning { recovered: true, result: SettleResponse }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer {\n this.onSettleFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Initialize by fetching supported kinds from all facilitators\n * Creates mappings for supported responses and facilitator clients\n * Earlier facilitators in the array get precedence\n */\n async initialize(): Promise<void> {\n // Clear existing mappings\n this.supportedResponsesMap.clear();\n this.facilitatorClientsMap.clear();\n let lastError: Error | undefined;\n\n // Fetch supported kinds from all facilitator clients\n // Process in order to give precedence to earlier facilitators\n for (const facilitatorClient of this.facilitatorClients) {\n try {\n const supported = await facilitatorClient.getSupported();\n\n // Process each supported kind (now flat array with version in each element)\n for (const kind of supported.kinds) {\n const x402Version = kind.x402Version;\n\n // Get or create version map for supported responses\n if (!this.supportedResponsesMap.has(x402Version)) {\n this.supportedResponsesMap.set(x402Version, new Map());\n }\n const responseVersionMap = this.supportedResponsesMap.get(x402Version)!;\n\n // Get or create version map for facilitator clients\n if (!this.facilitatorClientsMap.has(x402Version)) {\n this.facilitatorClientsMap.set(x402Version, new Map());\n }\n const clientVersionMap = this.facilitatorClientsMap.get(x402Version)!;\n\n // Get or create network map for responses\n if (!responseVersionMap.has(kind.network)) {\n responseVersionMap.set(kind.network, new Map());\n }\n const responseNetworkMap = responseVersionMap.get(kind.network)!;\n\n // Get or create network map for clients\n if (!clientVersionMap.has(kind.network)) {\n clientVersionMap.set(kind.network, new Map());\n }\n const clientNetworkMap = clientVersionMap.get(kind.network)!;\n\n // Only store if not already present (gives precedence to earlier facilitators)\n if (!responseNetworkMap.has(kind.scheme)) {\n responseNetworkMap.set(kind.scheme, supported);\n clientNetworkMap.set(kind.scheme, facilitatorClient);\n }\n }\n } catch (error) {\n lastError = error as Error;\n // Log error but continue with other facilitators\n console.warn(`Failed to fetch supported kinds from facilitator: ${error}`);\n }\n }\n\n if (this.supportedResponsesMap.size === 0) {\n throw lastError\n ? new Error(\n \"Failed to initialize: no supported payment kinds loaded from any facilitator.\",\n {\n cause: lastError,\n },\n )\n : new Error(\n \"Failed to initialize: no supported payment kinds loaded from any facilitator.\",\n );\n }\n }\n\n /**\n * Get supported kind for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The supported kind or undefined if not found\n */\n getSupportedKind(\n x402Version: number,\n network: Network,\n scheme: string,\n ): SupportedKind | undefined {\n const versionMap = this.supportedResponsesMap.get(x402Version);\n if (!versionMap) return undefined;\n\n const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);\n if (!supportedResponse) return undefined;\n\n // Find the specific kind from the response (kinds are flat array with version in each element)\n return supportedResponse.kinds.find(\n kind =>\n kind.x402Version === x402Version && kind.network === network && kind.scheme === scheme,\n );\n }\n\n /**\n * Get facilitator extensions for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The facilitator extensions or empty array if not found\n */\n getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[] {\n const versionMap = this.supportedResponsesMap.get(x402Version);\n if (!versionMap) return [];\n\n const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);\n return supportedResponse?.extensions || [];\n }\n\n /**\n * Build payment requirements for a protected resource\n *\n * @param resourceConfig - Configuration for the protected resource\n * @returns Array of payment requirements\n */\n async buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]> {\n const requirements: PaymentRequirements[] = [];\n\n // Find the matching server implementation\n const scheme = resourceConfig.scheme;\n const SchemeNetworkServer = findByNetworkAndScheme(\n this.registeredServerSchemes,\n scheme,\n resourceConfig.network,\n );\n\n if (!SchemeNetworkServer) {\n // Fallback to placeholder implementation if no server registered\n // TODO: Remove this fallback once implementations are registered\n console.warn(\n `No server implementation registered for scheme: ${scheme}, network: ${resourceConfig.network}`,\n );\n return requirements;\n }\n\n // Find the matching supported kind from facilitator\n const supportedKind = this.getSupportedKind(\n x402Version,\n resourceConfig.network,\n SchemeNetworkServer.scheme,\n );\n\n if (!supportedKind) {\n throw new Error(\n `Facilitator does not support ${SchemeNetworkServer.scheme} on ${resourceConfig.network}. ` +\n `Make sure to call initialize() to fetch supported kinds from facilitators.`,\n );\n }\n\n // Get facilitator extensions for this combination\n const facilitatorExtensions = this.getFacilitatorExtensions(\n x402Version,\n resourceConfig.network,\n SchemeNetworkServer.scheme,\n );\n\n // Parse the price using the scheme's price parser\n const parsedPrice = await SchemeNetworkServer.parsePrice(\n resourceConfig.price,\n resourceConfig.network,\n );\n\n // Build base payment requirements from resource config\n const baseRequirements: PaymentRequirements = {\n scheme: SchemeNetworkServer.scheme,\n network: resourceConfig.network,\n amount: parsedPrice.amount,\n asset: parsedPrice.asset,\n payTo: resourceConfig.payTo,\n maxTimeoutSeconds: resourceConfig.maxTimeoutSeconds || 300, // Default 5 minutes\n extra: {\n ...parsedPrice.extra,\n ...resourceConfig.extra, // Merge user-provided extra\n },\n };\n\n // Delegate to the implementation for scheme-specific enhancements\n // Note: enhancePaymentRequirements expects x402Version in the kind, so we add it back\n const requirement = await SchemeNetworkServer.enhancePaymentRequirements(\n baseRequirements,\n {\n ...supportedKind,\n x402Version,\n },\n facilitatorExtensions,\n );\n\n requirements.push(requirement);\n return requirements;\n }\n\n /**\n * Build payment requirements from multiple payment options\n * This method handles resolving dynamic payTo/price functions and builds requirements for each option\n *\n * @param paymentOptions - Array of payment options to convert\n * @param context - HTTP request context for resolving dynamic functions\n * @returns Array of payment requirements (one per option)\n */\n async buildPaymentRequirementsFromOptions<TContext = unknown>(\n paymentOptions: Array<{\n scheme: string;\n payTo: string | ((context: TContext) => string | Promise<string>);\n price: Price | ((context: TContext) => Price | Promise<Price>);\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>;\n }>,\n context: TContext,\n ): Promise<PaymentRequirements[]> {\n const allRequirements: PaymentRequirements[] = [];\n\n for (const option of paymentOptions) {\n // Resolve dynamic payTo and price if they are functions\n const resolvedPayTo =\n typeof option.payTo === \"function\" ? await option.payTo(context) : option.payTo;\n const resolvedPrice =\n typeof option.price === \"function\" ? await option.price(context) : option.price;\n\n const resourceConfig: ResourceConfig = {\n scheme: option.scheme,\n payTo: resolvedPayTo,\n price: resolvedPrice,\n network: option.network,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n extra: option.extra,\n };\n\n // Use existing buildPaymentRequirements for each option\n const requirements = await this.buildPaymentRequirements(resourceConfig);\n allRequirements.push(...requirements);\n }\n\n return allRequirements;\n }\n\n /**\n * Create a payment required response\n *\n * @param requirements - Payment requirements\n * @param resourceInfo - Resource information\n * @param error - Error message\n * @param extensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional transport-specific context (e.g., HTTP request, MCP tool context)\n * @returns Payment required response object\n */\n async createPaymentRequiredResponse(\n requirements: PaymentRequirements[],\n resourceInfo: ResourceInfo,\n error?: string,\n extensions?: Record<string, unknown>,\n transportContext?: unknown,\n ): Promise<PaymentRequired> {\n // V2 response with resource at top level\n let response: PaymentRequired = {\n x402Version: 2,\n error,\n resource: resourceInfo,\n accepts: requirements as PaymentRequirements[],\n };\n\n // Add extensions if provided\n if (extensions && Object.keys(extensions).length > 0) {\n response.extensions = extensions;\n }\n\n // Let declared extensions add data to PaymentRequired response\n if (extensions) {\n for (const [key, declaration] of Object.entries(extensions)) {\n const extension = this.registeredExtensions.get(key);\n if (extension?.enrichPaymentRequiredResponse) {\n try {\n const context: PaymentRequiredContext = {\n requirements,\n resourceInfo,\n error,\n paymentRequiredResponse: response,\n transportContext,\n };\n const extensionData = await extension.enrichPaymentRequiredResponse(\n declaration,\n context,\n );\n if (extensionData !== undefined) {\n if (!response.extensions) {\n response.extensions = {};\n }\n response.extensions[key] = extensionData;\n }\n } catch (error) {\n console.error(\n `Error in enrichPaymentRequiredResponse hook for extension ${key}:`,\n error,\n );\n }\n }\n }\n }\n\n return response;\n }\n\n /**\n * Verify a payment against requirements\n *\n * @param paymentPayload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Verification response\n */\n async verifyPayment(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const context: VerifyContext = {\n paymentPayload,\n requirements,\n };\n\n // Execute beforeVerify hooks\n for (const hook of this.beforeVerifyHooks) {\n try {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n return {\n isValid: false,\n invalidReason: result.reason,\n invalidMessage: result.message,\n };\n }\n } catch (error) {\n throw new VerifyError(400, {\n isValid: false,\n invalidReason: \"before_verify_hook_error\",\n invalidMessage: error instanceof Error ? error.message : \"\",\n });\n }\n }\n\n try {\n // Find the facilitator that supports this payment type\n const facilitatorClient = this.getFacilitatorClient(\n paymentPayload.x402Version,\n requirements.network,\n requirements.scheme,\n );\n\n let verifyResult: VerifyResponse;\n\n if (!facilitatorClient) {\n // Fallback: try all facilitators if no specific support found\n let lastError: Error | undefined;\n\n for (const client of this.facilitatorClients) {\n try {\n verifyResult = await client.verify(paymentPayload, requirements);\n break;\n } catch (error) {\n lastError = error as Error;\n }\n }\n\n if (!verifyResult!) {\n throw (\n lastError ||\n new Error(\n `No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`,\n )\n );\n }\n } else {\n // Use the specific facilitator that supports this payment\n verifyResult = await facilitatorClient.verify(paymentPayload, requirements);\n }\n\n // Execute afterVerify hooks\n const resultContext: VerifyResultContext = {\n ...context,\n result: verifyResult,\n };\n\n for (const hook of this.afterVerifyHooks) {\n await hook(resultContext);\n }\n\n return verifyResult;\n } catch (error) {\n const failureContext: VerifyFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onVerifyFailure hooks\n for (const hook of this.onVerifyFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.result;\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Settle a verified payment\n *\n * @param paymentPayload - The payment payload to settle\n * @param requirements - The payment requirements\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)\n * @param settlementOverrides - Optional overrides for settlement parameters (e.g., partial settlement amount)\n * @returns Settlement response\n */\n async settlePayment(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n transportContext?: unknown,\n settlementOverrides?: SettlementOverrides,\n ): Promise<SettleResponse> {\n // Apply settlement overrides (e.g., partial settlement for upto scheme)\n let effectiveRequirements = requirements;\n if (settlementOverrides?.amount !== undefined) {\n const scheme = findByNetworkAndScheme(\n this.registeredServerSchemes,\n requirements.scheme,\n requirements.network as Network,\n );\n const decimals =\n scheme?.getAssetDecimals?.(requirements.asset ?? \"\", requirements.network as Network) ?? 6;\n effectiveRequirements = {\n ...requirements,\n amount: resolveSettlementOverrideAmount(settlementOverrides.amount, requirements, decimals),\n };\n }\n\n const context: SettleContext = {\n paymentPayload,\n requirements: effectiveRequirements,\n };\n\n // Execute beforeSettle hooks\n for (const hook of this.beforeSettleHooks) {\n try {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new SettleError(400, {\n success: false,\n errorReason: result.reason,\n errorMessage: result.message,\n transaction: \"\",\n network: requirements.network,\n });\n }\n } catch (error) {\n if (error instanceof SettleError) {\n throw error;\n }\n throw new SettleError(400, {\n success: false,\n errorReason: \"before_settle_hook_error\",\n errorMessage: error instanceof Error ? error.message : \"\",\n transaction: \"\",\n network: requirements.network,\n });\n }\n }\n\n try {\n // Find the facilitator that supports this payment type\n const facilitatorClient = this.getFacilitatorClient(\n paymentPayload.x402Version,\n effectiveRequirements.network,\n effectiveRequirements.scheme,\n );\n\n let settleResult: SettleResponse;\n\n if (!facilitatorClient) {\n // Fallback: try all facilitators if no specific support found\n let lastError: Error | undefined;\n\n for (const client of this.facilitatorClients) {\n try {\n settleResult = await client.settle(paymentPayload, effectiveRequirements);\n break;\n } catch (error) {\n lastError = error as Error;\n }\n }\n\n if (!settleResult!) {\n throw (\n lastError ||\n new Error(\n `No facilitator supports ${effectiveRequirements.scheme} on ${effectiveRequirements.network} for v${paymentPayload.x402Version}`,\n )\n );\n }\n } else {\n // Use the specific facilitator that supports this payment\n settleResult = await facilitatorClient.settle(paymentPayload, effectiveRequirements);\n }\n\n // Execute afterSettle hooks\n const resultContext: SettleResultContext = {\n ...context,\n result: settleResult,\n transportContext,\n };\n\n for (const hook of this.afterSettleHooks) {\n await hook(resultContext);\n }\n\n // Let declared extensions add data to settlement response\n if (declaredExtensions) {\n for (const [key, declaration] of Object.entries(declaredExtensions)) {\n const extension = this.registeredExtensions.get(key);\n if (extension?.enrichSettlementResponse) {\n try {\n const extensionData = await extension.enrichSettlementResponse(\n declaration,\n resultContext,\n );\n if (extensionData !== undefined) {\n if (!settleResult.extensions) {\n settleResult.extensions = {};\n }\n settleResult.extensions[key] = extensionData;\n }\n } catch (error) {\n console.error(`Error in enrichSettlementResponse hook for extension ${key}:`, error);\n }\n }\n }\n }\n\n return settleResult;\n } catch (error) {\n const failureContext: SettleFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onSettleFailure hooks\n for (const hook of this.onSettleFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.result;\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Find matching payment requirements for a payment\n *\n * @param availableRequirements - Array of available payment requirements\n * @param paymentPayload - The payment payload\n * @returns Matching payment requirements or undefined\n */\n findMatchingRequirements(\n availableRequirements: PaymentRequirements[],\n paymentPayload: PaymentPayload,\n ): PaymentRequirements | undefined {\n switch (paymentPayload.x402Version) {\n case 2:\n // For v2, match by accepted requirements\n return availableRequirements.find(paymentRequirements =>\n deepEqual(paymentRequirements, paymentPayload.accepted),\n );\n case 1:\n // For v1, match by scheme and network\n return availableRequirements.find(\n req =>\n req.scheme === paymentPayload.accepted.scheme &&\n req.network === paymentPayload.accepted.network,\n );\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Process a payment request\n *\n * @param paymentPayload - Optional payment payload if provided\n * @param resourceConfig - Configuration for the protected resource\n * @param resourceInfo - Information about the resource being accessed\n * @param extensions - Optional extensions to include in the response\n * @returns Processing result\n */\n async processPaymentRequest(\n paymentPayload: PaymentPayload | null,\n resourceConfig: ResourceConfig,\n resourceInfo: ResourceInfo,\n extensions?: Record<string, unknown>,\n ): Promise<{\n success: boolean;\n requiresPayment?: PaymentRequired;\n verificationResult?: VerifyResponse;\n settlementResult?: SettleResponse;\n error?: string;\n }> {\n const requirements = await this.buildPaymentRequirements(resourceConfig);\n\n if (!paymentPayload) {\n return {\n success: false,\n requiresPayment: await this.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"Payment required\",\n extensions,\n ),\n };\n }\n\n // Find matching requirements\n const matchingRequirements = this.findMatchingRequirements(requirements, paymentPayload);\n if (!matchingRequirements) {\n return {\n success: false,\n requiresPayment: await this.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"No matching payment requirements found\",\n extensions,\n ),\n };\n }\n\n // Verify payment\n const verificationResult = await this.verifyPayment(paymentPayload, matchingRequirements);\n if (!verificationResult.isValid) {\n return {\n success: false,\n error: verificationResult.invalidReason,\n verificationResult,\n };\n }\n\n // Payment verified, ready for settlement\n return {\n success: true,\n verificationResult,\n };\n }\n\n /**\n * Get facilitator client for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The facilitator client or undefined if not found\n */\n private getFacilitatorClient(\n x402Version: number,\n network: Network,\n scheme: string,\n ): FacilitatorClient | undefined {\n const versionMap = this.facilitatorClientsMap.get(x402Version);\n if (!versionMap) return undefined;\n\n // Use findByNetworkAndScheme for pattern matching\n return findByNetworkAndScheme(versionMap, scheme, network);\n }\n}\n\nexport default x402ResourceServer;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0IO,SAAS,gCACd,WACA,cACA,WAAmB,GACX;AAER,QAAM,eAAe,UAAU,MAAM,wBAAwB;AAC7D,MAAI,cAAc;AAChB,UAAM,CAAC,SAAS,UAAU,EAAE,IAAI,aAAa,CAAC,EAAE,MAAM,GAAG;AACzD,UAAM,gBAAgB,OAAO,OAAO,IAAI,OAAO,OAAO,QAAQ,OAAO,GAAG,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC;AACxF,UAAM,OAAO,OAAO,aAAa,MAAM;AACvC,YAAS,OAAO,gBAAiB,QAAQ,SAAS;AAAA,EACpD;AAGA,QAAM,cAAc,UAAU,MAAM,qBAAqB;AACzD,MAAI,aAAa;AACf,UAAM,UAAU,WAAW,YAAY,CAAC,CAAC;AACzC,WAAO,KAAK,MAAM,UAA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AoB;AACxF,QAAI,CAAC,mBAAmB,SAAS;AAC/B,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,mBAAmB;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAGA,WAAO;AAAA,MACL,SAAS;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,qBACND,cACA,SACA,QAC+B;AAC/B,UAAM,aAAa,KAAK,sBAAsB,IAAIA,YAAW;AAC7D,QAAI,CAAC,WAAY,QAAO;AAGxB,WAAO,uBAAuB,YAAY,QAAQ,OAAO;AAAA,EAC3D;AACF;","names":["x402Version","error"]}

@@ -1,1 +0,1 @@

export { A as AssetAmount, D as FacilitatorContext, F as FacilitatorExtension, f as FacilitatorResponseError, M as Money, z as MoneyParser, N as Network, P as PaymentPayload, C as PaymentPayloadContext, B as PaymentPayloadResult, m as PaymentPayloadV1, c as PaymentRequired, G as PaymentRequiredContext, l as PaymentRequiredV1, a as PaymentRequirements, k as PaymentRequirementsV1, j as Price, w as ResourceInfo, E as ResourceServerExtension, h as SchemeNetworkClient, b as SchemeNetworkFacilitator, y as SchemeNetworkServer, v as SettleError, s as SettleRequest, S as SettleResponse, i as SettleResultContext, t as SupportedResponse, u as VerifyError, r as VerifyRequest, V as VerifyResponse, g as getFacilitatorResponseError } from '../mechanisms-B3SXtgLV.mjs';
export { E as AssetAmount, Y as FacilitatorContext, F as FacilitatorExtension, f as FacilitatorResponseError, M as Money, U as MoneyParser, N as Network, P as PaymentPayload, X as PaymentPayloadContext, W as PaymentPayloadResult, w as PaymentPayloadV1, c as PaymentRequired, i as PaymentRequiredContext, v as PaymentRequiredV1, a as PaymentRequirements, u as PaymentRequirementsV1, t as Price, Q as ResourceInfo, Z as ResourceServerExtension, h as SchemeNetworkClient, b as SchemeNetworkFacilitator, T as SchemeNetworkServer, L as SettleError, I as SettleRequest, S as SettleResponse, n as SettleResultContext, J as SupportedResponse, K as VerifyError, G as VerifyRequest, V as VerifyResponse, g as getFacilitatorResponseError } from '../mechanisms-Djgn2ixv.mjs';

@@ -6,3 +6,3 @@ import {

getFacilitatorResponseError
} from "../chunk-VY72CEUI.mjs";
} from "../chunk-JUGE6MAI.mjs";
import "../chunk-BJTO5JO5.mjs";

@@ -9,0 +9,0 @@ export {

@@ -1,1 +0,1 @@

export { m as PaymentPayloadV1, l as PaymentRequiredV1, k as PaymentRequirementsV1, o as SettleRequestV1, p as SettleResponseV1, q as SupportedResponseV1, n as VerifyRequestV1 } from '../../mechanisms-B3SXtgLV.mjs';
export { w as PaymentPayloadV1, v as PaymentRequiredV1, u as PaymentRequirementsV1, z as SettleRequestV1, C as SettleResponseV1, D as SupportedResponseV1, y as VerifyRequestV1 } from '../../mechanisms-Djgn2ixv.mjs';

@@ -1,2 +0,2 @@

import { N as Network } from '../mechanisms-B3SXtgLV.mjs';
import { N as Network } from '../mechanisms-Djgn2ixv.mjs';

@@ -3,0 +3,0 @@ /**

{
"name": "@x402/core",
"version": "2.8.0",
"version": "2.9.0",
"main": "./dist/cjs/index.js",

@@ -9,4 +9,4 @@ "module": "./dist/esm/index.js",

"license": "Apache-2.0",
"author": "Coinbase Inc.",
"repository": "https://github.com/coinbase/x402",
"author": "x402 Foundation",
"repository": "https://github.com/x402-foundation/x402",
"description": "x402 Payment Protocol",

@@ -13,0 +13,0 @@ "devDependencies": {

@@ -289,6 +289,6 @@ # @x402/core

See the [examples directory](https://github.com/coinbase/x402/tree/main/examples/typescript) for complete examples.
See the [examples directory](https://github.com/x402-foundation/x402/tree/main/examples/typescript) for complete examples.
## Contributing
Contributions welcome! See [Contributing Guide](https://github.com/coinbase/x402/blob/main/CONTRIBUTING.md).
Contributions welcome! See [Contributing Guide](https://github.com/x402-foundation/x402/blob/main/CONTRIBUTING.md).
type PaymentRequirementsV1 = {
scheme: string;
network: Network;
maxAmountRequired: string;
resource: string;
description: string;
mimeType: string;
outputSchema: Record<string, unknown>;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
extra: Record<string, unknown>;
};
type PaymentRequiredV1 = {
x402Version: 1;
error?: string;
accepts: PaymentRequirementsV1[];
};
type PaymentPayloadV1 = {
x402Version: 1;
scheme: string;
network: Network;
payload: Record<string, unknown>;
};
type VerifyRequestV1 = {
x402Version: number;
paymentPayload: PaymentPayloadV1;
paymentRequirements: PaymentRequirementsV1;
};
type SettleRequestV1 = {
x402Version: number;
paymentPayload: PaymentPayloadV1;
paymentRequirements: PaymentRequirementsV1;
};
type SettleResponseV1 = {
success: boolean;
errorReason?: string;
errorMessage?: string;
payer?: string;
transaction: string;
network: Network;
};
type SupportedResponseV1 = {
kinds: {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
}[];
};
interface FacilitatorConfig {
url?: string;
createAuthHeaders?: () => Promise<{
verify: Record<string, string>;
settle: Record<string, string>;
supported: Record<string, string>;
}>;
}
/**
* Interface for facilitator clients
* Can be implemented for HTTP-based or local facilitators
*/
interface FacilitatorClient {
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
/**
* Get supported payment kinds and extensions from the facilitator
*
* @returns Supported payment kinds and extensions
*/
getSupported(): Promise<SupportedResponse>;
}
/**
* HTTP-based client for interacting with x402 facilitator services
* Handles HTTP communication with facilitator endpoints
*/
declare class HTTPFacilitatorClient implements FacilitatorClient {
readonly url: string;
private readonly _createAuthHeaders?;
/**
* Creates a new HTTPFacilitatorClient instance.
*
* @param config - Configuration options for the facilitator client
*/
constructor(config?: FacilitatorConfig);
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
/**
* Get supported payment kinds and extensions from the facilitator.
* Retries with exponential backoff on 429 rate limit errors.
*
* @returns Supported payment kinds and extensions
*/
getSupported(): Promise<SupportedResponse>;
/**
* Creates authentication headers for a specific path.
*
* @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
* @returns An object containing the authentication headers for the specified path
*/
createAuthHeaders(path: string): Promise<{
headers: Record<string, string>;
}>;
/**
* Helper to convert objects to JSON-safe format.
* Handles BigInt and other non-JSON types.
*
* @param obj - The object to convert
* @returns The JSON-safe representation of the object
*/
private toJsonSafe;
}
/**
* Configuration for a protected resource
* Only contains payment-specific configuration, not resource metadata
*/
interface ResourceConfig {
scheme: string;
payTo: string;
price: Price;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Lifecycle Hook Context Interfaces
*/
interface PaymentRequiredContext {
requirements: PaymentRequirements[];
resourceInfo: ResourceInfo;
error?: string;
paymentRequiredResponse: PaymentRequired;
transportContext?: unknown;
}
interface VerifyContext {
paymentPayload: PaymentPayload;
requirements: PaymentRequirements;
}
interface VerifyResultContext extends VerifyContext {
result: VerifyResponse;
}
interface VerifyFailureContext extends VerifyContext {
error: Error;
}
interface SettleContext {
paymentPayload: PaymentPayload;
requirements: PaymentRequirements;
}
interface SettleResultContext extends SettleContext {
result: SettleResponse;
transportContext?: unknown;
}
interface SettleFailureContext extends SettleContext {
error: Error;
}
/**
* Lifecycle Hook Type Definitions
*/
type BeforeVerifyHook = (context: VerifyContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
type AfterVerifyHook = (context: VerifyResultContext) => Promise<void>;
type OnVerifyFailureHook = (context: VerifyFailureContext) => Promise<void | {
recovered: true;
result: VerifyResponse;
}>;
type BeforeSettleHook = (context: SettleContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
type AfterSettleHook = (context: SettleResultContext) => Promise<void>;
type OnSettleFailureHook = (context: SettleFailureContext) => Promise<void | {
recovered: true;
result: SettleResponse;
}>;
/**
* Core x402 protocol server for resource protection
* Transport-agnostic implementation of the x402 payment protocol
*/
declare class x402ResourceServer {
private facilitatorClients;
private registeredServerSchemes;
private supportedResponsesMap;
private facilitatorClientsMap;
private registeredExtensions;
private beforeVerifyHooks;
private afterVerifyHooks;
private onVerifyFailureHooks;
private beforeSettleHooks;
private afterSettleHooks;
private onSettleFailureHooks;
/**
* Creates a new x402ResourceServer instance.
*
* @param facilitatorClients - Optional facilitator client(s) for payment processing
*/
constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]);
/**
* Register a scheme/network server implementation.
*
* @param network - The network identifier
* @param server - The scheme/network server implementation
* @returns The x402ResourceServer instance for chaining
*/
register(network: Network, server: SchemeNetworkServer): x402ResourceServer;
/**
* Check if a scheme is registered for a given network.
*
* @param network - The network identifier
* @param scheme - The payment scheme name
* @returns True if the scheme is registered for the network, false otherwise
*/
hasRegisteredScheme(network: Network, scheme: string): boolean;
/**
* Registers a resource service extension that can enrich extension declarations.
*
* @param extension - The extension to register
* @returns The x402ResourceServer instance for chaining
*/
registerExtension(extension: ResourceServerExtension): this;
/**
* Check if an extension is registered.
*
* @param key - The extension key
* @returns True if the extension is registered
*/
hasExtension(key: string): boolean;
/**
* Get all registered extensions.
*
* @returns Array of registered extensions
*/
getExtensions(): ResourceServerExtension[];
/**
* Enriches declared extensions using registered extension hooks.
*
* @param declaredExtensions - Extensions declared on the route
* @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
* @returns Enriched extensions map
*/
enrichExtensions(declaredExtensions: Record<string, unknown>, transportContext: unknown): Record<string, unknown>;
/**
* Register a hook to execute before payment verification.
* Can abort verification by returning { abort: true, reason: string }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer;
/**
* Register a hook to execute after successful payment verification.
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onAfterVerify(hook: AfterVerifyHook): x402ResourceServer;
/**
* Register a hook to execute when payment verification fails.
* Can recover from failure by returning { recovered: true, result: VerifyResponse }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer;
/**
* Register a hook to execute before payment settlement.
* Can abort settlement by returning { abort: true, reason: string }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer;
/**
* Register a hook to execute after successful payment settlement.
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onAfterSettle(hook: AfterSettleHook): x402ResourceServer;
/**
* Register a hook to execute when payment settlement fails.
* Can recover from failure by returning { recovered: true, result: SettleResponse }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer;
/**
* Initialize by fetching supported kinds from all facilitators
* Creates mappings for supported responses and facilitator clients
* Earlier facilitators in the array get precedence
*/
initialize(): Promise<void>;
/**
* Get supported kind for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The supported kind or undefined if not found
*/
getSupportedKind(x402Version: number, network: Network, scheme: string): SupportedKind | undefined;
/**
* Get facilitator extensions for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The facilitator extensions or empty array if not found
*/
getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[];
/**
* Build payment requirements for a protected resource
*
* @param resourceConfig - Configuration for the protected resource
* @returns Array of payment requirements
*/
buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]>;
/**
* Build payment requirements from multiple payment options
* This method handles resolving dynamic payTo/price functions and builds requirements for each option
*
* @param paymentOptions - Array of payment options to convert
* @param context - HTTP request context for resolving dynamic functions
* @returns Array of payment requirements (one per option)
*/
buildPaymentRequirementsFromOptions<TContext = unknown>(paymentOptions: Array<{
scheme: string;
payTo: string | ((context: TContext) => string | Promise<string>);
price: Price | ((context: TContext) => Price | Promise<Price>);
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}>, context: TContext): Promise<PaymentRequirements[]>;
/**
* Create a payment required response
*
* @param requirements - Payment requirements
* @param resourceInfo - Resource information
* @param error - Error message
* @param extensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional transport-specific context (e.g., HTTP request, MCP tool context)
* @returns Payment required response object
*/
createPaymentRequiredResponse(requirements: PaymentRequirements[], resourceInfo: ResourceInfo, error?: string, extensions?: Record<string, unknown>, transportContext?: unknown): Promise<PaymentRequired>;
/**
* Verify a payment against requirements
*
* @param paymentPayload - The payment payload to verify
* @param requirements - The payment requirements
* @returns Verification response
*/
verifyPayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a verified payment
*
* @param paymentPayload - The payment payload to settle
* @param requirements - The payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)
* @returns Settlement response
*/
settlePayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown): Promise<SettleResponse>;
/**
* Find matching payment requirements for a payment
*
* @param availableRequirements - Array of available payment requirements
* @param paymentPayload - The payment payload
* @returns Matching payment requirements or undefined
*/
findMatchingRequirements(availableRequirements: PaymentRequirements[], paymentPayload: PaymentPayload): PaymentRequirements | undefined;
/**
* Process a payment request
*
* @param paymentPayload - Optional payment payload if provided
* @param resourceConfig - Configuration for the protected resource
* @param resourceInfo - Information about the resource being accessed
* @param extensions - Optional extensions to include in the response
* @returns Processing result
*/
processPaymentRequest(paymentPayload: PaymentPayload | null, resourceConfig: ResourceConfig, resourceInfo: ResourceInfo, extensions?: Record<string, unknown>): Promise<{
success: boolean;
requiresPayment?: PaymentRequired;
verificationResult?: VerifyResponse;
settlementResult?: SettleResponse;
error?: string;
}>;
/**
* Get facilitator client for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The facilitator client or undefined if not found
*/
private getFacilitatorClient;
}
/**
* Base interface for facilitator extensions.
* Extensions registered with x402Facilitator are stored by key and made
* available to mechanism implementations via FacilitatorContext.
*
* Specific extensions extend this with additional capabilities:
*
* @example
* interface Erc20GasSponsoringExtension extends FacilitatorExtension {
* batchSigner: SmartWalletBatchSigner;
* }
*/
interface FacilitatorExtension {
key: string;
}
interface ResourceServerExtension {
key: string;
/**
* Enrich extension declaration with extension-specific data.
*
* @param declaration - Extension declaration from route config
* @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
* @returns Enriched extension declaration
*/
enrichDeclaration?: (declaration: unknown, transportContext: unknown) => unknown;
/**
* Called when generating a 402 PaymentRequired response.
* Return extension data to add to extensions[key], or undefined to skip.
*
* @param declaration - Extension declaration from route config
* @param context - PaymentRequired context containing response, requirements, and optional transportContext
* @returns Extension data to add to response.extensions[key]
*/
enrichPaymentRequiredResponse?: (declaration: unknown, context: PaymentRequiredContext) => Promise<unknown>;
/**
* Called after successful payment settlement.
* Return extension data to add to response.extensions[key], or undefined to skip.
*
* @param declaration - Extension declaration from route config
* @param context - Settlement result context containing payment payload, requirements, result and optional transportContext
* @returns Extension data to add to response.extensions[key]
*/
enrichSettlementResponse?: (declaration: unknown, context: SettleResultContext) => Promise<unknown>;
}
type Network = `${string}:${string}`;
type Money = string | number;
type AssetAmount = {
asset: string;
amount: string;
extra?: Record<string, unknown>;
};
type Price = Money | AssetAmount;
interface ResourceInfo {
url: string;
description?: string;
mimeType?: string;
}
type PaymentRequirements = {
scheme: string;
network: Network;
asset: string;
amount: string;
payTo: string;
maxTimeoutSeconds: number;
extra: Record<string, unknown>;
};
type PaymentRequired = {
x402Version: number;
error?: string;
resource: ResourceInfo;
accepts: PaymentRequirements[];
extensions?: Record<string, unknown>;
};
type PaymentPayload = {
x402Version: number;
resource?: ResourceInfo;
accepted: PaymentRequirements;
payload: Record<string, unknown>;
extensions?: Record<string, unknown>;
};
type VerifyRequest = {
x402Version: number;
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};
type VerifyResponse = {
isValid: boolean;
invalidReason?: string;
invalidMessage?: string;
payer?: string;
extensions?: Record<string, unknown>;
};
type SettleRequest = {
x402Version: number;
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};
type SettleResponse = {
success: boolean;
errorReason?: string;
errorMessage?: string;
payer?: string;
transaction: string;
network: Network;
extensions?: Record<string, unknown>;
};
type SupportedKind = {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
};
type SupportedResponse = {
kinds: SupportedKind[];
extensions: string[];
signers: Record<string, string[]>;
};
/**
* Error thrown when payment verification fails.
*/
declare class VerifyError extends Error {
readonly invalidReason?: string;
readonly invalidMessage?: string;
readonly payer?: string;
readonly statusCode: number;
/**
* Creates a VerifyError from a failed verification response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The verify response containing error details
*/
constructor(statusCode: number, response: VerifyResponse);
}
/**
* Error thrown when payment settlement fails.
*/
declare class SettleError extends Error {
readonly errorReason?: string;
readonly errorMessage?: string;
readonly payer?: string;
readonly transaction: string;
readonly network: Network;
readonly statusCode: number;
/**
* Creates a SettleError from a failed settlement response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The settle response containing error details
*/
constructor(statusCode: number, response: SettleResponse);
}
/**
* Error thrown when a facilitator returns malformed success payload data.
*/
declare class FacilitatorResponseError extends Error {
/**
* Creates a FacilitatorResponseError for malformed facilitator responses.
*
* @param message - The boundary error message
*/
constructor(message: string);
}
/**
* Walks an error cause chain to find the first facilitator response error.
*
* @param error - The thrown value to inspect
* @returns The nested facilitator response error, if present
*/
declare function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null;
/**
* Money parser function that converts a numeric amount to an AssetAmount
* Receives the amount as a decimal number (e.g., 1.50 for $1.50)
* Returns null to indicate "cannot handle this amount", causing fallback to next parser
* Always returns a Promise for consistency - use async/await
*
* @param amount - The decimal amount (e.g., 1.50)
* @param network - The network identifier for context
* @returns AssetAmount or null to try next parser
*/
type MoneyParser = (amount: number, network: Network) => Promise<AssetAmount | null>;
/**
* Result of createPaymentPayload - the core payload fields.
* Contains the x402 version, scheme-specific payload data, and optional extension data.
* Schemes may return extensions (e.g., EIP-2612 gas sponsoring) that get merged
* with server-declared extensions in the final PaymentPayload.
*/
type PaymentPayloadResult = Pick<PaymentPayload, "x402Version" | "payload"> & {
extensions?: Record<string, unknown>;
};
/**
* Context passed to scheme's createPaymentPayload for extensions awareness.
* Contains the server-declared extensions from PaymentRequired so the scheme
* can check which extensions are advertised and respond accordingly.
*/
interface PaymentPayloadContext {
extensions?: Record<string, unknown>;
}
interface SchemeNetworkClient {
readonly scheme: string;
createPaymentPayload(x402Version: number, paymentRequirements: PaymentRequirements, context?: PaymentPayloadContext): Promise<PaymentPayloadResult>;
}
/**
* Context passed to SchemeNetworkFacilitator.verify/settle, providing
* access to registered facilitator extensions. Mechanism implementations
* use this to retrieve extension-provided capabilities (e.g., a batch signer).
*/
interface FacilitatorContext {
getExtension<T extends FacilitatorExtension = FacilitatorExtension>(key: string): T | undefined;
}
interface SchemeNetworkFacilitator {
readonly scheme: string;
/**
* CAIP family pattern that this facilitator supports.
* Used to group signers by blockchain family in the supported response.
*
* @example
* // EVM facilitators
* readonly caipFamily = "eip155:*";
*
* @example
* // SVM facilitators
* readonly caipFamily = "solana:*";
*/
readonly caipFamily: string;
/**
* Get mechanism-specific extra data needed for the supported kinds endpoint.
* This method is called when building the facilitator's supported response.
*
* @param network - The network identifier for context
* @returns Extra data object or undefined if no extra data is needed
*
* @example
* // EVM schemes return undefined (no extra data needed)
* getExtra(network: Network): undefined {
* return undefined;
* }
*
* @example
* // SVM schemes return feePayer address
* getExtra(network: Network): Record<string, unknown> | undefined {
* return { feePayer: this.signer.address };
* }
*/
getExtra(network: Network): Record<string, unknown> | undefined;
/**
* Get signer addresses used by this facilitator for a given network.
* These are included in the supported response to help clients understand
* which addresses might sign/pay for transactions.
*
* Supports multiple addresses for load balancing, key rotation, and high availability.
*
* @param network - The network identifier
* @returns Array of signer addresses (wallet addresses, fee payer addresses, etc.)
*
* @example
* // EVM facilitator
* getSigners(network: string): string[] {
* return [...this.signer.getAddresses()];
* }
*
* @example
* // SVM facilitator
* getSigners(network: string): string[] {
* return [...this.signer.getAddresses()];
* }
*/
getSigners(network: string): string[];
verify(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<VerifyResponse>;
settle(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<SettleResponse>;
}
interface SchemeNetworkServer {
readonly scheme: string;
/**
* Convert a user-friendly price to the scheme's specific amount and asset format
* Always returns a Promise for consistency
*
* @param price - User-friendly price (e.g., "$0.10", "0.10", { amount: "100000", asset: "USDC" })
* @param network - The network identifier for context
* @returns Promise that resolves to the converted amount, asset identifier, and any extra metadata
*
* @example
* // For EVM networks with USDC:
* await parsePrice("$0.10", "eip155:8453") => { amount: "100000", asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }
*
* // For custom schemes:
* await parsePrice("10 points", "custom:network") => { amount: "10", asset: "points" }
*/
parsePrice(price: Price, network: Network): Promise<AssetAmount>;
/**
* Build payment requirements for this scheme/network combination
*
* @param paymentRequirements - Base payment requirements with amount/asset already set
* @param supportedKind - The supported kind from facilitator's /supported endpoint
* @param supportedKind.x402Version - The x402 version
* @param supportedKind.scheme - The payment scheme
* @param supportedKind.network - The network identifier
* @param supportedKind.extra - Optional extra metadata
* @param facilitatorExtensions - Extensions supported by the facilitator
* @returns Enhanced payment requirements ready to be sent to clients
*/
enhancePaymentRequirements(paymentRequirements: PaymentRequirements, supportedKind: {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
}, facilitatorExtensions: string[]): Promise<PaymentRequirements>;
}
export { type AssetAmount as A, type PaymentPayloadResult as B, type PaymentPayloadContext as C, type FacilitatorContext as D, type ResourceServerExtension as E, type FacilitatorExtension as F, type PaymentRequiredContext as G, HTTPFacilitatorClient as H, type Money as M, type Network as N, type PaymentPayload as P, type ResourceConfig as R, type SettleResponse as S, type VerifyResponse as V, type PaymentRequirements as a, type SchemeNetworkFacilitator as b, type PaymentRequired as c, type FacilitatorClient as d, type FacilitatorConfig as e, FacilitatorResponseError as f, getFacilitatorResponseError as g, type SchemeNetworkClient as h, type SettleResultContext as i, type Price as j, type PaymentRequirementsV1 as k, type PaymentRequiredV1 as l, type PaymentPayloadV1 as m, type VerifyRequestV1 as n, type SettleRequestV1 as o, type SettleResponseV1 as p, type SupportedResponseV1 as q, type VerifyRequest as r, type SettleRequest as s, type SupportedResponse as t, VerifyError as u, SettleError as v, type ResourceInfo as w, x402ResourceServer as x, type SchemeNetworkServer as y, type MoneyParser as z };
import { x as x402ResourceServer, j as Price, N as Network, S as SettleResponse, c as PaymentRequired, P as PaymentPayload, a as PaymentRequirements } from './mechanisms-B3SXtgLV.js';
/**
* Framework-agnostic HTTP adapter interface
* Implementations provide framework-specific HTTP operations
*/
interface HTTPAdapter {
getHeader(name: string): string | undefined;
getMethod(): string;
getPath(): string;
getUrl(): string;
getAcceptHeader(): string;
getUserAgent(): string;
/**
* Get query parameters from the request URL
*
* @returns Record of query parameter key-value pairs
*/
getQueryParams?(): Record<string, string | string[]>;
/**
* Get a specific query parameter by name
*
* @param name - The query parameter name
* @returns The query parameter value(s) or undefined
*/
getQueryParam?(name: string): string | string[] | undefined;
/**
* Get the parsed request body
* Framework adapters should parse JSON/form data appropriately
*
* @returns The parsed request body
*/
getBody?(): unknown;
}
/**
* Paywall configuration for HTML responses
*/
interface PaywallConfig {
appName?: string;
appLogo?: string;
sessionTokenEndpoint?: string;
currentUrl?: string;
testnet?: boolean;
}
/**
* Paywall provider interface for generating HTML
*/
interface PaywallProvider {
generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;
}
/**
* Dynamic payTo function that receives HTTP request context
*/
type DynamicPayTo = (context: HTTPRequestContext) => string | Promise<string>;
/**
* Dynamic price function that receives HTTP request context
*/
type DynamicPrice = (context: HTTPRequestContext) => Price | Promise<Price>;
/**
* Result of response body callbacks containing content type and body.
*/
interface HTTPResponseBody {
/**
* The content type for the response (e.g., 'application/json', 'text/plain').
*/
contentType: string;
/**
* The response body to include in the 402 response.
*/
body: unknown;
}
/**
* Dynamic function to generate a custom response for unpaid requests.
* Receives the HTTP request context and returns the content type and body to include in the 402 response.
*/
type UnpaidResponseBody = (context: HTTPRequestContext) => HTTPResponseBody | Promise<HTTPResponseBody>;
/**
* Dynamic function to generate a custom response for settlement failures.
* Receives the HTTP request context and settle failure result, returns the content type and body.
*/
type SettlementFailedResponseBody = (context: HTTPRequestContext, settleResult: Omit<ProcessSettleFailureResponse, "response">) => HTTPResponseBody | Promise<HTTPResponseBody>;
/**
* A single payment option for a route
* Represents one way a client can pay for access to the resource
*/
interface PaymentOption {
scheme: string;
payTo: string | DynamicPayTo;
price: Price | DynamicPrice;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Route configuration for HTTP endpoints
*
* The 'accepts' field defines payment options for the route.
* Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.
*/
interface RouteConfig {
accepts: PaymentOption | PaymentOption[];
resource?: string;
description?: string;
mimeType?: string;
customPaywallHtml?: string;
/**
* Optional callback to generate a custom response for unpaid API requests.
* This allows servers to return preview data, error messages, or other content
* when a request lacks payment.
*
* For browser requests (Accept: text/html), the paywall HTML takes precedence.
* This callback is only used for API clients.
*
* If not provided, defaults to { contentType: 'application/json', body: {} }.
*
* @param context - The HTTP request context
* @returns An object containing both contentType and body for the 402 response
*/
unpaidResponseBody?: UnpaidResponseBody;
/**
* Optional callback to generate a custom response for settlement failures.
* If not provided, defaults to { contentType: 'application/json', body: {} }.
*
* @param context - The HTTP request context
* @param settleResult - The settlement failure result
* @returns An object containing both contentType and body for the 402 response
*/
settlementFailedResponseBody?: SettlementFailedResponseBody;
extensions?: Record<string, unknown>;
}
/**
* Routes configuration - maps path patterns to route configs
*/
type RoutesConfig = Record<string, RouteConfig> | RouteConfig;
/**
* Hook that runs on every request to a protected route, before payment processing.
* Can grant access without payment, deny the request, or continue to payment flow.
*
* @returns
* - `void` - Continue to payment processing (default behavior)
* - `{ grantAccess: true }` - Grant access without requiring payment
* - `{ abort: true; reason: string }` - Deny the request (returns 403)
*/
type ProtectedRequestHook = (context: HTTPRequestContext, routeConfig: RouteConfig) => Promise<void | {
grantAccess: true;
} | {
abort: true;
reason: string;
}>;
/**
* Compiled route for efficient matching
*/
interface CompiledRoute {
verb: string;
regex: RegExp;
config: RouteConfig;
pattern: string;
}
/**
* HTTP request context that encapsulates all request data
*/
interface HTTPRequestContext {
adapter: HTTPAdapter;
path: string;
method: string;
paymentHeader?: string;
routePattern?: string;
}
/**
* HTTP transport context contains both request context and optional response data.
*/
interface HTTPTransportContext {
/** The HTTP request context */
request: HTTPRequestContext;
/** The response body buffer */
responseBody?: Buffer;
}
/**
* HTTP response instructions for the framework middleware
*/
interface HTTPResponseInstructions {
status: number;
headers: Record<string, string>;
body?: unknown;
isHtml?: boolean;
}
/**
* Result of processing an HTTP request for payment
*/
type HTTPProcessResult = {
type: "no-payment-required";
} | {
type: "payment-verified";
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
declaredExtensions?: Record<string, unknown>;
} | {
type: "payment-error";
response: HTTPResponseInstructions;
};
/**
* Result of processSettlement
*/
type ProcessSettleSuccessResponse = SettleResponse & {
success: true;
headers: Record<string, string>;
requirements: PaymentRequirements;
};
type ProcessSettleFailureResponse = SettleResponse & {
success: false;
errorReason: string;
errorMessage?: string;
headers: Record<string, string>;
response: HTTPResponseInstructions;
};
type ProcessSettleResultResponse = ProcessSettleSuccessResponse | ProcessSettleFailureResponse;
/**
* Represents a validation error for a specific route's payment configuration.
*/
interface RouteValidationError {
/** The route pattern (e.g., "GET /api/weather") */
routePattern: string;
/** The payment scheme that failed validation */
scheme: string;
/** The network that failed validation */
network: Network;
/** The type of validation failure */
reason: "missing_scheme" | "missing_facilitator";
/** Human-readable error message */
message: string;
}
/**
* Error thrown when route configuration validation fails.
*/
declare class RouteConfigurationError extends Error {
/** The validation errors that caused this exception */
readonly errors: RouteValidationError[];
/**
* Creates a new RouteConfigurationError with the given validation errors.
*
* @param errors - The validation errors that caused this exception.
*/
constructor(errors: RouteValidationError[]);
}
/**
* HTTP-enhanced x402 resource server
* Provides framework-agnostic HTTP protocol handling
*/
declare class x402HTTPResourceServer {
private ResourceServer;
private compiledRoutes;
private routesConfig;
private paywallProvider?;
private protectedRequestHooks;
/**
* Creates a new x402HTTPResourceServer instance.
*
* @param ResourceServer - The core x402ResourceServer instance to use
* @param routes - Route configuration for payment-protected endpoints
*/
constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig);
/**
* Get the underlying x402ResourceServer instance.
*
* @returns The underlying x402ResourceServer instance
*/
get server(): x402ResourceServer;
/**
* Get the routes configuration.
*
* @returns The routes configuration
*/
get routes(): RoutesConfig;
/**
* Initialize the HTTP resource server.
*
* This method initializes the underlying resource server (fetching facilitator support)
* and then validates that all route payment configurations have corresponding
* registered schemes and facilitator support.
*
* @throws RouteConfigurationError if any route's payment options don't have
* corresponding registered schemes or facilitator support
*
* @example
* ```typescript
* const httpServer = new x402HTTPResourceServer(server, routes);
* await httpServer.initialize();
* ```
*/
initialize(): Promise<void>;
/**
* Register a custom paywall provider for generating HTML
*
* @param provider - PaywallProvider instance
* @returns This service instance for chaining
*/
registerPaywallProvider(provider: PaywallProvider): this;
/**
* Register a hook that runs on every request to a protected route, before payment processing.
* Hooks are executed in order of registration. The first hook to return a non-void result wins.
*
* @param hook - The request hook function
* @returns The x402HTTPResourceServer instance for chaining
*/
onProtectedRequest(hook: ProtectedRequestHook): this;
/**
* Process HTTP request and return response instructions
* This is the main entry point for framework middleware
*
* @param context - HTTP request context
* @param paywallConfig - Optional paywall configuration
* @returns Process result indicating next action for middleware
*/
processHTTPRequest(context: HTTPRequestContext, paywallConfig?: PaywallConfig): Promise<HTTPProcessResult>;
/**
* Process settlement after successful response
*
* @param paymentPayload - The verified payment payload
* @param requirements - The matching payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional HTTP transport context
* @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
*/
processSettlement(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: HTTPTransportContext): Promise<ProcessSettleResultResponse>;
/**
* Check if a request requires payment based on route configuration
*
* @param context - HTTP request context
* @returns True if the route requires payment, false otherwise
*/
requiresPayment(context: HTTPRequestContext): boolean;
/**
* Build HTTPResponseInstructions for settlement failure.
* Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.
*
* @param failure - Settlement failure result with headers
* @param transportContext - Optional HTTP transport context for the request
* @returns HTTP response instructions for the 402 settlement failure response
*/
private buildSettlementFailureResponse;
/**
* Normalizes a RouteConfig's accepts field into an array of PaymentOptions
* Handles both single PaymentOption and array formats
*
* @param routeConfig - Route configuration
* @returns Array of payment options
*/
private normalizePaymentOptions;
/**
* Validates that all payment options in routes have corresponding registered schemes
* and facilitator support.
*
* @returns Array of validation errors (empty if all routes are valid)
*/
private validateRouteConfiguration;
/**
* Get route configuration for a request
*
* @param path - Request path
* @param method - HTTP method
* @returns Route configuration and pattern, or undefined if no match
*/
private getRouteConfig;
/**
* Extract payment from HTTP headers (handles v1 and v2)
*
* @param adapter - HTTP adapter
* @returns Decoded payment payload or null
*/
private extractPayment;
/**
* Check if request is from a web browser
*
* @param adapter - HTTP adapter
* @returns True if request appears to be from a browser
*/
private isWebBrowser;
/**
* Create HTTP response instructions from payment required
*
* @param paymentRequired - Payment requirements
* @param isWebBrowser - Whether request is from browser
* @param paywallConfig - Paywall configuration
* @param customHtml - Custom HTML template
* @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
* @returns Response instructions
*/
private createHTTPResponse;
/**
* Create HTTP payment required response (v1 puts in body, v2 puts in header)
*
* @param paymentRequired - Payment required object
* @returns Headers and body for the HTTP response
*/
private createHTTPPaymentRequiredResponse;
/**
* Create settlement response headers
*
* @param settleResponse - Settlement response
* @returns Headers to add to response
*/
private createSettlementHeaders;
/**
* Parse route pattern into verb and regex
*
* @param pattern - Route pattern like "GET /api/*", "/api/[id]", or "/api/:id"
* @returns Parsed pattern with verb and regex
*/
private parseRoutePattern;
/**
* Normalize path for matching
*
* @param path - Raw path from request
* @returns Normalized path
*/
private normalizePath;
/**
* Generate paywall HTML for browser requests
*
* @param paymentRequired - Payment required response
* @param paywallConfig - Optional paywall configuration
* @param customHtml - Optional custom HTML template
* @returns HTML string
*/
private generatePaywallHTML;
/**
* Extract display amount from payment requirements.
*
* @param paymentRequired - The payment required object
* @returns The display amount in decimal format
*/
private getDisplayAmount;
}
export { type CompiledRoute as C, type DynamicPayTo as D, type HTTPAdapter as H, type PaywallConfig as P, type RouteConfig as R, type SettlementFailedResponseBody as S, type UnpaidResponseBody as U, type HTTPRequestContext as a, type HTTPTransportContext as b, type HTTPResponseInstructions as c, type HTTPProcessResult as d, type PaywallProvider as e, type PaymentOption as f, type RoutesConfig as g, type DynamicPrice as h, type HTTPResponseBody as i, type ProcessSettleResultResponse as j, type ProcessSettleSuccessResponse as k, type ProcessSettleFailureResponse as l, type RouteValidationError as m, RouteConfigurationError as n, type ProtectedRequestHook as o, x402HTTPResourceServer as x };
import {
z
} from "./chunk-KMQH4MQI.mjs";
import {
x402Version
} from "./chunk-VE37GDG2.mjs";
import {
FacilitatorResponseError,
SettleError,
VerifyError
} from "./chunk-VY72CEUI.mjs";
import {
Base64EncodedRegex,
safeBase64Decode,
safeBase64Encode
} from "./chunk-TDLQZ6MP.mjs";
import {
__require
} from "./chunk-BJTO5JO5.mjs";
// src/http/x402HTTPResourceServer.ts
var RouteConfigurationError = class extends Error {
/**
* Creates a new RouteConfigurationError with the given validation errors.
*
* @param errors - The validation errors that caused this exception.
*/
constructor(errors) {
const message = `x402 Route Configuration Errors:
${errors.map((e) => ` - ${e.message}`).join("\n")}`;
super(message);
this.name = "RouteConfigurationError";
this.errors = errors;
}
};
var x402HTTPResourceServer = class {
/**
* Creates a new x402HTTPResourceServer instance.
*
* @param ResourceServer - The core x402ResourceServer instance to use
* @param routes - Route configuration for payment-protected endpoints
*/
constructor(ResourceServer, routes) {
this.compiledRoutes = [];
this.protectedRequestHooks = [];
this.ResourceServer = ResourceServer;
this.routesConfig = routes;
const normalizedRoutes = typeof routes === "object" && !("accepts" in routes) ? routes : { "*": routes };
for (const [pattern, config] of Object.entries(normalizedRoutes)) {
const parsed = this.parseRoutePattern(pattern);
this.compiledRoutes.push({
verb: parsed.verb,
regex: parsed.regex,
config,
pattern: parsed.path
});
}
}
/**
* Get the underlying x402ResourceServer instance.
*
* @returns The underlying x402ResourceServer instance
*/
get server() {
return this.ResourceServer;
}
/**
* Get the routes configuration.
*
* @returns The routes configuration
*/
get routes() {
return this.routesConfig;
}
/**
* Initialize the HTTP resource server.
*
* This method initializes the underlying resource server (fetching facilitator support)
* and then validates that all route payment configurations have corresponding
* registered schemes and facilitator support.
*
* @throws RouteConfigurationError if any route's payment options don't have
* corresponding registered schemes or facilitator support
*
* @example
* ```typescript
* const httpServer = new x402HTTPResourceServer(server, routes);
* await httpServer.initialize();
* ```
*/
async initialize() {
await this.ResourceServer.initialize();
const errors = this.validateRouteConfiguration();
if (errors.length > 0) {
throw new RouteConfigurationError(errors);
}
}
/**
* Register a custom paywall provider for generating HTML
*
* @param provider - PaywallProvider instance
* @returns This service instance for chaining
*/
registerPaywallProvider(provider) {
this.paywallProvider = provider;
return this;
}
/**
* Register a hook that runs on every request to a protected route, before payment processing.
* Hooks are executed in order of registration. The first hook to return a non-void result wins.
*
* @param hook - The request hook function
* @returns The x402HTTPResourceServer instance for chaining
*/
onProtectedRequest(hook) {
this.protectedRequestHooks.push(hook);
return this;
}
/**
* Process HTTP request and return response instructions
* This is the main entry point for framework middleware
*
* @param context - HTTP request context
* @param paywallConfig - Optional paywall configuration
* @returns Process result indicating next action for middleware
*/
async processHTTPRequest(context, paywallConfig) {
const { adapter, path, method } = context;
const routeMatch = this.getRouteConfig(path, method);
if (!routeMatch) {
return { type: "no-payment-required" };
}
const { config: routeConfig, pattern: routePattern } = routeMatch;
const enrichedContext = { ...context, routePattern };
for (const hook of this.protectedRequestHooks) {
const result = await hook(enrichedContext, routeConfig);
if (result && "grantAccess" in result) {
return { type: "no-payment-required" };
}
if (result && "abort" in result) {
return {
type: "payment-error",
response: {
status: 403,
headers: { "Content-Type": "application/json" },
body: { error: result.reason }
}
};
}
}
const paymentOptions = this.normalizePaymentOptions(routeConfig);
const paymentPayload = this.extractPayment(adapter);
const resourceInfo = {
url: routeConfig.resource || enrichedContext.adapter.getUrl(),
description: routeConfig.description || "",
mimeType: routeConfig.mimeType || ""
};
let requirements = await this.ResourceServer.buildPaymentRequirementsFromOptions(
paymentOptions,
enrichedContext
);
let extensions = routeConfig.extensions;
if (extensions) {
extensions = this.ResourceServer.enrichExtensions(extensions, enrichedContext);
}
const transportContext = { request: enrichedContext };
const paymentRequired = await this.ResourceServer.createPaymentRequiredResponse(
requirements,
resourceInfo,
!paymentPayload ? "Payment required" : void 0,
extensions,
transportContext
);
if (!paymentPayload) {
const unpaidBody = routeConfig.unpaidResponseBody ? await routeConfig.unpaidResponseBody(enrichedContext) : void 0;
return {
type: "payment-error",
response: this.createHTTPResponse(
paymentRequired,
this.isWebBrowser(adapter),
paywallConfig,
routeConfig.customPaywallHtml,
unpaidBody
)
};
}
try {
const matchingRequirements = this.ResourceServer.findMatchingRequirements(
paymentRequired.accepts,
paymentPayload
);
if (!matchingRequirements) {
const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(
requirements,
resourceInfo,
"No matching payment requirements",
routeConfig.extensions,
transportContext
);
return {
type: "payment-error",
response: this.createHTTPResponse(errorResponse, false, paywallConfig)
};
}
const verifyResult = await this.ResourceServer.verifyPayment(
paymentPayload,
matchingRequirements
);
if (!verifyResult.isValid) {
const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(
requirements,
resourceInfo,
verifyResult.invalidReason,
routeConfig.extensions,
transportContext
);
return {
type: "payment-error",
response: this.createHTTPResponse(errorResponse, false, paywallConfig)
};
}
return {
type: "payment-verified",
paymentPayload,
paymentRequirements: matchingRequirements,
declaredExtensions: routeConfig.extensions
};
} catch (error) {
if (error instanceof FacilitatorResponseError) {
throw error;
}
const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(
requirements,
resourceInfo,
error instanceof Error ? error.message : "Payment verification failed",
routeConfig.extensions,
transportContext
);
return {
type: "payment-error",
response: this.createHTTPResponse(errorResponse, false, paywallConfig)
};
}
}
/**
* Process settlement after successful response
*
* @param paymentPayload - The verified payment payload
* @param requirements - The matching payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional HTTP transport context
* @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
*/
async processSettlement(paymentPayload, requirements, declaredExtensions, transportContext) {
try {
const settleResponse = await this.ResourceServer.settlePayment(
paymentPayload,
requirements,
declaredExtensions,
transportContext
);
if (!settleResponse.success) {
const failure = {
...settleResponse,
success: false,
errorReason: settleResponse.errorReason || "Settlement failed",
errorMessage: settleResponse.errorMessage || settleResponse.errorReason || "Settlement failed",
headers: this.createSettlementHeaders(settleResponse)
};
const response = await this.buildSettlementFailureResponse(failure, transportContext);
return { ...failure, response };
}
return {
...settleResponse,
success: true,
headers: this.createSettlementHeaders(settleResponse),
requirements
};
} catch (error) {
if (error instanceof FacilitatorResponseError) {
throw error;
}
if (error instanceof SettleError) {
const errorReason2 = error.errorReason || error.message;
const settleResponse2 = {
success: false,
errorReason: errorReason2,
errorMessage: error.errorMessage || errorReason2,
payer: error.payer,
network: error.network,
transaction: error.transaction
};
const failure2 = {
...settleResponse2,
success: false,
errorReason: errorReason2,
headers: this.createSettlementHeaders(settleResponse2)
};
const response2 = await this.buildSettlementFailureResponse(failure2, transportContext);
return { ...failure2, response: response2 };
}
const errorReason = error instanceof Error ? error.message : "Settlement failed";
const settleResponse = {
success: false,
errorReason,
errorMessage: errorReason,
network: requirements.network,
transaction: ""
};
const failure = {
...settleResponse,
success: false,
errorReason,
headers: this.createSettlementHeaders(settleResponse)
};
const response = await this.buildSettlementFailureResponse(failure, transportContext);
return { ...failure, response };
}
}
/**
* Check if a request requires payment based on route configuration
*
* @param context - HTTP request context
* @returns True if the route requires payment, false otherwise
*/
requiresPayment(context) {
return this.getRouteConfig(context.path, context.method) !== void 0;
}
/**
* Build HTTPResponseInstructions for settlement failure.
* Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.
*
* @param failure - Settlement failure result with headers
* @param transportContext - Optional HTTP transport context for the request
* @returns HTTP response instructions for the 402 settlement failure response
*/
async buildSettlementFailureResponse(failure, transportContext) {
const settlementHeaders = failure.headers;
const routeConfig = transportContext ? this.getRouteConfig(transportContext.request.path, transportContext.request.method) : void 0;
const customBody = routeConfig?.config.settlementFailedResponseBody ? await routeConfig.config.settlementFailedResponseBody(transportContext.request, failure) : void 0;
const contentType = customBody ? customBody.contentType : "application/json";
const body = customBody ? customBody.body : {};
return {
status: 402,
headers: {
"Content-Type": contentType,
...settlementHeaders
},
body,
isHtml: contentType.includes("text/html")
};
}
/**
* Normalizes a RouteConfig's accepts field into an array of PaymentOptions
* Handles both single PaymentOption and array formats
*
* @param routeConfig - Route configuration
* @returns Array of payment options
*/
normalizePaymentOptions(routeConfig) {
return Array.isArray(routeConfig.accepts) ? routeConfig.accepts : [routeConfig.accepts];
}
/**
* Validates that all payment options in routes have corresponding registered schemes
* and facilitator support.
*
* @returns Array of validation errors (empty if all routes are valid)
*/
validateRouteConfiguration() {
const errors = [];
const normalizedRoutes = typeof this.routesConfig === "object" && !("accepts" in this.routesConfig) ? Object.entries(this.routesConfig) : [["*", this.routesConfig]];
for (const [pattern, config] of normalizedRoutes) {
const pathPart = pattern.includes(" ") ? pattern.split(/\s+/)[1] : pattern;
if (pathPart && pathPart.includes("*") && config.extensions && "bazaar" in config.extensions) {
console.warn(
`[x402] Route "${pattern}": Wildcard (*) patterns with bazaar discovery extensions will auto-generate parameter names (var1, var2, ...). Consider using named parameters instead (e.g. /weather/:city) for better discovery metadata.`
);
}
const paymentOptions = this.normalizePaymentOptions(config);
for (const option of paymentOptions) {
if (!this.ResourceServer.hasRegisteredScheme(option.network, option.scheme)) {
errors.push({
routePattern: pattern,
scheme: option.scheme,
network: option.network,
reason: "missing_scheme",
message: `Route "${pattern}": No scheme implementation registered for "${option.scheme}" on network "${option.network}"`
});
continue;
}
const supportedKind = this.ResourceServer.getSupportedKind(
x402Version,
option.network,
option.scheme
);
if (!supportedKind) {
errors.push({
routePattern: pattern,
scheme: option.scheme,
network: option.network,
reason: "missing_facilitator",
message: `Route "${pattern}": Facilitator does not support scheme "${option.scheme}" on network "${option.network}"`
});
}
}
}
return errors;
}
/**
* Get route configuration for a request
*
* @param path - Request path
* @param method - HTTP method
* @returns Route configuration and pattern, or undefined if no match
*/
getRouteConfig(path, method) {
const normalizedPath = this.normalizePath(path);
const upperMethod = method.toUpperCase();
const matchingRoute = this.compiledRoutes.find(
(route) => route.regex.test(normalizedPath) && (route.verb === "*" || route.verb === upperMethod)
);
if (!matchingRoute) return void 0;
return { config: matchingRoute.config, pattern: matchingRoute.pattern };
}
/**
* Extract payment from HTTP headers (handles v1 and v2)
*
* @param adapter - HTTP adapter
* @returns Decoded payment payload or null
*/
extractPayment(adapter) {
const header = adapter.getHeader("payment-signature") || adapter.getHeader("PAYMENT-SIGNATURE");
if (header) {
try {
return decodePaymentSignatureHeader(header);
} catch (error) {
console.warn("Failed to decode PAYMENT-SIGNATURE header:", error);
}
}
return null;
}
/**
* Check if request is from a web browser
*
* @param adapter - HTTP adapter
* @returns True if request appears to be from a browser
*/
isWebBrowser(adapter) {
const accept = adapter.getAcceptHeader();
const userAgent = adapter.getUserAgent();
return accept.includes("text/html") && userAgent.includes("Mozilla");
}
/**
* Create HTTP response instructions from payment required
*
* @param paymentRequired - Payment requirements
* @param isWebBrowser - Whether request is from browser
* @param paywallConfig - Paywall configuration
* @param customHtml - Custom HTML template
* @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
* @returns Response instructions
*/
createHTTPResponse(paymentRequired, isWebBrowser, paywallConfig, customHtml, unpaidResponse) {
const status = paymentRequired.error === "permit2_allowance_required" ? 412 : 402;
if (isWebBrowser) {
const html = this.generatePaywallHTML(paymentRequired, paywallConfig, customHtml);
return {
status,
headers: { "Content-Type": "text/html" },
body: html,
isHtml: true
};
}
const response = this.createHTTPPaymentRequiredResponse(paymentRequired);
const contentType = unpaidResponse ? unpaidResponse.contentType : "application/json";
const body = unpaidResponse ? unpaidResponse.body : {};
return {
status,
headers: {
"Content-Type": contentType,
...response.headers
},
body
};
}
/**
* Create HTTP payment required response (v1 puts in body, v2 puts in header)
*
* @param paymentRequired - Payment required object
* @returns Headers and body for the HTTP response
*/
createHTTPPaymentRequiredResponse(paymentRequired) {
return {
headers: {
"PAYMENT-REQUIRED": encodePaymentRequiredHeader(paymentRequired)
}
};
}
/**
* Create settlement response headers
*
* @param settleResponse - Settlement response
* @returns Headers to add to response
*/
createSettlementHeaders(settleResponse) {
const encoded = encodePaymentResponseHeader(settleResponse);
return { "PAYMENT-RESPONSE": encoded };
}
/**
* Parse route pattern into verb and regex
*
* @param pattern - Route pattern like "GET /api/*", "/api/[id]", or "/api/:id"
* @returns Parsed pattern with verb and regex
*/
parseRoutePattern(pattern) {
const [verb, path] = pattern.includes(" ") ? pattern.split(/\s+/) : ["*", pattern];
const regex = new RegExp(
`^${path.replace(/[$()+.?^{|}]/g, "\\$&").replace(/\*/g, ".*?").replace(/\[([^\]]+)\]/g, "[^/]+").replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, "[^/]+").replace(/\//g, "\\/")}$`,
"i"
);
return { verb: verb.toUpperCase(), regex, path };
}
/**
* Normalize path for matching
*
* @param path - Raw path from request
* @returns Normalized path
*/
normalizePath(path) {
const pathWithoutQuery = path.split(/[?#]/)[0];
let decodedOrRawPath;
try {
decodedOrRawPath = decodeURIComponent(pathWithoutQuery);
} catch {
decodedOrRawPath = pathWithoutQuery;
}
return decodedOrRawPath.replace(/\\/g, "/").replace(/\/+/g, "/").replace(/(.+?)\/+$/, "$1");
}
/**
* Generate paywall HTML for browser requests
*
* @param paymentRequired - Payment required response
* @param paywallConfig - Optional paywall configuration
* @param customHtml - Optional custom HTML template
* @returns HTML string
*/
generatePaywallHTML(paymentRequired, paywallConfig, customHtml) {
if (customHtml) {
return customHtml;
}
if (this.paywallProvider) {
return this.paywallProvider.generateHtml(paymentRequired, paywallConfig);
}
try {
const paywall = __require("@x402/paywall");
const displayAmount2 = this.getDisplayAmount(paymentRequired);
const resource2 = paymentRequired.resource;
return paywall.getPaywallHtml({
amount: displayAmount2,
paymentRequired,
currentUrl: resource2?.url || paywallConfig?.currentUrl || "",
testnet: paywallConfig?.testnet ?? true,
appName: paywallConfig?.appName,
appLogo: paywallConfig?.appLogo,
sessionTokenEndpoint: paywallConfig?.sessionTokenEndpoint
});
} catch {
}
const resource = paymentRequired.resource;
const displayAmount = this.getDisplayAmount(paymentRequired);
return `
<!DOCTYPE html>
<html>
<head>
<title>Payment Required</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div style="max-width: 600px; margin: 50px auto; padding: 20px; font-family: system-ui, -apple-system, sans-serif;">
${paywallConfig?.appLogo ? `<img src="${paywallConfig.appLogo}" alt="${paywallConfig.appName || "App"}" style="max-width: 200px; margin-bottom: 20px;">` : ""}
<h1>Payment Required</h1>
${resource ? `<p><strong>Resource:</strong> ${resource.description || resource.url}</p>` : ""}
<p><strong>Amount:</strong> $${displayAmount.toFixed(2)} USDC</p>
<div id="payment-widget"
data-requirements='${JSON.stringify(paymentRequired)}'
data-app-name="${paywallConfig?.appName || ""}"
data-testnet="${paywallConfig?.testnet || false}">
<!-- Install @x402/paywall for full wallet integration -->
<p style="margin-top: 2rem; padding: 1rem; background: #fef3c7; border-radius: 0.5rem;">
<strong>Note:</strong> Install <code>@x402/paywall</code> for full wallet connection and payment UI.
</p>
</div>
</div>
</body>
</html>
`;
}
/**
* Extract display amount from payment requirements.
*
* @param paymentRequired - The payment required object
* @returns The display amount in decimal format
*/
getDisplayAmount(paymentRequired) {
const accepts = paymentRequired.accepts;
if (accepts && accepts.length > 0) {
const firstReq = accepts[0];
if ("amount" in firstReq) {
return parseFloat(firstReq.amount) / 1e6;
}
}
return 0;
}
};
// src/http/httpFacilitatorClient.ts
var DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
var GET_SUPPORTED_RETRIES = 3;
var GET_SUPPORTED_RETRY_DELAY_MS = 1e3;
var verifyResponseSchema = z.object({
isValid: z.boolean(),
invalidReason: z.string().nullish().transform((v) => v ?? void 0),
invalidMessage: z.string().nullish().transform((v) => v ?? void 0),
payer: z.string().nullish().transform((v) => v ?? void 0),
extensions: z.record(z.string(), z.unknown()).nullish().transform((v) => v ?? void 0)
});
var settleResponseSchema = z.object({
success: z.boolean(),
errorReason: z.string().nullish().transform((v) => v ?? void 0),
errorMessage: z.string().nullish().transform((v) => v ?? void 0),
payer: z.string().nullish().transform((v) => v ?? void 0),
transaction: z.string(),
network: z.custom((value) => typeof value === "string"),
extensions: z.record(z.string(), z.unknown()).nullish().transform((v) => v ?? void 0)
});
var supportedKindSchema = z.object({
x402Version: z.number(),
scheme: z.string(),
network: z.custom(
(value) => typeof value === "string"
),
extra: z.record(z.string(), z.unknown()).nullish().transform((v) => v ?? void 0)
});
var supportedResponseSchema = z.object({
kinds: z.array(supportedKindSchema),
extensions: z.array(z.string()).default([]),
signers: z.record(z.string(), z.array(z.string())).default({})
});
function responseExcerpt(text, limit = 200) {
const compact = text.trim().replace(/\s+/g, " ");
if (!compact) {
return "<empty response>";
}
if (compact.length <= limit) {
return compact;
}
return `${compact.slice(0, limit - 3)}...`;
}
async function parseSuccessResponse(response, schema, operation) {
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
throw new FacilitatorResponseError(
`Facilitator ${operation} returned invalid JSON: ${responseExcerpt(text)}`
);
}
const parsed = schema.safeParse(data);
if (!parsed.success) {
throw new FacilitatorResponseError(
`Facilitator ${operation} returned invalid data: ${responseExcerpt(text)}`
);
}
return parsed.data;
}
var HTTPFacilitatorClient = class {
/**
* Creates a new HTTPFacilitatorClient instance.
*
* @param config - Configuration options for the facilitator client
*/
constructor(config) {
this.url = config?.url || DEFAULT_FACILITATOR_URL;
this._createAuthHeaders = config?.createAuthHeaders;
}
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
async verify(paymentPayload, paymentRequirements) {
let headers = {
"Content-Type": "application/json"
};
if (this._createAuthHeaders) {
const authHeaders = await this.createAuthHeaders("verify");
headers = { ...headers, ...authHeaders.headers };
}
const response = await fetch(`${this.url}/verify`, {
method: "POST",
headers,
body: JSON.stringify({
x402Version: paymentPayload.x402Version,
paymentPayload: this.toJsonSafe(paymentPayload),
paymentRequirements: this.toJsonSafe(paymentRequirements)
})
});
if (!response.ok) {
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
throw new Error(`Facilitator verify failed (${response.status}): ${responseExcerpt(text)}`);
}
if (typeof data === "object" && data !== null && "isValid" in data) {
throw new VerifyError(response.status, data);
}
throw new Error(
`Facilitator verify failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`
);
}
return parseSuccessResponse(response, verifyResponseSchema, "verify");
}
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
async settle(paymentPayload, paymentRequirements) {
let headers = {
"Content-Type": "application/json"
};
if (this._createAuthHeaders) {
const authHeaders = await this.createAuthHeaders("settle");
headers = { ...headers, ...authHeaders.headers };
}
const response = await fetch(`${this.url}/settle`, {
method: "POST",
headers,
body: JSON.stringify({
x402Version: paymentPayload.x402Version,
paymentPayload: this.toJsonSafe(paymentPayload),
paymentRequirements: this.toJsonSafe(paymentRequirements)
})
});
if (!response.ok) {
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
throw new Error(`Facilitator settle failed (${response.status}): ${responseExcerpt(text)}`);
}
if (typeof data === "object" && data !== null && "success" in data) {
throw new SettleError(response.status, data);
}
throw new Error(
`Facilitator settle failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`
);
}
return parseSuccessResponse(response, settleResponseSchema, "settle");
}
/**
* Get supported payment kinds and extensions from the facilitator.
* Retries with exponential backoff on 429 rate limit errors.
*
* @returns Supported payment kinds and extensions
*/
async getSupported() {
let headers = {
"Content-Type": "application/json"
};
if (this._createAuthHeaders) {
const authHeaders = await this.createAuthHeaders("supported");
headers = { ...headers, ...authHeaders.headers };
}
let lastError = null;
for (let attempt = 0; attempt < GET_SUPPORTED_RETRIES; attempt++) {
const response = await fetch(`${this.url}/supported`, {
method: "GET",
headers
});
if (response.ok) {
return parseSuccessResponse(response, supportedResponseSchema, "supported");
}
const errorText = await response.text().catch(() => response.statusText);
lastError = new Error(
`Facilitator getSupported failed (${response.status}): ${responseExcerpt(errorText)}`
);
if (response.status === 429 && attempt < GET_SUPPORTED_RETRIES - 1) {
const delay = GET_SUPPORTED_RETRY_DELAY_MS * Math.pow(2, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
throw lastError;
}
throw lastError ?? new Error("Facilitator getSupported failed after retries");
}
/**
* Creates authentication headers for a specific path.
*
* @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
* @returns An object containing the authentication headers for the specified path
*/
async createAuthHeaders(path) {
if (this._createAuthHeaders) {
const authHeaders = await this._createAuthHeaders();
return {
headers: authHeaders[path] ?? {}
};
}
return {
headers: {}
};
}
/**
* Helper to convert objects to JSON-safe format.
* Handles BigInt and other non-JSON types.
*
* @param obj - The object to convert
* @returns The JSON-safe representation of the object
*/
toJsonSafe(obj) {
return JSON.parse(
JSON.stringify(obj, (_, value) => typeof value === "bigint" ? value.toString() : value)
);
}
};
// src/http/x402HTTPClient.ts
var x402HTTPClient = class {
/**
* Creates a new x402HTTPClient instance.
*
* @param client - The underlying x402Client for payment logic
*/
constructor(client) {
this.client = client;
this.paymentRequiredHooks = [];
}
/**
* Register a hook to handle 402 responses before payment.
* Hooks run in order; first to return headers wins.
*
* @param hook - The hook function to register
* @returns This instance for chaining
*/
onPaymentRequired(hook) {
this.paymentRequiredHooks.push(hook);
return this;
}
/**
* Run hooks and return headers if any hook provides them.
*
* @param paymentRequired - The payment required response from the server
* @returns Headers to use for retry, or null to proceed to payment
*/
async handlePaymentRequired(paymentRequired) {
for (const hook of this.paymentRequiredHooks) {
const result = await hook({ paymentRequired });
if (result?.headers) {
return result.headers;
}
}
return null;
}
/**
* Encodes a payment payload into appropriate HTTP headers based on version.
*
* @param paymentPayload - The payment payload to encode
* @returns HTTP headers containing the encoded payment signature
*/
encodePaymentSignatureHeader(paymentPayload) {
switch (paymentPayload.x402Version) {
case 2:
return {
"PAYMENT-SIGNATURE": encodePaymentSignatureHeader(paymentPayload)
};
case 1:
return {
"X-PAYMENT": encodePaymentSignatureHeader(paymentPayload)
};
default:
throw new Error(
`Unsupported x402 version: ${paymentPayload.x402Version}`
);
}
}
/**
* Extracts payment required information from HTTP response.
*
* @param getHeader - Function to retrieve header value by name (case-insensitive)
* @param body - Optional response body for v1 compatibility
* @returns The payment required object
*/
getPaymentRequiredResponse(getHeader, body) {
const paymentRequired = getHeader("PAYMENT-REQUIRED");
if (paymentRequired) {
return decodePaymentRequiredHeader(paymentRequired);
}
if (body && body instanceof Object && "x402Version" in body && body.x402Version === 1) {
return body;
}
throw new Error("Invalid payment required response");
}
/**
* Extracts payment settlement response from HTTP headers.
*
* @param getHeader - Function to retrieve header value by name (case-insensitive)
* @returns The settlement response object
*/
getPaymentSettleResponse(getHeader) {
const paymentResponse = getHeader("PAYMENT-RESPONSE");
if (paymentResponse) {
return decodePaymentResponseHeader(paymentResponse);
}
const xPaymentResponse = getHeader("X-PAYMENT-RESPONSE");
if (xPaymentResponse) {
return decodePaymentResponseHeader(xPaymentResponse);
}
throw new Error("Payment response header not found");
}
/**
* Creates a payment payload for the given payment requirements.
* Delegates to the underlying x402Client.
*
* @param paymentRequired - The payment required response from the server
* @returns Promise resolving to the payment payload
*/
async createPaymentPayload(paymentRequired) {
return this.client.createPaymentPayload(paymentRequired);
}
};
// src/http/index.ts
function encodePaymentSignatureHeader(paymentPayload) {
return safeBase64Encode(JSON.stringify(paymentPayload));
}
function decodePaymentSignatureHeader(paymentSignatureHeader) {
if (!Base64EncodedRegex.test(paymentSignatureHeader)) {
throw new Error("Invalid payment signature header");
}
return JSON.parse(safeBase64Decode(paymentSignatureHeader));
}
function encodePaymentRequiredHeader(paymentRequired) {
return safeBase64Encode(JSON.stringify(paymentRequired));
}
function decodePaymentRequiredHeader(paymentRequiredHeader) {
if (!Base64EncodedRegex.test(paymentRequiredHeader)) {
throw new Error("Invalid payment required header");
}
return JSON.parse(safeBase64Decode(paymentRequiredHeader));
}
function encodePaymentResponseHeader(paymentResponse) {
return safeBase64Encode(JSON.stringify(paymentResponse));
}
function decodePaymentResponseHeader(paymentResponseHeader) {
if (!Base64EncodedRegex.test(paymentResponseHeader)) {
throw new Error("Invalid payment response header");
}
return JSON.parse(safeBase64Decode(paymentResponseHeader));
}
export {
RouteConfigurationError,
x402HTTPResourceServer,
HTTPFacilitatorClient,
encodePaymentSignatureHeader,
decodePaymentSignatureHeader,
encodePaymentRequiredHeader,
decodePaymentRequiredHeader,
encodePaymentResponseHeader,
decodePaymentResponseHeader,
x402HTTPClient
};
//# sourceMappingURL=chunk-ACVTKVCM.mjs.map

Sorry, the diff of this file is too big to display

// src/types/facilitator.ts
var VerifyError = class extends Error {
/**
* Creates a VerifyError from a failed verification response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The verify response containing error details
*/
constructor(statusCode, response) {
const reason = response.invalidReason || "unknown reason";
const message = response.invalidMessage;
super(message ? `${reason}: ${message}` : reason);
this.name = "VerifyError";
this.statusCode = statusCode;
this.invalidReason = response.invalidReason;
this.invalidMessage = response.invalidMessage;
this.payer = response.payer;
}
};
var SettleError = class extends Error {
/**
* Creates a SettleError from a failed settlement response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The settle response containing error details
*/
constructor(statusCode, response) {
const reason = response.errorReason || "unknown reason";
const message = response.errorMessage;
super(message ? `${reason}: ${message}` : reason);
this.name = "SettleError";
this.statusCode = statusCode;
this.errorReason = response.errorReason;
this.errorMessage = response.errorMessage;
this.payer = response.payer;
this.transaction = response.transaction;
this.network = response.network;
}
};
var FacilitatorResponseError = class extends Error {
/**
* Creates a FacilitatorResponseError for malformed facilitator responses.
*
* @param message - The boundary error message
*/
constructor(message) {
super(message);
this.name = "FacilitatorResponseError";
}
};
function getFacilitatorResponseError(error) {
let current = error;
while (current instanceof Error) {
if (current instanceof FacilitatorResponseError) {
return current;
}
current = current.cause;
}
return null;
}
export {
VerifyError,
SettleError,
FacilitatorResponseError,
getFacilitatorResponseError
};
//# sourceMappingURL=chunk-VY72CEUI.mjs.map
{"version":3,"sources":["../../src/types/facilitator.ts"],"sourcesContent":["import { PaymentPayload, PaymentRequirements } from \"./payments\";\nimport { Network } from \"./\";\n\nexport type VerifyRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type VerifyResponse = {\n isValid: boolean;\n invalidReason?: string;\n invalidMessage?: string;\n payer?: string;\n extensions?: Record<string, unknown>;\n};\n\nexport type SettleRequest = {\n x402Version: number;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n};\n\nexport type SettleResponse = {\n success: boolean;\n errorReason?: string;\n errorMessage?: string;\n payer?: string;\n transaction: string;\n network: Network;\n extensions?: Record<string, unknown>;\n};\n\nexport type SupportedKind = {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n};\n\nexport type SupportedResponse = {\n kinds: SupportedKind[];\n extensions: string[];\n signers: Record<string, string[]>; // CAIP family pattern → Signer addresses\n};\n\n/**\n * Error thrown when payment verification fails.\n */\nexport class VerifyError extends Error {\n readonly invalidReason?: string;\n readonly invalidMessage?: string;\n readonly payer?: string;\n readonly statusCode: number;\n\n /**\n * Creates a VerifyError from a failed verification response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The verify response containing error details\n */\n constructor(statusCode: number, response: VerifyResponse) {\n const reason = response.invalidReason || \"unknown reason\";\n const message = response.invalidMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"VerifyError\";\n this.statusCode = statusCode;\n this.invalidReason = response.invalidReason;\n this.invalidMessage = response.invalidMessage;\n this.payer = response.payer;\n }\n}\n\n/**\n * Error thrown when payment settlement fails.\n */\nexport class SettleError extends Error {\n readonly errorReason?: string;\n readonly errorMessage?: string;\n readonly payer?: string;\n readonly transaction: string;\n readonly network: Network;\n readonly statusCode: number;\n\n /**\n * Creates a SettleError from a failed settlement response.\n *\n * @param statusCode - HTTP status code from the facilitator\n * @param response - The settle response containing error details\n */\n constructor(statusCode: number, response: SettleResponse) {\n const reason = response.errorReason || \"unknown reason\";\n const message = response.errorMessage;\n super(message ? `${reason}: ${message}` : reason);\n this.name = \"SettleError\";\n this.statusCode = statusCode;\n this.errorReason = response.errorReason;\n this.errorMessage = response.errorMessage;\n this.payer = response.payer;\n this.transaction = response.transaction;\n this.network = response.network;\n }\n}\n\n/**\n * Error thrown when a facilitator returns malformed success payload data.\n */\nexport class FacilitatorResponseError extends Error {\n /**\n * Creates a FacilitatorResponseError for malformed facilitator responses.\n *\n * @param message - The boundary error message\n */\n constructor(message: string) {\n super(message);\n this.name = \"FacilitatorResponseError\";\n }\n}\n\n/**\n * Walks an error cause chain to find the first facilitator response error.\n *\n * @param error - The thrown value to inspect\n * @returns The nested facilitator response error, if present\n */\nexport function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null {\n let current = error;\n\n while (current instanceof Error) {\n if (current instanceof FacilitatorResponseError) {\n return current;\n }\n current = current.cause;\n }\n\n return null;\n}\n"],"mappings":";AAiDO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,iBAAiB;AACzC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,gBAAgB,SAAS;AAC9B,SAAK,iBAAiB,SAAS;AAC/B,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAKO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcrC,YAAY,YAAoB,UAA0B;AACxD,UAAM,SAAS,SAAS,eAAe;AACvC,UAAM,UAAU,SAAS;AACzB,UAAM,UAAU,GAAG,MAAM,KAAK,OAAO,KAAK,MAAM;AAChD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,cAAc,SAAS;AAC5B,SAAK,eAAe,SAAS;AAC7B,SAAK,QAAQ,SAAS;AACtB,SAAK,cAAc,SAAS;AAC5B,SAAK,UAAU,SAAS;AAAA,EAC1B;AACF;AAKO,IAAM,2BAAN,cAAuC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMlD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAQO,SAAS,4BAA4B,OAAiD;AAC3F,MAAI,UAAU;AAEd,SAAO,mBAAmB,OAAO;AAC/B,QAAI,mBAAmB,0BAA0B;AAC/C,aAAO;AAAA,IACT;AACA,cAAU,QAAQ;AAAA,EACpB;AAEA,SAAO;AACT;","names":[]}
type PaymentRequirementsV1 = {
scheme: string;
network: Network;
maxAmountRequired: string;
resource: string;
description: string;
mimeType: string;
outputSchema: Record<string, unknown>;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
extra: Record<string, unknown>;
};
type PaymentRequiredV1 = {
x402Version: 1;
error?: string;
accepts: PaymentRequirementsV1[];
};
type PaymentPayloadV1 = {
x402Version: 1;
scheme: string;
network: Network;
payload: Record<string, unknown>;
};
type VerifyRequestV1 = {
x402Version: number;
paymentPayload: PaymentPayloadV1;
paymentRequirements: PaymentRequirementsV1;
};
type SettleRequestV1 = {
x402Version: number;
paymentPayload: PaymentPayloadV1;
paymentRequirements: PaymentRequirementsV1;
};
type SettleResponseV1 = {
success: boolean;
errorReason?: string;
errorMessage?: string;
payer?: string;
transaction: string;
network: Network;
};
type SupportedResponseV1 = {
kinds: {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
}[];
};
interface FacilitatorConfig {
url?: string;
createAuthHeaders?: () => Promise<{
verify: Record<string, string>;
settle: Record<string, string>;
supported: Record<string, string>;
}>;
}
/**
* Interface for facilitator clients
* Can be implemented for HTTP-based or local facilitators
*/
interface FacilitatorClient {
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
/**
* Get supported payment kinds and extensions from the facilitator
*
* @returns Supported payment kinds and extensions
*/
getSupported(): Promise<SupportedResponse>;
}
/**
* HTTP-based client for interacting with x402 facilitator services
* Handles HTTP communication with facilitator endpoints
*/
declare class HTTPFacilitatorClient implements FacilitatorClient {
readonly url: string;
private readonly _createAuthHeaders?;
/**
* Creates a new HTTPFacilitatorClient instance.
*
* @param config - Configuration options for the facilitator client
*/
constructor(config?: FacilitatorConfig);
/**
* Verify a payment with the facilitator
*
* @param paymentPayload - The payment to verify
* @param paymentRequirements - The requirements to verify against
* @returns Verification response
*/
verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a payment with the facilitator
*
* @param paymentPayload - The payment to settle
* @param paymentRequirements - The requirements for settlement
* @returns Settlement response
*/
settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
/**
* Get supported payment kinds and extensions from the facilitator.
* Retries with exponential backoff on 429 rate limit errors.
*
* @returns Supported payment kinds and extensions
*/
getSupported(): Promise<SupportedResponse>;
/**
* Creates authentication headers for a specific path.
*
* @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
* @returns An object containing the authentication headers for the specified path
*/
createAuthHeaders(path: string): Promise<{
headers: Record<string, string>;
}>;
/**
* Helper to convert objects to JSON-safe format.
* Handles BigInt and other non-JSON types.
*
* @param obj - The object to convert
* @returns The JSON-safe representation of the object
*/
private toJsonSafe;
}
/**
* Configuration for a protected resource
* Only contains payment-specific configuration, not resource metadata
*/
interface ResourceConfig {
scheme: string;
payTo: string;
price: Price;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Lifecycle Hook Context Interfaces
*/
interface PaymentRequiredContext {
requirements: PaymentRequirements[];
resourceInfo: ResourceInfo;
error?: string;
paymentRequiredResponse: PaymentRequired;
transportContext?: unknown;
}
interface VerifyContext {
paymentPayload: PaymentPayload;
requirements: PaymentRequirements;
}
interface VerifyResultContext extends VerifyContext {
result: VerifyResponse;
}
interface VerifyFailureContext extends VerifyContext {
error: Error;
}
interface SettleContext {
paymentPayload: PaymentPayload;
requirements: PaymentRequirements;
}
interface SettleResultContext extends SettleContext {
result: SettleResponse;
transportContext?: unknown;
}
interface SettleFailureContext extends SettleContext {
error: Error;
}
/**
* Lifecycle Hook Type Definitions
*/
type BeforeVerifyHook = (context: VerifyContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
type AfterVerifyHook = (context: VerifyResultContext) => Promise<void>;
type OnVerifyFailureHook = (context: VerifyFailureContext) => Promise<void | {
recovered: true;
result: VerifyResponse;
}>;
type BeforeSettleHook = (context: SettleContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
type AfterSettleHook = (context: SettleResultContext) => Promise<void>;
type OnSettleFailureHook = (context: SettleFailureContext) => Promise<void | {
recovered: true;
result: SettleResponse;
}>;
/**
* Core x402 protocol server for resource protection
* Transport-agnostic implementation of the x402 payment protocol
*/
declare class x402ResourceServer {
private facilitatorClients;
private registeredServerSchemes;
private supportedResponsesMap;
private facilitatorClientsMap;
private registeredExtensions;
private beforeVerifyHooks;
private afterVerifyHooks;
private onVerifyFailureHooks;
private beforeSettleHooks;
private afterSettleHooks;
private onSettleFailureHooks;
/**
* Creates a new x402ResourceServer instance.
*
* @param facilitatorClients - Optional facilitator client(s) for payment processing
*/
constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]);
/**
* Register a scheme/network server implementation.
*
* @param network - The network identifier
* @param server - The scheme/network server implementation
* @returns The x402ResourceServer instance for chaining
*/
register(network: Network, server: SchemeNetworkServer): x402ResourceServer;
/**
* Check if a scheme is registered for a given network.
*
* @param network - The network identifier
* @param scheme - The payment scheme name
* @returns True if the scheme is registered for the network, false otherwise
*/
hasRegisteredScheme(network: Network, scheme: string): boolean;
/**
* Registers a resource service extension that can enrich extension declarations.
*
* @param extension - The extension to register
* @returns The x402ResourceServer instance for chaining
*/
registerExtension(extension: ResourceServerExtension): this;
/**
* Check if an extension is registered.
*
* @param key - The extension key
* @returns True if the extension is registered
*/
hasExtension(key: string): boolean;
/**
* Get all registered extensions.
*
* @returns Array of registered extensions
*/
getExtensions(): ResourceServerExtension[];
/**
* Enriches declared extensions using registered extension hooks.
*
* @param declaredExtensions - Extensions declared on the route
* @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
* @returns Enriched extensions map
*/
enrichExtensions(declaredExtensions: Record<string, unknown>, transportContext: unknown): Record<string, unknown>;
/**
* Register a hook to execute before payment verification.
* Can abort verification by returning { abort: true, reason: string }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer;
/**
* Register a hook to execute after successful payment verification.
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onAfterVerify(hook: AfterVerifyHook): x402ResourceServer;
/**
* Register a hook to execute when payment verification fails.
* Can recover from failure by returning { recovered: true, result: VerifyResponse }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer;
/**
* Register a hook to execute before payment settlement.
* Can abort settlement by returning { abort: true, reason: string }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer;
/**
* Register a hook to execute after successful payment settlement.
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onAfterSettle(hook: AfterSettleHook): x402ResourceServer;
/**
* Register a hook to execute when payment settlement fails.
* Can recover from failure by returning { recovered: true, result: SettleResponse }
*
* @param hook - The hook function to register
* @returns The x402ResourceServer instance for chaining
*/
onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer;
/**
* Initialize by fetching supported kinds from all facilitators
* Creates mappings for supported responses and facilitator clients
* Earlier facilitators in the array get precedence
*/
initialize(): Promise<void>;
/**
* Get supported kind for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The supported kind or undefined if not found
*/
getSupportedKind(x402Version: number, network: Network, scheme: string): SupportedKind | undefined;
/**
* Get facilitator extensions for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The facilitator extensions or empty array if not found
*/
getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[];
/**
* Build payment requirements for a protected resource
*
* @param resourceConfig - Configuration for the protected resource
* @returns Array of payment requirements
*/
buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]>;
/**
* Build payment requirements from multiple payment options
* This method handles resolving dynamic payTo/price functions and builds requirements for each option
*
* @param paymentOptions - Array of payment options to convert
* @param context - HTTP request context for resolving dynamic functions
* @returns Array of payment requirements (one per option)
*/
buildPaymentRequirementsFromOptions<TContext = unknown>(paymentOptions: Array<{
scheme: string;
payTo: string | ((context: TContext) => string | Promise<string>);
price: Price | ((context: TContext) => Price | Promise<Price>);
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}>, context: TContext): Promise<PaymentRequirements[]>;
/**
* Create a payment required response
*
* @param requirements - Payment requirements
* @param resourceInfo - Resource information
* @param error - Error message
* @param extensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional transport-specific context (e.g., HTTP request, MCP tool context)
* @returns Payment required response object
*/
createPaymentRequiredResponse(requirements: PaymentRequirements[], resourceInfo: ResourceInfo, error?: string, extensions?: Record<string, unknown>, transportContext?: unknown): Promise<PaymentRequired>;
/**
* Verify a payment against requirements
*
* @param paymentPayload - The payment payload to verify
* @param requirements - The payment requirements
* @returns Verification response
*/
verifyPayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
/**
* Settle a verified payment
*
* @param paymentPayload - The payment payload to settle
* @param requirements - The payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)
* @returns Settlement response
*/
settlePayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown): Promise<SettleResponse>;
/**
* Find matching payment requirements for a payment
*
* @param availableRequirements - Array of available payment requirements
* @param paymentPayload - The payment payload
* @returns Matching payment requirements or undefined
*/
findMatchingRequirements(availableRequirements: PaymentRequirements[], paymentPayload: PaymentPayload): PaymentRequirements | undefined;
/**
* Process a payment request
*
* @param paymentPayload - Optional payment payload if provided
* @param resourceConfig - Configuration for the protected resource
* @param resourceInfo - Information about the resource being accessed
* @param extensions - Optional extensions to include in the response
* @returns Processing result
*/
processPaymentRequest(paymentPayload: PaymentPayload | null, resourceConfig: ResourceConfig, resourceInfo: ResourceInfo, extensions?: Record<string, unknown>): Promise<{
success: boolean;
requiresPayment?: PaymentRequired;
verificationResult?: VerifyResponse;
settlementResult?: SettleResponse;
error?: string;
}>;
/**
* Get facilitator client for a specific version, network, and scheme
*
* @param x402Version - The x402 version
* @param network - The network identifier
* @param scheme - The payment scheme
* @returns The facilitator client or undefined if not found
*/
private getFacilitatorClient;
}
/**
* Base interface for facilitator extensions.
* Extensions registered with x402Facilitator are stored by key and made
* available to mechanism implementations via FacilitatorContext.
*
* Specific extensions extend this with additional capabilities:
*
* @example
* interface Erc20GasSponsoringExtension extends FacilitatorExtension {
* batchSigner: SmartWalletBatchSigner;
* }
*/
interface FacilitatorExtension {
key: string;
}
interface ResourceServerExtension {
key: string;
/**
* Enrich extension declaration with extension-specific data.
*
* @param declaration - Extension declaration from route config
* @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
* @returns Enriched extension declaration
*/
enrichDeclaration?: (declaration: unknown, transportContext: unknown) => unknown;
/**
* Called when generating a 402 PaymentRequired response.
* Return extension data to add to extensions[key], or undefined to skip.
*
* @param declaration - Extension declaration from route config
* @param context - PaymentRequired context containing response, requirements, and optional transportContext
* @returns Extension data to add to response.extensions[key]
*/
enrichPaymentRequiredResponse?: (declaration: unknown, context: PaymentRequiredContext) => Promise<unknown>;
/**
* Called after successful payment settlement.
* Return extension data to add to response.extensions[key], or undefined to skip.
*
* @param declaration - Extension declaration from route config
* @param context - Settlement result context containing payment payload, requirements, result and optional transportContext
* @returns Extension data to add to response.extensions[key]
*/
enrichSettlementResponse?: (declaration: unknown, context: SettleResultContext) => Promise<unknown>;
}
type Network = `${string}:${string}`;
type Money = string | number;
type AssetAmount = {
asset: string;
amount: string;
extra?: Record<string, unknown>;
};
type Price = Money | AssetAmount;
interface ResourceInfo {
url: string;
description?: string;
mimeType?: string;
}
type PaymentRequirements = {
scheme: string;
network: Network;
asset: string;
amount: string;
payTo: string;
maxTimeoutSeconds: number;
extra: Record<string, unknown>;
};
type PaymentRequired = {
x402Version: number;
error?: string;
resource: ResourceInfo;
accepts: PaymentRequirements[];
extensions?: Record<string, unknown>;
};
type PaymentPayload = {
x402Version: number;
resource?: ResourceInfo;
accepted: PaymentRequirements;
payload: Record<string, unknown>;
extensions?: Record<string, unknown>;
};
type VerifyRequest = {
x402Version: number;
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};
type VerifyResponse = {
isValid: boolean;
invalidReason?: string;
invalidMessage?: string;
payer?: string;
extensions?: Record<string, unknown>;
};
type SettleRequest = {
x402Version: number;
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};
type SettleResponse = {
success: boolean;
errorReason?: string;
errorMessage?: string;
payer?: string;
transaction: string;
network: Network;
extensions?: Record<string, unknown>;
};
type SupportedKind = {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
};
type SupportedResponse = {
kinds: SupportedKind[];
extensions: string[];
signers: Record<string, string[]>;
};
/**
* Error thrown when payment verification fails.
*/
declare class VerifyError extends Error {
readonly invalidReason?: string;
readonly invalidMessage?: string;
readonly payer?: string;
readonly statusCode: number;
/**
* Creates a VerifyError from a failed verification response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The verify response containing error details
*/
constructor(statusCode: number, response: VerifyResponse);
}
/**
* Error thrown when payment settlement fails.
*/
declare class SettleError extends Error {
readonly errorReason?: string;
readonly errorMessage?: string;
readonly payer?: string;
readonly transaction: string;
readonly network: Network;
readonly statusCode: number;
/**
* Creates a SettleError from a failed settlement response.
*
* @param statusCode - HTTP status code from the facilitator
* @param response - The settle response containing error details
*/
constructor(statusCode: number, response: SettleResponse);
}
/**
* Error thrown when a facilitator returns malformed success payload data.
*/
declare class FacilitatorResponseError extends Error {
/**
* Creates a FacilitatorResponseError for malformed facilitator responses.
*
* @param message - The boundary error message
*/
constructor(message: string);
}
/**
* Walks an error cause chain to find the first facilitator response error.
*
* @param error - The thrown value to inspect
* @returns The nested facilitator response error, if present
*/
declare function getFacilitatorResponseError(error: unknown): FacilitatorResponseError | null;
/**
* Money parser function that converts a numeric amount to an AssetAmount
* Receives the amount as a decimal number (e.g., 1.50 for $1.50)
* Returns null to indicate "cannot handle this amount", causing fallback to next parser
* Always returns a Promise for consistency - use async/await
*
* @param amount - The decimal amount (e.g., 1.50)
* @param network - The network identifier for context
* @returns AssetAmount or null to try next parser
*/
type MoneyParser = (amount: number, network: Network) => Promise<AssetAmount | null>;
/**
* Result of createPaymentPayload - the core payload fields.
* Contains the x402 version, scheme-specific payload data, and optional extension data.
* Schemes may return extensions (e.g., EIP-2612 gas sponsoring) that get merged
* with server-declared extensions in the final PaymentPayload.
*/
type PaymentPayloadResult = Pick<PaymentPayload, "x402Version" | "payload"> & {
extensions?: Record<string, unknown>;
};
/**
* Context passed to scheme's createPaymentPayload for extensions awareness.
* Contains the server-declared extensions from PaymentRequired so the scheme
* can check which extensions are advertised and respond accordingly.
*/
interface PaymentPayloadContext {
extensions?: Record<string, unknown>;
}
interface SchemeNetworkClient {
readonly scheme: string;
createPaymentPayload(x402Version: number, paymentRequirements: PaymentRequirements, context?: PaymentPayloadContext): Promise<PaymentPayloadResult>;
}
/**
* Context passed to SchemeNetworkFacilitator.verify/settle, providing
* access to registered facilitator extensions. Mechanism implementations
* use this to retrieve extension-provided capabilities (e.g., a batch signer).
*/
interface FacilitatorContext {
getExtension<T extends FacilitatorExtension = FacilitatorExtension>(key: string): T | undefined;
}
interface SchemeNetworkFacilitator {
readonly scheme: string;
/**
* CAIP family pattern that this facilitator supports.
* Used to group signers by blockchain family in the supported response.
*
* @example
* // EVM facilitators
* readonly caipFamily = "eip155:*";
*
* @example
* // SVM facilitators
* readonly caipFamily = "solana:*";
*/
readonly caipFamily: string;
/**
* Get mechanism-specific extra data needed for the supported kinds endpoint.
* This method is called when building the facilitator's supported response.
*
* @param network - The network identifier for context
* @returns Extra data object or undefined if no extra data is needed
*
* @example
* // EVM schemes return undefined (no extra data needed)
* getExtra(network: Network): undefined {
* return undefined;
* }
*
* @example
* // SVM schemes return feePayer address
* getExtra(network: Network): Record<string, unknown> | undefined {
* return { feePayer: this.signer.address };
* }
*/
getExtra(network: Network): Record<string, unknown> | undefined;
/**
* Get signer addresses used by this facilitator for a given network.
* These are included in the supported response to help clients understand
* which addresses might sign/pay for transactions.
*
* Supports multiple addresses for load balancing, key rotation, and high availability.
*
* @param network - The network identifier
* @returns Array of signer addresses (wallet addresses, fee payer addresses, etc.)
*
* @example
* // EVM facilitator
* getSigners(network: string): string[] {
* return [...this.signer.getAddresses()];
* }
*
* @example
* // SVM facilitator
* getSigners(network: string): string[] {
* return [...this.signer.getAddresses()];
* }
*/
getSigners(network: string): string[];
verify(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<VerifyResponse>;
settle(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<SettleResponse>;
}
interface SchemeNetworkServer {
readonly scheme: string;
/**
* Convert a user-friendly price to the scheme's specific amount and asset format
* Always returns a Promise for consistency
*
* @param price - User-friendly price (e.g., "$0.10", "0.10", { amount: "100000", asset: "USDC" })
* @param network - The network identifier for context
* @returns Promise that resolves to the converted amount, asset identifier, and any extra metadata
*
* @example
* // For EVM networks with USDC:
* await parsePrice("$0.10", "eip155:8453") => { amount: "100000", asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }
*
* // For custom schemes:
* await parsePrice("10 points", "custom:network") => { amount: "10", asset: "points" }
*/
parsePrice(price: Price, network: Network): Promise<AssetAmount>;
/**
* Build payment requirements for this scheme/network combination
*
* @param paymentRequirements - Base payment requirements with amount/asset already set
* @param supportedKind - The supported kind from facilitator's /supported endpoint
* @param supportedKind.x402Version - The x402 version
* @param supportedKind.scheme - The payment scheme
* @param supportedKind.network - The network identifier
* @param supportedKind.extra - Optional extra metadata
* @param facilitatorExtensions - Extensions supported by the facilitator
* @returns Enhanced payment requirements ready to be sent to clients
*/
enhancePaymentRequirements(paymentRequirements: PaymentRequirements, supportedKind: {
x402Version: number;
scheme: string;
network: Network;
extra?: Record<string, unknown>;
}, facilitatorExtensions: string[]): Promise<PaymentRequirements>;
}
export { type AssetAmount as A, type PaymentPayloadResult as B, type PaymentPayloadContext as C, type FacilitatorContext as D, type ResourceServerExtension as E, type FacilitatorExtension as F, type PaymentRequiredContext as G, HTTPFacilitatorClient as H, type Money as M, type Network as N, type PaymentPayload as P, type ResourceConfig as R, type SettleResponse as S, type VerifyResponse as V, type PaymentRequirements as a, type SchemeNetworkFacilitator as b, type PaymentRequired as c, type FacilitatorClient as d, type FacilitatorConfig as e, FacilitatorResponseError as f, getFacilitatorResponseError as g, type SchemeNetworkClient as h, type SettleResultContext as i, type Price as j, type PaymentRequirementsV1 as k, type PaymentRequiredV1 as l, type PaymentPayloadV1 as m, type VerifyRequestV1 as n, type SettleRequestV1 as o, type SettleResponseV1 as p, type SupportedResponseV1 as q, type VerifyRequest as r, type SettleRequest as s, type SupportedResponse as t, VerifyError as u, SettleError as v, type ResourceInfo as w, x402ResourceServer as x, type SchemeNetworkServer as y, type MoneyParser as z };
import { x as x402ResourceServer, j as Price, N as Network, S as SettleResponse, c as PaymentRequired, P as PaymentPayload, a as PaymentRequirements } from './mechanisms-B3SXtgLV.mjs';
/**
* Framework-agnostic HTTP adapter interface
* Implementations provide framework-specific HTTP operations
*/
interface HTTPAdapter {
getHeader(name: string): string | undefined;
getMethod(): string;
getPath(): string;
getUrl(): string;
getAcceptHeader(): string;
getUserAgent(): string;
/**
* Get query parameters from the request URL
*
* @returns Record of query parameter key-value pairs
*/
getQueryParams?(): Record<string, string | string[]>;
/**
* Get a specific query parameter by name
*
* @param name - The query parameter name
* @returns The query parameter value(s) or undefined
*/
getQueryParam?(name: string): string | string[] | undefined;
/**
* Get the parsed request body
* Framework adapters should parse JSON/form data appropriately
*
* @returns The parsed request body
*/
getBody?(): unknown;
}
/**
* Paywall configuration for HTML responses
*/
interface PaywallConfig {
appName?: string;
appLogo?: string;
sessionTokenEndpoint?: string;
currentUrl?: string;
testnet?: boolean;
}
/**
* Paywall provider interface for generating HTML
*/
interface PaywallProvider {
generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;
}
/**
* Dynamic payTo function that receives HTTP request context
*/
type DynamicPayTo = (context: HTTPRequestContext) => string | Promise<string>;
/**
* Dynamic price function that receives HTTP request context
*/
type DynamicPrice = (context: HTTPRequestContext) => Price | Promise<Price>;
/**
* Result of response body callbacks containing content type and body.
*/
interface HTTPResponseBody {
/**
* The content type for the response (e.g., 'application/json', 'text/plain').
*/
contentType: string;
/**
* The response body to include in the 402 response.
*/
body: unknown;
}
/**
* Dynamic function to generate a custom response for unpaid requests.
* Receives the HTTP request context and returns the content type and body to include in the 402 response.
*/
type UnpaidResponseBody = (context: HTTPRequestContext) => HTTPResponseBody | Promise<HTTPResponseBody>;
/**
* Dynamic function to generate a custom response for settlement failures.
* Receives the HTTP request context and settle failure result, returns the content type and body.
*/
type SettlementFailedResponseBody = (context: HTTPRequestContext, settleResult: Omit<ProcessSettleFailureResponse, "response">) => HTTPResponseBody | Promise<HTTPResponseBody>;
/**
* A single payment option for a route
* Represents one way a client can pay for access to the resource
*/
interface PaymentOption {
scheme: string;
payTo: string | DynamicPayTo;
price: Price | DynamicPrice;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Route configuration for HTTP endpoints
*
* The 'accepts' field defines payment options for the route.
* Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.
*/
interface RouteConfig {
accepts: PaymentOption | PaymentOption[];
resource?: string;
description?: string;
mimeType?: string;
customPaywallHtml?: string;
/**
* Optional callback to generate a custom response for unpaid API requests.
* This allows servers to return preview data, error messages, or other content
* when a request lacks payment.
*
* For browser requests (Accept: text/html), the paywall HTML takes precedence.
* This callback is only used for API clients.
*
* If not provided, defaults to { contentType: 'application/json', body: {} }.
*
* @param context - The HTTP request context
* @returns An object containing both contentType and body for the 402 response
*/
unpaidResponseBody?: UnpaidResponseBody;
/**
* Optional callback to generate a custom response for settlement failures.
* If not provided, defaults to { contentType: 'application/json', body: {} }.
*
* @param context - The HTTP request context
* @param settleResult - The settlement failure result
* @returns An object containing both contentType and body for the 402 response
*/
settlementFailedResponseBody?: SettlementFailedResponseBody;
extensions?: Record<string, unknown>;
}
/**
* Routes configuration - maps path patterns to route configs
*/
type RoutesConfig = Record<string, RouteConfig> | RouteConfig;
/**
* Hook that runs on every request to a protected route, before payment processing.
* Can grant access without payment, deny the request, or continue to payment flow.
*
* @returns
* - `void` - Continue to payment processing (default behavior)
* - `{ grantAccess: true }` - Grant access without requiring payment
* - `{ abort: true; reason: string }` - Deny the request (returns 403)
*/
type ProtectedRequestHook = (context: HTTPRequestContext, routeConfig: RouteConfig) => Promise<void | {
grantAccess: true;
} | {
abort: true;
reason: string;
}>;
/**
* Compiled route for efficient matching
*/
interface CompiledRoute {
verb: string;
regex: RegExp;
config: RouteConfig;
pattern: string;
}
/**
* HTTP request context that encapsulates all request data
*/
interface HTTPRequestContext {
adapter: HTTPAdapter;
path: string;
method: string;
paymentHeader?: string;
routePattern?: string;
}
/**
* HTTP transport context contains both request context and optional response data.
*/
interface HTTPTransportContext {
/** The HTTP request context */
request: HTTPRequestContext;
/** The response body buffer */
responseBody?: Buffer;
}
/**
* HTTP response instructions for the framework middleware
*/
interface HTTPResponseInstructions {
status: number;
headers: Record<string, string>;
body?: unknown;
isHtml?: boolean;
}
/**
* Result of processing an HTTP request for payment
*/
type HTTPProcessResult = {
type: "no-payment-required";
} | {
type: "payment-verified";
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
declaredExtensions?: Record<string, unknown>;
} | {
type: "payment-error";
response: HTTPResponseInstructions;
};
/**
* Result of processSettlement
*/
type ProcessSettleSuccessResponse = SettleResponse & {
success: true;
headers: Record<string, string>;
requirements: PaymentRequirements;
};
type ProcessSettleFailureResponse = SettleResponse & {
success: false;
errorReason: string;
errorMessage?: string;
headers: Record<string, string>;
response: HTTPResponseInstructions;
};
type ProcessSettleResultResponse = ProcessSettleSuccessResponse | ProcessSettleFailureResponse;
/**
* Represents a validation error for a specific route's payment configuration.
*/
interface RouteValidationError {
/** The route pattern (e.g., "GET /api/weather") */
routePattern: string;
/** The payment scheme that failed validation */
scheme: string;
/** The network that failed validation */
network: Network;
/** The type of validation failure */
reason: "missing_scheme" | "missing_facilitator";
/** Human-readable error message */
message: string;
}
/**
* Error thrown when route configuration validation fails.
*/
declare class RouteConfigurationError extends Error {
/** The validation errors that caused this exception */
readonly errors: RouteValidationError[];
/**
* Creates a new RouteConfigurationError with the given validation errors.
*
* @param errors - The validation errors that caused this exception.
*/
constructor(errors: RouteValidationError[]);
}
/**
* HTTP-enhanced x402 resource server
* Provides framework-agnostic HTTP protocol handling
*/
declare class x402HTTPResourceServer {
private ResourceServer;
private compiledRoutes;
private routesConfig;
private paywallProvider?;
private protectedRequestHooks;
/**
* Creates a new x402HTTPResourceServer instance.
*
* @param ResourceServer - The core x402ResourceServer instance to use
* @param routes - Route configuration for payment-protected endpoints
*/
constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig);
/**
* Get the underlying x402ResourceServer instance.
*
* @returns The underlying x402ResourceServer instance
*/
get server(): x402ResourceServer;
/**
* Get the routes configuration.
*
* @returns The routes configuration
*/
get routes(): RoutesConfig;
/**
* Initialize the HTTP resource server.
*
* This method initializes the underlying resource server (fetching facilitator support)
* and then validates that all route payment configurations have corresponding
* registered schemes and facilitator support.
*
* @throws RouteConfigurationError if any route's payment options don't have
* corresponding registered schemes or facilitator support
*
* @example
* ```typescript
* const httpServer = new x402HTTPResourceServer(server, routes);
* await httpServer.initialize();
* ```
*/
initialize(): Promise<void>;
/**
* Register a custom paywall provider for generating HTML
*
* @param provider - PaywallProvider instance
* @returns This service instance for chaining
*/
registerPaywallProvider(provider: PaywallProvider): this;
/**
* Register a hook that runs on every request to a protected route, before payment processing.
* Hooks are executed in order of registration. The first hook to return a non-void result wins.
*
* @param hook - The request hook function
* @returns The x402HTTPResourceServer instance for chaining
*/
onProtectedRequest(hook: ProtectedRequestHook): this;
/**
* Process HTTP request and return response instructions
* This is the main entry point for framework middleware
*
* @param context - HTTP request context
* @param paywallConfig - Optional paywall configuration
* @returns Process result indicating next action for middleware
*/
processHTTPRequest(context: HTTPRequestContext, paywallConfig?: PaywallConfig): Promise<HTTPProcessResult>;
/**
* Process settlement after successful response
*
* @param paymentPayload - The verified payment payload
* @param requirements - The matching payment requirements
* @param declaredExtensions - Optional declared extensions (for per-key enrichment)
* @param transportContext - Optional HTTP transport context
* @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
*/
processSettlement(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: HTTPTransportContext): Promise<ProcessSettleResultResponse>;
/**
* Check if a request requires payment based on route configuration
*
* @param context - HTTP request context
* @returns True if the route requires payment, false otherwise
*/
requiresPayment(context: HTTPRequestContext): boolean;
/**
* Build HTTPResponseInstructions for settlement failure.
* Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.
*
* @param failure - Settlement failure result with headers
* @param transportContext - Optional HTTP transport context for the request
* @returns HTTP response instructions for the 402 settlement failure response
*/
private buildSettlementFailureResponse;
/**
* Normalizes a RouteConfig's accepts field into an array of PaymentOptions
* Handles both single PaymentOption and array formats
*
* @param routeConfig - Route configuration
* @returns Array of payment options
*/
private normalizePaymentOptions;
/**
* Validates that all payment options in routes have corresponding registered schemes
* and facilitator support.
*
* @returns Array of validation errors (empty if all routes are valid)
*/
private validateRouteConfiguration;
/**
* Get route configuration for a request
*
* @param path - Request path
* @param method - HTTP method
* @returns Route configuration and pattern, or undefined if no match
*/
private getRouteConfig;
/**
* Extract payment from HTTP headers (handles v1 and v2)
*
* @param adapter - HTTP adapter
* @returns Decoded payment payload or null
*/
private extractPayment;
/**
* Check if request is from a web browser
*
* @param adapter - HTTP adapter
* @returns True if request appears to be from a browser
*/
private isWebBrowser;
/**
* Create HTTP response instructions from payment required
*
* @param paymentRequired - Payment requirements
* @param isWebBrowser - Whether request is from browser
* @param paywallConfig - Paywall configuration
* @param customHtml - Custom HTML template
* @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
* @returns Response instructions
*/
private createHTTPResponse;
/**
* Create HTTP payment required response (v1 puts in body, v2 puts in header)
*
* @param paymentRequired - Payment required object
* @returns Headers and body for the HTTP response
*/
private createHTTPPaymentRequiredResponse;
/**
* Create settlement response headers
*
* @param settleResponse - Settlement response
* @returns Headers to add to response
*/
private createSettlementHeaders;
/**
* Parse route pattern into verb and regex
*
* @param pattern - Route pattern like "GET /api/*", "/api/[id]", or "/api/:id"
* @returns Parsed pattern with verb and regex
*/
private parseRoutePattern;
/**
* Normalize path for matching
*
* @param path - Raw path from request
* @returns Normalized path
*/
private normalizePath;
/**
* Generate paywall HTML for browser requests
*
* @param paymentRequired - Payment required response
* @param paywallConfig - Optional paywall configuration
* @param customHtml - Optional custom HTML template
* @returns HTML string
*/
private generatePaywallHTML;
/**
* Extract display amount from payment requirements.
*
* @param paymentRequired - The payment required object
* @returns The display amount in decimal format
*/
private getDisplayAmount;
}
export { type CompiledRoute as C, type DynamicPayTo as D, type HTTPAdapter as H, type PaywallConfig as P, type RouteConfig as R, type SettlementFailedResponseBody as S, type UnpaidResponseBody as U, type HTTPRequestContext as a, type HTTPTransportContext as b, type HTTPResponseInstructions as c, type HTTPProcessResult as d, type PaywallProvider as e, type PaymentOption as f, type RoutesConfig as g, type DynamicPrice as h, type HTTPResponseBody as i, type ProcessSettleResultResponse as j, type ProcessSettleSuccessResponse as k, type ProcessSettleFailureResponse as l, type RouteValidationError as m, RouteConfigurationError as n, type ProtectedRequestHook as o, x402HTTPResourceServer as x };

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display