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.10.0
to
2.11.0
+850
dist/cjs/mechanisms-C6YmSXgy.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>;
}[];
};
/**
* Recursive readonly for hook contexts so accidental in-place mutation is visible at compile time.
* (Runtime mutation is still possible via other references; see extension enrich validation.)
*/
type DeepReadonly<T> = T extends (infer U)[] ? ReadonlyArray<DeepReadonly<U>> : T extends object ? {
readonly [K in keyof T]: DeepReadonly<T[K]>;
} : T;
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;
/**
* Payment recipient. Use a **vacant** value (`""` or whitespace-only) when an extension must
* fill `payTo` during `enrichPaymentRequiredResponse`; non-vacant values are **immutable** there
* so extensions cannot redirect funds to an arbitrary address.
*/
payTo: string;
price: Price;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Context for `enrichPaymentRequiredResponse`. Extensions may merge extension payload via the
* return value. In-place edits to `paymentRequiredResponse.accepts` are **allowlisted** only
* (see {@link assertAcceptsAllowlistedAfterExtensionEnrich}): `scheme`, `network`, and
* `maxTimeoutSeconds` are immutable; `payTo`, `amount`, and `asset` may change only when the
* baseline value was vacant; `extra` may add keys but must not change or remove baseline keys.
*/
interface PaymentRequiredContext {
requirements: PaymentRequirements[];
resourceInfo: ResourceInfo;
error?: string;
paymentRequiredResponse: PaymentRequired;
transportContext?: unknown;
}
/**
* Verify / settle lifecycle hook context: treat as **read-only** for core protocol fields.
* Control flow uses **abort** / **recover** return values only, not in-place mutation.
*/
interface VerifyContext {
paymentPayload: DeepReadonly<PaymentPayload>;
requirements: DeepReadonly<PaymentRequirements>;
declaredExtensions: DeepReadonly<Record<string, unknown>>;
transportContext?: unknown;
}
interface VerifyResultContext extends VerifyContext {
result: DeepReadonly<VerifyResponse>;
}
interface VerifyFailureContext extends VerifyContext {
error: Error;
}
interface SettleContext {
paymentPayload: DeepReadonly<PaymentPayload>;
requirements: DeepReadonly<PaymentRequirements>;
declaredExtensions: DeepReadonly<Record<string, unknown>>;
transportContext?: unknown;
}
interface SettleResultContext extends SettleContext {
result: DeepReadonly<SettleResponse>;
}
interface SettleFailureContext extends SettleContext {
error: Error;
}
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 extensionHookAdapters;
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;
/**
* Returns the decimal precision for the asset specified in the given payment requirements.
* Looks up the registered scheme for the network and delegates to its getAssetDecimals
* method if available. Falls back to 6 (standard for USDC stablecoins) when the scheme
* does not implement getAssetDecimals or is not registered.
*
* @param requirements - The payment requirements containing scheme, network, and asset
* @returns The number of decimal places for the asset
*/
getAssetDecimalsForRequirements(requirements: PaymentRequirements): number;
/**
* Registers a resource server extension (enrichment and optional verify/settle hooks).
* Re-registering the same key overwrites; omitting `hooks` removes adapter handles for that key.
*
* @param extension - Extension definition including `key` and optional `hooks`
* @returns This server 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>;
/**
* Verifies a payment against requirements, running manual and in-use extension hooks.
*
* @param paymentPayload - Signed payment payload from the client
* @param requirements - Requirements matched to the payload
* @param declaredExtensions - Optional per-extension declarations for the request
* @param transportContext - Optional transport-specific context (e.g. HTTP, MCP)
* @returns Facilitator verify outcome, or abort/recovery as driven by hooks
*/
verifyPayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown): 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
* @param transportContext - Optional transport context for extension hooks and enrichment
* @returns Processing result
*/
processPaymentRequest(paymentPayload: PaymentPayload | null, resourceConfig: ResourceConfig, resourceInfo: ResourceInfo, extensions?: Record<string, unknown>, transportContext?: unknown): Promise<{
success: boolean;
requiresPayment?: PaymentRequired;
verificationResult?: VerifyResponse;
settlementResult?: SettleResponse;
error?: string;
}>;
/**
* Logs a warning when a manual or extension adapter lifecycle hook throws.
*
* @param phase - Lifecycle phase name (e.g. `beforeVerify`)
* @param label - Hook source label from {@link getLabeledHooks} (manual index or extension key)
* @param error - Thrown value or rejection reason
*/
private warnResourceServerHookFailure;
/**
* Logs a warning when a registered extension enrichment hook throws.
*
* @param extensionKey - Registered extension identifier
* @param hookName - Hook method name (e.g. `enrichDeclaration`)
* @param error - Thrown value or rejection reason
*/
private warnExtensionHookFailure;
/**
* Manual hooks first, then extension adapters for keys in `extensionKeysInUse`.
* Each entry carries a stable label for logging when a hook throws.
*
* @param phase - Hook slot (e.g. `beforeVerify`)
* @param extensionKeysInUse - Declared extension keys for this request
* @returns Hooks in invocation order with source labels
*/
private getLabeledHooks;
/**
* 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;
}
interface FacilitatorExtension {
key: string;
}
/**
* Per-extension verify/settle hooks. Contexts are **read-only** for core protocol fields; use
* **abort** / **recover** return values instead of mutating `paymentPayload`, `requirements`, etc.
*/
interface ResourceServerExtensionHooks {
onBeforeVerify?: (declaration: unknown, context: VerifyContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
onAfterVerify?: (declaration: unknown, context: VerifyResultContext) => Promise<void>;
onVerifyFailure?: (declaration: unknown, context: VerifyFailureContext) => Promise<void | {
recovered: true;
result: VerifyResponse;
}>;
onBeforeSettle?: (declaration: unknown, context: SettleContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
onAfterSettle?: (declaration: unknown, context: SettleResultContext) => Promise<void>;
onSettleFailure?: (declaration: unknown, context: SettleFailureContext) => Promise<void | {
recovered: true;
result: SettleResponse;
}>;
}
interface ResourceServerExtension {
key: string;
enrichDeclaration?: (declaration: unknown, transportContext: unknown) => unknown;
/**
* Return value merges into `extensions[key]`. In-place edits to `accepts` are allowlisted only
* (see server `assertAcceptsAllowlistedAfterExtensionEnrich`): vacant `payTo` / `amount` / `asset`
* may be filled; locked values and `scheme` / `network` / `maxTimeoutSeconds` / baseline `extra`
* entries are immutable.
*/
enrichPaymentRequiredResponse?: (declaration: unknown, context: PaymentRequiredContext) => Promise<unknown>;
/**
* Return value merges into `settleResult.extensions[key]`. Facilitator fields (`success`,
* `transaction`, `network`, etc.) must not be changed; only `extensions` is merged from the hook.
*/
enrichSettlementResponse?: (declaration: unknown, context: SettleResultContext) => Promise<unknown>;
/** Installed on `registerExtension`; runs only when `declaredExtensions[key]` is defined. */
hooks?: ResourceServerExtensionHooks;
}
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 DeepReadonly as $, 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 ResourceServerExtensionHooks as _, 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 PaymentRequiredContext as h, type VerifyContext as i, type VerifyResultContext as j, type VerifyFailureContext as k, type SettleContext as l, type SettleResultContext as m, type SettleFailureContext as n, type SettlementOverrides as o, type BeforeSettleHook as p, type AfterSettleHook as q, type OnSettleFailureHook as r, type Price as s, type SchemeNetworkClient 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, s as Price, N as Network, S as SettleResponse, c as PaymentRequired, P as PaymentPayload, a as PaymentRequirements, o as SettlementOverrides } from './mechanisms-C6YmSXgy.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;
/**
* Check if any routes in the configuration declare bazaar extensions.
*
* @param routes - Route configuration
* @returns True if any route has extensions.bazaar defined
*/
declare function checkIfBazaarNeeded(routes: RoutesConfig): boolean;
/**
* 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.
* Uses the registered scheme's decimal precision for the asset, falling back to 6.
*
* @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, checkIfBazaarNeeded as q, x402HTTPResourceServer as x };
// src/utils/index.ts
function numberToDecimalString(n) {
const str = n.toString();
if (!/[eE]/.test(str)) return str;
const [significand, exponentStr] = str.split(/[eE]/);
const exp = parseInt(exponentStr, 10);
const negative = significand.startsWith("-");
const abs = negative ? significand.slice(1) : significand;
const [intDigits, fracDigits = ""] = abs.split(".");
const allDigits = intDigits + fracDigits;
const decimalPos = intDigits.length + exp;
let result;
if (decimalPos <= 0) {
result = "0." + "0".repeat(-decimalPos) + allDigits;
} else if (decimalPos >= allDigits.length) {
result = allDigits + "0".repeat(decimalPos - allDigits.length);
} else {
result = allDigits.slice(0, decimalPos) + "." + allDigits.slice(decimalPos);
}
return (negative ? "-" : "") + result;
}
function convertToTokenAmount(decimalAmount, decimals) {
if (/[eE]/.test(decimalAmount)) {
throw new Error(
`Invalid amount: ${decimalAmount} \u2014 use decimal notation, not scientific notation`
);
}
if (!/^-?\d+\.?\d*$/.test(decimalAmount)) {
throw new Error(`Invalid amount: ${decimalAmount}`);
}
const [intPart, decPart = ""] = decimalAmount.split(".");
const paddedDec = decPart.padEnd(decimals, "0").slice(0, decimals);
const tokenAmount = (intPart + paddedDec).replace(/^0+/, "") || "0";
if (tokenAmount === "0" && /[1-9]/.test(decimalAmount)) {
throw new Error(
`Amount ${decimalAmount} is too small to represent with ${decimals} decimal places`
);
}
return tokenAmount;
}
var findSchemesByNetwork = (map, network) => {
let implementationsByScheme = map.get(network);
if (!implementationsByScheme) {
for (const [registeredNetworkPattern, implementations] of map.entries()) {
const pattern = registeredNetworkPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
const regex = new RegExp(`^${pattern}$`);
if (regex.test(network)) {
implementationsByScheme = implementations;
break;
}
}
}
return implementationsByScheme;
};
var findByNetworkAndScheme = (map, scheme, network) => {
return findSchemesByNetwork(map, network)?.get(scheme);
};
var findFacilitatorBySchemeAndNetwork = (schemeMap, scheme, network) => {
const schemeData = schemeMap.get(scheme);
if (!schemeData) return void 0;
if (schemeData.networks.has(network)) {
return schemeData.facilitator;
}
const patternRegex = new RegExp("^" + schemeData.pattern.replace("*", ".*") + "$");
if (patternRegex.test(network)) {
return schemeData.facilitator;
}
return void 0;
};
var Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;
function safeBase64Encode(data) {
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
const bytes = new TextEncoder().encode(data);
const binaryString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
return globalThis.btoa(binaryString);
}
return Buffer.from(data, "utf8").toString("base64");
}
function safeBase64Decode(data) {
if (typeof globalThis !== "undefined" && typeof globalThis.atob === "function") {
const binaryString = globalThis.atob(data);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const decoder = new TextDecoder("utf-8");
return decoder.decode(bytes);
}
return Buffer.from(data, "base64").toString("utf-8");
}
function deepEqual(obj1, obj2) {
const normalize = (obj) => {
if (obj === null || obj === void 0) return JSON.stringify(obj);
if (typeof obj !== "object") return JSON.stringify(obj);
if (Array.isArray(obj)) {
return JSON.stringify(
obj.map(
(item) => typeof item === "object" && item !== null ? JSON.parse(normalize(item)) : item
)
);
}
const sorted = {};
Object.keys(obj).sort().forEach((key) => {
const value = obj[key];
sorted[key] = typeof value === "object" && value !== null ? JSON.parse(normalize(value)) : value;
});
return JSON.stringify(sorted);
};
try {
return normalize(obj1) === normalize(obj2);
} catch {
return JSON.stringify(obj1) === JSON.stringify(obj2);
}
}
export {
numberToDecimalString,
convertToTokenAmount,
findSchemesByNetwork,
findByNetworkAndScheme,
findFacilitatorBySchemeAndNetwork,
Base64EncodedRegex,
safeBase64Encode,
safeBase64Decode,
deepEqual
};
//# sourceMappingURL=chunk-4BKQ2IT7.mjs.map
{"version":3,"sources":["../../src/utils/index.ts"],"sourcesContent":["import { Network } from \"../types\";\n\n/**\n * Converts a JavaScript number to a plain decimal string, expanding scientific notation\n * via string manipulation rather than parseFloat round-tripping.\n *\n * e.g. 1e-7 → \"0.0000001\", 4.02 → \"4.02\"\n *\n * @param n - The number to convert\n * @returns A plain decimal string representation with no scientific notation\n */\nexport function numberToDecimalString(n: number): string {\n const str = n.toString();\n if (!/[eE]/.test(str)) return str;\n\n const [significand, exponentStr] = str.split(/[eE]/);\n const exp = parseInt(exponentStr, 10);\n const negative = significand.startsWith(\"-\");\n const abs = negative ? significand.slice(1) : significand;\n const [intDigits, fracDigits = \"\"] = abs.split(\".\");\n const allDigits = intDigits + fracDigits;\n const decimalPos = intDigits.length + exp;\n\n let result: string;\n if (decimalPos <= 0) {\n result = \"0.\" + \"0\".repeat(-decimalPos) + allDigits;\n } else if (decimalPos >= allDigits.length) {\n result = allDigits + \"0\".repeat(decimalPos - allDigits.length);\n } else {\n result = allDigits.slice(0, decimalPos) + \".\" + allDigits.slice(decimalPos);\n }\n return (negative ? \"-\" : \"\") + result;\n}\n\n/**\n * Convert a decimal amount to token smallest units.\n * Accepts only plain decimal strings — scientific notation is not allowed.\n * Throws if the amount is non-zero but too small to represent with the given decimal precision.\n *\n * @param decimalAmount - The decimal amount as a plain string (e.g., \"0.10\")\n * @param decimals - The number of decimals for the token (e.g., 6 for USDC)\n * @returns The amount in smallest units as a string\n */\nexport function convertToTokenAmount(decimalAmount: string, decimals: number): string {\n if (/[eE]/.test(decimalAmount)) {\n throw new Error(\n `Invalid amount: ${decimalAmount} — use decimal notation, not scientific notation`,\n );\n }\n if (!/^-?\\d+\\.?\\d*$/.test(decimalAmount)) {\n throw new Error(`Invalid amount: ${decimalAmount}`);\n }\n const [intPart, decPart = \"\"] = decimalAmount.split(\".\");\n const paddedDec = decPart.padEnd(decimals, \"0\").slice(0, decimals);\n const tokenAmount = (intPart + paddedDec).replace(/^0+/, \"\") || \"0\";\n if (tokenAmount === \"0\" && /[1-9]/.test(decimalAmount)) {\n throw new Error(\n `Amount ${decimalAmount} is too small to represent with ${decimals} decimal places`,\n );\n }\n return tokenAmount;\n}\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData<T> {\n facilitator: T;\n networks: Set<Network>;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = <T>(\n map: Map<string, Map<string, T>>,\n network: Network,\n): Map<string, T> | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = <T>(\n map: Map<string, Map<string, T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = <T>(\n schemeMap: Map<string, SchemeData<T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record<string, unknown> = {};\n Object.keys(obj as Record<string, unknown>)\n .sort()\n .forEach(key => {\n const value = (obj as Record<string, unknown>)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n"],"mappings":";AAWO,SAAS,sBAAsB,GAAmB;AACvD,QAAM,MAAM,EAAE,SAAS;AACvB,MAAI,CAAC,OAAO,KAAK,GAAG,EAAG,QAAO;AAE9B,QAAM,CAAC,aAAa,WAAW,IAAI,IAAI,MAAM,MAAM;AACnD,QAAM,MAAM,SAAS,aAAa,EAAE;AACpC,QAAM,WAAW,YAAY,WAAW,GAAG;AAC3C,QAAM,MAAM,WAAW,YAAY,MAAM,CAAC,IAAI;AAC9C,QAAM,CAAC,WAAW,aAAa,EAAE,IAAI,IAAI,MAAM,GAAG;AAClD,QAAM,YAAY,YAAY;AAC9B,QAAM,aAAa,UAAU,SAAS;AAEtC,MAAI;AACJ,MAAI,cAAc,GAAG;AACnB,aAAS,OAAO,IAAI,OAAO,CAAC,UAAU,IAAI;AAAA,EAC5C,WAAW,cAAc,UAAU,QAAQ;AACzC,aAAS,YAAY,IAAI,OAAO,aAAa,UAAU,MAAM;AAAA,EAC/D,OAAO;AACL,aAAS,UAAU,MAAM,GAAG,UAAU,IAAI,MAAM,UAAU,MAAM,UAAU;AAAA,EAC5E;AACA,UAAQ,WAAW,MAAM,MAAM;AACjC;AAWO,SAAS,qBAAqB,eAAuB,UAA0B;AACpF,MAAI,OAAO,KAAK,aAAa,GAAG;AAC9B,UAAM,IAAI;AAAA,MACR,mBAAmB,aAAa;AAAA,IAClC;AAAA,EACF;AACA,MAAI,CAAC,gBAAgB,KAAK,aAAa,GAAG;AACxC,UAAM,IAAI,MAAM,mBAAmB,aAAa,EAAE;AAAA,EACpD;AACA,QAAM,CAAC,SAAS,UAAU,EAAE,IAAI,cAAc,MAAM,GAAG;AACvD,QAAM,YAAY,QAAQ,OAAO,UAAU,GAAG,EAAE,MAAM,GAAG,QAAQ;AACjE,QAAM,eAAe,UAAU,WAAW,QAAQ,OAAO,EAAE,KAAK;AAChE,MAAI,gBAAgB,OAAO,QAAQ,KAAK,aAAa,GAAG;AACtD,UAAM,IAAI;AAAA,MACR,UAAU,aAAa,mCAAmC,QAAQ;AAAA,IACpE;AAAA,EACF;AACA,SAAO;AACT;AAWO,IAAM,uBAAuB,CAClC,KACA,YAC+B;AAE/B,MAAI,0BAA0B,IAAI,IAAI,OAAO;AAE7C,MAAI,CAAC,yBAAyB;AAE5B,eAAW,CAAC,0BAA0B,eAAe,KAAK,IAAI,QAAQ,GAAG;AAGvE,YAAM,UAAU,yBACb,QAAQ,uBAAuB,MAAM,EACrC,QAAQ,SAAS,IAAI;AAExB,YAAM,QAAQ,IAAI,OAAO,IAAI,OAAO,GAAG;AAEvC,UAAI,MAAM,KAAK,OAAO,GAAG;AACvB,kCAA0B;AAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,IAAM,yBAAyB,CACpC,KACA,QACA,YACkB;AAClB,SAAO,qBAAqB,KAAK,OAAO,GAAG,IAAI,MAAM;AACvD;AAWO,IAAM,oCAAoC,CAC/C,WACA,QACA,YACkB;AAClB,QAAM,aAAa,UAAU,IAAI,MAAM;AACvC,MAAI,CAAC,WAAY,QAAO;AAGxB,MAAI,WAAW,SAAS,IAAI,OAAO,GAAG;AACpC,WAAO,WAAW;AAAA,EACpB;AAGA,QAAM,eAAe,IAAI,OAAO,MAAM,WAAW,QAAQ,QAAQ,KAAK,IAAI,IAAI,GAAG;AACjF,MAAI,aAAa,KAAK,OAAO,GAAG;AAC9B,WAAO,WAAW;AAAA,EACpB;AAEA,SAAO;AACT;AAEO,IAAM,qBAAqB;AAQ3B,SAAS,iBAAiB,MAAsB;AACrD,MAAI,OAAO,eAAe,eAAe,OAAO,WAAW,SAAS,YAAY;AAC9E,UAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;AAC3C,UAAM,eAAe,MAAM,KAAK,OAAO,UAAQ,OAAO,aAAa,IAAI,CAAC,EAAE,KAAK,EAAE;AACjF,WAAO,WAAW,KAAK,YAAY;AAAA,EACrC;AACA,SAAO,OAAO,KAAK,MAAM,MAAM,EAAE,SAAS,QAAQ;AACpD;AAQO,SAAS,iBAAiB,MAAsB;AACrD,MAAI,OAAO,eAAe,eAAe,OAAO,WAAW,SAAS,YAAY;AAC9E,UAAM,eAAe,WAAW,KAAK,IAAI;AACzC,UAAM,QAAQ,IAAI,WAAW,aAAa,MAAM;AAChD,aAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,YAAM,CAAC,IAAI,aAAa,WAAW,CAAC;AAAA,IACtC;AACA,UAAM,UAAU,IAAI,YAAY,OAAO;AACvC,WAAO,QAAQ,OAAO,KAAK;AAAA,EAC7B;AACA,SAAO,OAAO,KAAK,MAAM,QAAQ,EAAE,SAAS,OAAO;AACrD;AAUO,SAAS,UAAU,MAAe,MAAwB;AAG/D,QAAM,YAAY,CAAC,QAAyB;AAE1C,QAAI,QAAQ,QAAQ,QAAQ,OAAW,QAAO,KAAK,UAAU,GAAG;AAChE,QAAI,OAAO,QAAQ,SAAU,QAAO,KAAK,UAAU,GAAG;AAGtD,QAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,aAAO,KAAK;AAAA,QACV,IAAI;AAAA,UAAI,UACN,OAAO,SAAS,YAAY,SAAS,OAAO,KAAK,MAAM,UAAU,IAAI,CAAC,IAAI;AAAA,QAC5E;AAAA,MACF;AAAA,IACF;AAGA,UAAM,SAAkC,CAAC;AACzC,WAAO,KAAK,GAA8B,EACvC,KAAK,EACL,QAAQ,SAAO;AACd,YAAM,QAAS,IAAgC,GAAG;AAClD,aAAO,GAAG,IACR,OAAO,UAAU,YAAY,UAAU,OAAO,KAAK,MAAM,UAAU,KAAK,CAAC,IAAI;AAAA,IACjF,CAAC;AACH,WAAO,KAAK,UAAU,MAAM;AAAA,EAC9B;AAEA,MAAI;AACF,WAAO,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,EAC3C,QAAQ;AAEN,WAAO,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,IAAI;AAAA,EACrD;AACF;","names":[]}
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-4BKQ2IT7.mjs";
import {
__require
} from "./chunk-BJTO5JO5.mjs";
// src/http/x402HTTPResourceServer.ts
var SETTLEMENT_OVERRIDES_HEADER = "Settlement-Overrides";
function checkIfBazaarNeeded(routes) {
if ("accepts" in routes) {
return !!(routes.extensions && "bazaar" in routes.extensions);
}
return Object.values(routes).some((routeConfig) => {
return !!(routeConfig.extensions && "bazaar" in routeConfig.extensions);
});
}
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",
extensions ?? {},
transportContext
);
return {
type: "payment-error",
response: this.createHTTPResponse(errorResponse, false, paywallConfig)
};
}
const verifyResult = await this.ResourceServer.verifyPayment(
paymentPayload,
matchingRequirements,
extensions ?? {},
transportContext
);
if (!verifyResult.isValid) {
const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(
requirements,
resourceInfo,
verifyResult.invalidReason,
extensions ?? {},
transportContext
);
return {
type: "payment-error",
response: this.createHTTPResponse(errorResponse, false, paywallConfig)
};
}
return {
type: "payment-verified",
paymentPayload,
paymentRequirements: matchingRequirements,
declaredExtensions: 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",
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);
const firstAccept = paymentRequired.accepts?.[0];
const decimals = firstAccept && "amount" in firstAccept ? this.ResourceServer.getAssetDecimalsForRequirements(firstAccept) : 6;
const safeDecimals = Math.min(Math.max(decimals, 0), 100);
const displayAmountText = parseFloat(displayAmount.toFixed(safeDecimals)).toString();
const assetLabel = typeof firstAccept?.extra?.name === "string" ? firstAccept.extra.name : firstAccept?.asset ? `...${firstAccept.asset.slice(-6)}` : "Token";
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> ${displayAmountText} ${assetLabel}</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.
* Uses the registered scheme's decimal precision for the asset, falling back to 6.
*
* @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) {
const decimals = this.ResourceServer.getAssetDecimalsForRequirements(firstReq);
return parseFloat(firstReq.amount) / 10 ** decimals;
}
}
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,
checkIfBazaarNeeded,
RouteConfigurationError,
x402HTTPResourceServer,
HTTPFacilitatorClient,
encodePaymentSignatureHeader,
decodePaymentSignatureHeader,
encodePaymentRequiredHeader,
decodePaymentRequiredHeader,
encodePaymentResponseHeader,
decodePaymentResponseHeader,
x402HTTPClient
};
//# sourceMappingURL=chunk-G3XJUKWR.mjs.map

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

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>;
}[];
};
/**
* Recursive readonly for hook contexts so accidental in-place mutation is visible at compile time.
* (Runtime mutation is still possible via other references; see extension enrich validation.)
*/
type DeepReadonly<T> = T extends (infer U)[] ? ReadonlyArray<DeepReadonly<U>> : T extends object ? {
readonly [K in keyof T]: DeepReadonly<T[K]>;
} : T;
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;
/**
* Payment recipient. Use a **vacant** value (`""` or whitespace-only) when an extension must
* fill `payTo` during `enrichPaymentRequiredResponse`; non-vacant values are **immutable** there
* so extensions cannot redirect funds to an arbitrary address.
*/
payTo: string;
price: Price;
network: Network;
maxTimeoutSeconds?: number;
extra?: Record<string, unknown>;
}
/**
* Context for `enrichPaymentRequiredResponse`. Extensions may merge extension payload via the
* return value. In-place edits to `paymentRequiredResponse.accepts` are **allowlisted** only
* (see {@link assertAcceptsAllowlistedAfterExtensionEnrich}): `scheme`, `network`, and
* `maxTimeoutSeconds` are immutable; `payTo`, `amount`, and `asset` may change only when the
* baseline value was vacant; `extra` may add keys but must not change or remove baseline keys.
*/
interface PaymentRequiredContext {
requirements: PaymentRequirements[];
resourceInfo: ResourceInfo;
error?: string;
paymentRequiredResponse: PaymentRequired;
transportContext?: unknown;
}
/**
* Verify / settle lifecycle hook context: treat as **read-only** for core protocol fields.
* Control flow uses **abort** / **recover** return values only, not in-place mutation.
*/
interface VerifyContext {
paymentPayload: DeepReadonly<PaymentPayload>;
requirements: DeepReadonly<PaymentRequirements>;
declaredExtensions: DeepReadonly<Record<string, unknown>>;
transportContext?: unknown;
}
interface VerifyResultContext extends VerifyContext {
result: DeepReadonly<VerifyResponse>;
}
interface VerifyFailureContext extends VerifyContext {
error: Error;
}
interface SettleContext {
paymentPayload: DeepReadonly<PaymentPayload>;
requirements: DeepReadonly<PaymentRequirements>;
declaredExtensions: DeepReadonly<Record<string, unknown>>;
transportContext?: unknown;
}
interface SettleResultContext extends SettleContext {
result: DeepReadonly<SettleResponse>;
}
interface SettleFailureContext extends SettleContext {
error: Error;
}
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 extensionHookAdapters;
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;
/**
* Returns the decimal precision for the asset specified in the given payment requirements.
* Looks up the registered scheme for the network and delegates to its getAssetDecimals
* method if available. Falls back to 6 (standard for USDC stablecoins) when the scheme
* does not implement getAssetDecimals or is not registered.
*
* @param requirements - The payment requirements containing scheme, network, and asset
* @returns The number of decimal places for the asset
*/
getAssetDecimalsForRequirements(requirements: PaymentRequirements): number;
/**
* Registers a resource server extension (enrichment and optional verify/settle hooks).
* Re-registering the same key overwrites; omitting `hooks` removes adapter handles for that key.
*
* @param extension - Extension definition including `key` and optional `hooks`
* @returns This server 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>;
/**
* Verifies a payment against requirements, running manual and in-use extension hooks.
*
* @param paymentPayload - Signed payment payload from the client
* @param requirements - Requirements matched to the payload
* @param declaredExtensions - Optional per-extension declarations for the request
* @param transportContext - Optional transport-specific context (e.g. HTTP, MCP)
* @returns Facilitator verify outcome, or abort/recovery as driven by hooks
*/
verifyPayment(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: unknown): 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
* @param transportContext - Optional transport context for extension hooks and enrichment
* @returns Processing result
*/
processPaymentRequest(paymentPayload: PaymentPayload | null, resourceConfig: ResourceConfig, resourceInfo: ResourceInfo, extensions?: Record<string, unknown>, transportContext?: unknown): Promise<{
success: boolean;
requiresPayment?: PaymentRequired;
verificationResult?: VerifyResponse;
settlementResult?: SettleResponse;
error?: string;
}>;
/**
* Logs a warning when a manual or extension adapter lifecycle hook throws.
*
* @param phase - Lifecycle phase name (e.g. `beforeVerify`)
* @param label - Hook source label from {@link getLabeledHooks} (manual index or extension key)
* @param error - Thrown value or rejection reason
*/
private warnResourceServerHookFailure;
/**
* Logs a warning when a registered extension enrichment hook throws.
*
* @param extensionKey - Registered extension identifier
* @param hookName - Hook method name (e.g. `enrichDeclaration`)
* @param error - Thrown value or rejection reason
*/
private warnExtensionHookFailure;
/**
* Manual hooks first, then extension adapters for keys in `extensionKeysInUse`.
* Each entry carries a stable label for logging when a hook throws.
*
* @param phase - Hook slot (e.g. `beforeVerify`)
* @param extensionKeysInUse - Declared extension keys for this request
* @returns Hooks in invocation order with source labels
*/
private getLabeledHooks;
/**
* 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;
}
interface FacilitatorExtension {
key: string;
}
/**
* Per-extension verify/settle hooks. Contexts are **read-only** for core protocol fields; use
* **abort** / **recover** return values instead of mutating `paymentPayload`, `requirements`, etc.
*/
interface ResourceServerExtensionHooks {
onBeforeVerify?: (declaration: unknown, context: VerifyContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
onAfterVerify?: (declaration: unknown, context: VerifyResultContext) => Promise<void>;
onVerifyFailure?: (declaration: unknown, context: VerifyFailureContext) => Promise<void | {
recovered: true;
result: VerifyResponse;
}>;
onBeforeSettle?: (declaration: unknown, context: SettleContext) => Promise<void | {
abort: true;
reason: string;
message?: string;
}>;
onAfterSettle?: (declaration: unknown, context: SettleResultContext) => Promise<void>;
onSettleFailure?: (declaration: unknown, context: SettleFailureContext) => Promise<void | {
recovered: true;
result: SettleResponse;
}>;
}
interface ResourceServerExtension {
key: string;
enrichDeclaration?: (declaration: unknown, transportContext: unknown) => unknown;
/**
* Return value merges into `extensions[key]`. In-place edits to `accepts` are allowlisted only
* (see server `assertAcceptsAllowlistedAfterExtensionEnrich`): vacant `payTo` / `amount` / `asset`
* may be filled; locked values and `scheme` / `network` / `maxTimeoutSeconds` / baseline `extra`
* entries are immutable.
*/
enrichPaymentRequiredResponse?: (declaration: unknown, context: PaymentRequiredContext) => Promise<unknown>;
/**
* Return value merges into `settleResult.extensions[key]`. Facilitator fields (`success`,
* `transaction`, `network`, etc.) must not be changed; only `extensions` is merged from the hook.
*/
enrichSettlementResponse?: (declaration: unknown, context: SettleResultContext) => Promise<unknown>;
/** Installed on `registerExtension`; runs only when `declaredExtensions[key]` is defined. */
hooks?: ResourceServerExtensionHooks;
}
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 DeepReadonly as $, 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 ResourceServerExtensionHooks as _, 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 PaymentRequiredContext as h, type VerifyContext as i, type VerifyResultContext as j, type VerifyFailureContext as k, type SettleContext as l, type SettleResultContext as m, type SettleFailureContext as n, type SettlementOverrides as o, type BeforeSettleHook as p, type AfterSettleHook as q, type OnSettleFailureHook as r, type Price as s, type SchemeNetworkClient 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, s as Price, N as Network, S as SettleResponse, c as PaymentRequired, P as PaymentPayload, a as PaymentRequirements, o as SettlementOverrides } from './mechanisms-C6YmSXgy.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;
/**
* Check if any routes in the configuration declare bazaar extensions.
*
* @param routes - Route configuration
* @returns True if any route has extensions.bazaar defined
*/
declare function checkIfBazaarNeeded(routes: RoutesConfig): boolean;
/**
* 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.
* Uses the registered scheme's decimal precision for the asset, falling back to 6.
*
* @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, checkIfBazaarNeeded as q, 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-Djgn2ixv.js';
import { c as PaymentRequired, a as PaymentRequirements, P as PaymentPayload, N as Network, t as SchemeNetworkClient, S as SettleResponse } from '../mechanisms-C6YmSXgy.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-Djgn2ixv.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-C6YmSXgy.js';

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

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

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';
import { P as PaymentPayload, c as PaymentRequired, S as SettleResponse } from '../mechanisms-C6YmSXgy.js';
export { d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, g as getFacilitatorResponseError } from '../mechanisms-C6YmSXgy.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-CVhfZSvj.js';
export { PaymentRequiredContext, PaymentRequiredHook, x402HTTPClient } from '../client/index.js';

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

@@ -304,3 +304,3 @@ "use strict";

"No matching payment requirements",
routeConfig.extensions,
extensions ?? {},
transportContext

@@ -315,3 +315,5 @@ );

paymentPayload,
matchingRequirements
matchingRequirements,
extensions ?? {},
transportContext
);

@@ -323,3 +325,3 @@ if (!verifyResult.isValid) {

verifyResult.invalidReason,
routeConfig.extensions,
extensions ?? {},
transportContext

@@ -336,3 +338,3 @@ );

paymentRequirements: matchingRequirements,
declaredExtensions: routeConfig.extensions
declaredExtensions: extensions ?? {}
};

@@ -347,3 +349,3 @@ } catch (error) {

error instanceof Error ? error.message : "Payment verification failed",
routeConfig.extensions,
extensions ?? {},
transportContext

@@ -708,2 +710,7 @@ );

const displayAmount = this.getDisplayAmount(paymentRequired);
const firstAccept = paymentRequired.accepts?.[0];
const decimals = firstAccept && "amount" in firstAccept ? this.ResourceServer.getAssetDecimalsForRequirements(firstAccept) : 6;
const safeDecimals = Math.min(Math.max(decimals, 0), 100);
const displayAmountText = parseFloat(displayAmount.toFixed(safeDecimals)).toString();
const assetLabel = typeof firstAccept?.extra?.name === "string" ? firstAccept.extra.name : firstAccept?.asset ? `...${firstAccept.asset.slice(-6)}` : "Token";
return `

@@ -722,3 +729,3 @@ <!DOCTYPE html>

${resource ? `<p><strong>Resource:</strong> ${resource.description || resource.url}</p>` : ""}
<p><strong>Amount:</strong> $${displayAmount.toFixed(2)} USDC</p>
<p><strong>Amount:</strong> ${displayAmountText} ${assetLabel}</p>
<div id="payment-widget"

@@ -740,2 +747,3 @@ data-requirements='${JSON.stringify(paymentRequired)}'

* Extract display amount from payment requirements.
* Uses the registered scheme's decimal precision for the asset, falling back to 6.
*

@@ -750,3 +758,4 @@ * @param paymentRequired - The payment required object

if ("amount" in firstReq) {
return parseFloat(firstReq.amount) / 1e6;
const decimals = this.ResourceServer.getAssetDecimalsForRequirements(firstReq);
return parseFloat(firstReq.amount) / 10 ** decimals;
}

@@ -753,0 +762,0 @@ }

@@ -73,10 +73,10 @@ import { z } from 'zod';

}, "strip", z.ZodTypeAny, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -86,10 +86,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -120,10 +120,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, "strip", z.ZodTypeAny, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -133,10 +133,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -149,10 +149,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

accepts: {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -166,10 +166,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

accepts: {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -192,9 +192,9 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, "strip", z.ZodTypeAny, {
network: string;
scheme: string;
network: string;
x402Version: 1;
payload: Record<string, unknown>;
}, {
network: string;
scheme: string;
network: string;
x402Version: 1;

@@ -217,16 +217,16 @@ payload: Record<string, unknown>;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -264,16 +264,16 @@ }>;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -290,12 +290,12 @@ }>, "many">;

accepts: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}[];
extensions?: Record<string, unknown> | null | undefined;
error?: string | undefined;
extensions?: Record<string, unknown> | null | undefined;
}, {

@@ -309,12 +309,12 @@ resource: {

accepts: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}[];
extensions?: Record<string, unknown> | null | undefined;
error?: string | undefined;
extensions?: Record<string, unknown> | null | undefined;
}>;

@@ -350,16 +350,16 @@ type PaymentRequiredV2 = z.infer<typeof PaymentRequiredV2Schema>;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -373,10 +373,11 @@ }>;

accepted: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
};
extensions?: Record<string, unknown> | null | undefined;
resource?: {

@@ -387,3 +388,2 @@ url: string;

} | undefined;
extensions?: Record<string, unknown> | null | undefined;
}, {

@@ -393,10 +393,11 @@ x402Version: 2;

accepted: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
};
extensions?: Record<string, unknown> | null | undefined;
resource?: {

@@ -407,3 +408,2 @@ url: string;

} | undefined;
extensions?: Record<string, unknown> | null | undefined;
}>;

@@ -428,10 +428,10 @@ type PaymentPayloadV2 = z.infer<typeof PaymentPayloadV2Schema>;

}, "strip", z.ZodTypeAny, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -441,10 +441,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -462,16 +462,16 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -500,10 +500,10 @@ }>]>;

}, "strip", z.ZodTypeAny, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -513,10 +513,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -529,10 +529,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

accepts: {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -546,10 +546,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

accepts: {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -585,16 +585,16 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -611,12 +611,12 @@ }>, "many">;

accepts: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}[];
extensions?: Record<string, unknown> | null | undefined;
error?: string | undefined;
extensions?: Record<string, unknown> | null | undefined;
}, {

@@ -630,12 +630,12 @@ resource: {

accepts: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}[];
extensions?: Record<string, unknown> | null | undefined;
error?: string | undefined;
extensions?: Record<string, unknown> | null | undefined;
}>]>;

@@ -653,9 +653,9 @@ type PaymentRequired = z.infer<typeof PaymentRequiredSchema>;

}, "strip", z.ZodTypeAny, {
network: string;
scheme: string;
network: string;
x402Version: 1;
payload: Record<string, unknown>;
}, {
network: string;
scheme: string;
network: string;
x402Version: 1;

@@ -687,16 +687,16 @@ payload: Record<string, unknown>;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -710,10 +710,11 @@ }>;

accepted: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
};
extensions?: Record<string, unknown> | null | undefined;
resource?: {

@@ -724,3 +725,2 @@ url: string;

} | undefined;
extensions?: Record<string, unknown> | null | undefined;
}, {

@@ -730,10 +730,11 @@ x402Version: 2;

accepted: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
};
extensions?: Record<string, unknown> | null | undefined;
resource?: {

@@ -744,3 +745,2 @@ url: string;

} | undefined;
extensions?: Record<string, unknown> | null | undefined;
}>]>;

@@ -747,0 +747,0 @@ type PaymentPayload = z.infer<typeof PaymentPayloadSchema>;

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

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';
import { a as PaymentRequirements, S as SettleResponse } from '../mechanisms-C6YmSXgy.js';
export { q as AfterSettleHook, A as AfterVerifyHook, p as BeforeSettleHook, B as BeforeVerifyHook, d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, r as OnSettleFailureHook, O as OnVerifyFailureHook, h as PaymentRequiredContext, R as ResourceConfig, l as SettleContext, n as SettleFailureContext, m as SettleResultContext, o as SettlementOverrides, i as VerifyContext, k as VerifyFailureContext, j as VerifyResultContext, g as getFacilitatorResponseError, x as x402ResourceServer } from '../mechanisms-C6YmSXgy.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, q as checkIfBazaarNeeded, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-CVhfZSvj.js';
/**
* True when a string field is treated as unset and may be filled by `enrichPaymentRequiredResponse`.
*
* @param value - Candidate string from `PaymentRequirements` (e.g. `payTo`, `amount`, `asset`)
* @returns Whether the field counts as vacant (empty or whitespace-only)
*/
declare function isVacantStringField(value: string): boolean;
/**
* Deep snapshot of `accepts` entries before any `enrichPaymentRequiredResponse` runs.
*
* @param requirements - Payment requirement rows to clone
* @returns Cloned requirements suitable as an immutable baseline for policy checks
*/
declare function snapshotPaymentRequirementsList(requirements: PaymentRequirements[]): PaymentRequirements[];
/**
* After extension enrichment, each `accepts[i]` must still match the baseline except that
* **`payTo`**, **`amount`**, and **`asset`** may change only when the baseline value is vacant
* (whitespace-only string). **`scheme`**, **`network`**, and **`maxTimeoutSeconds`** are never
* writable by extensions. **`extra`** may gain new keys; values for keys present in the baseline
* must be unchanged (deep-equal).
*
* @param baseline - Snapshot taken before any enrich hooks for this response
* @param current - Live `accepts` entries after an extension enrich step
* @param extensionKey - Registered extension key (for error messages)
* @returns Nothing; throws if the policy is violated
*/
declare function assertAcceptsAllowlistedAfterExtensionEnrich(baseline: PaymentRequirements[], current: PaymentRequirements[], extensionKey: string): void;
/**
* Immutable subset of {@link SettleResponse} compared across settlement extension enrich.
*/
type SettleResponseCoreSnapshot = Pick<SettleResponse, "success" | "transaction" | "network" | "amount" | "payer" | "errorReason" | "errorMessage">;
/**
* Captures facilitator-settled fields that extensions must not rewrite.
*
* @param result - Settlement response from the facilitator
* @returns Plain snapshot of core fields for later comparison
*/
declare function snapshotSettleResponseCore(result: SettleResponse): SettleResponseCoreSnapshot;
/**
* Ensures `enrichSettlementResponse` did not rewrite facilitator outcome fields; only
* `extensions` may be populated via the merger (in addition to in-place adds on `extensions`).
*
* @param before - Snapshot taken before extension settlement enrich
* @param after - Live settlement result after an extension enrich step
* @param extensionKey - Registered extension key (for error messages)
* @returns Nothing; throws if a core field changed
*/
declare function assertSettleResponseCoreUnchanged(before: SettleResponseCoreSnapshot, after: SettleResponse, extensionKey: string): void;
export { type SettleResponseCoreSnapshot, assertAcceptsAllowlistedAfterExtensionEnrich, assertSettleResponseCoreUnchanged, isVacantStringField, snapshotPaymentRequirementsList, snapshotSettleResponseCore };

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

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';
export { E as AssetAmount, $ as DeepReadonly, 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, h as PaymentRequiredContext, v as PaymentRequiredV1, a as PaymentRequirements, u as PaymentRequirementsV1, s as Price, Q as ResourceInfo, Z as ResourceServerExtension, _ as ResourceServerExtensionHooks, t as SchemeNetworkClient, b as SchemeNetworkFacilitator, T as SchemeNetworkServer, l as SettleContext, L as SettleError, n as SettleFailureContext, I as SettleRequest, S as SettleResponse, m as SettleResultContext, J as SupportedResponse, i as VerifyContext, K as VerifyError, k as VerifyFailureContext, G as VerifyRequest, V as VerifyResponse, j as VerifyResultContext, g as getFacilitatorResponseError } from '../mechanisms-C6YmSXgy.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 /** 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":[]}
{"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 ResourceServerExtensionHooks,\n PaymentRequiredContext,\n SettleResultContext,\n VerifyContext,\n VerifyResultContext,\n VerifyFailureContext,\n SettleContext,\n SettleFailureContext,\n} from \"./extensions\";\n\nexport type { DeepReadonly } from \"./readonly\";\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 { 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';
export { w as PaymentPayloadV1, v as PaymentRequiredV1, u as PaymentRequirementsV1, z as SettleRequestV1, C as SettleResponseV1, D as SupportedResponseV1, y as VerifyRequestV1 } from '../../mechanisms-C6YmSXgy.js';

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

import { N as Network } from '../mechanisms-Djgn2ixv.js';
import { N as Network } from '../mechanisms-C6YmSXgy.js';
/**
* Converts a JavaScript number to a plain decimal string, expanding scientific notation
* via string manipulation rather than parseFloat round-tripping.
*
* e.g. 1e-7 → "0.0000001", 4.02 → "4.02"
*
* @param n - The number to convert
* @returns A plain decimal string representation with no scientific notation
*/
declare function numberToDecimalString(n: number): string;
/**
* Convert a decimal amount to token smallest units.
* Accepts only plain decimal strings — scientific notation is not allowed.
* Throws if the amount is non-zero but too small to represent with the given decimal precision.
*
* @param decimalAmount - The decimal amount as a plain string (e.g., "0.10")
* @param decimals - The number of decimals for the token (e.g., 6 for USDC)
* @returns The amount in smallest units as a string
*/
declare function convertToTokenAmount(decimalAmount: string, decimals: number): string;
/**
* Scheme data structure for facilitator storage

@@ -48,2 +68,2 @@ */

export { Base64EncodedRegex, type SchemeData, deepEqual, findByNetworkAndScheme, findFacilitatorBySchemeAndNetwork, findSchemesByNetwork, safeBase64Decode, safeBase64Encode };
export { Base64EncodedRegex, type SchemeData, convertToTokenAmount, deepEqual, findByNetworkAndScheme, findFacilitatorBySchemeAndNetwork, findSchemesByNetwork, numberToDecimalString, safeBase64Decode, safeBase64Encode };

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

Base64EncodedRegex: () => Base64EncodedRegex,
convertToTokenAmount: () => convertToTokenAmount,
deepEqual: () => deepEqual,

@@ -29,2 +30,3 @@ findByNetworkAndScheme: () => findByNetworkAndScheme,

findSchemesByNetwork: () => findSchemesByNetwork,
numberToDecimalString: () => numberToDecimalString,
safeBase64Decode: () => safeBase64Decode,

@@ -34,2 +36,41 @@ safeBase64Encode: () => safeBase64Encode

module.exports = __toCommonJS(utils_exports);
function numberToDecimalString(n) {
const str = n.toString();
if (!/[eE]/.test(str)) return str;
const [significand, exponentStr] = str.split(/[eE]/);
const exp = parseInt(exponentStr, 10);
const negative = significand.startsWith("-");
const abs = negative ? significand.slice(1) : significand;
const [intDigits, fracDigits = ""] = abs.split(".");
const allDigits = intDigits + fracDigits;
const decimalPos = intDigits.length + exp;
let result;
if (decimalPos <= 0) {
result = "0." + "0".repeat(-decimalPos) + allDigits;
} else if (decimalPos >= allDigits.length) {
result = allDigits + "0".repeat(decimalPos - allDigits.length);
} else {
result = allDigits.slice(0, decimalPos) + "." + allDigits.slice(decimalPos);
}
return (negative ? "-" : "") + result;
}
function convertToTokenAmount(decimalAmount, decimals) {
if (/[eE]/.test(decimalAmount)) {
throw new Error(
`Invalid amount: ${decimalAmount} \u2014 use decimal notation, not scientific notation`
);
}
if (!/^-?\d+\.?\d*$/.test(decimalAmount)) {
throw new Error(`Invalid amount: ${decimalAmount}`);
}
const [intPart, decPart = ""] = decimalAmount.split(".");
const paddedDec = decPart.padEnd(decimals, "0").slice(0, decimals);
const tokenAmount = (intPart + paddedDec).replace(/^0+/, "") || "0";
if (tokenAmount === "0" && /[1-9]/.test(decimalAmount)) {
throw new Error(
`Amount ${decimalAmount} is too small to represent with ${decimals} decimal places`
);
}
return tokenAmount;
}
var findSchemesByNetwork = (map, network) => {

@@ -112,2 +153,3 @@ let implementationsByScheme = map.get(network);

Base64EncodedRegex,
convertToTokenAmount,
deepEqual,

@@ -117,2 +159,3 @@ findByNetworkAndScheme,

findSchemesByNetwork,
numberToDecimalString,
safeBase64Decode,

@@ -119,0 +162,0 @@ safeBase64Encode

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

{"version":3,"sources":["../../../src/utils/index.ts"],"sourcesContent":["import { Network } from \"../types\";\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData<T> {\n facilitator: T;\n networks: Set<Network>;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = <T>(\n map: Map<string, Map<string, T>>,\n network: Network,\n): Map<string, T> | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = <T>(\n map: Map<string, Map<string, T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = <T>(\n schemeMap: Map<string, SchemeData<T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record<string, unknown> = {};\n Object.keys(obj as Record<string, unknown>)\n .sort()\n .forEach(key => {\n const value = (obj as Record<string, unknown>)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWO,IAAM,uBAAuB,CAClC,KACA,YAC+B;AAE/B,MAAI,0BAA0B,IAAI,IAAI,OAAO;AAE7C,MAAI,CAAC,yBAAyB;AAE5B,eAAW,CAAC,0BAA0B,eAAe,KAAK,IAAI,QAAQ,GAAG;AAGvE,YAAM,UAAU,yBACb,QAAQ,uBAAuB,MAAM,EACrC,QAAQ,SAAS,IAAI;AAExB,YAAM,QAAQ,IAAI,OAAO,IAAI,OAAO,GAAG;AAEvC,UAAI,MAAM,KAAK,OAAO,GAAG;AACvB,kCAA0B;AAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,IAAM,yBAAyB,CACpC,KACA,QACA,YACkB;AAClB,SAAO,qBAAqB,KAAK,OAAO,GAAG,IAAI,MAAM;AACvD;AAWO,IAAM,oCAAoC,CAC/C,WACA,QACA,YACkB;AAClB,QAAM,aAAa,UAAU,IAAI,MAAM;AACvC,MAAI,CAAC,WAAY,QAAO;AAGxB,MAAI,WAAW,SAAS,IAAI,OAAO,GAAG;AACpC,WAAO,WAAW;AAAA,EACpB;AAGA,QAAM,eAAe,IAAI,OAAO,MAAM,WAAW,QAAQ,QAAQ,KAAK,IAAI,IAAI,GAAG;AACjF,MAAI,aAAa,KAAK,OAAO,GAAG;AAC9B,WAAO,WAAW;AAAA,EACpB;AAEA,SAAO;AACT;AAEO,IAAM,qBAAqB;AAQ3B,SAAS,iBAAiB,MAAsB;AACrD,MAAI,OAAO,eAAe,eAAe,OAAO,WAAW,SAAS,YAAY;AAC9E,UAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;AAC3C,UAAM,eAAe,MAAM,KAAK,OAAO,UAAQ,OAAO,aAAa,IAAI,CAAC,EAAE,KAAK,EAAE;AACjF,WAAO,WAAW,KAAK,YAAY;AAAA,EACrC;AACA,SAAO,OAAO,KAAK,MAAM,MAAM,EAAE,SAAS,QAAQ;AACpD;AAQO,SAAS,iBAAiB,MAAsB;AACrD,MAAI,OAAO,eAAe,eAAe,OAAO,WAAW,SAAS,YAAY;AAC9E,UAAM,eAAe,WAAW,KAAK,IAAI;AACzC,UAAM,QAAQ,IAAI,WAAW,aAAa,MAAM;AAChD,aAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,YAAM,CAAC,IAAI,aAAa,WAAW,CAAC;AAAA,IACtC;AACA,UAAM,UAAU,IAAI,YAAY,OAAO;AACvC,WAAO,QAAQ,OAAO,KAAK;AAAA,EAC7B;AACA,SAAO,OAAO,KAAK,MAAM,QAAQ,EAAE,SAAS,OAAO;AACrD;AAUO,SAAS,UAAU,MAAe,MAAwB;AAG/D,QAAM,YAAY,CAAC,QAAyB;AAE1C,QAAI,QAAQ,QAAQ,QAAQ,OAAW,QAAO,KAAK,UAAU,GAAG;AAChE,QAAI,OAAO,QAAQ,SAAU,QAAO,KAAK,UAAU,GAAG;AAGtD,QAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,aAAO,KAAK;AAAA,QACV,IAAI;AAAA,UAAI,UACN,OAAO,SAAS,YAAY,SAAS,OAAO,KAAK,MAAM,UAAU,IAAI,CAAC,IAAI;AAAA,QAC5E;AAAA,MACF;AAAA,IACF;AAGA,UAAM,SAAkC,CAAC;AACzC,WAAO,KAAK,GAA8B,EACvC,KAAK,EACL,QAAQ,SAAO;AACd,YAAM,QAAS,IAAgC,GAAG;AAClD,aAAO,GAAG,IACR,OAAO,UAAU,YAAY,UAAU,OAAO,KAAK,MAAM,UAAU,KAAK,CAAC,IAAI;AAAA,IACjF,CAAC;AACH,WAAO,KAAK,UAAU,MAAM;AAAA,EAC9B;AAEA,MAAI;AACF,WAAO,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,EAC3C,QAAQ;AAEN,WAAO,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,IAAI;AAAA,EACrD;AACF;","names":[]}
{"version":3,"sources":["../../../src/utils/index.ts"],"sourcesContent":["import { Network } from \"../types\";\n\n/**\n * Converts a JavaScript number to a plain decimal string, expanding scientific notation\n * via string manipulation rather than parseFloat round-tripping.\n *\n * e.g. 1e-7 → \"0.0000001\", 4.02 → \"4.02\"\n *\n * @param n - The number to convert\n * @returns A plain decimal string representation with no scientific notation\n */\nexport function numberToDecimalString(n: number): string {\n const str = n.toString();\n if (!/[eE]/.test(str)) return str;\n\n const [significand, exponentStr] = str.split(/[eE]/);\n const exp = parseInt(exponentStr, 10);\n const negative = significand.startsWith(\"-\");\n const abs = negative ? significand.slice(1) : significand;\n const [intDigits, fracDigits = \"\"] = abs.split(\".\");\n const allDigits = intDigits + fracDigits;\n const decimalPos = intDigits.length + exp;\n\n let result: string;\n if (decimalPos <= 0) {\n result = \"0.\" + \"0\".repeat(-decimalPos) + allDigits;\n } else if (decimalPos >= allDigits.length) {\n result = allDigits + \"0\".repeat(decimalPos - allDigits.length);\n } else {\n result = allDigits.slice(0, decimalPos) + \".\" + allDigits.slice(decimalPos);\n }\n return (negative ? \"-\" : \"\") + result;\n}\n\n/**\n * Convert a decimal amount to token smallest units.\n * Accepts only plain decimal strings — scientific notation is not allowed.\n * Throws if the amount is non-zero but too small to represent with the given decimal precision.\n *\n * @param decimalAmount - The decimal amount as a plain string (e.g., \"0.10\")\n * @param decimals - The number of decimals for the token (e.g., 6 for USDC)\n * @returns The amount in smallest units as a string\n */\nexport function convertToTokenAmount(decimalAmount: string, decimals: number): string {\n if (/[eE]/.test(decimalAmount)) {\n throw new Error(\n `Invalid amount: ${decimalAmount} — use decimal notation, not scientific notation`,\n );\n }\n if (!/^-?\\d+\\.?\\d*$/.test(decimalAmount)) {\n throw new Error(`Invalid amount: ${decimalAmount}`);\n }\n const [intPart, decPart = \"\"] = decimalAmount.split(\".\");\n const paddedDec = decPart.padEnd(decimals, \"0\").slice(0, decimals);\n const tokenAmount = (intPart + paddedDec).replace(/^0+/, \"\") || \"0\";\n if (tokenAmount === \"0\" && /[1-9]/.test(decimalAmount)) {\n throw new Error(\n `Amount ${decimalAmount} is too small to represent with ${decimals} decimal places`,\n );\n }\n return tokenAmount;\n}\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData<T> {\n facilitator: T;\n networks: Set<Network>;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = <T>(\n map: Map<string, Map<string, T>>,\n network: Network,\n): Map<string, T> | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = <T>(\n map: Map<string, Map<string, T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = <T>(\n schemeMap: Map<string, SchemeData<T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record<string, unknown> = {};\n Object.keys(obj as Record<string, unknown>)\n .sort()\n .forEach(key => {\n const value = (obj as Record<string, unknown>)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWO,SAAS,sBAAsB,GAAmB;AACvD,QAAM,MAAM,EAAE,SAAS;AACvB,MAAI,CAAC,OAAO,KAAK,GAAG,EAAG,QAAO;AAE9B,QAAM,CAAC,aAAa,WAAW,IAAI,IAAI,MAAM,MAAM;AACnD,QAAM,MAAM,SAAS,aAAa,EAAE;AACpC,QAAM,WAAW,YAAY,WAAW,GAAG;AAC3C,QAAM,MAAM,WAAW,YAAY,MAAM,CAAC,IAAI;AAC9C,QAAM,CAAC,WAAW,aAAa,EAAE,IAAI,IAAI,MAAM,GAAG;AAClD,QAAM,YAAY,YAAY;AAC9B,QAAM,aAAa,UAAU,SAAS;AAEtC,MAAI;AACJ,MAAI,cAAc,GAAG;AACnB,aAAS,OAAO,IAAI,OAAO,CAAC,UAAU,IAAI;AAAA,EAC5C,WAAW,cAAc,UAAU,QAAQ;AACzC,aAAS,YAAY,IAAI,OAAO,aAAa,UAAU,MAAM;AAAA,EAC/D,OAAO;AACL,aAAS,UAAU,MAAM,GAAG,UAAU,IAAI,MAAM,UAAU,MAAM,UAAU;AAAA,EAC5E;AACA,UAAQ,WAAW,MAAM,MAAM;AACjC;AAWO,SAAS,qBAAqB,eAAuB,UAA0B;AACpF,MAAI,OAAO,KAAK,aAAa,GAAG;AAC9B,UAAM,IAAI;AAAA,MACR,mBAAmB,aAAa;AAAA,IAClC;AAAA,EACF;AACA,MAAI,CAAC,gBAAgB,KAAK,aAAa,GAAG;AACxC,UAAM,IAAI,MAAM,mBAAmB,aAAa,EAAE;AAAA,EACpD;AACA,QAAM,CAAC,SAAS,UAAU,EAAE,IAAI,cAAc,MAAM,GAAG;AACvD,QAAM,YAAY,QAAQ,OAAO,UAAU,GAAG,EAAE,MAAM,GAAG,QAAQ;AACjE,QAAM,eAAe,UAAU,WAAW,QAAQ,OAAO,EAAE,KAAK;AAChE,MAAI,gBAAgB,OAAO,QAAQ,KAAK,aAAa,GAAG;AACtD,UAAM,IAAI;AAAA,MACR,UAAU,aAAa,mCAAmC,QAAQ;AAAA,IACpE;AAAA,EACF;AACA,SAAO;AACT;AAWO,IAAM,uBAAuB,CAClC,KACA,YAC+B;AAE/B,MAAI,0BAA0B,IAAI,IAAI,OAAO;AAE7C,MAAI,CAAC,yBAAyB;AAE5B,eAAW,CAAC,0BAA0B,eAAe,KAAK,IAAI,QAAQ,GAAG;AAGvE,YAAM,UAAU,yBACb,QAAQ,uBAAuB,MAAM,EACrC,QAAQ,SAAS,IAAI;AAExB,YAAM,QAAQ,IAAI,OAAO,IAAI,OAAO,GAAG;AAEvC,UAAI,MAAM,KAAK,OAAO,GAAG;AACvB,kCAA0B;AAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,IAAM,yBAAyB,CACpC,KACA,QACA,YACkB;AAClB,SAAO,qBAAqB,KAAK,OAAO,GAAG,IAAI,MAAM;AACvD;AAWO,IAAM,oCAAoC,CAC/C,WACA,QACA,YACkB;AAClB,QAAM,aAAa,UAAU,IAAI,MAAM;AACvC,MAAI,CAAC,WAAY,QAAO;AAGxB,MAAI,WAAW,SAAS,IAAI,OAAO,GAAG;AACpC,WAAO,WAAW;AAAA,EACpB;AAGA,QAAM,eAAe,IAAI,OAAO,MAAM,WAAW,QAAQ,QAAQ,KAAK,IAAI,IAAI,GAAG;AACjF,MAAI,aAAa,KAAK,OAAO,GAAG;AAC9B,WAAO,WAAW;AAAA,EACpB;AAEA,SAAO;AACT;AAEO,IAAM,qBAAqB;AAQ3B,SAAS,iBAAiB,MAAsB;AACrD,MAAI,OAAO,eAAe,eAAe,OAAO,WAAW,SAAS,YAAY;AAC9E,UAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;AAC3C,UAAM,eAAe,MAAM,KAAK,OAAO,UAAQ,OAAO,aAAa,IAAI,CAAC,EAAE,KAAK,EAAE;AACjF,WAAO,WAAW,KAAK,YAAY;AAAA,EACrC;AACA,SAAO,OAAO,KAAK,MAAM,MAAM,EAAE,SAAS,QAAQ;AACpD;AAQO,SAAS,iBAAiB,MAAsB;AACrD,MAAI,OAAO,eAAe,eAAe,OAAO,WAAW,SAAS,YAAY;AAC9E,UAAM,eAAe,WAAW,KAAK,IAAI;AACzC,UAAM,QAAQ,IAAI,WAAW,aAAa,MAAM;AAChD,aAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,YAAM,CAAC,IAAI,aAAa,WAAW,CAAC;AAAA,IACtC;AACA,UAAM,UAAU,IAAI,YAAY,OAAO;AACvC,WAAO,QAAQ,OAAO,KAAK;AAAA,EAC7B;AACA,SAAO,OAAO,KAAK,MAAM,QAAQ,EAAE,SAAS,OAAO;AACrD;AAUO,SAAS,UAAU,MAAe,MAAwB;AAG/D,QAAM,YAAY,CAAC,QAAyB;AAE1C,QAAI,QAAQ,QAAQ,QAAQ,OAAW,QAAO,KAAK,UAAU,GAAG;AAChE,QAAI,OAAO,QAAQ,SAAU,QAAO,KAAK,UAAU,GAAG;AAGtD,QAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,aAAO,KAAK;AAAA,QACV,IAAI;AAAA,UAAI,UACN,OAAO,SAAS,YAAY,SAAS,OAAO,KAAK,MAAM,UAAU,IAAI,CAAC,IAAI;AAAA,QAC5E;AAAA,MACF;AAAA,IACF;AAGA,UAAM,SAAkC,CAAC;AACzC,WAAO,KAAK,GAA8B,EACvC,KAAK,EACL,QAAQ,SAAO;AACd,YAAM,QAAS,IAAgC,GAAG;AAClD,aAAO,GAAG,IACR,OAAO,UAAU,YAAY,UAAU,OAAO,KAAK,MAAM,UAAU,KAAK,CAAC,IAAI;AAAA,IACjF,CAAC;AACH,WAAO,KAAK,UAAU,MAAM;AAAA,EAC9B;AAEA,MAAI;AACF,WAAO,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,EAC3C,QAAQ;AAEN,WAAO,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,IAAI;AAAA,EACrD;AACF;","names":[]}

@@ -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-Djgn2ixv.mjs';
import { c as PaymentRequired, a as PaymentRequirements, P as PaymentPayload, N as Network, t as SchemeNetworkClient, S as SettleResponse } from '../mechanisms-C6YmSXgy.mjs';

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

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

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

findSchemesByNetwork
} from "../chunk-TDLQZ6MP.mjs";
} from "../chunk-4BKQ2IT7.mjs";
import "../chunk-BJTO5JO5.mjs";

@@ -15,0 +15,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-Djgn2ixv.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-C6YmSXgy.mjs';

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

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

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';
import { P as PaymentPayload, c as PaymentRequired, S as SettleResponse } from '../mechanisms-C6YmSXgy.mjs';
export { d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, g as getFacilitatorResponseError } from '../mechanisms-C6YmSXgy.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-DozxbWk6.mjs';
export { PaymentRequiredContext, PaymentRequiredHook, x402HTTPClient } from '../client/index.mjs';

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

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

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

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

} from "../chunk-JUGE6MAI.mjs";
import "../chunk-TDLQZ6MP.mjs";
import "../chunk-4BKQ2IT7.mjs";
import "../chunk-BJTO5JO5.mjs";

@@ -23,0 +23,0 @@ export {

@@ -73,10 +73,10 @@ import { z } from 'zod';

}, "strip", z.ZodTypeAny, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -86,10 +86,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -120,10 +120,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, "strip", z.ZodTypeAny, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -133,10 +133,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -149,10 +149,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

accepts: {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -166,10 +166,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

accepts: {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -192,9 +192,9 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, "strip", z.ZodTypeAny, {
network: string;
scheme: string;
network: string;
x402Version: 1;
payload: Record<string, unknown>;
}, {
network: string;
scheme: string;
network: string;
x402Version: 1;

@@ -217,16 +217,16 @@ payload: Record<string, unknown>;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -264,16 +264,16 @@ }>;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -290,12 +290,12 @@ }>, "many">;

accepts: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}[];
extensions?: Record<string, unknown> | null | undefined;
error?: string | undefined;
extensions?: Record<string, unknown> | null | undefined;
}, {

@@ -309,12 +309,12 @@ resource: {

accepts: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}[];
extensions?: Record<string, unknown> | null | undefined;
error?: string | undefined;
extensions?: Record<string, unknown> | null | undefined;
}>;

@@ -350,16 +350,16 @@ type PaymentRequiredV2 = z.infer<typeof PaymentRequiredV2Schema>;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -373,10 +373,11 @@ }>;

accepted: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
};
extensions?: Record<string, unknown> | null | undefined;
resource?: {

@@ -387,3 +388,2 @@ url: string;

} | undefined;
extensions?: Record<string, unknown> | null | undefined;
}, {

@@ -393,10 +393,11 @@ x402Version: 2;

accepted: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
};
extensions?: Record<string, unknown> | null | undefined;
resource?: {

@@ -407,3 +408,2 @@ url: string;

} | undefined;
extensions?: Record<string, unknown> | null | undefined;
}>;

@@ -428,10 +428,10 @@ type PaymentPayloadV2 = z.infer<typeof PaymentPayloadV2Schema>;

}, "strip", z.ZodTypeAny, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -441,10 +441,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -462,16 +462,16 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -500,10 +500,10 @@ }>]>;

}, "strip", z.ZodTypeAny, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -513,10 +513,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -529,10 +529,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

accepts: {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -546,10 +546,10 @@ outputSchema?: Record<string, unknown> | null | undefined;

accepts: {
payTo: string;
asset: string;
network: string;
description: string;
scheme: string;
network: string;
maxAmountRequired: string;
resource: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
mimeType?: string | undefined;

@@ -585,16 +585,16 @@ outputSchema?: Record<string, unknown> | null | undefined;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -611,12 +611,12 @@ }>, "many">;

accepts: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}[];
extensions?: Record<string, unknown> | null | undefined;
error?: string | undefined;
extensions?: Record<string, unknown> | null | undefined;
}, {

@@ -630,12 +630,12 @@ resource: {

accepts: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}[];
extensions?: Record<string, unknown> | null | undefined;
error?: string | undefined;
extensions?: Record<string, unknown> | null | undefined;
}>]>;

@@ -653,9 +653,9 @@ type PaymentRequired = z.infer<typeof PaymentRequiredSchema>;

}, "strip", z.ZodTypeAny, {
network: string;
scheme: string;
network: string;
x402Version: 1;
payload: Record<string, unknown>;
}, {
network: string;
scheme: string;
network: string;
x402Version: 1;

@@ -687,16 +687,16 @@ payload: Record<string, unknown>;

}, "strip", z.ZodTypeAny, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
}, {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;

@@ -710,10 +710,11 @@ }>;

accepted: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
};
extensions?: Record<string, unknown> | null | undefined;
resource?: {

@@ -724,3 +725,2 @@ url: string;

} | undefined;
extensions?: Record<string, unknown> | null | undefined;
}, {

@@ -730,10 +730,11 @@ x402Version: 2;

accepted: {
payTo: string;
amount: string;
asset: string;
network: string;
scheme: string;
network: string;
payTo: string;
maxTimeoutSeconds: number;
asset: string;
amount: string;
extra?: Record<string, unknown> | null | undefined;
};
extensions?: Record<string, unknown> | null | undefined;
resource?: {

@@ -744,3 +745,2 @@ url: string;

} | undefined;
extensions?: Record<string, unknown> | null | undefined;
}>]>;

@@ -747,0 +747,0 @@ type PaymentPayload = z.infer<typeof PaymentPayloadSchema>;

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

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 { a as PaymentRequirements, S as SettleResponse } from '../mechanisms-C6YmSXgy.mjs';
export { q as AfterSettleHook, A as AfterVerifyHook, p as BeforeSettleHook, B as BeforeVerifyHook, d as FacilitatorClient, e as FacilitatorConfig, f as FacilitatorResponseError, H as HTTPFacilitatorClient, r as OnSettleFailureHook, O as OnVerifyFailureHook, h as PaymentRequiredContext, R as ResourceConfig, l as SettleContext, n as SettleFailureContext, m as SettleResultContext, o as SettlementOverrides, i as VerifyContext, k as VerifyFailureContext, j as VerifyResultContext, g as getFacilitatorResponseError, x as x402ResourceServer } from '../mechanisms-C6YmSXgy.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, q as checkIfBazaarNeeded, x as x402HTTPResourceServer } from '../x402HTTPResourceServer-DozxbWk6.mjs';
/**
* True when a string field is treated as unset and may be filled by `enrichPaymentRequiredResponse`.
*
* @param value - Candidate string from `PaymentRequirements` (e.g. `payTo`, `amount`, `asset`)
* @returns Whether the field counts as vacant (empty or whitespace-only)
*/
declare function isVacantStringField(value: string): boolean;
/**
* Deep snapshot of `accepts` entries before any `enrichPaymentRequiredResponse` runs.
*
* @param requirements - Payment requirement rows to clone
* @returns Cloned requirements suitable as an immutable baseline for policy checks
*/
declare function snapshotPaymentRequirementsList(requirements: PaymentRequirements[]): PaymentRequirements[];
/**
* After extension enrichment, each `accepts[i]` must still match the baseline except that
* **`payTo`**, **`amount`**, and **`asset`** may change only when the baseline value is vacant
* (whitespace-only string). **`scheme`**, **`network`**, and **`maxTimeoutSeconds`** are never
* writable by extensions. **`extra`** may gain new keys; values for keys present in the baseline
* must be unchanged (deep-equal).
*
* @param baseline - Snapshot taken before any enrich hooks for this response
* @param current - Live `accepts` entries after an extension enrich step
* @param extensionKey - Registered extension key (for error messages)
* @returns Nothing; throws if the policy is violated
*/
declare function assertAcceptsAllowlistedAfterExtensionEnrich(baseline: PaymentRequirements[], current: PaymentRequirements[], extensionKey: string): void;
/**
* Immutable subset of {@link SettleResponse} compared across settlement extension enrich.
*/
type SettleResponseCoreSnapshot = Pick<SettleResponse, "success" | "transaction" | "network" | "amount" | "payer" | "errorReason" | "errorMessage">;
/**
* Captures facilitator-settled fields that extensions must not rewrite.
*
* @param result - Settlement response from the facilitator
* @returns Plain snapshot of core fields for later comparison
*/
declare function snapshotSettleResponseCore(result: SettleResponse): SettleResponseCoreSnapshot;
/**
* Ensures `enrichSettlementResponse` did not rewrite facilitator outcome fields; only
* `extensions` may be populated via the merger (in addition to in-place adds on `extensions`).
*
* @param before - Snapshot taken before extension settlement enrich
* @param after - Live settlement result after an extension enrich step
* @param extensionKey - Registered extension key (for error messages)
* @returns Nothing; throws if a core field changed
*/
declare function assertSettleResponseCoreUnchanged(before: SettleResponseCoreSnapshot, after: SettleResponse, extensionKey: string): void;
export { type SettleResponseCoreSnapshot, assertAcceptsAllowlistedAfterExtensionEnrich, assertSettleResponseCoreUnchanged, isVacantStringField, snapshotPaymentRequirementsList, snapshotSettleResponseCore };

@@ -5,4 +5,5 @@ import {

SETTLEMENT_OVERRIDES_HEADER,
checkIfBazaarNeeded,
x402HTTPResourceServer
} from "../chunk-JFGRL3BL.mjs";
} from "../chunk-G3XJUKWR.mjs";
import "../chunk-KMQH4MQI.mjs";

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

SettleError,
VerifyError,
getFacilitatorResponseError

@@ -22,5 +22,87 @@ } from "../chunk-JUGE6MAI.mjs";

findByNetworkAndScheme
} from "../chunk-TDLQZ6MP.mjs";
} from "../chunk-4BKQ2IT7.mjs";
import "../chunk-BJTO5JO5.mjs";
// src/server/extensionResponsePolicy.ts
function isVacantStringField(value) {
return value.trim() === "";
}
function snapshotPaymentRequirementsList(requirements) {
return requirements.map((req) => ({
...req,
extra: structuredClone(req.extra)
}));
}
function assertAcceptsAllowlistedAfterExtensionEnrich(baseline, current, extensionKey) {
if (baseline.length !== current.length) {
throw new Error(
`[x402] extension "${extensionKey}" violated accepts mutation policy: accepts length changed (${baseline.length} \u2192 ${current.length})`
);
}
for (let i = 0; i < baseline.length; i++) {
const b = baseline[i];
const c = current[i];
if (b.scheme !== c.scheme || b.network !== c.network) {
throw new Error(
`[x402] extension "${extensionKey}" violated accepts mutation policy: scheme/network are immutable (index ${i})`
);
}
if (b.maxTimeoutSeconds !== c.maxTimeoutSeconds) {
throw new Error(
`[x402] extension "${extensionKey}" violated accepts mutation policy: maxTimeoutSeconds is immutable (index ${i})`
);
}
for (const field of ["payTo", "amount", "asset"]) {
const bv = b[field];
const cv = c[field];
if (!isVacantStringField(bv) && cv !== bv) {
throw new Error(
`[x402] extension "${extensionKey}" violated accepts mutation policy: "${field}" may only be set when the resource left it vacant (""); non-vacant values are immutable (index ${i})`
);
}
}
for (const key of Object.keys(b.extra)) {
if (!Object.prototype.hasOwnProperty.call(c.extra, key)) {
throw new Error(
`[x402] extension "${extensionKey}" violated accepts mutation policy: extra["${key}"] was removed (index ${i})`
);
}
if (!deepEqual(c.extra[key], b.extra[key])) {
throw new Error(
`[x402] extension "${extensionKey}" violated accepts mutation policy: extra["${key}"] may not be changed (index ${i})`
);
}
}
}
}
function snapshotSettleResponseCore(result) {
return {
success: result.success,
transaction: result.transaction,
network: result.network,
amount: result.amount,
payer: result.payer,
errorReason: result.errorReason,
errorMessage: result.errorMessage
};
}
function assertSettleResponseCoreUnchanged(before, after, extensionKey) {
const keys = [
"success",
"transaction",
"network",
"amount",
"payer",
"errorReason",
"errorMessage"
];
for (const k of keys) {
if (!deepEqual(after[k], before[k])) {
throw new Error(
`[x402] extension "${extensionKey}" violated settlement mutation policy: field "${String(k)}" is immutable after facilitator settle`
);
}
}
}
// src/server/x402ResourceServer.ts

@@ -53,2 +135,3 @@ function resolveSettlementOverrideAmount(rawAmount, requirements, decimals = 6) {

this.registeredExtensions = /* @__PURE__ */ new Map();
this.extensionHookAdapters = /* @__PURE__ */ new Map();
this.beforeVerifyHooks = [];

@@ -96,9 +179,56 @@ this.afterVerifyHooks = [];

/**
* Registers a resource service extension that can enrich extension declarations.
* Returns the decimal precision for the asset specified in the given payment requirements.
* Looks up the registered scheme for the network and delegates to its getAssetDecimals
* method if available. Falls back to 6 (standard for USDC stablecoins) when the scheme
* does not implement getAssetDecimals or is not registered.
*
* @param extension - The extension to register
* @returns The x402ResourceServer instance for chaining
* @param requirements - The payment requirements containing scheme, network, and asset
* @returns The number of decimal places for the asset
*/
getAssetDecimalsForRequirements(requirements) {
const scheme = findByNetworkAndScheme(
this.registeredServerSchemes,
requirements.scheme,
requirements.network
);
return scheme?.getAssetDecimals?.(requirements.asset ?? "", requirements.network) ?? 6;
}
/**
* Registers a resource server extension (enrichment and optional verify/settle hooks).
* Re-registering the same key overwrites; omitting `hooks` removes adapter handles for that key.
*
* @param extension - Extension definition including `key` and optional `hooks`
* @returns This server instance for chaining
*/
registerExtension(extension) {
this.registeredExtensions.set(extension.key, extension);
const extensionKey = extension.key;
const extensionHooks = extension.hooks;
if (!extensionHooks) {
this.extensionHookAdapters.delete(extensionKey);
return this;
}
const handles = {};
const bindExtensionHookAdapter = (extensionHookKey, adapterPhase) => {
const impl = extensionHooks[extensionHookKey];
if (!impl) return;
handles[adapterPhase] = (async (ctx) => {
if (ctx.declaredExtensions[extensionKey] === void 0) return;
return impl(
ctx.declaredExtensions[extensionKey],
ctx
);
});
};
bindExtensionHookAdapter("onBeforeVerify", "beforeVerify");
bindExtensionHookAdapter("onAfterVerify", "afterVerify");
bindExtensionHookAdapter("onVerifyFailure", "onVerifyFailure");
bindExtensionHookAdapter("onBeforeSettle", "beforeSettle");
bindExtensionHookAdapter("onAfterSettle", "afterSettle");
bindExtensionHookAdapter("onSettleFailure", "onSettleFailure");
if (Object.keys(handles).length > 0) {
this.extensionHookAdapters.set(extensionKey, handles);
} else {
this.extensionHookAdapters.delete(extensionKey);
}
return this;

@@ -135,3 +265,8 @@ }

if (extension?.enrichDeclaration) {
enriched[key] = extension.enrichDeclaration(declaration, transportContext);
try {
enriched[key] = extension.enrichDeclaration(declaration, transportContext);
} catch (error) {
this.warnExtensionHookFailure(key, "enrichDeclaration", error);
enriched[key] = declaration;
}
} else {

@@ -390,2 +525,7 @@ enriched[key] = declaration;

async createPaymentRequiredResponse(requirements, resourceInfo, error, extensions, transportContext) {
const acceptsClone = requirements.map((req) => ({
...req,
extra: structuredClone(req.extra)
}));
let baselineAccepts = snapshotPaymentRequirementsList(acceptsClone);
let response = {

@@ -395,3 +535,3 @@ x402Version: 2,

resource: resourceInfo,
accepts: requirements
accepts: acceptsClone
};

@@ -407,3 +547,3 @@ if (extensions && Object.keys(extensions).length > 0) {

const context = {
requirements,
requirements: acceptsClone,
resourceInfo,

@@ -425,7 +565,6 @@ error,

} catch (error2) {
console.error(
`Error in enrichPaymentRequiredResponse hook for extension ${key}:`,
error2
);
this.warnExtensionHookFailure(key, "enrichPaymentRequiredResponse", error2);
}
assertAcceptsAllowlistedAfterExtensionEnrich(baselineAccepts, acceptsClone, key);
baselineAccepts = snapshotPaymentRequirementsList(acceptsClone);
}

@@ -437,14 +576,20 @@ }

/**
* Verify a payment against requirements
* Verifies a payment against requirements, running manual and in-use extension hooks.
*
* @param paymentPayload - The payment payload to verify
* @param requirements - The payment requirements
* @returns Verification response
* @param paymentPayload - Signed payment payload from the client
* @param requirements - Requirements matched to the payload
* @param declaredExtensions - Optional per-extension declarations for the request
* @param transportContext - Optional transport-specific context (e.g. HTTP, MCP)
* @returns Facilitator verify outcome, or abort/recovery as driven by hooks
*/
async verifyPayment(paymentPayload, requirements) {
async verifyPayment(paymentPayload, requirements, declaredExtensions, transportContext) {
const resolvedDeclaredExtensions = declaredExtensions ?? {};
const extensionKeysInUse = Object.keys(resolvedDeclaredExtensions);
const context = {
paymentPayload,
requirements
requirements,
declaredExtensions: resolvedDeclaredExtensions,
transportContext
};
for (const hook of this.beforeVerifyHooks) {
for (const { label, hook } of this.getLabeledHooks("beforeVerify", extensionKeysInUse)) {
try {

@@ -460,7 +605,3 @@ const result = await hook(context);

} catch (error) {
throw new VerifyError(400, {
isValid: false,
invalidReason: "before_verify_hook_error",
invalidMessage: error instanceof Error ? error.message : ""
});
this.warnResourceServerHookFailure("beforeVerify", label, error);
}

@@ -497,4 +638,8 @@ }

};
for (const hook of this.afterVerifyHooks) {
await hook(resultContext);
for (const { label, hook } of this.getLabeledHooks("afterVerify", extensionKeysInUse)) {
try {
await hook(resultContext);
} catch (error) {
this.warnResourceServerHookFailure("afterVerify", label, error);
}
}

@@ -507,6 +652,10 @@ return verifyResult;

};
for (const hook of this.onVerifyFailureHooks) {
const result = await hook(failureContext);
if (result && "recovered" in result && result.recovered) {
return result.result;
for (const { label, hook } of this.getLabeledHooks("onVerifyFailure", extensionKeysInUse)) {
try {
const result = await hook(failureContext);
if (result && "recovered" in result && result.recovered) {
return result.result;
}
} catch (error2) {
this.warnResourceServerHookFailure("onVerifyFailure", label, error2);
}

@@ -528,2 +677,4 @@ }

async settlePayment(paymentPayload, requirements, declaredExtensions, transportContext, settlementOverrides) {
const resolvedDeclaredExtensions = declaredExtensions ?? {};
const extensionKeysInUse = Object.keys(resolvedDeclaredExtensions);
let effectiveRequirements = requirements;

@@ -544,5 +695,7 @@ if (settlementOverrides?.amount !== void 0) {

paymentPayload,
requirements: effectiveRequirements
requirements: effectiveRequirements,
declaredExtensions: resolvedDeclaredExtensions,
transportContext
};
for (const hook of this.beforeSettleHooks) {
for (const { label, hook } of this.getLabeledHooks("beforeSettle", extensionKeysInUse)) {
try {

@@ -563,9 +716,3 @@ const result = await hook(context);

}
throw new SettleError(400, {
success: false,
errorReason: "before_settle_hook_error",
errorMessage: error instanceof Error ? error.message : "",
transaction: "",
network: requirements.network
});
this.warnResourceServerHookFailure("beforeSettle", label, error);
}

@@ -600,10 +747,14 @@ }

...context,
result: settleResult,
transportContext
result: settleResult
};
for (const hook of this.afterSettleHooks) {
await hook(resultContext);
for (const { label, hook } of this.getLabeledHooks("afterSettle", extensionKeysInUse)) {
try {
await hook(resultContext);
} catch (error) {
this.warnResourceServerHookFailure("afterSettle", label, error);
}
}
if (declaredExtensions) {
for (const [key, declaration] of Object.entries(declaredExtensions)) {
if (Object.keys(resolvedDeclaredExtensions).length > 0) {
const settleCoreSnapshot = snapshotSettleResponseCore(settleResult);
for (const [key, declaration] of Object.entries(resolvedDeclaredExtensions)) {
const extension = this.registeredExtensions.get(key);

@@ -623,4 +774,5 @@ if (extension?.enrichSettlementResponse) {

} catch (error) {
console.error(`Error in enrichSettlementResponse hook for extension ${key}:`, error);
this.warnExtensionHookFailure(key, "enrichSettlementResponse", error);
}
assertSettleResponseCoreUnchanged(settleCoreSnapshot, settleResult, key);
}

@@ -635,6 +787,10 @@ }

};
for (const hook of this.onSettleFailureHooks) {
const result = await hook(failureContext);
if (result && "recovered" in result && result.recovered) {
return result.result;
for (const { label, hook } of this.getLabeledHooks("onSettleFailure", extensionKeysInUse)) {
try {
const result = await hook(failureContext);
if (result && "recovered" in result && result.recovered) {
return result.result;
}
} catch (error2) {
this.warnResourceServerHookFailure("onSettleFailure", label, error2);
}

@@ -675,6 +831,8 @@ }

* @param extensions - Optional extensions to include in the response
* @param transportContext - Optional transport context for extension hooks and enrichment
* @returns Processing result
*/
async processPaymentRequest(paymentPayload, resourceConfig, resourceInfo, extensions) {
async processPaymentRequest(paymentPayload, resourceConfig, resourceInfo, extensions, transportContext) {
const requirements = await this.buildPaymentRequirements(resourceConfig);
const resolvedRouteExtensions = extensions ?? {};
if (!paymentPayload) {

@@ -687,7 +845,18 @@ return {

"Payment required",
extensions
extensions,
transportContext
)
};
}
const matchingRequirements = this.findMatchingRequirements(requirements, paymentPayload);
const paymentRequired = await this.createPaymentRequiredResponse(
requirements,
resourceInfo,
void 0,
extensions,
transportContext
);
const matchingRequirements = this.findMatchingRequirements(
paymentRequired.accepts,
paymentPayload
);
if (!matchingRequirements) {

@@ -700,7 +869,13 @@ return {

"No matching payment requirements found",
extensions
extensions,
transportContext
)
};
}
const verificationResult = await this.verifyPayment(paymentPayload, matchingRequirements);
const verificationResult = await this.verifyPayment(
paymentPayload,
matchingRequirements,
resolvedRouteExtensions,
transportContext
);
if (!verificationResult.isValid) {

@@ -719,2 +894,49 @@ return {

/**
* Logs a warning when a manual or extension adapter lifecycle hook throws.
*
* @param phase - Lifecycle phase name (e.g. `beforeVerify`)
* @param label - Hook source label from {@link getLabeledHooks} (manual index or extension key)
* @param error - Thrown value or rejection reason
*/
warnResourceServerHookFailure(phase, label, error) {
const detail = error instanceof Error ? error.message : String(error);
console.warn(`[x402] Resource server ${phase} hook threw (${label}): ${detail}`);
}
/**
* Logs a warning when a registered extension enrichment hook throws.
*
* @param extensionKey - Registered extension identifier
* @param hookName - Hook method name (e.g. `enrichDeclaration`)
* @param error - Thrown value or rejection reason
*/
warnExtensionHookFailure(extensionKey, hookName, error) {
const detail = error instanceof Error ? error.message : String(error);
console.warn(`[x402] extension "${extensionKey}" ${hookName} threw: ${detail}`);
}
/**
* Manual hooks first, then extension adapters for keys in `extensionKeysInUse`.
* Each entry carries a stable label for logging when a hook throws.
*
* @param phase - Hook slot (e.g. `beforeVerify`)
* @param extensionKeysInUse - Declared extension keys for this request
* @returns Hooks in invocation order with source labels
*/
getLabeledHooks(phase, extensionKeysInUse) {
const manualKey = `${phase}Hooks`;
const manual = this[manualKey];
const out = [];
manual.forEach((hook, index) => {
out.push({ label: `manual ${phase} hook #${index}`, hook });
});
const inUse = new Set(extensionKeysInUse);
for (const [extensionKey, adapterHandles] of this.extensionHookAdapters.entries()) {
if (!inUse.has(extensionKey)) continue;
const hook = adapterHandles[phase];
if (hook !== void 0) {
out.push({ label: `extension "${extensionKey}" ${phase}`, hook });
}
}
return out;
}
/**
* Get facilitator client for a specific version, network, and scheme

@@ -738,3 +960,9 @@ *

SETTLEMENT_OVERRIDES_HEADER,
assertAcceptsAllowlistedAfterExtensionEnrich,
assertSettleResponseCoreUnchanged,
checkIfBazaarNeeded,
getFacilitatorResponseError,
isVacantStringField,
snapshotPaymentRequirementsList,
snapshotSettleResponseCore,
x402HTTPResourceServer,

@@ -741,0 +969,0 @@ x402ResourceServer

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

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';
export { E as AssetAmount, $ as DeepReadonly, 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, h as PaymentRequiredContext, v as PaymentRequiredV1, a as PaymentRequirements, u as PaymentRequirementsV1, s as Price, Q as ResourceInfo, Z as ResourceServerExtension, _ as ResourceServerExtensionHooks, t as SchemeNetworkClient, b as SchemeNetworkFacilitator, T as SchemeNetworkServer, l as SettleContext, L as SettleError, n as SettleFailureContext, I as SettleRequest, S as SettleResponse, m as SettleResultContext, J as SupportedResponse, i as VerifyContext, K as VerifyError, k as VerifyFailureContext, G as VerifyRequest, V as VerifyResponse, j as VerifyResultContext, g as getFacilitatorResponseError } from '../mechanisms-C6YmSXgy.mjs';

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

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';
export { w as PaymentPayloadV1, v as PaymentRequiredV1, u as PaymentRequirementsV1, z as SettleRequestV1, C as SettleResponseV1, D as SupportedResponseV1, y as VerifyRequestV1 } from '../../mechanisms-C6YmSXgy.mjs';

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

import { N as Network } from '../mechanisms-Djgn2ixv.mjs';
import { N as Network } from '../mechanisms-C6YmSXgy.mjs';
/**
* Converts a JavaScript number to a plain decimal string, expanding scientific notation
* via string manipulation rather than parseFloat round-tripping.
*
* e.g. 1e-7 → "0.0000001", 4.02 → "4.02"
*
* @param n - The number to convert
* @returns A plain decimal string representation with no scientific notation
*/
declare function numberToDecimalString(n: number): string;
/**
* Convert a decimal amount to token smallest units.
* Accepts only plain decimal strings — scientific notation is not allowed.
* Throws if the amount is non-zero but too small to represent with the given decimal precision.
*
* @param decimalAmount - The decimal amount as a plain string (e.g., "0.10")
* @param decimals - The number of decimals for the token (e.g., 6 for USDC)
* @returns The amount in smallest units as a string
*/
declare function convertToTokenAmount(decimalAmount: string, decimals: number): string;
/**
* Scheme data structure for facilitator storage

@@ -48,2 +68,2 @@ */

export { Base64EncodedRegex, type SchemeData, deepEqual, findByNetworkAndScheme, findFacilitatorBySchemeAndNetwork, findSchemesByNetwork, safeBase64Decode, safeBase64Encode };
export { Base64EncodedRegex, type SchemeData, convertToTokenAmount, deepEqual, findByNetworkAndScheme, findFacilitatorBySchemeAndNetwork, findSchemesByNetwork, numberToDecimalString, safeBase64Decode, safeBase64Encode };
import {
Base64EncodedRegex,
convertToTokenAmount,
deepEqual,

@@ -7,8 +8,10 @@ findByNetworkAndScheme,

findSchemesByNetwork,
numberToDecimalString,
safeBase64Decode,
safeBase64Encode
} from "../chunk-TDLQZ6MP.mjs";
} from "../chunk-4BKQ2IT7.mjs";
import "../chunk-BJTO5JO5.mjs";
export {
Base64EncodedRegex,
convertToTokenAmount,
deepEqual,

@@ -18,2 +21,3 @@ findByNetworkAndScheme,

findSchemesByNetwork,
numberToDecimalString,
safeBase64Decode,

@@ -20,0 +24,0 @@ safeBase64Encode

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

@@ -5,0 +5,0 @@ "module": "./dist/esm/index.js",

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

# @x402/core
# `@x402/core` • [![npm version](https://img.shields.io/npm/v/%40x402%2Fcore.svg)](https://www.npmjs.com/package/@x402/core)

@@ -3,0 +3,0 @@ Core implementation of the x402 payment protocol for TypeScript/JavaScript applications. Provides transport-agnostic client, server and facilitator components.

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/utils/index.ts
var findSchemesByNetwork = (map, network) => {
let implementationsByScheme = map.get(network);
if (!implementationsByScheme) {
for (const [registeredNetworkPattern, implementations] of map.entries()) {
const pattern = registeredNetworkPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
const regex = new RegExp(`^${pattern}$`);
if (regex.test(network)) {
implementationsByScheme = implementations;
break;
}
}
}
return implementationsByScheme;
};
var findByNetworkAndScheme = (map, scheme, network) => {
return findSchemesByNetwork(map, network)?.get(scheme);
};
var findFacilitatorBySchemeAndNetwork = (schemeMap, scheme, network) => {
const schemeData = schemeMap.get(scheme);
if (!schemeData) return void 0;
if (schemeData.networks.has(network)) {
return schemeData.facilitator;
}
const patternRegex = new RegExp("^" + schemeData.pattern.replace("*", ".*") + "$");
if (patternRegex.test(network)) {
return schemeData.facilitator;
}
return void 0;
};
var Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;
function safeBase64Encode(data) {
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
const bytes = new TextEncoder().encode(data);
const binaryString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
return globalThis.btoa(binaryString);
}
return Buffer.from(data, "utf8").toString("base64");
}
function safeBase64Decode(data) {
if (typeof globalThis !== "undefined" && typeof globalThis.atob === "function") {
const binaryString = globalThis.atob(data);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const decoder = new TextDecoder("utf-8");
return decoder.decode(bytes);
}
return Buffer.from(data, "base64").toString("utf-8");
}
function deepEqual(obj1, obj2) {
const normalize = (obj) => {
if (obj === null || obj === void 0) return JSON.stringify(obj);
if (typeof obj !== "object") return JSON.stringify(obj);
if (Array.isArray(obj)) {
return JSON.stringify(
obj.map(
(item) => typeof item === "object" && item !== null ? JSON.parse(normalize(item)) : item
)
);
}
const sorted = {};
Object.keys(obj).sort().forEach((key) => {
const value = obj[key];
sorted[key] = typeof value === "object" && value !== null ? JSON.parse(normalize(value)) : value;
});
return JSON.stringify(sorted);
};
try {
return normalize(obj1) === normalize(obj2);
} catch {
return JSON.stringify(obj1) === JSON.stringify(obj2);
}
}
export {
findSchemesByNetwork,
findByNetworkAndScheme,
findFacilitatorBySchemeAndNetwork,
Base64EncodedRegex,
safeBase64Encode,
safeBase64Decode,
deepEqual
};
//# sourceMappingURL=chunk-TDLQZ6MP.mjs.map
{"version":3,"sources":["../../src/utils/index.ts"],"sourcesContent":["import { Network } from \"../types\";\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData<T> {\n facilitator: T;\n networks: Set<Network>;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = <T>(\n map: Map<string, Map<string, T>>,\n network: Network,\n): Map<string, T> | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = <T>(\n map: Map<string, Map<string, T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = <T>(\n schemeMap: Map<string, SchemeData<T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record<string, unknown> = {};\n Object.keys(obj as Record<string, unknown>)\n .sort()\n .forEach(key => {\n const value = (obj as Record<string, unknown>)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n"],"mappings":";AAWO,IAAM,uBAAuB,CAClC,KACA,YAC+B;AAE/B,MAAI,0BAA0B,IAAI,IAAI,OAAO;AAE7C,MAAI,CAAC,yBAAyB;AAE5B,eAAW,CAAC,0BAA0B,eAAe,KAAK,IAAI,QAAQ,GAAG;AAGvE,YAAM,UAAU,yBACb,QAAQ,uBAAuB,MAAM,EACrC,QAAQ,SAAS,IAAI;AAExB,YAAM,QAAQ,IAAI,OAAO,IAAI,OAAO,GAAG;AAEvC,UAAI,MAAM,KAAK,OAAO,GAAG;AACvB,kCAA0B;AAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,IAAM,yBAAyB,CACpC,KACA,QACA,YACkB;AAClB,SAAO,qBAAqB,KAAK,OAAO,GAAG,IAAI,MAAM;AACvD;AAWO,IAAM,oCAAoC,CAC/C,WACA,QACA,YACkB;AAClB,QAAM,aAAa,UAAU,IAAI,MAAM;AACvC,MAAI,CAAC,WAAY,QAAO;AAGxB,MAAI,WAAW,SAAS,IAAI,OAAO,GAAG;AACpC,WAAO,WAAW;AAAA,EACpB;AAGA,QAAM,eAAe,IAAI,OAAO,MAAM,WAAW,QAAQ,QAAQ,KAAK,IAAI,IAAI,GAAG;AACjF,MAAI,aAAa,KAAK,OAAO,GAAG;AAC9B,WAAO,WAAW;AAAA,EACpB;AAEA,SAAO;AACT;AAEO,IAAM,qBAAqB;AAQ3B,SAAS,iBAAiB,MAAsB;AACrD,MAAI,OAAO,eAAe,eAAe,OAAO,WAAW,SAAS,YAAY;AAC9E,UAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;AAC3C,UAAM,eAAe,MAAM,KAAK,OAAO,UAAQ,OAAO,aAAa,IAAI,CAAC,EAAE,KAAK,EAAE;AACjF,WAAO,WAAW,KAAK,YAAY;AAAA,EACrC;AACA,SAAO,OAAO,KAAK,MAAM,MAAM,EAAE,SAAS,QAAQ;AACpD;AAQO,SAAS,iBAAiB,MAAsB;AACrD,MAAI,OAAO,eAAe,eAAe,OAAO,WAAW,SAAS,YAAY;AAC9E,UAAM,eAAe,WAAW,KAAK,IAAI;AACzC,UAAM,QAAQ,IAAI,WAAW,aAAa,MAAM;AAChD,aAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,YAAM,CAAC,IAAI,aAAa,WAAW,CAAC;AAAA,IACtC;AACA,UAAM,UAAU,IAAI,YAAY,OAAO;AACvC,WAAO,QAAQ,OAAO,KAAK;AAAA,EAC7B;AACA,SAAO,OAAO,KAAK,MAAM,QAAQ,EAAE,SAAS,OAAO;AACrD;AAUO,SAAS,UAAU,MAAe,MAAwB;AAG/D,QAAM,YAAY,CAAC,QAAyB;AAE1C,QAAI,QAAQ,QAAQ,QAAQ,OAAW,QAAO,KAAK,UAAU,GAAG;AAChE,QAAI,OAAO,QAAQ,SAAU,QAAO,KAAK,UAAU,GAAG;AAGtD,QAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,aAAO,KAAK;AAAA,QACV,IAAI;AAAA,UAAI,UACN,OAAO,SAAS,YAAY,SAAS,OAAO,KAAK,MAAM,UAAU,IAAI,CAAC,IAAI;AAAA,QAC5E;AAAA,MACF;AAAA,IACF;AAGA,UAAM,SAAkC,CAAC;AACzC,WAAO,KAAK,GAA8B,EACvC,KAAK,EACL,QAAQ,SAAO;AACd,YAAM,QAAS,IAAgC,GAAG;AAClD,aAAO,GAAG,IACR,OAAO,UAAU,YAAY,UAAU,OAAO,KAAK,MAAM,UAAU,KAAK,CAAC,IAAI;AAAA,IACjF,CAAC;AACH,WAAO,KAAK,UAAU,MAAM;AAAA,EAC9B;AAEA,MAAI;AACF,WAAO,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,EAC3C,QAAQ;AAEN,WAAO,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,IAAI;AAAA,EACrD;AACF;","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 };

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

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

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