import { B as BatchFacilitatorConfig, F as FacilitatorBeforeVerifyHook, a as FacilitatorAfterVerifyHook, b as FacilitatorOnVerifyFailureHook, c as FacilitatorBeforeSettleHook, d as FacilitatorAfterSettleHook, e as FacilitatorOnSettleFailureHook, P as ProtectedRequestHook, f as BeforeVerifyHook, A as AfterVerifyHook, O as OnVerifyFailureHook, g as BeforeSettleHook, h as AfterSettleHook, i as OnSettleFailureHook, j as OnVerifiedPaymentCanceledHook } from '../hooks-BKkPP7ic.js'; export { G as GATEWAY_AUTH_VALIDITY_WINDOW_SECONDS } from '../hooks-BKkPP7ic.js'; import { ExactEvmScheme } from '@x402/evm/exact/server'; import { PaymentRequirements as PaymentRequirements$1, Network } from '@x402/core/types'; export { isBatchPayment } from '../index.js'; import { IncomingMessage, ServerResponse } from 'http'; import 'viem'; /** * PaymentPayload interface (minimal subset needed). */ interface PaymentPayload { x402Version: number; resource?: { url: string; description: string; mimeType: string; }; accepted?: Record; payload: Record; extensions?: Record; } /** * PaymentRequirements interface (minimal subset needed). */ interface PaymentRequirements { scheme: string; network: string; asset: string; amount: string; payTo: string; maxTimeoutSeconds: number; extra?: Record; } /** * VerifyResponse from facilitator. */ interface VerifyResponse { isValid: boolean; invalidReason?: string; payer?: string; } /** * SettleResponse from facilitator. */ interface SettleResponse { success: boolean; errorReason?: string; payer?: string; transaction: string; network: string; } /** * SupportedKind from facilitator. */ interface SupportedKind { x402Version: number; scheme: string; network: string; extra?: Record; } /** * SupportedResponse from facilitator. */ interface SupportedResponse { kinds: SupportedKind[]; extensions: string[]; signers: Record; } /** * FacilitatorClient interface from @x402/core. */ interface FacilitatorClient { verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise; settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise; getSupported(): Promise; } /** * Circle Gateway Facilitator Client. * * A FacilitatorClient implementation that communicates with Circle Gateway's * x402 endpoints for verification and settlement of batched payments. * * The client calls: * - `POST /v1/x402/verify` for payment verification * - `POST /v1/x402/settle` for payment settlement * - `GET /v1/x402/supported` for supported payment kinds * * Lifecycle hooks (`onBeforeVerify`, `onAfterVerify`, `onVerifyFailure`, * `onBeforeSettle`, `onAfterSettle`, `onSettleFailure`) are supported with * the same semantics as the standard SDK's `x402Facilitator` — see * https://docs.x402.org/advanced-concepts/lifecycle-hooks for details. * * @example * ```typescript * import { x402ResourceServer } from "@x402/core/server"; * import { BatchFacilitatorClient } from "@circle-fin/x402-batching/server"; * * const circleClient = new BatchFacilitatorClient({ * url: "https://gateway.circle.com", * }); * * const server = new x402ResourceServer([circleClient]); * await server.initialize(); * ``` */ declare class BatchFacilitatorClient implements FacilitatorClient { readonly url: string; private readonly _createAuthHeaders?; private readonly _headers; private beforeVerifyHooks; private afterVerifyHooks; private onVerifyFailureHooks; private beforeSettleHooks; private afterSettleHooks; private onSettleFailureHooks; /** * Creates a new BatchFacilitatorClient. * * @param config - Configuration including Gateway URL and optional auth headers */ constructor(config?: BatchFacilitatorConfig); private gatewayApiHeaders; /** * Register a hook that runs before facilitator verification. * Return `{ abort: true, reason }` to short-circuit and treat the payment * as invalid (returns `{ isValid: false, invalidReason: reason }`). */ onBeforeVerify(hook: FacilitatorBeforeVerifyHook): this; /** * Register a hook that runs after a successful verification (`isValid: true`). * Not invoked when verification fails — use {@link onVerifyFailure} for that. */ onAfterVerify(hook: FacilitatorAfterVerifyHook): this; /** * Register a hook that runs when verification fails — either when the * facilitator returns `isValid: false` or when an exception is thrown. * Return `{ recovered: true, result }` to override the failure with a * successful verification result. */ onVerifyFailure(hook: FacilitatorOnVerifyFailureHook): this; /** * Register a hook that runs before facilitator settlement. Return * `{ abort: true, reason }` to throw `Error("Settlement aborted: ")`. */ onBeforeSettle(hook: FacilitatorBeforeSettleHook): this; /** * Register a hook that runs after a successful settlement. */ onAfterSettle(hook: FacilitatorAfterSettleHook): this; /** * Register a hook that runs when settlement throws. Return * `{ recovered: true, result }` to swallow the error and return `result` * to the caller as if settlement had succeeded. */ onSettleFailure(hook: FacilitatorOnSettleFailureHook): this; /** * Verify a payment with Circle Gateway. * * @param paymentPayload - The payment payload to verify * @param paymentRequirements - The payment requirements * @returns Verification response */ verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise; /** * Settle a payment with Circle Gateway. * * @param paymentPayload - The payment payload to settle * @param paymentRequirements - The payment requirements * @returns Settlement response */ settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise; /** * HTTP call into Circle Gateway's /verify endpoint. Split out so the hook * machinery in `verify()` reads cleanly. */ private callVerify; /** * HTTP call into Circle Gateway's /settle endpoint. Split out so the hook * machinery in `settle()` reads cleanly. */ private callSettle; /** * Get supported payment kinds from Circle Gateway. * * This fetches the supported networks and their GatewayWallet contract addresses. * The response includes `extra.verifyingContract` for each supported network. * * @returns Supported payment kinds and extensions */ getSupported(): Promise; /** * Helper to convert objects to JSON-safe format. * Handles BigInt and other non-JSON types. */ private toJsonSafe; } /** * Gateway EVM Scheme for x402 resource servers. * * Extends `ExactEvmScheme` with two Gateway-specific behaviors: * * 1. **enhancePaymentRequirements** — merges `supportedKind.extra` (e.g. * `verifyingContract`) into `paymentRequirements.extra`. The base * `ExactEvmScheme` discards this, but Gateway clients need it to * construct the correct EIP-712 signing domain. * * 2. **Money parsers** — registers USDC address mappings for all * Gateway-supported networks so `parsePrice("$0.01")` works * without manual `registerMoneyParser()` calls. * * @example * ```typescript * import { GatewayEvmScheme } from "@circle-fin/x402-batching/server"; * import { x402ResourceServer } from "@x402/express"; * * const resourceServer = new x402ResourceServer(facilitators) * .register("eip155:5042002", new GatewayEvmScheme()); * ``` */ declare class GatewayEvmScheme extends ExactEvmScheme { constructor(); /** * Enhances payment requirements by merging the facilitator's extra data. * * The base `ExactEvmScheme.enhancePaymentRequirements` returns requirements * unchanged, dropping `supportedKind.extra`. Gateway payments require * `extra.verifyingContract` (and other fields like `name`, `version`) to * be present for clients to construct the correct signing domain. */ enhancePaymentRequirements(paymentRequirements: PaymentRequirements$1, supportedKind: { x402Version: number; scheme: string; network: Network; extra?: Record; }, extensionKeys: string[]): Promise; /** * Registers money parsers for all Gateway-supported networks. * * Builds a `network → USDC address` lookup from `CHAIN_CONFIGS` and * registers a single parser that converts dollar amounts to USDC atomic * units (6 decimals) for any Gateway-supported chain. * * Returns `null` for unknown networks so `ExactEvmScheme`'s built-in * parser handles them. */ private registerGatewayMoneyParsers; } /** * Configuration for Gateway middleware. */ interface GatewayMiddlewareConfig { /** Seller's wallet address to receive payments */ sellerAddress: string; /** * Networks to accept payments on. * - If omitted, accepts payments on ALL Gateway-supported networks (recommended) * - Can be a single network string or array of networks * - Format: CAIP-2 (e.g., 'eip155:8453' for Base, 'eip155:5042002' for Arc Testnet) */ networks?: string | string[]; /** * Optional Gateway facilitator URL. * Defaults to mainnet: "https://gateway-api.circle.com". * For testnet, pass "https://gateway-api-testnet.circle.com". */ facilitatorUrl?: string; /** Additional headers merged into every outbound facilitator request. */ headers?: Record; /** Optional resource description */ description?: string; } /** * Express-compatible request with payment info. */ interface PaymentRequest extends IncomingMessage { payment?: { /** Whether the payment was verified */ verified: boolean; /** Payer's address */ payer: string; /** Amount paid in smallest units */ amount: string; /** Network the payment was made on */ network: string; /** Transaction hash after settlement */ transaction?: string; }; body?: unknown; } /** * Express-compatible response. */ interface PaymentResponse extends ServerResponse { json?: (data: unknown) => void; status?: (code: number) => PaymentResponse; } /** * Express-compatible next function. */ type NextFunction = (err?: unknown) => void; /** * Express-compatible middleware function. */ type MiddlewareFunction = (req: PaymentRequest, res: PaymentResponse, next: NextFunction) => void | Promise; /** * Gateway middleware instance. * * The middleware exposes lifecycle hooks that mirror the standard SDK's * `x402ResourceServer` and `x402HTTPResourceServer`: * * - `onProtectedRequest` — runs first, before any payment processing. Can grant * access without payment (e.g. API key auth) or deny outright (returns 403). * - `onBeforeVerify` / `onAfterVerify` / `onVerifyFailure` — wrap the verify call. * - `onBeforeSettle` / `onAfterSettle` / `onSettleFailure` — wrap the settle call. * - `onVerifiedPaymentCanceled` — fires when a payment was verified but the * protected handler erred and we never settled. (Note: with this transport * middleware, settlement happens inline before `next()` runs, so the * cancellation hook only fires when the same request encounters a settle * failure that aborts further processing.) * * See https://docs.x402.org/advanced-concepts/lifecycle-hooks for the * canonical reference. All hooks return promises and can be chained. */ interface GatewayMiddleware { /** * Require payment for a resource. * * @param price - Price in dollars (e.g., '$0.01' or '0.01') * @returns Express-compatible middleware * * @example * ```typescript * app.get('/resource', gateway.require('$0.01'), (req, res) => { * res.json({ content: '...' }); * }); * * app.post('/generate', gateway.require('$0.05'), (req, res) => { * res.json({ result: '...' }); * }); * ``` */ require: (price: string) => MiddlewareFunction; /** * Verify a payment without settling. */ verify: (payment: unknown) => Promise<{ valid: boolean; payer?: string; error?: string; }>; /** * Settle a verified payment. */ settle: (payment: unknown) => Promise<{ success: boolean; transaction?: string; error?: string; }>; /** See {@link GatewayMiddleware} for hook semantics. */ onProtectedRequest: (hook: ProtectedRequestHook) => GatewayMiddleware; /** See {@link GatewayMiddleware} for hook semantics. */ onBeforeVerify: (hook: BeforeVerifyHook) => GatewayMiddleware; /** See {@link GatewayMiddleware} for hook semantics. */ onAfterVerify: (hook: AfterVerifyHook) => GatewayMiddleware; /** See {@link GatewayMiddleware} for hook semantics. */ onVerifyFailure: (hook: OnVerifyFailureHook) => GatewayMiddleware; /** See {@link GatewayMiddleware} for hook semantics. */ onBeforeSettle: (hook: BeforeSettleHook) => GatewayMiddleware; /** See {@link GatewayMiddleware} for hook semantics. */ onAfterSettle: (hook: AfterSettleHook) => GatewayMiddleware; /** See {@link GatewayMiddleware} for hook semantics. */ onSettleFailure: (hook: OnSettleFailureHook) => GatewayMiddleware; /** See {@link GatewayMiddleware} for hook semantics. */ onVerifiedPaymentCanceled: (hook: OnVerifiedPaymentCanceledHook) => GatewayMiddleware; } /** * Create a Gateway middleware instance. * * By default, accepts payments on ALL Gateway-supported networks. Buyers can * pay from any chain where they have Gateway balance. * * @param config - Middleware configuration * @returns Gateway middleware * * @example * ```typescript * import express from 'express'; * import { createGatewayMiddleware } from '@circle-fin/x402-batching/server'; * * const app = express(); * * // Accept payments on all Gateway-supported networks (recommended) * const gateway = createGatewayMiddleware({ * sellerAddress: '0x...', * }); * * // Or restrict to specific networks * const gateway = createGatewayMiddleware({ * sellerAddress: '0x...', * networks: ['eip155:5042002', 'eip155:84532'], // Arc Testnet + Base Sepolia * }); * * app.get('/resource', gateway.require('$0.01'), (req, res) => { * res.json({ content: 'Paid content!' }); * }); * * // Bypass payment for callers carrying an API key * gateway.onProtectedRequest(async (ctx) => { * if (await isValidApiKey(ctx.getHeader('x-api-key'))) { * return { grantAccess: true }; * } * }); * ``` */ declare function createGatewayMiddleware(config: GatewayMiddlewareConfig): GatewayMiddleware; export { BatchFacilitatorClient, GatewayEvmScheme, type GatewayMiddleware, type GatewayMiddlewareConfig, type PaymentRequest, type PaymentResponse, createGatewayMiddleware };