UNPKG

@payai/x402

Version:

PayAI-distributed wrapper for @x402/core v2

330 lines (326 loc) 13.6 kB
import { c as PaymentRequired, a as PaymentRequirements, P as PaymentPayload, N as Network, h as SchemeNetworkClient, S as SettleResponse } from '../mechanisms-CDlcy1I8.js'; /** * Client Hook Context Interfaces */ interface PaymentCreationContext { paymentRequired: PaymentRequired; selectedRequirements: PaymentRequirements; } interface PaymentCreatedContext extends PaymentCreationContext { paymentPayload: PaymentPayload; } interface PaymentCreationFailureContext extends PaymentCreationContext { error: Error; } /** * Client Hook Type Definitions */ type BeforePaymentCreationHook = (context: PaymentCreationContext) => Promise<void | { abort: true; reason: string; }>; type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise<void>; type OnPaymentCreationFailureHook = (context: PaymentCreationFailureContext) => Promise<void | { recovered: true; payload: PaymentPayload; }>; type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements; /** * Extension that can enrich payment payloads on the client side. * * Client extensions are invoked after the scheme creates the base payment payload * but before it is returned. This allows mechanism-specific logic (e.g., EVM EIP-2612 * permit signing) to enrich the payload's extensions data. */ interface ClientExtension { /** * Unique key identifying this extension (e.g., "eip2612GasSponsoring"). * Must match the extension key used in PaymentRequired.extensions. */ key: string; /** * Called after payload creation when the extension key is present in * paymentRequired.extensions. Allows the extension to enrich the payload * with extension-specific data (e.g., signing an EIP-2612 permit). * * @param paymentPayload - The payment payload to enrich * @param paymentRequired - The original PaymentRequired response * @returns The enriched payment payload */ enrichPaymentPayload?: (paymentPayload: PaymentPayload, paymentRequired: PaymentRequired) => Promise<PaymentPayload>; } /** * A policy function that filters or transforms payment requirements. * Policies are applied in order before the selector chooses the final option. * * @param x402Version - The x402 protocol version * @param paymentRequirements - Array of payment requirements to filter/transform * @returns Filtered array of payment requirements */ type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[]; /** * Configuration for registering a payment scheme with a specific network */ interface SchemeRegistration { /** * The network identifier (e.g., 'eip155:8453', 'solana:mainnet') */ network: Network; /** * The scheme client implementation for this network */ client: SchemeNetworkClient; /** * The x402 protocol version to use for this scheme * * @default 2 */ x402Version?: number; } /** * Configuration options for the fetch wrapper */ interface x402ClientConfig { /** * Array of scheme registrations defining which payment methods are supported */ schemes: SchemeRegistration[]; /** * Policies to apply to the client */ policies?: PaymentPolicy[]; /** * Custom payment requirements selector function * If not provided, uses the default selector (first available option) */ paymentRequirementsSelector?: SelectPaymentRequirements; } /** * Core client for managing x402 payment schemes and creating payment payloads. * * Handles registration of payment schemes, policy-based filtering of payment requirements, * and creation of payment payloads based on server requirements. */ declare class x402Client { private readonly paymentRequirementsSelector; private readonly registeredClientSchemes; private readonly policies; private readonly registeredExtensions; private beforePaymentCreationHooks; private afterPaymentCreationHooks; private onPaymentCreationFailureHooks; /** * Creates a new x402Client instance. * * @param paymentRequirementsSelector - Function to select payment requirements from available options */ constructor(paymentRequirementsSelector?: SelectPaymentRequirements); /** * Creates a new x402Client instance from a configuration object. * * @param config - The client configuration including schemes, policies, and payment requirements selector * @returns A configured x402Client instance */ static fromConfig(config: x402ClientConfig): x402Client; /** * Registers a scheme client for the current x402 version. * * @param network - The network to register the client for * @param client - The scheme network client to register * @returns The x402Client instance for chaining */ register(network: Network, client: SchemeNetworkClient): x402Client; /** * Registers a scheme client for x402 version 1. * * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet') * @param client - The scheme network client to register * @returns The x402Client instance for chaining */ registerV1(network: string, client: SchemeNetworkClient): x402Client; /** * Registers a policy to filter or transform payment requirements. * * Policies are applied in order after filtering by registered schemes * and before the selector chooses the final payment requirement. * * @param policy - Function to filter/transform payment requirements * @returns The x402Client instance for chaining * * @example * ```typescript * // Prefer cheaper options * client.registerPolicy((version, reqs) => * reqs.filter(r => BigInt(r.value) < BigInt('1000000')) * ); * * // Prefer specific networks * client.registerPolicy((version, reqs) => * reqs.filter(r => r.network.startsWith('eip155:')) * ); * ``` */ registerPolicy(policy: PaymentPolicy): x402Client; /** * Registers a client extension that can enrich payment payloads. * * Extensions are invoked after the scheme creates the base payload and the * payload is wrapped with extensions/resource/accepted data. If the extension's * key is present in `paymentRequired.extensions`, the extension's * `enrichPaymentPayload` hook is called to modify the payload. * * @param extension - The client extension to register * @returns The x402Client instance for chaining */ registerExtension(extension: ClientExtension): x402Client; /** * Register a hook to execute before payment payload creation. * Can abort creation by returning { abort: true, reason: string } * * @param hook - The hook function to register * @returns The x402Client instance for chaining */ onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client; /** * Register a hook to execute after successful payment payload creation. * * @param hook - The hook function to register * @returns The x402Client instance for chaining */ onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client; /** * Register a hook to execute when payment payload creation fails. * Can recover from failure by returning { recovered: true, payload: PaymentPayload } * * @param hook - The hook function to register * @returns The x402Client instance for chaining */ onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client; /** * Creates a payment payload based on a PaymentRequired response. * * Automatically extracts x402Version, resource, and extensions from the PaymentRequired * response and constructs a complete PaymentPayload with the accepted requirements. * * @param paymentRequired - The PaymentRequired response from the server * @returns Promise resolving to the complete payment payload */ createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload>; /** * Merges server-declared extensions with scheme-provided extensions. * Scheme extensions overlay on top of server extensions at each key, * preserving server-provided schema while overlaying scheme-provided info. * * @param serverExtensions - Extensions declared by the server in the 402 response * @param schemeExtensions - Extensions provided by the scheme client (e.g. EIP-2612) * @returns The merged extensions object, or undefined if both inputs are undefined */ private mergeExtensions; /** * Enriches a payment payload by calling registered extension hooks. * For each extension key present in the PaymentRequired response, * invokes the corresponding extension's enrichPaymentPayload callback. * * @param paymentPayload - The payment payload to enrich with extension data * @param paymentRequired - The PaymentRequired response containing extension declarations * @returns The enriched payment payload with extension data applied */ private enrichPaymentPayloadWithExtensions; /** * Selects appropriate payment requirements based on registered clients and policies. * * Selection process: * 1. Filter by registered schemes (network + scheme support) * 2. Apply all registered policies in order * 3. Use selector to choose final requirement * * @param x402Version - The x402 protocol version * @param paymentRequirements - Array of available payment requirements * @returns The selected payment requirements */ private selectPaymentRequirements; /** * Internal method to register a scheme client. * * @param x402Version - The x402 protocol version * @param network - The network to register the client for * @param client - The scheme network client to register * @returns The x402Client instance for chaining */ private _registerScheme; } /** * Context provided to onPaymentRequired hooks. */ interface PaymentRequiredContext { paymentRequired: PaymentRequired; } /** * Hook called when a 402 response is received, before payment processing. * Return headers to try before payment, or void to proceed directly to payment. */ type PaymentRequiredHook = (context: PaymentRequiredContext) => Promise<{ headers: Record<string, string>; } | void>; /** * HTTP-specific client for handling x402 payment protocol over HTTP. * * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality * for payment headers and responses while maintaining the builder pattern. */ declare class x402HTTPClient { private readonly client; private paymentRequiredHooks; /** * Creates a new x402HTTPClient instance. * * @param client - The underlying x402Client for payment logic */ constructor(client: x402Client); /** * 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: PaymentRequiredHook): 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 */ handlePaymentRequired(paymentRequired: PaymentRequired): Promise<Record<string, string> | 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: PaymentPayload): Record<string, string>; /** * 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: (name: string) => string | null | undefined, body?: unknown): PaymentRequired; /** * 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: (name: string) => string | null | undefined): SettleResponse; /** * 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 */ createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload>; } export { type AfterPaymentCreationHook, type BeforePaymentCreationHook, type ClientExtension, type OnPaymentCreationFailureHook, type PaymentCreatedContext, type PaymentCreationContext, type PaymentCreationFailureContext, type PaymentPolicy, type PaymentRequiredContext, type PaymentRequiredHook, type SchemeRegistration, type SelectPaymentRequirements, x402Client, type x402ClientConfig, x402HTTPClient };