@agent-score/commerce 1.7.0 → 1.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/{_response-DpB-cm2c.d.mts → _response-9yp6Fit2.d.mts} +13 -11
- package/dist/{_response-C2yFQoIA.d.ts → _response-CC6jNb8q.d.ts} +13 -11
- package/dist/challenge/index.d.mts +6 -5
- package/dist/challenge/index.d.ts +6 -5
- package/dist/challenge/index.js.map +1 -1
- package/dist/challenge/index.mjs.map +1 -1
- package/dist/core.d.mts +36 -27
- package/dist/core.d.ts +36 -27
- package/dist/core.js +21 -101
- package/dist/core.js.map +1 -1
- package/dist/core.mjs +21 -101
- package/dist/core.mjs.map +1 -1
- package/dist/identity/express.d.mts +12 -13
- package/dist/identity/express.d.ts +12 -13
- package/dist/identity/express.js +38 -121
- package/dist/identity/express.js.map +1 -1
- package/dist/identity/express.mjs +36 -118
- package/dist/identity/express.mjs.map +1 -1
- package/dist/identity/fastify.d.mts +12 -11
- package/dist/identity/fastify.d.ts +12 -11
- package/dist/identity/fastify.js +38 -121
- package/dist/identity/fastify.js.map +1 -1
- package/dist/identity/fastify.mjs +36 -118
- package/dist/identity/fastify.mjs.map +1 -1
- package/dist/identity/hono.d.mts +13 -28
- package/dist/identity/hono.d.ts +13 -28
- package/dist/identity/hono.js +31 -123
- package/dist/identity/hono.js.map +1 -1
- package/dist/identity/hono.mjs +29 -120
- package/dist/identity/hono.mjs.map +1 -1
- package/dist/identity/nextjs.d.mts +8 -7
- package/dist/identity/nextjs.d.ts +8 -7
- package/dist/identity/nextjs.js +27 -119
- package/dist/identity/nextjs.js.map +1 -1
- package/dist/identity/nextjs.mjs +27 -118
- package/dist/identity/nextjs.mjs.map +1 -1
- package/dist/identity/policy.d.mts +1 -0
- package/dist/identity/policy.d.ts +1 -0
- package/dist/identity/web.d.mts +12 -14
- package/dist/identity/web.d.ts +12 -14
- package/dist/identity/web.js +27 -119
- package/dist/identity/web.js.map +1 -1
- package/dist/identity/web.mjs +27 -118
- package/dist/identity/web.mjs.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -6
- package/dist/index.mjs.map +1 -1
- package/dist/payment/index.d.mts +2 -2
- package/dist/payment/index.d.ts +2 -2
- package/dist/payment/index.js.map +1 -1
- package/dist/payment/index.mjs.map +1 -1
- package/dist/{signer-kCAJUZwp.d.mts → signer-CFVQsWjL.d.mts} +1 -6
- package/dist/{signer-kCAJUZwp.d.ts → signer-CFVQsWjL.d.ts} +1 -6
- package/dist/stripe-multichain/index.d.mts +1 -1
- package/dist/stripe-multichain/index.d.ts +1 -1
- package/dist/stripe-multichain/index.js.map +1 -1
- package/dist/stripe-multichain/index.mjs.map +1 -1
- package/package.json +11 -9
package/dist/payment/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { P as PaymentRequiredHeaderInput, a as aliasAmountFields, p as paymentRequiredHeader, w as wwwAuthenticateHeader } from '../wwwauthenticate-CU1eNvMQ.mjs';
|
|
2
|
-
export { P as PaymentSigner, S as SignerNetwork,
|
|
2
|
+
export { P as PaymentSigner, S as SignerNetwork, e as extractPaymentSigner, r as readX402PaymentHeader } from '../signer-CFVQsWjL.mjs';
|
|
3
3
|
|
|
4
4
|
interface PaymentRequestInput {
|
|
5
5
|
/** Symbolic rail name (e.g., 'tempo-mainnet', 'x402-base-mainnet') — fills in defaults */
|
|
@@ -781,7 +781,7 @@ declare function buildPaymentHeaders(input: BuildPaymentHeadersInput): PaymentHe
|
|
|
781
781
|
* `/v1/credentials/wallets` capture endpoint dedupes correctly and the operator's
|
|
782
782
|
* `transaction_count` doesn't inflate.
|
|
783
783
|
*
|
|
784
|
-
* Convention
|
|
784
|
+
* Convention:
|
|
785
785
|
* 1. Prefer the upstream payment-rail's stable identifier (Stripe PaymentIntent id, x402
|
|
786
786
|
* tx hash) when one exists — those are already idempotent on their side.
|
|
787
787
|
* 2. Fall back to a synthesized `pi-{orderId}-{amountCents}` key when no upstream id is
|
package/dist/payment/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { P as PaymentRequiredHeaderInput, a as aliasAmountFields, p as paymentRequiredHeader, w as wwwAuthenticateHeader } from '../wwwauthenticate-CU1eNvMQ.js';
|
|
2
|
-
export { P as PaymentSigner, S as SignerNetwork,
|
|
2
|
+
export { P as PaymentSigner, S as SignerNetwork, e as extractPaymentSigner, r as readX402PaymentHeader } from '../signer-CFVQsWjL.js';
|
|
3
3
|
|
|
4
4
|
interface PaymentRequestInput {
|
|
5
5
|
/** Symbolic rail name (e.g., 'tempo-mainnet', 'x402-base-mainnet') — fills in defaults */
|
|
@@ -781,7 +781,7 @@ declare function buildPaymentHeaders(input: BuildPaymentHeadersInput): PaymentHe
|
|
|
781
781
|
* `/v1/credentials/wallets` capture endpoint dedupes correctly and the operator's
|
|
782
782
|
* `transaction_count` doesn't inflate.
|
|
783
783
|
*
|
|
784
|
-
* Convention
|
|
784
|
+
* Convention:
|
|
785
785
|
* 1. Prefer the upstream payment-rail's stable identifier (Stripe PaymentIntent id, x402
|
|
786
786
|
* tx hash) when one exists — those are already idempotent on their side.
|
|
787
787
|
* 2. Fall back to a synthesized `pi-{orderId}-{amountCents}` key when no upstream id is
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/payment/index.ts","../../src/payment/networks.ts","../../src/payment/usdc.ts","../../src/payment/rails.ts","../../src/payment/directive.ts","../../src/payment/x402.ts","../../src/payment/x402_server.ts","../../src/payment/x402_settle.ts","../../src/payment/x402_validation.ts","../../src/stripe-multichain/mppx_stripe.ts","../../src/payment/mppx_server.ts","../../src/payment/dispatch.ts","../../src/payment/wwwauthenticate.ts","../../src/payment/headers.ts","../../src/payment/idempotency.ts","../../src/signer.ts","../../src/payment/settlement_override.ts"],"sourcesContent":["export * from './directive';\nexport * from './networks';\nexport * from './usdc';\nexport * from './rails';\nexport * from './x402';\nexport * from './x402_server';\nexport * from './x402_settle';\nexport * from './x402_validation';\nexport * from './mppx_server';\nexport * from './dispatch';\nexport * from './wwwauthenticate';\nexport * from './headers';\nexport * from './idempotency';\nexport * from './signer';\nexport * from './settlement_override';\n","/**\n * Named network registry. Vendors reference symbolic names (`networks.base.mainnet.caip2`)\n * instead of magic strings. Lifted from agentscore-pay's constants.\n */\nexport const networks = {\n base: {\n mainnet: { caip2: 'eip155:8453' as const, chainId: 8453 },\n sepolia: { caip2: 'eip155:84532' as const, chainId: 84532 },\n },\n solana: {\n mainnet: { caip2: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' as const },\n devnet: { caip2: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1' as const },\n },\n tempo: {\n mainnet: { caip2: 'eip155:4217' as const, chainId: 4217 },\n testnet: { caip2: 'eip155:42431' as const, chainId: 42431 },\n },\n} as const;\n\nexport type NetworkFamily = keyof typeof networks;\n\n/**\n * Returns the family name (base/solana/tempo) for a given CAIP-2 network string,\n * or null if the network isn't in the registry. Useful for routing settlement\n * by network.\n */\nexport function networkFamily(caip2: string): NetworkFamily | null {\n if (caip2 === networks.base.mainnet.caip2 || caip2 === networks.base.sepolia.caip2) return 'base';\n if (caip2 === networks.solana.mainnet.caip2 || caip2 === networks.solana.devnet.caip2) return 'solana';\n if (caip2 === networks.tempo.mainnet.caip2 || caip2 === networks.tempo.testnet.caip2) return 'tempo';\n if (caip2.startsWith('solana:')) return 'solana';\n return null;\n}\n","/**\n * USDC token registry per network. Used by paymentDirective and rail definitions.\n * Lifted from agentscore-pay's constants.\n */\nexport const USDC = {\n base: {\n mainnet: { address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' as const, decimals: 6 },\n sepolia: { address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' as const, decimals: 6 },\n },\n solana: {\n mainnet: { mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', decimals: 6 },\n devnet: { mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', decimals: 6 },\n },\n tempo: {\n mainnet: { address: '0x20C000000000000000000000b9537d11c60E8b50' as const, decimals: 6 },\n testnet: { address: '0x20c0000000000000000000000000000000000000' as const, decimals: 6 },\n },\n} as const;\n","import { networks } from './networks';\nimport { USDC } from './usdc';\n\n/**\n * Symbolic rail names mapped to their protocol details. Vendors pass `rail: 'tempo-mainnet'`\n * to the directive builder and the SDK fills in method/network/decimals/currency from this\n * registry. Custom rails not in this registry can be passed by setting the lower-level\n * fields directly on the directive builder.\n */\nexport const rails = {\n 'tempo-mainnet': {\n method: 'tempo',\n network: networks.tempo.mainnet.caip2,\n chainId: networks.tempo.mainnet.chainId,\n currency: USDC.tempo.mainnet.address,\n decimals: USDC.tempo.mainnet.decimals,\n asset: USDC.tempo.mainnet.address,\n },\n 'tempo-testnet': {\n method: 'tempo',\n network: networks.tempo.testnet.caip2,\n chainId: networks.tempo.testnet.chainId,\n currency: USDC.tempo.testnet.address,\n decimals: USDC.tempo.testnet.decimals,\n asset: USDC.tempo.testnet.address,\n },\n 'x402-base-mainnet': {\n method: 'x402',\n network: networks.base.mainnet.caip2,\n chainId: networks.base.mainnet.chainId,\n currency: USDC.base.mainnet.address,\n decimals: USDC.base.mainnet.decimals,\n asset: USDC.base.mainnet.address,\n },\n 'x402-base-sepolia': {\n method: 'x402',\n network: networks.base.sepolia.caip2,\n chainId: networks.base.sepolia.chainId,\n currency: USDC.base.sepolia.address,\n decimals: USDC.base.sepolia.decimals,\n asset: USDC.base.sepolia.address,\n },\n // Upto rails — pay UP TO a max amount (Permit2-based, vs EIP-3009 for exact). Use for\n // variable-cost APIs where the actual cost depends on output (LLM tokens, bandwidth, etc.).\n // Only available on EVM networks; Solana svm doesn't ship an upto scheme yet.\n 'x402-base-mainnet-upto': {\n method: 'x402-upto',\n network: networks.base.mainnet.caip2,\n chainId: networks.base.mainnet.chainId,\n currency: USDC.base.mainnet.address,\n decimals: USDC.base.mainnet.decimals,\n asset: USDC.base.mainnet.address,\n },\n 'x402-base-sepolia-upto': {\n method: 'x402-upto',\n network: networks.base.sepolia.caip2,\n chainId: networks.base.sepolia.chainId,\n currency: USDC.base.sepolia.address,\n decimals: USDC.base.sepolia.decimals,\n asset: USDC.base.sepolia.address,\n },\n 'mpp-solana-mainnet': {\n method: 'solana',\n network: networks.solana.mainnet.caip2,\n currency: USDC.solana.mainnet.mint,\n decimals: USDC.solana.mainnet.decimals,\n asset: USDC.solana.mainnet.mint,\n },\n 'mpp-solana-devnet': {\n method: 'solana',\n network: networks.solana.devnet.caip2,\n currency: USDC.solana.devnet.mint,\n decimals: USDC.solana.devnet.decimals,\n asset: USDC.solana.devnet.mint,\n },\n 'stripe-spt': {\n method: 'stripe',\n currency: 'usd',\n decimals: 2,\n },\n} as const;\n\nexport type RailName = keyof typeof rails;\n\nexport interface RailDefinition {\n method: string;\n network?: string;\n chainId?: number;\n currency: string;\n decimals: number;\n asset?: string;\n}\n\n/**\n * Lookup a rail definition by symbolic name. Returns undefined if the rail isn't in\n * the registry — vendors with custom rails should pass the low-level fields directly.\n */\nexport function lookupRail(name: string): RailDefinition | undefined {\n return rails[name as RailName] as RailDefinition | undefined;\n}\n","import { lookupRail } from './rails';\n\nexport interface PaymentRequestInput {\n /** Symbolic rail name (e.g., 'tempo-mainnet', 'x402-base-mainnet') — fills in defaults */\n rail?: string;\n /** Amount in USD as a number or string. Converted to raw integer using `decimals`. */\n amountUsd: string | number;\n /** Token contract address or currency code. Defaults from rail. */\n currency?: string;\n /** Decimal precision for the amount. Defaults from rail (6 for USDC, 2 for USD). */\n decimals?: number;\n /** Recipient address (on-chain). Optional for stripe-style rails. */\n recipient?: string;\n /** EVM chain ID (goes into methodDetails.chainId). Defaults from rail. */\n chainId?: number;\n /** Stripe profile_id or similar (goes into methodDetails.networkId — note camelCase per link-cli's mpp decode validator). */\n networkId?: string;\n}\n\n/**\n * Build the base64-encoded `request` blob for an MPP Payment directive (per the\n * paymentauth.org spec). Output shape matches what link-cli `mpp decode` expects:\n *\n * { amount: \"<raw_integer>\", currency: \"<token>\", recipient?: \"<addr>\",\n * methodDetails?: { chainId?: number, networkId?: string } }\n */\nexport function buildPaymentRequestBlob(input: PaymentRequestInput): string {\n const railDef = input.rail ? lookupRail(input.rail) : undefined;\n const decimals = input.decimals ?? railDef?.decimals ?? 6;\n const currency = input.currency ?? railDef?.currency ?? 'usd';\n const chainId = input.chainId ?? railDef?.chainId;\n\n const amountNum = typeof input.amountUsd === 'string' ? Number(input.amountUsd) : input.amountUsd;\n const amountRaw = BigInt(Math.round(amountNum * 10 ** decimals)).toString();\n const blob: Record<string, unknown> = { amount: amountRaw, currency, decimals };\n if (input.recipient) blob.recipient = input.recipient;\n const methodDetails: Record<string, unknown> = {};\n if (chainId !== undefined) methodDetails.chainId = chainId;\n if (input.networkId) methodDetails.networkId = input.networkId;\n if (Object.keys(methodDetails).length > 0) blob.methodDetails = methodDetails;\n return Buffer.from(JSON.stringify(blob)).toString('base64url');\n}\n\nexport interface PaymentDirectiveInput {\n /** Symbolic rail name — sets `method` automatically */\n rail?: string;\n /** Challenge id (unique per request, used to correlate retries) */\n id: string;\n /** Realm — the host of the merchant URL (e.g., \"agents.merchant.example\") */\n realm: string;\n /** MPP method name. Defaults from rail (e.g., 'tempo', 'stripe'). */\n method?: string;\n /** MPP intent. Defaults to 'charge'. */\n intent?: string;\n /** ISO-8601 expiry timestamp. Defaults to now + 5 minutes. */\n expires?: string;\n /** Base64-encoded request blob. Pass the result of buildPaymentRequestBlob. */\n request: string;\n}\n\n/**\n * Format an MPP Payment directive string for the WWW-Authenticate header.\n * Output shape: `Payment id=\"...\", realm=\"...\", method=\"...\", intent=\"charge\",\n * expires=\"...\", request=\"<base64>\"`\n */\nexport function paymentDirective(input: PaymentDirectiveInput): string {\n const railDef = input.rail ? lookupRail(input.rail) : undefined;\n const method = input.method ?? railDef?.method ?? 'unknown';\n const intent = input.intent ?? 'charge';\n const expires = input.expires ?? new Date(Date.now() + 5 * 60 * 1000).toISOString();\n return `Payment id=\"${input.id}\", realm=\"${input.realm}\", method=\"${method}\", intent=\"${intent}\", expires=\"${expires}\", request=\"${input.request}\"`;\n}\n\nexport interface BuildPaymentDirectiveInput\n extends Omit<PaymentRequestInput, 'rail'>,\n Omit<PaymentDirectiveInput, 'request'> {\n rail: string;\n}\n\n/**\n * Convenience: build the request blob and the directive in one call. Most vendors\n * want this rather than the two-step form.\n */\nexport function buildPaymentDirective(input: BuildPaymentDirectiveInput): string {\n const request = buildPaymentRequestBlob({\n rail: input.rail,\n amountUsd: input.amountUsd,\n currency: input.currency,\n decimals: input.decimals,\n recipient: input.recipient,\n chainId: input.chainId,\n networkId: input.networkId,\n });\n return paymentDirective({\n rail: input.rail,\n id: input.id,\n realm: input.realm,\n method: input.method,\n intent: input.intent,\n expires: input.expires,\n request,\n });\n}\n","/**\n * Generic x402 server interface. Different versions of @x402/core may expose different\n * shapes; we only require register() and (optionally) registerV1().\n */\nexport interface X402ServerLike {\n register(network: string, scheme: unknown): void;\n registerV1?(network: string, scheme: unknown): void;\n}\n\n/**\n * Registers an x402 scheme on both v1 and v2 of the protocol.\n *\n * Why: the @x402/core HTTP parser hardcodes `x402Version === 1`, while the client's\n * `.register()` defaults to v2. Without registering on both versions, a merchant\n * emitting a v1 response gets \"No client registered for x402 version: 1\" even\n * though the scheme handler is identical between versions. Every merchant trips\n * on this; the helper hides the workaround.\n */\nexport function registerX402SchemesV1V2(\n server: X402ServerLike,\n network: string,\n scheme: unknown,\n): void {\n server.register(network, scheme);\n if (typeof server.registerV1 === 'function') {\n server.registerV1(network, scheme);\n }\n}\n","import { networks } from './networks';\nimport { registerX402SchemesV1V2 } from './x402';\n\nexport type X402SymbolicRail =\n | 'x402-base-mainnet'\n | 'x402-base-sepolia'\n | 'x402-base-mainnet-upto'\n | 'x402-base-sepolia-upto';\n\nexport type X402FacilitatorChoice = 'coinbase' | 'http' | unknown;\n\nexport interface CreateX402ServerOptions {\n /**\n * Facilitator selection:\n * - 'coinbase' → Coinbase CDP facilitator (requires `@coinbase/x402` installed)\n * - 'http' → HTTP-only public testnet facilitator\n * - any object → custom facilitator instance, used directly\n * - omitted → defaults to 'http'\n */\n facilitator?: X402FacilitatorChoice;\n /**\n * Symbolic rail names to register schemes for. Each gets v1+v2 dual-register applied.\n * Requires `@x402/evm` peer dep installed.\n */\n rails?: X402SymbolicRail[];\n /** Advanced: register custom {network, scheme} pairs (in addition to or instead of `rails`). */\n schemes?: { network: string; scheme: unknown }[];\n /** Register the Bazaar discovery extension. Requires `@x402/extensions` installed. */\n bazaar?: boolean;\n /** Initialize the server immediately (calls facilitator). Default true. */\n initialize?: boolean;\n}\n\n/**\n * Loose type for the x402 resource server. We name the methods commerce calls during\n * setup; everything else (settlePayment, buildPaymentRequirements, processPaymentRequest,\n * enrichExtensions, etc.) is callable via the index signature so vendor code can use the\n * full @x402/core surface without us having to mirror every method signature.\n */\nexport interface X402Server {\n register(network: string, scheme: unknown): void;\n registerV1?(network: string, scheme: unknown): void;\n registerExtension(ext: unknown): void;\n initialize(): Promise<void>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}\n\ninterface X402CoreModule {\n x402ResourceServer: new (facilitator?: unknown) => X402Server;\n HTTPFacilitatorClient: new (facilitator?: unknown) => unknown;\n}\n\ninterface SchemeModule {\n ExactEvmScheme?: new () => unknown;\n UptoEvmScheme?: new () => unknown;\n}\n\ninterface CoinbaseModule {\n facilitator?: unknown;\n}\n\ninterface BazaarModule {\n bazaarResourceServerExtension?: unknown;\n}\n\n/**\n * One-call x402 server setup. Resolves facilitator, constructs the server, registers\n * schemes per network with v1+v2 dual-register, optionally adds the Bazaar extension,\n * and initializes — replaces ~15 lines of boilerplate with a single config call.\n *\n * x402 packages are peer dependencies — vendors install only the schemes they use.\n * Throws a guiding error if a required peer is missing.\n *\n * const server = await createX402Server({\n * facilitator: 'coinbase',\n * rails: ['x402-base-mainnet'],\n * bazaar: true,\n * });\n */\nexport async function createX402Server(opts: CreateX402ServerOptions = {}): Promise<X402Server> {\n const x402Core = (await dynamicImport<X402CoreModule>('@x402/core/server')) ?? null;\n /* v8 ignore start -- peer-dep-absence guard; @x402/core is installed in test env */\n if (!x402Core) {\n throw new Error(\n '@x402/core not installed — `npm install @x402/core` to use createX402Server.',\n );\n }\n /* v8 ignore stop */\n\n let facilitator: unknown;\n if (opts.facilitator === 'coinbase') {\n const cb = await dynamicImport<CoinbaseModule>('@coinbase/x402');\n /* v8 ignore start -- peer-dep-absence guard; @coinbase/x402 is installed in test env */\n if (!cb?.facilitator) {\n throw new Error(\n '@coinbase/x402 not installed — `npm install @coinbase/x402` for facilitator: \"coinbase\".',\n );\n }\n /* v8 ignore stop */\n facilitator = new x402Core.HTTPFacilitatorClient(cb.facilitator);\n } else if (opts.facilitator === undefined || opts.facilitator === 'http') {\n facilitator = new x402Core.HTTPFacilitatorClient();\n } else {\n facilitator = opts.facilitator;\n }\n\n const server = new x402Core.x402ResourceServer(facilitator);\n\n let evmExactModule: SchemeModule | null = null;\n let evmUptoModule: SchemeModule | null = null;\n for (const rail of opts.rails ?? []) {\n const isUpto = rail.endsWith('-upto');\n if (rail.startsWith('x402-base')) {\n const baseRail = isUpto ? rail.slice(0, -5) : rail;\n const network =\n baseRail === 'x402-base-mainnet' ? networks.base.mainnet.caip2 : networks.base.sepolia.caip2;\n if (isUpto) {\n evmUptoModule ??= await dynamicImport<SchemeModule>('@x402/evm/upto/server');\n /* v8 ignore start -- peer-dep-absence guard; @x402/evm is installed in test env */\n if (!evmUptoModule?.UptoEvmScheme) {\n throw new Error('@x402/evm not installed — `npm install @x402/evm` for x402 base upto rails.');\n }\n /* v8 ignore stop */\n registerX402SchemesV1V2(server, network, new evmUptoModule.UptoEvmScheme());\n } else {\n evmExactModule ??= await dynamicImport<SchemeModule>('@x402/evm/exact/server');\n /* v8 ignore start -- peer-dep-absence guard; @x402/evm is installed in test env */\n if (!evmExactModule?.ExactEvmScheme) {\n throw new Error('@x402/evm not installed — `npm install @x402/evm` for x402 base rails.');\n }\n /* v8 ignore stop */\n registerX402SchemesV1V2(server, network, new evmExactModule.ExactEvmScheme());\n }\n }\n }\n\n for (const { network, scheme } of opts.schemes ?? []) {\n registerX402SchemesV1V2(server, network, scheme);\n }\n\n if (opts.bazaar) {\n const bazaar = await dynamicImport<BazaarModule>('@x402/extensions/bazaar');\n /* v8 ignore start -- peer-dep-absence guard; @x402/extensions is installed in test env */\n if (!bazaar?.bazaarResourceServerExtension) {\n throw new Error(\n '@x402/extensions not installed — `npm install @x402/extensions` for bazaar discovery.',\n );\n }\n /* v8 ignore stop */\n server.registerExtension(bazaar.bazaarResourceServerExtension);\n }\n\n if (opts.initialize !== false) {\n await server.initialize();\n }\n return server;\n}\n\nexport interface BuildX402AcceptsForOptions {\n network: string;\n price: string;\n payTo: string;\n scheme?: string;\n maxTimeoutSeconds?: number;\n extensions?: string[];\n}\n\n/**\n * Build x402 `accepts[]` entries for a 402 challenge body.\n *\n * Wraps `server.buildPaymentRequirements(...)` so merchants don't have to:\n *\n * 1. Construct the resource-config object themselves\n * 2. Remember to serialize each Pydantic-equivalent requirement back to a\n * plain object before stitching it into the 402 body\n * 3. Hardcode `extra` (which differs by the actual on-chain contract — base\n * mainnet USDC has `name: \"USD Coin\"`, base sepolia USDC has `name: \"USDC\"`;\n * EIP-712 domain hashes differ, so getting this wrong silently breaks every\n * signature verify at the facilitator)\n *\n * Returns a list of plain objects in the shape that x402 expects on the wire —\n * drop them straight into the `accepts` field of the 402 challenge body.\n */\nexport async function buildX402AcceptsFor402(\n server: X402Server,\n opts: BuildX402AcceptsForOptions,\n): Promise<unknown[]> {\n const requirements = await server.buildPaymentRequirements(\n {\n scheme: opts.scheme ?? 'exact',\n network: opts.network,\n price: opts.price,\n payTo: opts.payTo,\n maxTimeoutSeconds: opts.maxTimeoutSeconds ?? 300,\n },\n opts.extensions,\n );\n return Array.isArray(requirements) ? requirements : [];\n}\n\nasync function dynamicImport<T>(moduleName: string): Promise<T | null> {\n try {\n return (await import(moduleName)) as T;\n } catch {\n return null;\n }\n}\n","/**\n * `processX402Settle`: single-call x402 verify+settle for merchants.\n *\n * Wraps the four x402-server steps every x402-accepting merchant repeats:\n * 1. `buildPaymentRequirements(resourceConfig)`: builds the requirement entries the\n * facilitator validates against\n * 2. `enrichExtensions(extension, transportContext)`: folds in Bazaar (or other)\n * extensions for the verify step\n * 3. `processPaymentRequest(payload, resourceConfig, resourceMeta, extensions)`:\n * runs verify against the facilitator\n * 4. `settlePayment(payload, matchedRequirement)`: settles on-chain\n *\n * Returns a tagged result so the caller can map errors to merchant-shaped responses\n * without owning the orchestration boilerplate. Use `classifyX402SettleResult` to\n * map the tagged result to a recommended HTTP response.\n */\n\nimport type { X402Server } from './x402_server';\n\nexport interface ProcessX402SettleInput {\n /** The x402 server instance from `createX402Server`. */\n x402Server: X402Server;\n /** The verified x402 payload extracted from the X-Payment header. */\n payload: unknown;\n /** Resource configuration the facilitator validates against (network, price, payTo,\n * asset, maxTimeoutSeconds, etc.). Shape is x402-server-specific. */\n resourceConfig: unknown;\n /** Resource metadata exposed to the facilitator (URL, description, mime type). */\n resourceMeta: { url: string; description: string; mimeType: string };\n /** Optional extension to enrich during verify (e.g. Bazaar). */\n extension?: unknown;\n /** Transport context for the extension enrich step. Defaults to `{ method: 'POST',\n * adapter: { getPath: () => new URL(resourceMeta.url).pathname }, routePattern: <pathname> }`. */\n transportContext?: unknown;\n}\n\nexport type ProcessX402SettleResult =\n | {\n success: true;\n /** The matched requirement passed to `settlePayment`. */\n matchedRequirement: unknown;\n /** The settlement response from the facilitator. */\n settleResult: unknown;\n /** Base64-encoded JSON of `settleResult`, ready to set as the `payment-response`\n * HTTP header on the merchant's success response. x402 clients (`@x402/fetch`,\n * `agentscore-pay`) read this to confirm settlement landed. `undefined` when\n * there's no settle result (shouldn't happen on success path but typed defensively). */\n paymentResponseHeader: string | undefined;\n /** The x402 server's `processPaymentRequest` verify result. */\n verifyResult: { success: true; [key: string]: unknown };\n }\n /** No-requirements branch: `buildPaymentRequirements` returned an empty array, so\n * there is nothing to verify against. Indicates a merchant-side misconfiguration\n * (resource config doesn't match any registered scheme/network).\n * Recommended response: log `reason` server-side; map to a controlled 500 to the\n * consumer via `classifyX402SettleResult`. */\n | { success: false; phase: 'no_requirements'; reason: string }\n /** Verify-failed branch: the facilitator's verify step ran and returned\n * `{ success: false, ... }`. Payload is structurally invalid, expired, signed by\n * the wrong wallet, or otherwise rejected by facilitator policy.\n * Recommended response: log `verifyResult` server-side; map to a controlled 400\n * with `payment_proof_invalid` to the consumer via `classifyX402SettleResult`. */\n | { success: false; phase: 'verify_failed'; verifyResult: unknown }\n /** Settle-failed branch: verify succeeded but `settlePayment` threw (on-chain\n * rejection, RPC outage, facilitator broadcast failure, etc.). The agent's\n * credential was valid; funds did not move.\n * Recommended response: log raw `error` server-side; map to a controlled 503 with\n * `payment_provider_unavailable` to the consumer via `classifyX402SettleResult`. */\n | { success: false; phase: 'settle_failed'; error: unknown; matchedRequirement: unknown }\n | {\n success: false;\n /** Facilitator threw an unexpected error during one of the verify-stage calls\n * (build requirements, extension enrich, or processPaymentRequest). Most common\n * cause: the facilitator client rejects the configured network. Coinbase's CDP\n * facilitator throws on Solana devnet because it only supports mainnet networks;\n * Stripe's SPT facilitator throws on EVM networks; etc.\n * Recommended response: log raw `error` server-side; map to a controlled 503\n * with `payment_provider_unavailable` to the consumer via `classifyX402SettleResult`\n * so the agent can pick a different rail. */\n phase: 'facilitator_error';\n /** Which verify-stage step threw. */\n step: 'build_requirements' | 'enrich_extensions' | 'process_payment_request';\n error: unknown;\n };\n\n/**\n * The merchant-shaped response for a non-success `ProcessX402SettleResult`.\n *\n * `status` / `code` / `message` are safe to send back to the consumer. `nextSteps`\n * is the agent-instructions block describing what the agent should do next. Raw\n * facilitator errors stay server-side: do NOT serialize the original `error` /\n * `verifyResult` / `reason` to the consumer; log them yourself.\n */\nexport interface ClassifiedX402Error {\n status: 400 | 500 | 503;\n code:\n | 'payment_proof_invalid'\n | 'payment_provider_unavailable'\n | 'payment_internal_error';\n message: string;\n nextSteps: {\n action: string;\n user_message: string;\n retry_after_seconds?: number;\n };\n}\n\n/**\n * Map a `ProcessX402SettleResult` to the recommended merchant response.\n *\n * Returns `null` for `success: true`. For each error phase, returns a controlled\n * status / code / message / nextSteps tuple. Replaces error-message string-sniffing\n * with a phase-based dispatch so merchants stop coupling to facilitator-specific\n * error text.\n *\n * Phase mapping:\n * - `verify_failed` → 400 `payment_proof_invalid` / `regenerate_payment_credential`\n * - `facilitator_error` → 503 `payment_provider_unavailable` / `try_different_rail`\n * - `settle_failed` → 503 `payment_provider_unavailable` / `retry_or_swap_method`\n * - `no_requirements` → 500 `payment_internal_error` / `contact_support`\n *\n * Always log the raw `result` server-side before responding; the returned object\n * is intentionally facilitator-agnostic and never carries raw error detail.\n */\nexport function classifyX402SettleResult(\n result: ProcessX402SettleResult,\n): ClassifiedX402Error | null {\n if (result.success) return null;\n switch (result.phase) {\n case 'no_requirements':\n return {\n status: 500,\n code: 'payment_internal_error',\n message: 'Failed to build x402 payment requirements for this configuration',\n nextSteps: {\n action: 'contact_support',\n user_message:\n 'The merchant could not produce a payment challenge for this request. Try again later or contact support.',\n },\n };\n case 'verify_failed':\n return {\n status: 400,\n code: 'payment_proof_invalid',\n message: 'Payment credential failed verification; regenerate from a fresh 402 challenge',\n nextSteps: {\n action: 'regenerate_payment_credential',\n user_message:\n 'The payment credential was rejected at verify time. Discard it, fetch a fresh 402 challenge, and re-sign.',\n },\n };\n case 'facilitator_error':\n return {\n status: 503,\n code: 'payment_provider_unavailable',\n message: 'Payment provider could not process this network configuration',\n nextSteps: {\n action: 'try_different_rail',\n user_message:\n 'This rail is currently unavailable. Pick a different rail from the 402 challenge and retry.',\n },\n };\n case 'settle_failed':\n return {\n status: 503,\n code: 'payment_provider_unavailable',\n message: 'Payment credential verified but on-chain settlement failed',\n nextSteps: {\n action: 'retry_or_swap_method',\n retry_after_seconds: 10,\n user_message:\n 'Transient settlement error. Retry in a few seconds, or pick a different rail from the 402 challenge.',\n },\n };\n }\n}\n\nexport async function processX402Settle(input: ProcessX402SettleInput): Promise<ProcessX402SettleResult> {\n const server = input.x402Server as unknown as {\n buildPaymentRequirements: (cfg: unknown) => Promise<unknown[]>;\n enrichExtensions: (ext: unknown, ctx: unknown) => unknown;\n processPaymentRequest: (\n payload: unknown,\n cfg: unknown,\n meta: unknown,\n ext: unknown,\n ) => Promise<{ success: boolean; [key: string]: unknown }>;\n settlePayment: (payload: unknown, requirement: unknown) => Promise<unknown>;\n };\n\n let builtRequirements: unknown[];\n try {\n builtRequirements = await server.buildPaymentRequirements(input.resourceConfig);\n } catch (err) {\n return { success: false, phase: 'facilitator_error', step: 'build_requirements', error: err };\n }\n const matchedRequirement = builtRequirements[0];\n if (!matchedRequirement) {\n return { success: false, phase: 'no_requirements', reason: 'x402Server.buildPaymentRequirements returned empty' };\n }\n\n const transportContext = input.transportContext ?? (() => {\n const path = new URL(input.resourceMeta.url).pathname;\n return { method: 'POST', adapter: { getPath: () => path }, routePattern: path };\n })();\n\n let enrichedExt: unknown;\n try {\n enrichedExt = input.extension !== undefined\n ? server.enrichExtensions(input.extension, transportContext)\n : undefined;\n } catch (err) {\n return { success: false, phase: 'facilitator_error', step: 'enrich_extensions', error: err };\n }\n\n let verifyResult: { success: boolean; [key: string]: unknown };\n try {\n verifyResult = await server.processPaymentRequest(\n input.payload,\n input.resourceConfig,\n input.resourceMeta,\n enrichedExt,\n );\n } catch (err) {\n return { success: false, phase: 'facilitator_error', step: 'process_payment_request', error: err };\n }\n\n if (!verifyResult.success) {\n return { success: false, phase: 'verify_failed', verifyResult };\n }\n\n try {\n const settleResult = await server.settlePayment(input.payload, matchedRequirement);\n const paymentResponseHeader = settleResult\n ? Buffer.from(JSON.stringify(settleResult)).toString('base64')\n : undefined;\n return {\n success: true,\n matchedRequirement,\n settleResult,\n paymentResponseHeader,\n verifyResult: verifyResult as { success: true; [key: string]: unknown },\n };\n } catch (err) {\n return { success: false, phase: 'settle_failed', error: err, matchedRequirement };\n }\n}\n","/**\n * x402 boot-time + per-request validation helpers.\n *\n * Two layers of validation every x402-accepting merchant repeats:\n *\n * - **Boot-time**: validate the configured `X402_BASE_NETWORK` env var is in the\n * supported set. Failing loud at boot is much better than per-request \"unsupported\n * network\" errors after a misconfigured deploy.\n *\n * - **Per-request**: when an x402 X-Payment header arrives, parse the base64 payload,\n * extract the signed network + payTo, validate against the merchant's accepted\n * network, validate the payTo address shape, and check that the payTo was minted by\n * THIS merchant (cache hit). Each step has its own denial code and `next_steps`\n * shape — getting the message right by hand across 4 conditions is fiddly.\n */\n\nimport { networks } from './networks';\n\n/** CAIP-2 networks the commerce SDK supports for x402 Base (EVM USDC). */\nexport const X402_SUPPORTED_BASE_NETWORKS = new Set<string>([\n networks.base.mainnet.caip2,\n networks.base.sepolia.caip2,\n]);\n\nexport interface ValidateX402NetworkConfigInput {\n /** CAIP-2 base network string (e.g. `'eip155:8453'`). */\n baseNetwork: string;\n}\n\n/**\n * Boot-time guard: throws if the base network isn't supported. Call once at module\n * init / server boot.\n *\n * Throws `Error` with a message that names the unsupported value AND lists the valid\n * options — agents tracking down a misconfigured deploy don't need to grep for the\n * supported list.\n */\nexport function validateX402NetworkConfig(input: ValidateX402NetworkConfigInput): void {\n if (!X402_SUPPORTED_BASE_NETWORKS.has(input.baseNetwork)) {\n throw new Error(\n `X402_BASE_NETWORK=${input.baseNetwork} is not supported. Use one of: ${[...X402_SUPPORTED_BASE_NETWORKS].join(', ')}`,\n );\n }\n}\n\nconst EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\nexport interface VerifyX402RequestInput {\n /** The incoming Request — `verifyX402Request` reads the X-Payment / payment-signature header. */\n request: Request;\n /** Async lookup that returns true when the address was minted by this merchant\n * (typically `piCache.hasAddress`). The check validates that the credential's\n * deposit address matches one the merchant actually minted. */\n isCachedAddress: (address: string) => Promise<boolean>;\n /** The merchant's accepted Base network. CAIP-2, e.g. `'eip155:8453'`. */\n acceptedNetwork: string;\n}\n\nexport type VerifyX402RequestResult =\n | {\n ok: true;\n /** The base64-decoded JSON payload from the X-Payment header. */\n payload: { accepted?: { network?: string; payTo?: string }; [key: string]: unknown };\n /** The CAIP-2 network the agent signed for. */\n signedNetwork: string;\n /** The on-chain pay-to address the agent signed for (already validated). */\n signedPayTo: string;\n }\n | {\n ok: false;\n /** Suitable as a JSON body for the merchant's denial response. Includes\n * `next_steps` with `regenerate_payment_credential` action + a per-condition\n * `user_message` and a footgun `warning` so agents can recover deterministically\n * from the response alone. */\n body: {\n error: { code: string; message: string };\n next_steps: {\n action: 'regenerate_payment_credential';\n user_message: string;\n warning: string;\n };\n };\n /** HTTP status to use for the denial response. */\n status: 400;\n };\n\nconst REGENERATE_WARNING =\n 'Use `agentscore-pay pay --chain base` (or `tempo request` for Tempo USDC) so the credential is signed and submitted via the protocol handshake. Do NOT use `tempo wallet transfer` — that sends USDC on-chain but does not complete the handshake.';\n\nfunction regenerateBody(message: string, userMessage: string) {\n return {\n error: { code: 'payment_proof_invalid' as const, message },\n next_steps: {\n action: 'regenerate_payment_credential' as const,\n user_message: userMessage,\n warning: REGENERATE_WARNING,\n },\n };\n}\n\n/**\n * Per-request: parse the x402 X-Payment header, validate the network + payTo, and\n * confirm the address was minted by this merchant. One call replaces ~45 lines of\n * inline header decode + regex validation + cache lookup.\n *\n * Returns `{ok: true, payload, signedNetwork, signedPayTo}` when valid; the caller\n * passes `payload` straight into `processX402Settle`.\n *\n * Returns `{ok: false, body, status}` when invalid — the merchant just does\n * `return c.json(body, status)` (or framework equivalent).\n *\n * Reads the header from `payment-signature` first, falling back to `x-payment` (both\n * are in the wild as the binary-friendly transport name evolved).\n */\nexport async function verifyX402Request(input: VerifyX402RequestInput): Promise<VerifyX402RequestResult> {\n const headerValue =\n input.request.headers.get('payment-signature')\n ?? input.request.headers.get('x-payment');\n if (!headerValue) {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n 'X-Payment header missing',\n 'No X-Payment header was sent. Generate the credential from the 402 challenge and resubmit on the same endpoint.',\n ),\n };\n }\n\n let payload: { accepted?: { network?: string; payTo?: string }; [key: string]: unknown };\n try {\n payload = JSON.parse(Buffer.from(headerValue, 'base64').toString());\n } catch {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n 'X-Payment header is not valid base64 JSON',\n 'The payment credential could not be decoded. Reconstruct the credential from the 402 challenge and retry.',\n ),\n };\n }\n\n const signedNetwork = payload.accepted?.network;\n const signedPayTo = payload.accepted?.payTo;\n\n if (!signedNetwork || signedNetwork !== input.acceptedNetwork) {\n if (signedNetwork && signedNetwork.toLowerCase().startsWith('solana:')) {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n `x402 on ${signedNetwork} is not accepted; Solana payments must use the \\`solana/charge\\` rail advertised in the 402 challenge. This server accepts x402 on ${input.acceptedNetwork} only.`,\n 'Solana payments are not accepted over x402 at this merchant. Pick the `solana/charge` rail from the 402 challenge and re-sign.',\n ),\n };\n }\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n `Unsupported x402 network ${signedNetwork ?? '<missing>'}; this server accepts ${input.acceptedNetwork}.`,\n 'The credential signed for an unsupported network. Pick the accepted network from the 402 challenge and re-sign.',\n ),\n };\n }\n\n const addressShapeOk = typeof signedPayTo === 'string' && EVM_ADDRESS_RE.test(signedPayTo);\n\n if (!signedPayTo || !addressShapeOk) {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n `Payment payload missing or malformed accepted.payTo address for network ${signedNetwork}`,\n 'The credential payload is missing or malformed payTo for the signed network. Reconstruct the credential from the 402 challenge.',\n ),\n };\n }\n\n if (!(await input.isCachedAddress(signedPayTo))) {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n 'payTo address not found in cache or expired. Request a fresh 402 challenge and retry.',\n 'The deposit address is unknown or expired on this server. Request a fresh 402 challenge and re-sign against the new payTo.',\n ),\n };\n }\n\n return { ok: true, payload, signedNetwork, signedPayTo };\n}\n","export interface CreateMppxStripeInput {\n /** Stripe profile_id / network_id (the value advertised in your `stripe/charge` accepted_methods entry). */\n profileId: string;\n /** Stripe secret key — mppx uses it to validate inbound SharedPaymentTokens. */\n secretKey: string;\n /** Payment method types this stripe rail accepts. Default ['card', 'link']. */\n paymentMethodTypes?: string[];\n}\n\n/**\n * Wraps the `mppStripe.charge(...)` boilerplate from `mppx/server`. Returns the value\n * vendors pass into `Mppx.create({ methods: [...] })`. mppx is an OPTIONAL peer dependency —\n * vendors who don't use Stripe SPT don't need to install it.\n *\n * Example:\n *\n * import { Mppx, tempo } from 'mppx/server';\n * import { createMppxStripe } from '@agent-score/commerce/stripe-multichain';\n *\n * const stripeMethod = await createMppxStripe({\n * profileId: process.env.STRIPE_PROFILE_ID!,\n * secretKey: process.env.STRIPE_SECRET_KEY!,\n * });\n *\n * const mppx = Mppx.create({\n * methods: [tempo.charge({...}), stripeMethod],\n * secretKey: process.env.MPP_SECRET_KEY!,\n * });\n *\n * Throws if mppx is not installed.\n */\nexport async function createMppxStripe(input: CreateMppxStripeInput): Promise<unknown> {\n const moduleName = 'mppx/server';\n const mppx = (await import(moduleName).catch(() => null)) as {\n stripe?: {\n charge: (config: {\n networkId: string;\n paymentMethodTypes?: string[];\n secretKey: string;\n }) => unknown;\n };\n } | null;\n /* v8 ignore start -- peer-dep-absence guard; mppx is installed in the test env so this branch can't be exercised without mocking the dynamic import */\n if (!mppx?.stripe?.charge) {\n throw new Error(\n 'mppx not installed — install with `npm install mppx` to use createMppxStripe.',\n );\n }\n /* v8 ignore stop */\n return mppx.stripe.charge({\n networkId: input.profileId,\n paymentMethodTypes: input.paymentMethodTypes ?? ['card', 'link'],\n secretKey: input.secretKey,\n });\n}\n","import { createMppxStripe } from '../stripe-multichain/mppx_stripe';\nimport { USDC } from './usdc';\n\nexport type SolanaMppNetwork = 'mainnet-beta' | 'devnet' | 'localnet';\n\nexport interface CreateMppxServerOptions {\n /** Symbolic rail config — commerce wires the boilerplate (tempo.charge, mppStripe.charge, solana.charge, etc.). */\n rails?: {\n /** One-shot Tempo USDC charge (intent: 'charge'). */\n tempo?: {\n recipient: string;\n /** Custom currency token. Default: USDC on Tempo. */\n currency?: string;\n /** Use Tempo testnet (Moderato). Default false. */\n testnet?: boolean;\n };\n /**\n * Solana SPL charge (intent: 'charge'). Bakes createAssociatedTokenIdempotent\n * into the buyer's tx so payments work against any payTo, fresh or warmed.\n *\n * Requires `@solana/mpp` + `@solana/kit` peer deps.\n * Underlying spec: paymentauth.org/draft-solana-charge-00.\n */\n solana?: {\n /** Base58-encoded Solana recipient public key. */\n recipient: string;\n /** SPL token mint (base58). Default: USDC for the selected network. */\n currency?: string;\n /** Token decimals. Default 6 (USDC). */\n decimals?: number;\n /** Solana network. Default 'mainnet-beta'. */\n network?: SolanaMppNetwork;\n /** Custom RPC URL. Default: public RPC for the network. */\n rpcUrl?: string;\n /**\n * Optional fee-payer signer for server-side fee sponsorship. When provided,\n * the server's pubkey is advertised as `feePayerKey` in the 402 challenge and\n * the server co-signs settle txs as fee payer (so buyers don't need SOL, and\n * ATA-creation rent is server-funded). Construct via\n * `@solana/kit`'s `createKeyPairSignerFromBytes` or equivalent.\n *\n * Typed as `unknown` to avoid a hard dep on @solana/kit at this layer; pass any\n * `TransactionPartialSigner` from `@solana/kit`.\n */\n signer?: unknown;\n /** SPL token program hint (TOKEN_PROGRAM or TOKEN_2022_PROGRAM). Auto-detected when omitted. */\n tokenProgram?: string;\n };\n /**\n * Tempo session (intent: 'session') — pay-as-you-go channel for repeated calls or\n * SSE-streamed responses. Vendor brings their own ChannelStore (DB-backed implementation\n * tracking open channels + voucher state) and an `escrowContract` address.\n */\n tempo_session?: {\n recipient: string;\n currency?: string;\n testnet?: boolean;\n /**\n * On-chain escrow contract address that holds channel deposits and pays out\n * cumulative vouchers on settlement. Vendor-deployed.\n */\n escrowContract: string;\n /**\n * Channel store implementation tracking open channels + cumulative voucher state.\n * Pass an instance of mppx's `ChannelStore` interface (you can use the in-memory\n * default for dev or implement a Postgres/Redis-backed store for production).\n */\n store: unknown;\n /** Optional supported chains; defaults to mppx defaults. */\n chains?: unknown;\n };\n /** Stripe SPT (Shared Payment Token) — see also @agent-score/commerce/stripe-multichain. */\n stripe?: {\n profileId: string;\n secretKey: string;\n paymentMethodTypes?: string[];\n };\n };\n /** Advanced: pass mppx method instances directly (in addition to or instead of `rails`). */\n methods?: unknown[];\n /** MPP secret key (merchant's). */\n secretKey: string;\n}\n\ninterface MppxModule {\n Mppx?: { create: (opts: { methods: unknown[]; secretKey: string }) => unknown };\n tempo?: {\n charge: (opts: { currency: string; recipient: string; testnet?: boolean }) => unknown;\n session?: (opts: {\n currency: string;\n recipient: string;\n escrowContract: string;\n store: unknown;\n testnet?: boolean;\n chains?: unknown;\n }) => unknown;\n };\n}\n\ninterface SolanaMppModule {\n charge?: (opts: {\n recipient: string;\n currency?: string;\n decimals?: number;\n network?: string;\n rpcUrl?: string;\n signer?: unknown;\n tokenProgram?: string;\n }) => unknown;\n}\n\n/**\n * One-call mppx server setup. Wires `tempo.charge(...)`, `tempo.session(...)`, and Stripe SPT\n * (via createMppxStripe) from symbolic rail config, replacing the boilerplate of constructing\n * each method by hand.\n *\n * const mppx = await createMppxServer({\n * rails: {\n * tempo: { recipient: TEMPO_ADDR, testnet: false }, // intent: 'charge'\n * tempo_session: { // intent: 'session'\n * recipient: TEMPO_ADDR,\n * escrowContract: ESCROW_ADDR,\n * store: myChannelStore,\n * },\n * stripe: { profileId: STRIPE_PROFILE_ID, secretKey: STRIPE_SECRET_KEY },\n * },\n * secretKey: MPP_SECRET_KEY,\n * });\n *\n * `mppx` is an OPTIONAL peer dependency — install it only if you accept MPP rails.\n */\nexport async function createMppxServer(opts: CreateMppxServerOptions): Promise<unknown> {\n const mppx = await dynamicImport<MppxModule>('mppx/server');\n /* v8 ignore start -- peer-dep-absence guard; mppx is installed in the test env */\n if (!mppx?.Mppx?.create) {\n throw new Error('mppx not installed — `npm install mppx` to use createMppxServer.');\n }\n /* v8 ignore stop */\n\n const methods: unknown[] = [...(opts.methods ?? [])];\n\n if (opts.rails?.tempo) {\n /* v8 ignore start -- peer-dep version-mismatch guard; current mppx ships tempo.charge */\n if (!mppx.tempo?.charge) {\n throw new Error('mppx.tempo.charge not available — check installed mppx version.');\n }\n /* v8 ignore stop */\n const t = opts.rails.tempo;\n const defaultCurrency = t.testnet ? USDC.tempo.testnet.address : USDC.tempo.mainnet.address;\n methods.push(\n mppx.tempo.charge({\n currency: t.currency ?? defaultCurrency,\n recipient: t.recipient,\n testnet: t.testnet ?? false,\n }),\n );\n }\n\n if (opts.rails?.tempo_session) {\n /* v8 ignore start -- peer-dep version-mismatch guard; current mppx ships tempo.session */\n if (!mppx.tempo?.session) {\n throw new Error(\n 'mppx.tempo.session not available — your mppx version may not support sessions yet. Upgrade with `npm install mppx@latest`.',\n );\n }\n /* v8 ignore stop */\n const s = opts.rails.tempo_session;\n const defaultCurrency = s.testnet ? USDC.tempo.testnet.address : USDC.tempo.mainnet.address;\n methods.push(\n mppx.tempo.session({\n currency: s.currency ?? defaultCurrency,\n recipient: s.recipient,\n escrowContract: s.escrowContract,\n store: s.store,\n testnet: s.testnet ?? false,\n ...(s.chains ? { chains: s.chains } : {}),\n }),\n );\n }\n\n if (opts.rails?.solana) {\n const solanaMpp = await dynamicImport<SolanaMppModule>('@solana/mpp/server');\n if (!solanaMpp?.charge) {\n throw new Error(\n '@solana/mpp not installed — `npm install @solana/mpp @solana/kit` to use the solana rail.',\n );\n }\n const s = opts.rails.solana;\n const network: SolanaMppNetwork = s.network ?? 'mainnet-beta';\n const defaultMint =\n network === 'mainnet-beta' ? USDC.solana.mainnet.mint : USDC.solana.devnet.mint;\n const defaultDecimals =\n network === 'mainnet-beta' ? USDC.solana.mainnet.decimals : USDC.solana.devnet.decimals;\n const baseMethod = solanaMpp.charge({\n recipient: s.recipient,\n currency: s.currency ?? defaultMint,\n decimals: s.decimals ?? defaultDecimals,\n network,\n ...(s.rpcUrl ? { rpcUrl: s.rpcUrl } : {}),\n ...(s.signer ? { signer: s.signer } : {}),\n ...(s.tokenProgram ? { tokenProgram: s.tokenProgram } : {}),\n }) as SolanaChargeMethod;\n const rpcUrl =\n s.rpcUrl ??\n (network === 'mainnet-beta'\n ? 'https://api.mainnet-beta.solana.com'\n : network === 'devnet'\n ? 'https://api.devnet.solana.com'\n : 'http://localhost:8899');\n methods.push(wrapSolanaChargeWithFinalizedBlockhash(baseMethod, rpcUrl));\n }\n\n if (opts.rails?.stripe) {\n const stripeMethod = await createMppxStripe(opts.rails.stripe);\n methods.push(stripeMethod);\n }\n\n return mppx.Mppx.create({ methods, secretKey: opts.secretKey });\n}\n\nasync function dynamicImport<T>(moduleName: string): Promise<T | null> {\n try {\n return (await import(moduleName)) as T;\n } catch {\n return null;\n }\n}\n\ntype SolanaChargeRequestArgs = { credential?: unknown; request?: unknown };\ntype SolanaChargeMethod = {\n request?: (args: SolanaChargeRequestArgs) => Promise<unknown>;\n} & Record<string, unknown>;\n\n/**\n * Wraps `@solana/mpp.charge()`'s Method so the issued challenge carries a\n * `finalized` blockhash instead of `confirmed`.\n *\n * `@solana/mpp` <= 0.5.2 fetches `getLatestBlockhash` with `commitment: 'confirmed'`\n * but its broadcast `sendTransaction` sets `skipPreflight: false` without an\n * overridden `preflightCommitment`. The RPC server's default preflight commitment\n * is `finalized`, which rejects any blockhash that hasn't yet finalized with a\n * \"Blockhash not found\" error. Handing the client a `finalized` blockhash up\n * front sidesteps the mismatch.\n *\n * Trade-off: the signing window shrinks from ~58s (confirmed) to ~46s (finalized).\n * Fine for agent-driven flows; manual signing flows still have plenty of margin.\n */\nexport function wrapSolanaChargeWithFinalizedBlockhash(\n baseMethod: SolanaChargeMethod,\n rpcUrl: string,\n): SolanaChargeMethod {\n return {\n ...baseMethod,\n async request(args: SolanaChargeRequestArgs) {\n const orig = (await baseMethod.request!(args)) as\n | { methodDetails?: Record<string, unknown> }\n | undefined;\n if (args.credential || !orig || typeof orig !== 'object') return orig;\n try {\n const res = await fetch(rpcUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n id: 1,\n jsonrpc: '2.0',\n method: 'getLatestBlockhash',\n params: [{ commitment: 'finalized' }],\n }),\n });\n const data = (await res.json()) as { result?: { value?: { blockhash?: string } } };\n const finalized = data?.result?.value?.blockhash;\n if (finalized) {\n return {\n ...orig,\n methodDetails: { ...(orig.methodDetails ?? {}), recentBlockhash: finalized },\n };\n }\n } catch {\n /* fall back to upstream's confirmed blockhash */\n }\n return orig;\n },\n };\n}\n","export interface SettlementHandlers<TPayload, TResult> {\n evm?: (payload: TPayload) => TResult | Promise<TResult>;\n svm?: (payload: TPayload) => TResult | Promise<TResult>;\n}\n\nexport interface SettlementPayloadLike {\n accepted: { network: string };\n}\n\n/**\n * Dispatches a settlement payload to the right network-family handler based on\n * the CAIP-2 network string in `payload.accepted.network`:\n *\n * - eip155:* → handlers.evm\n * - solana:* → handlers.svm\n *\n * Throws if the network is unrecognized or the matching handler is missing.\n * Most vendors will register handlers for both rail families they accept.\n */\nexport async function dispatchSettlementByNetwork<\n TPayload extends SettlementPayloadLike,\n TResult,\n>(\n payload: TPayload,\n handlers: SettlementHandlers<TPayload, TResult>,\n): Promise<TResult> {\n const network = payload.accepted.network;\n if (network.startsWith('eip155:')) {\n if (!handlers.evm) {\n throw new Error(`No EVM settlement handler registered (network: ${network})`);\n }\n return handlers.evm(payload);\n }\n if (network.startsWith('solana:')) {\n if (!handlers.svm) {\n throw new Error(`No Solana settlement handler registered (network: ${network})`);\n }\n return handlers.svm(payload);\n }\n throw new Error(`Unrecognized network in settlement payload: ${network}`);\n}\n","/**\n * Joins multiple Payment directives into a single WWW-Authenticate header value.\n * Per RFC 7235, multiple challenges are comma-separated.\n */\nexport function wwwAuthenticateHeader(directives: string[]): string {\n return directives.join(', ');\n}\n\nexport interface PaymentRequiredHeaderInput {\n x402Version: 1 | 2;\n accepts: unknown[];\n resource?: { url: string; mimeType?: string };\n}\n\n/**\n * Add the v1↔v2 amount-field alias to each accepts entry. Idempotent. Used by both\n * `paymentRequiredHeader` (header emit) and `build402Body` (body emit) so every\n * x402 entry on the wire carries BOTH `amount` (v2 spec) AND `maxAmountRequired`\n * (v1 spec) — strict v1-only parsers (e.g. Coinbase awal at `payments-mcp.coinbase.com`,\n * which is hardcoded to read `maxAmountRequired`) work alongside strict v2 parsers,\n * which ignore the alias.\n */\nexport function aliasAmountFields(accepts: unknown[]): unknown[] {\n return accepts.map((entry) => {\n if (entry === null || typeof entry !== 'object') return entry;\n const e = entry as Record<string, unknown>;\n const hasAmount = e.amount !== undefined;\n const hasMaxAmount = e.maxAmountRequired !== undefined;\n if (hasAmount && !hasMaxAmount) return { ...e, maxAmountRequired: e.amount };\n if (hasMaxAmount && !hasAmount) return { ...e, amount: e.maxAmountRequired };\n return e;\n });\n}\n\n/**\n * Encode the standard x402 PAYMENT-REQUIRED header (base64-encoded JSON of the\n * PaymentRequired object). Clients that recognize the header (`@x402/fetch`,\n * `@x402/core` HTTPClient, `agentscore-pay`) prefer it over body fields.\n *\n * Note: do NOT add a v1↔v2 amount-field alias here. `@x402/core`'s\n * `findMatchingRequirements` uses `deepEqual` against the agent's signed\n * `accepted` payload — any field present on one side and missing on the other\n * (e.g. `maxAmountRequired` on the wire body but not in `buildPaymentRequirements`'s\n * output) makes the match silently fail at settle time. Keep `accepts` shape\n * identical to whatever `buildPaymentRequirements` produces server-side.\n */\nexport function paymentRequiredHeader(input: PaymentRequiredHeaderInput): string {\n return Buffer.from(JSON.stringify(input)).toString('base64');\n}\n","/**\n * Multi-rail payment header bundle — one call composes both `WWW-Authenticate` (the\n * `paymentauth.org` Payment directives) and the standard x402 `PAYMENT-REQUIRED` header\n * from a single rails declaration. Reduces ~10 lines of merchant boilerplate per 402\n * response.\n *\n * Layered on top of `paymentDirective` / `wwwAuthenticateHeader` / `paymentRequiredHeader`\n * — those primitives stay exposed for vendors who want full control.\n */\n\nimport { buildPaymentDirective, type BuildPaymentDirectiveInput } from './directive';\nimport { paymentRequiredHeader, wwwAuthenticateHeader } from './wwwauthenticate';\n\nexport interface PaymentHeadersRail {\n /** Symbolic rail name — `tempo-mainnet`, `x402-base-mainnet`, `stripe`, etc. */\n rail: string;\n /** Amount in USD as a number or string. */\n amountUsd: string | number;\n /** Recipient address (on-chain) — required for crypto rails. */\n recipient?: string;\n /** Stripe profile_id / network_id — required for `stripe` rail. */\n networkId?: string;\n /** EVM chain id override — usually inferred from rail. */\n chainId?: number;\n /** Token contract / currency override — usually inferred from rail. */\n currency?: string;\n /** Decimal precision override — usually inferred from rail (USDC=6, etc.). */\n decimals?: number;\n /** MPP method override — usually inferred from rail. */\n method?: string;\n /** MPP intent. Default `charge`. */\n intent?: string;\n /** ISO-8601 expiry. Default now + 5 min. */\n expires?: string;\n}\n\nexport interface BuildPaymentHeadersInput {\n /** Rails the merchant accepts on this 402. Each becomes one `Payment` directive. */\n rails: PaymentHeadersRail[];\n /** Order id used as the directive challenge id (per-rail it becomes `${orderId}-${rail}`). */\n orderId: string;\n /** Realm — the host of the merchant URL (e.g. `agents.merchant.example`). */\n realm: string;\n /**\n * Optional x402 `accepts` array — included as the standard PAYMENT-REQUIRED header so\n * x402 clients (`@x402/fetch`, `@x402/core` HTTPClient, `agentscore-pay`) can parse the\n * base64-encoded JSON form instead of the WWW-Authenticate text directives. Pass\n * `undefined` (or omit) to skip the PAYMENT-REQUIRED header.\n */\n x402?: { accepts: unknown[]; version?: 1 | 2; resource?: { url: string; mimeType?: string } };\n}\n\nexport interface PaymentHeadersResult {\n 'www-authenticate': string;\n 'PAYMENT-REQUIRED'?: string;\n}\n\n/**\n * Compose `WWW-Authenticate` (multi-directive) and `PAYMENT-REQUIRED` (x402 base64) headers\n * from a single rails declaration. Returns an object suitable for spreading into a\n * `Headers` constructor or the `headers` field of a `Response`.\n *\n * Example:\n * ```ts\n * const headers = buildPaymentHeaders({\n * orderId: 'ord_123',\n * realm: 'agents.merchant.example',\n * rails: [\n * { rail: 'tempo-mainnet', amountUsd: 25, recipient: TEMPO_ADDR },\n * { rail: 'x402-base-mainnet', amountUsd: 25, recipient: BASE_ADDR },\n * { rail: 'stripe', amountUsd: 25, networkId: STRIPE_PROFILE_ID },\n * ],\n * x402: { accepts: x402Accepts, version: 1 },\n * });\n * return new Response(JSON.stringify(body), { status: 402, headers });\n * ```\n */\nexport function buildPaymentHeaders(input: BuildPaymentHeadersInput): PaymentHeadersResult {\n const directives = input.rails.map((rail) => {\n const directiveInput: BuildPaymentDirectiveInput = {\n id: `${input.orderId}-${rail.rail}`,\n realm: input.realm,\n rail: rail.rail,\n amountUsd: rail.amountUsd,\n };\n if (rail.recipient !== undefined) directiveInput.recipient = rail.recipient;\n if (rail.networkId !== undefined) directiveInput.networkId = rail.networkId;\n if (rail.chainId !== undefined) directiveInput.chainId = rail.chainId;\n if (rail.currency !== undefined) directiveInput.currency = rail.currency;\n if (rail.decimals !== undefined) directiveInput.decimals = rail.decimals;\n if (rail.method !== undefined) directiveInput.method = rail.method;\n if (rail.intent !== undefined) directiveInput.intent = rail.intent;\n if (rail.expires !== undefined) directiveInput.expires = rail.expires;\n return buildPaymentDirective(directiveInput);\n });\n\n const result: PaymentHeadersResult = {\n 'www-authenticate': wwwAuthenticateHeader(directives),\n };\n\n if (input.x402) {\n result['PAYMENT-REQUIRED'] = paymentRequiredHeader({\n x402Version: input.x402.version ?? 2,\n accepts: input.x402.accepts,\n ...(input.x402.resource ? { resource: input.x402.resource } : {}),\n });\n }\n\n return result;\n}\n","/**\n * Idempotency-key composition.\n *\n * Stable per-payment keys that retries of the same logical payment can reuse, so AgentScore's\n * `/v1/credentials/wallets` capture endpoint dedupes correctly and the operator's\n * `transaction_count` doesn't inflate.\n *\n * Convention (matches what martin-estate uses today):\n * 1. Prefer the upstream payment-rail's stable identifier (Stripe PaymentIntent id, x402\n * tx hash) when one exists — those are already idempotent on their side.\n * 2. Fall back to a synthesized `pi-{orderId}-{amountCents}` key when no upstream id is\n * available (e.g. pre-creation, or rails without a PI concept).\n * 3. Server caps idempotency keys at 200 chars; this helper warns when that boundary is\n * crossed so a future caller doesn't silently get truncation collisions.\n */\n\nconst SERVER_IDEMPOTENCY_KEY_MAX = 200;\n\nexport interface BuildIdempotencyKeyInput {\n /** Upstream rail's stable payment id — Stripe PaymentIntent id, x402 tx hash, etc. Wins when present. */\n paymentIntentId?: string | null;\n /** Order id — used to compose a fallback key when no paymentIntentId exists. */\n orderId?: string | null;\n /** Amount in cents (or smallest currency unit) — added to the fallback for extra collision resistance. */\n amountCents?: number;\n /** Optional extra prefix to namespace the key (e.g. `\"refund\"`, `\"void\"`). */\n prefix?: string;\n}\n\n/**\n * Compose a stable idempotency key for AgentScore wallet capture and other retry-safe POSTs.\n *\n * Returns `undefined` when no inputs are present (caller should treat as \"no idempotency\n * key — first attempt only\", same shape as omitting the field entirely).\n *\n * Examples:\n * ```ts\n * buildIdempotencyKey({ paymentIntentId: 'pi_abc' }); // → 'pi_abc'\n * buildIdempotencyKey({ orderId: 'ord_x', amountCents: 25000 }); // → 'pi-ord_x-25000'\n * buildIdempotencyKey({ orderId: 'ord_x' }); // → 'pi-ord_x'\n * buildIdempotencyKey({ paymentIntentId: 'pi_abc', prefix: 'refund' }); // → 'refund-pi_abc'\n * buildIdempotencyKey({}); // → undefined\n * ```\n */\nexport function buildIdempotencyKey(input: BuildIdempotencyKeyInput): string | undefined {\n const prefix = input.prefix ? `${input.prefix}-` : '';\n\n if (input.paymentIntentId) {\n const key = `${prefix}${input.paymentIntentId}`;\n return clampKey(key);\n }\n\n if (input.orderId) {\n const amountSuffix = input.amountCents !== undefined ? `-${input.amountCents}` : '';\n const key = `${prefix}pi-${input.orderId}${amountSuffix}`;\n return clampKey(key);\n }\n\n return undefined;\n}\n\nfunction clampKey(key: string): string {\n if (key.length <= SERVER_IDEMPOTENCY_KEY_MAX) return key;\n // Server truncates anyway; surfacing the warning here gives callers a chance to design\n // shorter inputs. We still return the original key (server-side truncation is the source\n // of truth) — clamping client-side would change semantics for any caller already\n // depending on the full string for their own dedup.\n console.warn(\n `[agentscore-commerce] idempotency key longer than ${SERVER_IDEMPOTENCY_KEY_MAX} chars — server will truncate, may cause silent collisions if multiple keys share the first ${SERVER_IDEMPOTENCY_KEY_MAX} chars.`,\n );\n return key;\n}\n","/**\n * Payment-signer extraction.\n *\n * Shared between merchants and the gate. Three paths recover a wallet signer:\n *\n * - **Tempo MPP** — `Authorization: Payment <base64>`; credential `source` is a DID of the\n * form `did:pkh:eip155:<chain>:<address>`.\n * - **Solana MPP `solana/charge`** — `Authorization: Payment <base64>`; recovery via either\n * a `did:pkh:solana:<genesis>:<address>` source (when set by the client) or by decoding\n * the credential's signed-tx payload and reading the SPL `TransferChecked` authority\n * (pull mode only — `payload.type === 'transaction'`).\n * - **x402 EIP-3009 (EVM, e.g. Base/Sepolia)** — `payment-signature` / `x-payment`;\n * decoded payload carries `payload.authorization.from`.\n *\n * Optional peer deps: `mppx` for MPP credentials, `@solana/kit` for the Solana tx-decode\n * fallback. Both dynamic-imported; merchants who don't accept that rail don't need them.\n */\n\nexport type SignerNetwork = 'evm' | 'solana';\n\nconst TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\nconst TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';\nconst TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\ninterface SolanaKitMinimal {\n getBase64Codec: () => { encode: (s: string) => Uint8Array };\n getTransactionDecoder: () => { decode: (b: Uint8Array) => { messageBytes: Uint8Array } };\n getCompiledTransactionMessageDecoder: () => {\n decode: (b: Uint8Array) => {\n staticAccounts: ReadonlyArray<string>;\n instructions: ReadonlyArray<{\n programAddressIndex: number;\n accountIndices?: number[];\n data?: Uint8Array;\n }>;\n };\n };\n}\n\n/**\n * Decode a Solana MPP `solana/charge` credential's `payload.transaction` (base64-encoded\n * signed Solana tx) and return the SPL `TransferChecked` authority — the source-ATA owner,\n * which is the buyer's wallet. Pull mode only (`payload.type === 'transaction'`); push mode\n * (`payload.type === 'signature'`) returns null because recovery would require an RPC fetch.\n */\nasync function extractSolanaSignerFromCredential(credential: unknown): Promise<string | null> {\n const payload = (credential as { payload?: { transaction?: string; type?: string } }).payload;\n if (!payload?.transaction || payload.type !== 'transaction') return null;\n\n const moduleName = '@solana/kit';\n const kit = (await import(moduleName).catch(() => null)) as SolanaKitMinimal | null;\n if (!kit?.getBase64Codec || !kit.getTransactionDecoder || !kit.getCompiledTransactionMessageDecoder) {\n return null;\n }\n\n try {\n const txBytes = kit.getBase64Codec().encode(payload.transaction);\n const decoded = kit.getTransactionDecoder().decode(txBytes);\n const message = kit.getCompiledTransactionMessageDecoder().decode(decoded.messageBytes);\n\n // SPL TransferChecked accounts: [source ATA, mint, destination ATA, authority, ...signers].\n // Returns the FIRST matched authority. For multi-recipient `splits` txs, the buyer\n // signs ONE tx with N TransferChecked instructions all sharing the same authority,\n // so first-match is correct; if a tx ever surfaces with mismatched authorities the\n // first one wins (acceptable since both belong to whoever signed the tx).\n for (const ix of message.instructions) {\n const programId = message.staticAccounts[ix.programAddressIndex];\n if (programId !== TOKEN_PROGRAM && programId !== TOKEN_2022_PROGRAM) continue;\n const data = ix.data;\n if (!data || data.length === 0 || data[0] !== TRANSFER_CHECKED_DISCRIMINATOR) continue;\n const accountIndices = ix.accountIndices ?? [];\n const authorityIndex = accountIndices[3];\n if (authorityIndex === undefined) continue;\n // v0 transactions can carry account indices that resolve via address lookup tables;\n // staticAccounts only holds the static set. If the index is out of range, the\n // authority sits in a lookup table we'd need RPC to resolve. Skip cleanly with a\n // warning rather than returning the wrong address.\n if (authorityIndex >= message.staticAccounts.length) {\n console.warn(\n '[gate] Solana TransferChecked authority resolves through an address lookup table; ' +\n 'signer-match recovery requires the static-account form. Skipping.',\n );\n continue;\n }\n const authority = message.staticAccounts[authorityIndex];\n if (authority) return authority;\n }\n return null;\n } catch (err) {\n console.warn('[gate] Solana credential decode failed:', err instanceof Error ? err.message : err);\n return null;\n }\n}\n\nexport interface PaymentSigner {\n /** Recovered wallet address (EVM lowercased; Solana base58 preserved verbatim). */\n address: string;\n /** Network family — used by `captureWallet` and downstream cross-chain attribution. */\n network: SignerNetwork;\n}\n\n/**\n * Recover the signer wallet from the incoming payment credential, including the network\n * family. Returns `null` when no wallet signature is present (e.g. Stripe SPT, card-only\n * payments, or no credential yet).\n *\n * @param request - the inbound `Request`\n * @param x402PaymentHeader - the value of `payment-signature` or `x-payment` header, if any.\n * Extracted separately because some frameworks (Express) don't expose a web `Request` object.\n */\nexport async function extractPaymentSigner(\n request: Request,\n x402PaymentHeader?: string,\n): Promise<PaymentSigner | null> {\n // MPP — Authorization: Payment <base64>\n const authHeader = request.headers.get('authorization');\n if (authHeader) {\n try {\n const moduleName = 'mppx';\n const mppx = (await import(moduleName).catch(() => null)) as {\n Credential?: {\n extractPaymentScheme: (h: string) => unknown;\n fromRequest: (r: Request) => unknown;\n };\n } | null;\n if (mppx?.Credential?.extractPaymentScheme(authHeader)) {\n const credential = mppx.Credential.fromRequest(request);\n const source = (credential as { source?: string }).source;\n const evmMatch = source?.match(/^did:pkh:eip155:\\d+:(0x[0-9a-fA-F]{40})$/);\n if (evmMatch) return { address: evmMatch[1]!.toLowerCase(), network: 'evm' };\n // Solana CAIP-10: did:pkh:solana:<genesis-base58>:<address-base58>\n const solMatch = source?.match(/^did:pkh:solana:[1-9A-HJ-NP-Za-km-z]{32,44}:([1-9A-HJ-NP-Za-km-z]{32,44})$/);\n if (solMatch) return { address: solMatch[1]!, network: 'solana' };\n // Fallback: source not set by upstream client. Decode the credential's signed-tx\n // payload to find the SPL TransferChecked authority (= source-ATA owner = buyer\n // wallet). Pull mode only.\n const solanaFromTx = await extractSolanaSignerFromCredential(credential);\n if (solanaFromTx) return { address: solanaFromTx, network: 'solana' };\n }\n } catch (err) {\n console.warn('[gate] MPP signer extraction failed:', err instanceof Error ? err.message : err);\n }\n }\n\n // x402 — base64 JSON, EIP-3009 only. EVM `payload.authorization.from` is the signer.\n if (x402PaymentHeader) {\n try {\n const decoded = atob(x402PaymentHeader);\n const parsed = JSON.parse(decoded) as {\n payload?: { authorization?: { from?: string } };\n };\n const from = parsed?.payload?.authorization?.from;\n if (typeof from === 'string' && /^0x[0-9a-fA-F]{40}$/.test(from)) {\n return { address: from.toLowerCase(), network: 'evm' };\n }\n } catch (err) {\n console.warn('[gate] x402 signer extraction failed:', err instanceof Error ? err.message : err);\n }\n }\n\n return null;\n}\n\n/**\n * Address-only convenience over {@link extractPaymentSigner}. Used by the gate adapters\n * (verifyWalletSignerMatch) where only the address matters for operator comparison.\n */\nexport async function extractPaymentSignerAddress(\n request: Request,\n x402PaymentHeader?: string,\n): Promise<string | null> {\n const result = await extractPaymentSigner(request, x402PaymentHeader);\n return result?.address ?? null;\n}\n\n/**\n * Read the x402 payment header from a `Request`, matching the alternate names merchants might\n * use. Falls back to reading either header directly.\n */\nexport function readX402PaymentHeader(request: Request): string | undefined {\n return (\n request.headers.get('payment-signature') ??\n request.headers.get('x-payment') ??\n undefined\n );\n}\n","/**\n * x402 Settlement-Overrides header helpers — used with the `upto` scheme to specify the\n * actual amount to charge after the work is done. The header is JSON-encoded and lives\n * on the merchant's response; the facilitator settles for that amount instead of the\n * advertised maximum.\n *\n * Per the x402 docs (https://docs.x402.org/getting-started/quickstart-for-sellers), the\n * amount field accepts three formats:\n * - raw atomic units, e.g., '1000' for $0.001 USDC at 6 decimals\n * - percentage, e.g., '50%' of the authorized maximum\n * - dollar price, e.g., '$0.05' (converted to atomic via the network's default token)\n */\n\nexport const SETTLEMENT_OVERRIDES_HEADER = 'Settlement-Overrides';\n\nexport interface SettlementOverrides {\n /** Raw atomic units, '<n>%' percentage, or '$X.YZ' dollar price. */\n amount: string;\n}\n\n/**\n * Build a `{ name, value }` pair for the x402 Settlement-Overrides header. Vendors\n * set this on their response to direct the facilitator to settle for the actual amount\n * (used in the upto scheme flow):\n *\n * const { name, value } = settlementOverrideHeader({ amount: '1500' });\n * res.setHeader(name, value); // Express\n * c.header(name, value); // Hono\n */\nexport function settlementOverrideHeader(overrides: SettlementOverrides): { name: string; value: string } {\n return { name: SETTLEMENT_OVERRIDES_HEADER, value: JSON.stringify(overrides) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,IAAM,WAAW;AAAA,EACtB,MAAM;AAAA,IACJ,SAAS,EAAE,OAAO,eAAwB,SAAS,KAAK;AAAA,IACxD,SAAS,EAAE,OAAO,gBAAyB,SAAS,MAAM;AAAA,EAC5D;AAAA,EACA,QAAQ;AAAA,IACN,SAAS,EAAE,OAAO,0CAAmD;AAAA,IACrE,QAAQ,EAAE,OAAO,0CAAmD;AAAA,EACtE;AAAA,EACA,OAAO;AAAA,IACL,SAAS,EAAE,OAAO,eAAwB,SAAS,KAAK;AAAA,IACxD,SAAS,EAAE,OAAO,gBAAyB,SAAS,MAAM;AAAA,EAC5D;AACF;AASO,SAAS,cAAc,OAAqC;AACjE,MAAI,UAAU,SAAS,KAAK,QAAQ,SAAS,UAAU,SAAS,KAAK,QAAQ,MAAO,QAAO;AAC3F,MAAI,UAAU,SAAS,OAAO,QAAQ,SAAS,UAAU,SAAS,OAAO,OAAO,MAAO,QAAO;AAC9F,MAAI,UAAU,SAAS,MAAM,QAAQ,SAAS,UAAU,SAAS,MAAM,QAAQ,MAAO,QAAO;AAC7F,MAAI,MAAM,WAAW,SAAS,EAAG,QAAO;AACxC,SAAO;AACT;;;AC5BO,IAAM,OAAO;AAAA,EAClB,MAAM;AAAA,IACJ,SAAS,EAAE,SAAS,8CAAuD,UA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QAAQ,QAAQ,IAAI,WAAW,KAC/B;AAEJ;;;AC5KO,IAAM,8BAA8B;AAgBpC,SAAS,yBAAyB,WAAiE;AACxG,SAAO,EAAE,MAAM,6BAA6B,OAAO,KAAK,UAAU,SAAS,EAAE;AAC/E;","names":["dynamicImport"]}
|
|
1
|
+
{"version":3,"sources":["../../src/payment/index.ts","../../src/payment/networks.ts","../../src/payment/usdc.ts","../../src/payment/rails.ts","../../src/payment/directive.ts","../../src/payment/x402.ts","../../src/payment/x402_server.ts","../../src/payment/x402_settle.ts","../../src/payment/x402_validation.ts","../../src/stripe-multichain/mppx_stripe.ts","../../src/payment/mppx_server.ts","../../src/payment/dispatch.ts","../../src/payment/wwwauthenticate.ts","../../src/payment/headers.ts","../../src/payment/idempotency.ts","../../src/signer.ts","../../src/payment/settlement_override.ts"],"sourcesContent":["export * from './directive';\nexport * from './networks';\nexport * from './usdc';\nexport * from './rails';\nexport * from './x402';\nexport * from './x402_server';\nexport * from './x402_settle';\nexport * from './x402_validation';\nexport * from './mppx_server';\nexport * from './dispatch';\nexport * from './wwwauthenticate';\nexport * from './headers';\nexport * from './idempotency';\nexport * from './signer';\nexport * from './settlement_override';\n","/**\n * Named network registry. Vendors reference symbolic names (`networks.base.mainnet.caip2`)\n * instead of magic strings. Lifted from agentscore-pay's constants.\n */\nexport const networks = {\n base: {\n mainnet: { caip2: 'eip155:8453' as const, chainId: 8453 },\n sepolia: { caip2: 'eip155:84532' as const, chainId: 84532 },\n },\n solana: {\n mainnet: { caip2: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' as const },\n devnet: { caip2: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1' as const },\n },\n tempo: {\n mainnet: { caip2: 'eip155:4217' as const, chainId: 4217 },\n testnet: { caip2: 'eip155:42431' as const, chainId: 42431 },\n },\n} as const;\n\nexport type NetworkFamily = keyof typeof networks;\n\n/**\n * Returns the family name (base/solana/tempo) for a given CAIP-2 network string,\n * or null if the network isn't in the registry. Useful for routing settlement\n * by network.\n */\nexport function networkFamily(caip2: string): NetworkFamily | null {\n if (caip2 === networks.base.mainnet.caip2 || caip2 === networks.base.sepolia.caip2) return 'base';\n if (caip2 === networks.solana.mainnet.caip2 || caip2 === networks.solana.devnet.caip2) return 'solana';\n if (caip2 === networks.tempo.mainnet.caip2 || caip2 === networks.tempo.testnet.caip2) return 'tempo';\n if (caip2.startsWith('solana:')) return 'solana';\n return null;\n}\n","/**\n * USDC token registry per network. Used by paymentDirective and rail definitions.\n * Lifted from agentscore-pay's constants.\n */\nexport const USDC = {\n base: {\n mainnet: { address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' as const, decimals: 6 },\n sepolia: { address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' as const, decimals: 6 },\n },\n solana: {\n mainnet: { mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', decimals: 6 },\n devnet: { mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', decimals: 6 },\n },\n tempo: {\n mainnet: { address: '0x20C000000000000000000000b9537d11c60E8b50' as const, decimals: 6 },\n testnet: { address: '0x20c0000000000000000000000000000000000000' as const, decimals: 6 },\n },\n} as const;\n","import { networks } from './networks';\nimport { USDC } from './usdc';\n\n/**\n * Symbolic rail names mapped to their protocol details. Vendors pass `rail: 'tempo-mainnet'`\n * to the directive builder and the SDK fills in method/network/decimals/currency from this\n * registry. Custom rails not in this registry can be passed by setting the lower-level\n * fields directly on the directive builder.\n */\nexport const rails = {\n 'tempo-mainnet': {\n method: 'tempo',\n network: networks.tempo.mainnet.caip2,\n chainId: networks.tempo.mainnet.chainId,\n currency: USDC.tempo.mainnet.address,\n decimals: USDC.tempo.mainnet.decimals,\n asset: USDC.tempo.mainnet.address,\n },\n 'tempo-testnet': {\n method: 'tempo',\n network: networks.tempo.testnet.caip2,\n chainId: networks.tempo.testnet.chainId,\n currency: USDC.tempo.testnet.address,\n decimals: USDC.tempo.testnet.decimals,\n asset: USDC.tempo.testnet.address,\n },\n 'x402-base-mainnet': {\n method: 'x402',\n network: networks.base.mainnet.caip2,\n chainId: networks.base.mainnet.chainId,\n currency: USDC.base.mainnet.address,\n decimals: USDC.base.mainnet.decimals,\n asset: USDC.base.mainnet.address,\n },\n 'x402-base-sepolia': {\n method: 'x402',\n network: networks.base.sepolia.caip2,\n chainId: networks.base.sepolia.chainId,\n currency: USDC.base.sepolia.address,\n decimals: USDC.base.sepolia.decimals,\n asset: USDC.base.sepolia.address,\n },\n // Upto rails — pay UP TO a max amount (Permit2-based, vs EIP-3009 for exact). Use for\n // variable-cost APIs where the actual cost depends on output (LLM tokens, bandwidth, etc.).\n // Only available on EVM networks; Solana svm doesn't ship an upto scheme yet.\n 'x402-base-mainnet-upto': {\n method: 'x402-upto',\n network: networks.base.mainnet.caip2,\n chainId: networks.base.mainnet.chainId,\n currency: USDC.base.mainnet.address,\n decimals: USDC.base.mainnet.decimals,\n asset: USDC.base.mainnet.address,\n },\n 'x402-base-sepolia-upto': {\n method: 'x402-upto',\n network: networks.base.sepolia.caip2,\n chainId: networks.base.sepolia.chainId,\n currency: USDC.base.sepolia.address,\n decimals: USDC.base.sepolia.decimals,\n asset: USDC.base.sepolia.address,\n },\n 'mpp-solana-mainnet': {\n method: 'solana',\n network: networks.solana.mainnet.caip2,\n currency: USDC.solana.mainnet.mint,\n decimals: USDC.solana.mainnet.decimals,\n asset: USDC.solana.mainnet.mint,\n },\n 'mpp-solana-devnet': {\n method: 'solana',\n network: networks.solana.devnet.caip2,\n currency: USDC.solana.devnet.mint,\n decimals: USDC.solana.devnet.decimals,\n asset: USDC.solana.devnet.mint,\n },\n 'stripe-spt': {\n method: 'stripe',\n currency: 'usd',\n decimals: 2,\n },\n} as const;\n\nexport type RailName = keyof typeof rails;\n\nexport interface RailDefinition {\n method: string;\n network?: string;\n chainId?: number;\n currency: string;\n decimals: number;\n asset?: string;\n}\n\n/**\n * Lookup a rail definition by symbolic name. Returns undefined if the rail isn't in\n * the registry — vendors with custom rails should pass the low-level fields directly.\n */\nexport function lookupRail(name: string): RailDefinition | undefined {\n return rails[name as RailName] as RailDefinition | undefined;\n}\n","import { lookupRail } from './rails';\n\nexport interface PaymentRequestInput {\n /** Symbolic rail name (e.g., 'tempo-mainnet', 'x402-base-mainnet') — fills in defaults */\n rail?: string;\n /** Amount in USD as a number or string. Converted to raw integer using `decimals`. */\n amountUsd: string | number;\n /** Token contract address or currency code. Defaults from rail. */\n currency?: string;\n /** Decimal precision for the amount. Defaults from rail (6 for USDC, 2 for USD). */\n decimals?: number;\n /** Recipient address (on-chain). Optional for stripe-style rails. */\n recipient?: string;\n /** EVM chain ID (goes into methodDetails.chainId). Defaults from rail. */\n chainId?: number;\n /** Stripe profile_id or similar (goes into methodDetails.networkId — note camelCase per link-cli's mpp decode validator). */\n networkId?: string;\n}\n\n/**\n * Build the base64-encoded `request` blob for an MPP Payment directive (per the\n * paymentauth.org spec). Output shape matches what link-cli `mpp decode` expects:\n *\n * { amount: \"<raw_integer>\", currency: \"<token>\", recipient?: \"<addr>\",\n * methodDetails?: { chainId?: number, networkId?: string } }\n */\nexport function buildPaymentRequestBlob(input: PaymentRequestInput): string {\n const railDef = input.rail ? lookupRail(input.rail) : undefined;\n const decimals = input.decimals ?? railDef?.decimals ?? 6;\n const currency = input.currency ?? railDef?.currency ?? 'usd';\n const chainId = input.chainId ?? railDef?.chainId;\n\n const amountNum = typeof input.amountUsd === 'string' ? Number(input.amountUsd) : input.amountUsd;\n const amountRaw = BigInt(Math.round(amountNum * 10 ** decimals)).toString();\n const blob: Record<string, unknown> = { amount: amountRaw, currency, decimals };\n if (input.recipient) blob.recipient = input.recipient;\n const methodDetails: Record<string, unknown> = {};\n if (chainId !== undefined) methodDetails.chainId = chainId;\n if (input.networkId) methodDetails.networkId = input.networkId;\n if (Object.keys(methodDetails).length > 0) blob.methodDetails = methodDetails;\n return Buffer.from(JSON.stringify(blob)).toString('base64url');\n}\n\nexport interface PaymentDirectiveInput {\n /** Symbolic rail name — sets `method` automatically */\n rail?: string;\n /** Challenge id (unique per request, used to correlate retries) */\n id: string;\n /** Realm — the host of the merchant URL (e.g., \"agents.merchant.example\") */\n realm: string;\n /** MPP method name. Defaults from rail (e.g., 'tempo', 'stripe'). */\n method?: string;\n /** MPP intent. Defaults to 'charge'. */\n intent?: string;\n /** ISO-8601 expiry timestamp. Defaults to now + 5 minutes. */\n expires?: string;\n /** Base64-encoded request blob. Pass the result of buildPaymentRequestBlob. */\n request: string;\n}\n\n/**\n * Format an MPP Payment directive string for the WWW-Authenticate header.\n * Output shape: `Payment id=\"...\", realm=\"...\", method=\"...\", intent=\"charge\",\n * expires=\"...\", request=\"<base64>\"`\n */\nexport function paymentDirective(input: PaymentDirectiveInput): string {\n const railDef = input.rail ? lookupRail(input.rail) : undefined;\n const method = input.method ?? railDef?.method ?? 'unknown';\n const intent = input.intent ?? 'charge';\n const expires = input.expires ?? new Date(Date.now() + 5 * 60 * 1000).toISOString();\n return `Payment id=\"${input.id}\", realm=\"${input.realm}\", method=\"${method}\", intent=\"${intent}\", expires=\"${expires}\", request=\"${input.request}\"`;\n}\n\nexport interface BuildPaymentDirectiveInput\n extends Omit<PaymentRequestInput, 'rail'>,\n Omit<PaymentDirectiveInput, 'request'> {\n rail: string;\n}\n\n/**\n * Convenience: build the request blob and the directive in one call. Most vendors\n * want this rather than the two-step form.\n */\nexport function buildPaymentDirective(input: BuildPaymentDirectiveInput): string {\n const request = buildPaymentRequestBlob({\n rail: input.rail,\n amountUsd: input.amountUsd,\n currency: input.currency,\n decimals: input.decimals,\n recipient: input.recipient,\n chainId: input.chainId,\n networkId: input.networkId,\n });\n return paymentDirective({\n rail: input.rail,\n id: input.id,\n realm: input.realm,\n method: input.method,\n intent: input.intent,\n expires: input.expires,\n request,\n });\n}\n","/**\n * Generic x402 server interface. Different versions of @x402/core may expose different\n * shapes; we only require register() and (optionally) registerV1().\n */\nexport interface X402ServerLike {\n register(network: string, scheme: unknown): void;\n registerV1?(network: string, scheme: unknown): void;\n}\n\n/**\n * Registers an x402 scheme on both v1 and v2 of the protocol.\n *\n * Why: the @x402/core HTTP parser hardcodes `x402Version === 1`, while the client's\n * `.register()` defaults to v2. Without registering on both versions, a merchant\n * emitting a v1 response gets \"No client registered for x402 version: 1\" even\n * though the scheme handler is identical between versions. Every merchant trips\n * on this; the helper hides the workaround.\n */\nexport function registerX402SchemesV1V2(\n server: X402ServerLike,\n network: string,\n scheme: unknown,\n): void {\n server.register(network, scheme);\n if (typeof server.registerV1 === 'function') {\n server.registerV1(network, scheme);\n }\n}\n","import { networks } from './networks';\nimport { registerX402SchemesV1V2 } from './x402';\n\nexport type X402SymbolicRail =\n | 'x402-base-mainnet'\n | 'x402-base-sepolia'\n | 'x402-base-mainnet-upto'\n | 'x402-base-sepolia-upto';\n\nexport type X402FacilitatorChoice = 'coinbase' | 'http' | unknown;\n\nexport interface CreateX402ServerOptions {\n /**\n * Facilitator selection:\n * - 'coinbase' → Coinbase CDP facilitator (requires `@coinbase/x402` installed)\n * - 'http' → HTTP-only public testnet facilitator\n * - any object → custom facilitator instance, used directly\n * - omitted → defaults to 'http'\n */\n facilitator?: X402FacilitatorChoice;\n /**\n * Symbolic rail names to register schemes for. Each gets v1+v2 dual-register applied.\n * Requires `@x402/evm` peer dep installed.\n */\n rails?: X402SymbolicRail[];\n /** Advanced: register custom {network, scheme} pairs (in addition to or instead of `rails`). */\n schemes?: { network: string; scheme: unknown }[];\n /** Register the Bazaar discovery extension. Requires `@x402/extensions` installed. */\n bazaar?: boolean;\n /** Initialize the server immediately (calls facilitator). Default true. */\n initialize?: boolean;\n}\n\n/**\n * Loose type for the x402 resource server. We name the methods commerce calls during\n * setup; everything else (settlePayment, buildPaymentRequirements, processPaymentRequest,\n * enrichExtensions, etc.) is callable via the index signature so vendor code can use the\n * full @x402/core surface without us having to mirror every method signature.\n */\nexport interface X402Server {\n register(network: string, scheme: unknown): void;\n registerV1?(network: string, scheme: unknown): void;\n registerExtension(ext: unknown): void;\n initialize(): Promise<void>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}\n\ninterface X402CoreModule {\n x402ResourceServer: new (facilitator?: unknown) => X402Server;\n HTTPFacilitatorClient: new (facilitator?: unknown) => unknown;\n}\n\ninterface SchemeModule {\n ExactEvmScheme?: new () => unknown;\n UptoEvmScheme?: new () => unknown;\n}\n\ninterface CoinbaseModule {\n facilitator?: unknown;\n}\n\ninterface BazaarModule {\n bazaarResourceServerExtension?: unknown;\n}\n\n/**\n * One-call x402 server setup. Resolves facilitator, constructs the server, registers\n * schemes per network with v1+v2 dual-register, optionally adds the Bazaar extension,\n * and initializes — replaces ~15 lines of boilerplate with a single config call.\n *\n * x402 packages are peer dependencies — vendors install only the schemes they use.\n * Throws a guiding error if a required peer is missing.\n *\n * const server = await createX402Server({\n * facilitator: 'coinbase',\n * rails: ['x402-base-mainnet'],\n * bazaar: true,\n * });\n */\nexport async function createX402Server(opts: CreateX402ServerOptions = {}): Promise<X402Server> {\n const x402Core = (await dynamicImport<X402CoreModule>('@x402/core/server')) ?? null;\n /* v8 ignore start -- peer-dep-absence guard; @x402/core is installed in test env */\n if (!x402Core) {\n throw new Error(\n '@x402/core not installed — `npm install @x402/core` to use createX402Server.',\n );\n }\n /* v8 ignore stop */\n\n let facilitator: unknown;\n if (opts.facilitator === 'coinbase') {\n const cb = await dynamicImport<CoinbaseModule>('@coinbase/x402');\n /* v8 ignore start -- peer-dep-absence guard; @coinbase/x402 is installed in test env */\n if (!cb?.facilitator) {\n throw new Error(\n '@coinbase/x402 not installed — `npm install @coinbase/x402` for facilitator: \"coinbase\".',\n );\n }\n /* v8 ignore stop */\n facilitator = new x402Core.HTTPFacilitatorClient(cb.facilitator);\n } else if (opts.facilitator === undefined || opts.facilitator === 'http') {\n facilitator = new x402Core.HTTPFacilitatorClient();\n } else {\n facilitator = opts.facilitator;\n }\n\n const server = new x402Core.x402ResourceServer(facilitator);\n\n let evmExactModule: SchemeModule | null = null;\n let evmUptoModule: SchemeModule | null = null;\n for (const rail of opts.rails ?? []) {\n const isUpto = rail.endsWith('-upto');\n if (rail.startsWith('x402-base')) {\n const baseRail = isUpto ? rail.slice(0, -5) : rail;\n const network =\n baseRail === 'x402-base-mainnet' ? networks.base.mainnet.caip2 : networks.base.sepolia.caip2;\n if (isUpto) {\n evmUptoModule ??= await dynamicImport<SchemeModule>('@x402/evm/upto/server');\n /* v8 ignore start -- peer-dep-absence guard; @x402/evm is installed in test env */\n if (!evmUptoModule?.UptoEvmScheme) {\n throw new Error('@x402/evm not installed — `npm install @x402/evm` for x402 base upto rails.');\n }\n /* v8 ignore stop */\n registerX402SchemesV1V2(server, network, new evmUptoModule.UptoEvmScheme());\n } else {\n evmExactModule ??= await dynamicImport<SchemeModule>('@x402/evm/exact/server');\n /* v8 ignore start -- peer-dep-absence guard; @x402/evm is installed in test env */\n if (!evmExactModule?.ExactEvmScheme) {\n throw new Error('@x402/evm not installed — `npm install @x402/evm` for x402 base rails.');\n }\n /* v8 ignore stop */\n registerX402SchemesV1V2(server, network, new evmExactModule.ExactEvmScheme());\n }\n }\n }\n\n for (const { network, scheme } of opts.schemes ?? []) {\n registerX402SchemesV1V2(server, network, scheme);\n }\n\n if (opts.bazaar) {\n const bazaar = await dynamicImport<BazaarModule>('@x402/extensions/bazaar');\n /* v8 ignore start -- peer-dep-absence guard; @x402/extensions is installed in test env */\n if (!bazaar?.bazaarResourceServerExtension) {\n throw new Error(\n '@x402/extensions not installed — `npm install @x402/extensions` for bazaar discovery.',\n );\n }\n /* v8 ignore stop */\n server.registerExtension(bazaar.bazaarResourceServerExtension);\n }\n\n if (opts.initialize !== false) {\n await server.initialize();\n }\n return server;\n}\n\nexport interface BuildX402AcceptsForOptions {\n network: string;\n price: string;\n payTo: string;\n scheme?: string;\n maxTimeoutSeconds?: number;\n extensions?: string[];\n}\n\n/**\n * Build x402 `accepts[]` entries for a 402 challenge body.\n *\n * Wraps `server.buildPaymentRequirements(...)` so merchants don't have to:\n *\n * 1. Construct the resource-config object themselves\n * 2. Remember to serialize each Pydantic-equivalent requirement back to a\n * plain object before stitching it into the 402 body\n * 3. Hardcode `extra` (which differs by the actual on-chain contract — base\n * mainnet USDC has `name: \"USD Coin\"`, base sepolia USDC has `name: \"USDC\"`;\n * EIP-712 domain hashes differ, so getting this wrong silently breaks every\n * signature verify at the facilitator)\n *\n * Returns a list of plain objects in the shape that x402 expects on the wire —\n * drop them straight into the `accepts` field of the 402 challenge body.\n */\nexport async function buildX402AcceptsFor402(\n server: X402Server,\n opts: BuildX402AcceptsForOptions,\n): Promise<unknown[]> {\n const requirements = await server.buildPaymentRequirements(\n {\n scheme: opts.scheme ?? 'exact',\n network: opts.network,\n price: opts.price,\n payTo: opts.payTo,\n maxTimeoutSeconds: opts.maxTimeoutSeconds ?? 300,\n },\n opts.extensions,\n );\n return Array.isArray(requirements) ? requirements : [];\n}\n\nasync function dynamicImport<T>(moduleName: string): Promise<T | null> {\n try {\n return (await import(moduleName)) as T;\n } catch {\n return null;\n }\n}\n","/**\n * `processX402Settle`: single-call x402 verify+settle for merchants.\n *\n * Wraps the four x402-server steps every x402-accepting merchant repeats:\n * 1. `buildPaymentRequirements(resourceConfig)`: builds the requirement entries the\n * facilitator validates against\n * 2. `enrichExtensions(extension, transportContext)`: folds in Bazaar (or other)\n * extensions for the verify step\n * 3. `processPaymentRequest(payload, resourceConfig, resourceMeta, extensions)`:\n * runs verify against the facilitator\n * 4. `settlePayment(payload, matchedRequirement)`: settles on-chain\n *\n * Returns a tagged result so the caller can map errors to merchant-shaped responses\n * without owning the orchestration boilerplate. Use `classifyX402SettleResult` to\n * map the tagged result to a recommended HTTP response.\n */\n\nimport type { X402Server } from './x402_server';\n\nexport interface ProcessX402SettleInput {\n /** The x402 server instance from `createX402Server`. */\n x402Server: X402Server;\n /** The verified x402 payload extracted from the X-Payment header. */\n payload: unknown;\n /** Resource configuration the facilitator validates against (network, price, payTo,\n * asset, maxTimeoutSeconds, etc.). Shape is x402-server-specific. */\n resourceConfig: unknown;\n /** Resource metadata exposed to the facilitator (URL, description, mime type). */\n resourceMeta: { url: string; description: string; mimeType: string };\n /** Optional extension to enrich during verify (e.g. Bazaar). */\n extension?: unknown;\n /** Transport context for the extension enrich step. Defaults to `{ method: 'POST',\n * adapter: { getPath: () => new URL(resourceMeta.url).pathname }, routePattern: <pathname> }`. */\n transportContext?: unknown;\n}\n\nexport type ProcessX402SettleResult =\n | {\n success: true;\n /** The matched requirement passed to `settlePayment`. */\n matchedRequirement: unknown;\n /** The settlement response from the facilitator. */\n settleResult: unknown;\n /** Base64-encoded JSON of `settleResult`, ready to set as the `payment-response`\n * HTTP header on the merchant's success response. x402 clients (`@x402/fetch`,\n * `agentscore-pay`) read this to confirm settlement landed. `undefined` when\n * there's no settle result (shouldn't happen on success path but typed defensively). */\n paymentResponseHeader: string | undefined;\n /** The x402 server's `processPaymentRequest` verify result. */\n verifyResult: { success: true; [key: string]: unknown };\n }\n /** No-requirements branch: `buildPaymentRequirements` returned an empty array, so\n * there is nothing to verify against. Indicates a merchant-side misconfiguration\n * (resource config doesn't match any registered scheme/network).\n * Recommended response: log `reason` server-side; map to a controlled 500 to the\n * consumer via `classifyX402SettleResult`. */\n | { success: false; phase: 'no_requirements'; reason: string }\n /** Verify-failed branch: the facilitator's verify step ran and returned\n * `{ success: false, ... }`. Payload is structurally invalid, expired, signed by\n * the wrong wallet, or otherwise rejected by facilitator policy.\n * Recommended response: log `verifyResult` server-side; map to a controlled 400\n * with `payment_proof_invalid` to the consumer via `classifyX402SettleResult`. */\n | { success: false; phase: 'verify_failed'; verifyResult: unknown }\n /** Settle-failed branch: verify succeeded but `settlePayment` threw (on-chain\n * rejection, RPC outage, facilitator broadcast failure, etc.). The agent's\n * credential was valid; funds did not move.\n * Recommended response: log raw `error` server-side; map to a controlled 503 with\n * `payment_provider_unavailable` to the consumer via `classifyX402SettleResult`. */\n | { success: false; phase: 'settle_failed'; error: unknown; matchedRequirement: unknown }\n | {\n success: false;\n /** Facilitator threw an unexpected error during one of the verify-stage calls\n * (build requirements, extension enrich, or processPaymentRequest). Most common\n * cause: the facilitator client rejects the configured network. Coinbase's CDP\n * facilitator throws on Solana devnet because it only supports mainnet networks;\n * Stripe's SPT facilitator throws on EVM networks; etc.\n * Recommended response: log raw `error` server-side; map to a controlled 503\n * with `payment_provider_unavailable` to the consumer via `classifyX402SettleResult`\n * so the agent can pick a different rail. */\n phase: 'facilitator_error';\n /** Which verify-stage step threw. */\n step: 'build_requirements' | 'enrich_extensions' | 'process_payment_request';\n error: unknown;\n };\n\n/**\n * The merchant-shaped response for a non-success `ProcessX402SettleResult`.\n *\n * `status` / `code` / `message` are safe to send back to the consumer. `nextSteps`\n * is the agent-instructions block describing what the agent should do next. Raw\n * facilitator errors stay server-side: do NOT serialize the original `error` /\n * `verifyResult` / `reason` to the consumer; log them yourself.\n */\nexport interface ClassifiedX402Error {\n status: 400 | 500 | 503;\n code:\n | 'payment_proof_invalid'\n | 'payment_provider_unavailable'\n | 'payment_internal_error';\n message: string;\n nextSteps: {\n action: string;\n user_message: string;\n retry_after_seconds?: number;\n };\n}\n\n/**\n * Map a `ProcessX402SettleResult` to the recommended merchant response.\n *\n * Returns `null` for `success: true`. For each error phase, returns a controlled\n * status / code / message / nextSteps tuple. Replaces error-message string-sniffing\n * with a phase-based dispatch so merchants stop coupling to facilitator-specific\n * error text.\n *\n * Phase mapping:\n * - `verify_failed` → 400 `payment_proof_invalid` / `regenerate_payment_credential`\n * - `facilitator_error` → 503 `payment_provider_unavailable` / `try_different_rail`\n * - `settle_failed` → 503 `payment_provider_unavailable` / `retry_or_swap_method`\n * - `no_requirements` → 500 `payment_internal_error` / `contact_support`\n *\n * Always log the raw `result` server-side before responding; the returned object\n * is intentionally facilitator-agnostic and never carries raw error detail.\n */\nexport function classifyX402SettleResult(\n result: ProcessX402SettleResult,\n): ClassifiedX402Error | null {\n if (result.success) return null;\n switch (result.phase) {\n case 'no_requirements':\n return {\n status: 500,\n code: 'payment_internal_error',\n message: 'Failed to build x402 payment requirements for this configuration',\n nextSteps: {\n action: 'contact_support',\n user_message:\n 'The merchant could not produce a payment challenge for this request. Try again later or contact support.',\n },\n };\n case 'verify_failed':\n return {\n status: 400,\n code: 'payment_proof_invalid',\n message: 'Payment credential failed verification; regenerate from a fresh 402 challenge',\n nextSteps: {\n action: 'regenerate_payment_credential',\n user_message:\n 'The payment credential was rejected at verify time. Discard it, fetch a fresh 402 challenge, and re-sign.',\n },\n };\n case 'facilitator_error':\n return {\n status: 503,\n code: 'payment_provider_unavailable',\n message: 'Payment provider could not process this network configuration',\n nextSteps: {\n action: 'try_different_rail',\n user_message:\n 'This rail is currently unavailable. Pick a different rail from the 402 challenge and retry.',\n },\n };\n case 'settle_failed':\n return {\n status: 503,\n code: 'payment_provider_unavailable',\n message: 'Payment credential verified but on-chain settlement failed',\n nextSteps: {\n action: 'retry_or_swap_method',\n retry_after_seconds: 10,\n user_message:\n 'Transient settlement error. Retry in a few seconds, or pick a different rail from the 402 challenge.',\n },\n };\n }\n}\n\nexport async function processX402Settle(input: ProcessX402SettleInput): Promise<ProcessX402SettleResult> {\n const server = input.x402Server as unknown as {\n buildPaymentRequirements: (cfg: unknown) => Promise<unknown[]>;\n enrichExtensions: (ext: unknown, ctx: unknown) => unknown;\n processPaymentRequest: (\n payload: unknown,\n cfg: unknown,\n meta: unknown,\n ext: unknown,\n ) => Promise<{ success: boolean; [key: string]: unknown }>;\n settlePayment: (payload: unknown, requirement: unknown) => Promise<unknown>;\n };\n\n let builtRequirements: unknown[];\n try {\n builtRequirements = await server.buildPaymentRequirements(input.resourceConfig);\n } catch (err) {\n return { success: false, phase: 'facilitator_error', step: 'build_requirements', error: err };\n }\n const matchedRequirement = builtRequirements[0];\n if (!matchedRequirement) {\n return { success: false, phase: 'no_requirements', reason: 'x402Server.buildPaymentRequirements returned empty' };\n }\n\n const transportContext = input.transportContext ?? (() => {\n const path = new URL(input.resourceMeta.url).pathname;\n return { method: 'POST', adapter: { getPath: () => path }, routePattern: path };\n })();\n\n let enrichedExt: unknown;\n try {\n enrichedExt = input.extension !== undefined\n ? server.enrichExtensions(input.extension, transportContext)\n : undefined;\n } catch (err) {\n return { success: false, phase: 'facilitator_error', step: 'enrich_extensions', error: err };\n }\n\n let verifyResult: { success: boolean; [key: string]: unknown };\n try {\n verifyResult = await server.processPaymentRequest(\n input.payload,\n input.resourceConfig,\n input.resourceMeta,\n enrichedExt,\n );\n } catch (err) {\n return { success: false, phase: 'facilitator_error', step: 'process_payment_request', error: err };\n }\n\n if (!verifyResult.success) {\n return { success: false, phase: 'verify_failed', verifyResult };\n }\n\n try {\n const settleResult = await server.settlePayment(input.payload, matchedRequirement);\n const paymentResponseHeader = settleResult\n ? Buffer.from(JSON.stringify(settleResult)).toString('base64')\n : undefined;\n return {\n success: true,\n matchedRequirement,\n settleResult,\n paymentResponseHeader,\n verifyResult: verifyResult as { success: true; [key: string]: unknown },\n };\n } catch (err) {\n return { success: false, phase: 'settle_failed', error: err, matchedRequirement };\n }\n}\n","/**\n * x402 boot-time + per-request validation helpers.\n *\n * Two layers of validation every x402-accepting merchant repeats:\n *\n * - **Boot-time**: validate the configured `X402_BASE_NETWORK` env var is in the\n * supported set. Failing loud at boot is much better than per-request \"unsupported\n * network\" errors after a misconfigured deploy.\n *\n * - **Per-request**: when an x402 X-Payment header arrives, parse the base64 payload,\n * extract the signed network + payTo, validate against the merchant's accepted\n * network, validate the payTo address shape, and check that the payTo was minted by\n * THIS merchant (cache hit). Each step has its own denial code and `next_steps`\n * shape — getting the message right by hand across 4 conditions is fiddly.\n */\n\nimport { networks } from './networks';\n\n/** CAIP-2 networks the commerce SDK supports for x402 Base (EVM USDC). */\nexport const X402_SUPPORTED_BASE_NETWORKS = new Set<string>([\n networks.base.mainnet.caip2,\n networks.base.sepolia.caip2,\n]);\n\nexport interface ValidateX402NetworkConfigInput {\n /** CAIP-2 base network string (e.g. `'eip155:8453'`). */\n baseNetwork: string;\n}\n\n/**\n * Boot-time guard: throws if the base network isn't supported. Call once at module\n * init / server boot.\n *\n * Throws `Error` with a message that names the unsupported value AND lists the valid\n * options — agents tracking down a misconfigured deploy don't need to grep for the\n * supported list.\n */\nexport function validateX402NetworkConfig(input: ValidateX402NetworkConfigInput): void {\n if (!X402_SUPPORTED_BASE_NETWORKS.has(input.baseNetwork)) {\n throw new Error(\n `X402_BASE_NETWORK=${input.baseNetwork} is not supported. Use one of: ${[...X402_SUPPORTED_BASE_NETWORKS].join(', ')}`,\n );\n }\n}\n\nconst EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\nexport interface VerifyX402RequestInput {\n /** The incoming Request — `verifyX402Request` reads the X-Payment / payment-signature header. */\n request: Request;\n /** Async lookup that returns true when the address was minted by this merchant\n * (typically `piCache.hasAddress`). The check validates that the credential's\n * deposit address matches one the merchant actually minted. */\n isCachedAddress: (address: string) => Promise<boolean>;\n /** The merchant's accepted Base network. CAIP-2, e.g. `'eip155:8453'`. */\n acceptedNetwork: string;\n}\n\nexport type VerifyX402RequestResult =\n | {\n ok: true;\n /** The base64-decoded JSON payload from the X-Payment header. */\n payload: { accepted?: { network?: string; payTo?: string }; [key: string]: unknown };\n /** The CAIP-2 network the agent signed for. */\n signedNetwork: string;\n /** The on-chain pay-to address the agent signed for (already validated). */\n signedPayTo: string;\n }\n | {\n ok: false;\n /** Suitable as a JSON body for the merchant's denial response. Includes\n * `next_steps` with `regenerate_payment_credential` action + a per-condition\n * `user_message` and a footgun `warning` so agents can recover deterministically\n * from the response alone. */\n body: {\n error: { code: string; message: string };\n next_steps: {\n action: 'regenerate_payment_credential';\n user_message: string;\n warning: string;\n };\n };\n /** HTTP status to use for the denial response. */\n status: 400;\n };\n\nconst REGENERATE_WARNING =\n 'Use `agentscore-pay pay --chain base` (or `tempo request` for Tempo USDC) so the credential is signed and submitted via the protocol handshake. Do NOT use `tempo wallet transfer` — that sends USDC on-chain but does not complete the handshake.';\n\nfunction regenerateBody(message: string, userMessage: string) {\n return {\n error: { code: 'payment_proof_invalid' as const, message },\n next_steps: {\n action: 'regenerate_payment_credential' as const,\n user_message: userMessage,\n warning: REGENERATE_WARNING,\n },\n };\n}\n\n/**\n * Per-request: parse the x402 X-Payment header, validate the network + payTo, and\n * confirm the address was minted by this merchant. One call replaces ~45 lines of\n * inline header decode + regex validation + cache lookup.\n *\n * Returns `{ok: true, payload, signedNetwork, signedPayTo}` when valid; the caller\n * passes `payload` straight into `processX402Settle`.\n *\n * Returns `{ok: false, body, status}` when invalid — the merchant just does\n * `return c.json(body, status)` (or framework equivalent).\n *\n * Reads the header from `payment-signature` first, falling back to `x-payment` (both\n * are in the wild as the binary-friendly transport name evolved).\n */\nexport async function verifyX402Request(input: VerifyX402RequestInput): Promise<VerifyX402RequestResult> {\n const headerValue =\n input.request.headers.get('payment-signature')\n ?? input.request.headers.get('x-payment');\n if (!headerValue) {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n 'X-Payment header missing',\n 'No X-Payment header was sent. Generate the credential from the 402 challenge and resubmit on the same endpoint.',\n ),\n };\n }\n\n let payload: { accepted?: { network?: string; payTo?: string }; [key: string]: unknown };\n try {\n payload = JSON.parse(Buffer.from(headerValue, 'base64').toString());\n } catch {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n 'X-Payment header is not valid base64 JSON',\n 'The payment credential could not be decoded. Reconstruct the credential from the 402 challenge and retry.',\n ),\n };\n }\n\n const signedNetwork = payload.accepted?.network;\n const signedPayTo = payload.accepted?.payTo;\n\n if (!signedNetwork || signedNetwork !== input.acceptedNetwork) {\n if (signedNetwork && signedNetwork.toLowerCase().startsWith('solana:')) {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n `x402 on ${signedNetwork} is not accepted; Solana payments must use the \\`solana/charge\\` rail advertised in the 402 challenge. This server accepts x402 on ${input.acceptedNetwork} only.`,\n 'Solana payments are not accepted over x402 at this merchant. Pick the `solana/charge` rail from the 402 challenge and re-sign.',\n ),\n };\n }\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n `Unsupported x402 network ${signedNetwork ?? '<missing>'}; this server accepts ${input.acceptedNetwork}.`,\n 'The credential signed for an unsupported network. Pick the accepted network from the 402 challenge and re-sign.',\n ),\n };\n }\n\n const addressShapeOk = typeof signedPayTo === 'string' && EVM_ADDRESS_RE.test(signedPayTo);\n\n if (!signedPayTo || !addressShapeOk) {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n `Payment payload missing or malformed accepted.payTo address for network ${signedNetwork}`,\n 'The credential payload is missing or malformed payTo for the signed network. Reconstruct the credential from the 402 challenge.',\n ),\n };\n }\n\n if (!(await input.isCachedAddress(signedPayTo))) {\n return {\n ok: false,\n status: 400,\n body: regenerateBody(\n 'payTo address not found in cache or expired. Request a fresh 402 challenge and retry.',\n 'The deposit address is unknown or expired on this server. Request a fresh 402 challenge and re-sign against the new payTo.',\n ),\n };\n }\n\n return { ok: true, payload, signedNetwork, signedPayTo };\n}\n","export interface CreateMppxStripeInput {\n /** Stripe profile_id / network_id (the value advertised in your `stripe/charge` accepted_methods entry). */\n profileId: string;\n /** Stripe secret key — mppx uses it to validate inbound SharedPaymentTokens. */\n secretKey: string;\n /** Payment method types this stripe rail accepts. Default ['card', 'link']. */\n paymentMethodTypes?: string[];\n}\n\n/**\n * Wraps the `mppStripe.charge(...)` boilerplate from `mppx/server`. Returns the value\n * vendors pass into `Mppx.create({ methods: [...] })`. mppx is an OPTIONAL peer dependency —\n * vendors who don't use Stripe SPT don't need to install it.\n *\n * Example:\n *\n * import { Mppx, tempo } from 'mppx/server';\n * import { createMppxStripe } from '@agent-score/commerce/stripe-multichain';\n *\n * const stripeMethod = await createMppxStripe({\n * profileId: process.env.STRIPE_PROFILE_ID!,\n * secretKey: process.env.STRIPE_SECRET_KEY!,\n * });\n *\n * const mppx = Mppx.create({\n * methods: [tempo.charge({...}), stripeMethod],\n * secretKey: process.env.MPP_SECRET_KEY!,\n * });\n *\n * Throws if mppx is not installed.\n */\nexport async function createMppxStripe(input: CreateMppxStripeInput): Promise<unknown> {\n const moduleName = 'mppx/server';\n const mppx = (await import(moduleName).catch(() => null)) as {\n stripe?: {\n charge: (config: {\n networkId: string;\n paymentMethodTypes?: string[];\n secretKey: string;\n }) => unknown;\n };\n } | null;\n /* v8 ignore start -- peer-dep-absence guard; mppx is installed in the test env so this branch can't be exercised without mocking the dynamic import */\n if (!mppx?.stripe?.charge) {\n throw new Error(\n 'mppx not installed — install with `npm install mppx` to use createMppxStripe.',\n );\n }\n /* v8 ignore stop */\n return mppx.stripe.charge({\n networkId: input.profileId,\n paymentMethodTypes: input.paymentMethodTypes ?? ['card', 'link'],\n secretKey: input.secretKey,\n });\n}\n","import { createMppxStripe } from '../stripe-multichain/mppx_stripe';\nimport { USDC } from './usdc';\n\nexport type SolanaMppNetwork = 'mainnet-beta' | 'devnet' | 'localnet';\n\nexport interface CreateMppxServerOptions {\n /** Symbolic rail config — commerce wires the boilerplate (tempo.charge, mppStripe.charge, solana.charge, etc.). */\n rails?: {\n /** One-shot Tempo USDC charge (intent: 'charge'). */\n tempo?: {\n recipient: string;\n /** Custom currency token. Default: USDC on Tempo. */\n currency?: string;\n /** Use Tempo testnet (Moderato). Default false. */\n testnet?: boolean;\n };\n /**\n * Solana SPL charge (intent: 'charge'). Bakes createAssociatedTokenIdempotent\n * into the buyer's tx so payments work against any payTo, fresh or warmed.\n *\n * Requires `@solana/mpp` + `@solana/kit` peer deps.\n * Underlying spec: paymentauth.org/draft-solana-charge-00.\n */\n solana?: {\n /** Base58-encoded Solana recipient public key. */\n recipient: string;\n /** SPL token mint (base58). Default: USDC for the selected network. */\n currency?: string;\n /** Token decimals. Default 6 (USDC). */\n decimals?: number;\n /** Solana network. Default 'mainnet-beta'. */\n network?: SolanaMppNetwork;\n /** Custom RPC URL. Default: public RPC for the network. */\n rpcUrl?: string;\n /**\n * Optional fee-payer signer for server-side fee sponsorship. When provided,\n * the server's pubkey is advertised as `feePayerKey` in the 402 challenge and\n * the server co-signs settle txs as fee payer (so buyers don't need SOL, and\n * ATA-creation rent is server-funded). Construct via\n * `@solana/kit`'s `createKeyPairSignerFromBytes` or equivalent.\n *\n * Typed as `unknown` to avoid a hard dep on @solana/kit at this layer; pass any\n * `TransactionPartialSigner` from `@solana/kit`.\n */\n signer?: unknown;\n /** SPL token program hint (TOKEN_PROGRAM or TOKEN_2022_PROGRAM). Auto-detected when omitted. */\n tokenProgram?: string;\n };\n /**\n * Tempo session (intent: 'session') — pay-as-you-go channel for repeated calls or\n * SSE-streamed responses. Vendor brings their own ChannelStore (DB-backed implementation\n * tracking open channels + voucher state) and an `escrowContract` address.\n */\n tempo_session?: {\n recipient: string;\n currency?: string;\n testnet?: boolean;\n /**\n * On-chain escrow contract address that holds channel deposits and pays out\n * cumulative vouchers on settlement. Vendor-deployed.\n */\n escrowContract: string;\n /**\n * Channel store implementation tracking open channels + cumulative voucher state.\n * Pass an instance of mppx's `ChannelStore` interface (you can use the in-memory\n * default for dev or implement a Postgres/Redis-backed store for production).\n */\n store: unknown;\n /** Optional supported chains; defaults to mppx defaults. */\n chains?: unknown;\n };\n /** Stripe SPT (Shared Payment Token) — see also @agent-score/commerce/stripe-multichain. */\n stripe?: {\n profileId: string;\n secretKey: string;\n paymentMethodTypes?: string[];\n };\n };\n /** Advanced: pass mppx method instances directly (in addition to or instead of `rails`). */\n methods?: unknown[];\n /** MPP secret key (merchant's). */\n secretKey: string;\n}\n\ninterface MppxModule {\n Mppx?: { create: (opts: { methods: unknown[]; secretKey: string }) => unknown };\n tempo?: {\n charge: (opts: { currency: string; recipient: string; testnet?: boolean }) => unknown;\n session?: (opts: {\n currency: string;\n recipient: string;\n escrowContract: string;\n store: unknown;\n testnet?: boolean;\n chains?: unknown;\n }) => unknown;\n };\n}\n\ninterface SolanaMppModule {\n charge?: (opts: {\n recipient: string;\n currency?: string;\n decimals?: number;\n network?: string;\n rpcUrl?: string;\n signer?: unknown;\n tokenProgram?: string;\n }) => unknown;\n}\n\n/**\n * One-call mppx server setup. Wires `tempo.charge(...)`, `tempo.session(...)`, and Stripe SPT\n * (via createMppxStripe) from symbolic rail config, replacing the boilerplate of constructing\n * each method by hand.\n *\n * const mppx = await createMppxServer({\n * rails: {\n * tempo: { recipient: TEMPO_ADDR, testnet: false }, // intent: 'charge'\n * tempo_session: { // intent: 'session'\n * recipient: TEMPO_ADDR,\n * escrowContract: ESCROW_ADDR,\n * store: myChannelStore,\n * },\n * stripe: { profileId: STRIPE_PROFILE_ID, secretKey: STRIPE_SECRET_KEY },\n * },\n * secretKey: MPP_SECRET_KEY,\n * });\n *\n * `mppx` is an OPTIONAL peer dependency — install it only if you accept MPP rails.\n */\nexport async function createMppxServer(opts: CreateMppxServerOptions): Promise<unknown> {\n const mppx = await dynamicImport<MppxModule>('mppx/server');\n /* v8 ignore start -- peer-dep-absence guard; mppx is installed in the test env */\n if (!mppx?.Mppx?.create) {\n throw new Error('mppx not installed — `npm install mppx` to use createMppxServer.');\n }\n /* v8 ignore stop */\n\n const methods: unknown[] = [...(opts.methods ?? [])];\n\n if (opts.rails?.tempo) {\n /* v8 ignore start -- peer-dep version-mismatch guard; current mppx ships tempo.charge */\n if (!mppx.tempo?.charge) {\n throw new Error('mppx.tempo.charge not available — check installed mppx version.');\n }\n /* v8 ignore stop */\n const t = opts.rails.tempo;\n const defaultCurrency = t.testnet ? USDC.tempo.testnet.address : USDC.tempo.mainnet.address;\n methods.push(\n mppx.tempo.charge({\n currency: t.currency ?? defaultCurrency,\n recipient: t.recipient,\n testnet: t.testnet ?? false,\n }),\n );\n }\n\n if (opts.rails?.tempo_session) {\n /* v8 ignore start -- peer-dep version-mismatch guard; current mppx ships tempo.session */\n if (!mppx.tempo?.session) {\n throw new Error(\n 'mppx.tempo.session not available — your mppx version may not support sessions yet. Upgrade with `npm install mppx@latest`.',\n );\n }\n /* v8 ignore stop */\n const s = opts.rails.tempo_session;\n const defaultCurrency = s.testnet ? USDC.tempo.testnet.address : USDC.tempo.mainnet.address;\n methods.push(\n mppx.tempo.session({\n currency: s.currency ?? defaultCurrency,\n recipient: s.recipient,\n escrowContract: s.escrowContract,\n store: s.store,\n testnet: s.testnet ?? false,\n ...(s.chains ? { chains: s.chains } : {}),\n }),\n );\n }\n\n if (opts.rails?.solana) {\n const solanaMpp = await dynamicImport<SolanaMppModule>('@solana/mpp/server');\n if (!solanaMpp?.charge) {\n throw new Error(\n '@solana/mpp not installed — `npm install @solana/mpp @solana/kit` to use the solana rail.',\n );\n }\n const s = opts.rails.solana;\n const network: SolanaMppNetwork = s.network ?? 'mainnet-beta';\n const defaultMint =\n network === 'mainnet-beta' ? USDC.solana.mainnet.mint : USDC.solana.devnet.mint;\n const defaultDecimals =\n network === 'mainnet-beta' ? USDC.solana.mainnet.decimals : USDC.solana.devnet.decimals;\n const baseMethod = solanaMpp.charge({\n recipient: s.recipient,\n currency: s.currency ?? defaultMint,\n decimals: s.decimals ?? defaultDecimals,\n network,\n ...(s.rpcUrl ? { rpcUrl: s.rpcUrl } : {}),\n ...(s.signer ? { signer: s.signer } : {}),\n ...(s.tokenProgram ? { tokenProgram: s.tokenProgram } : {}),\n }) as SolanaChargeMethod;\n const rpcUrl =\n s.rpcUrl ??\n (network === 'mainnet-beta'\n ? 'https://api.mainnet-beta.solana.com'\n : network === 'devnet'\n ? 'https://api.devnet.solana.com'\n : 'http://localhost:8899');\n methods.push(wrapSolanaChargeWithFinalizedBlockhash(baseMethod, rpcUrl));\n }\n\n if (opts.rails?.stripe) {\n const stripeMethod = await createMppxStripe(opts.rails.stripe);\n methods.push(stripeMethod);\n }\n\n return mppx.Mppx.create({ methods, secretKey: opts.secretKey });\n}\n\nasync function dynamicImport<T>(moduleName: string): Promise<T | null> {\n try {\n return (await import(moduleName)) as T;\n } catch {\n return null;\n }\n}\n\ntype SolanaChargeRequestArgs = { credential?: unknown; request?: unknown };\ntype SolanaChargeMethod = {\n request?: (args: SolanaChargeRequestArgs) => Promise<unknown>;\n} & Record<string, unknown>;\n\n/**\n * Wraps `@solana/mpp.charge()`'s Method so the issued challenge carries a\n * `finalized` blockhash instead of `confirmed`.\n *\n * `@solana/mpp` <= 0.5.2 fetches `getLatestBlockhash` with `commitment: 'confirmed'`\n * but its broadcast `sendTransaction` sets `skipPreflight: false` without an\n * overridden `preflightCommitment`. The RPC server's default preflight commitment\n * is `finalized`, which rejects any blockhash that hasn't yet finalized with a\n * \"Blockhash not found\" error. Handing the client a `finalized` blockhash up\n * front sidesteps the mismatch.\n *\n * Trade-off: the signing window shrinks from ~58s (confirmed) to ~46s (finalized).\n * Fine for agent-driven flows; manual signing flows still have plenty of margin.\n */\nexport function wrapSolanaChargeWithFinalizedBlockhash(\n baseMethod: SolanaChargeMethod,\n rpcUrl: string,\n): SolanaChargeMethod {\n return {\n ...baseMethod,\n async request(args: SolanaChargeRequestArgs) {\n const orig = (await baseMethod.request!(args)) as\n | { methodDetails?: Record<string, unknown> }\n | undefined;\n if (args.credential || !orig || typeof orig !== 'object') return orig;\n try {\n const res = await fetch(rpcUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n id: 1,\n jsonrpc: '2.0',\n method: 'getLatestBlockhash',\n params: [{ commitment: 'finalized' }],\n }),\n });\n const data = (await res.json()) as { result?: { value?: { blockhash?: string } } };\n const finalized = data?.result?.value?.blockhash;\n if (finalized) {\n return {\n ...orig,\n methodDetails: { ...(orig.methodDetails ?? {}), recentBlockhash: finalized },\n };\n }\n } catch {\n /* fall back to upstream's confirmed blockhash */\n }\n return orig;\n },\n };\n}\n","export interface SettlementHandlers<TPayload, TResult> {\n evm?: (payload: TPayload) => TResult | Promise<TResult>;\n svm?: (payload: TPayload) => TResult | Promise<TResult>;\n}\n\nexport interface SettlementPayloadLike {\n accepted: { network: string };\n}\n\n/**\n * Dispatches a settlement payload to the right network-family handler based on\n * the CAIP-2 network string in `payload.accepted.network`:\n *\n * - eip155:* → handlers.evm\n * - solana:* → handlers.svm\n *\n * Throws if the network is unrecognized or the matching handler is missing.\n * Most vendors will register handlers for both rail families they accept.\n */\nexport async function dispatchSettlementByNetwork<\n TPayload extends SettlementPayloadLike,\n TResult,\n>(\n payload: TPayload,\n handlers: SettlementHandlers<TPayload, TResult>,\n): Promise<TResult> {\n const network = payload.accepted.network;\n if (network.startsWith('eip155:')) {\n if (!handlers.evm) {\n throw new Error(`No EVM settlement handler registered (network: ${network})`);\n }\n return handlers.evm(payload);\n }\n if (network.startsWith('solana:')) {\n if (!handlers.svm) {\n throw new Error(`No Solana settlement handler registered (network: ${network})`);\n }\n return handlers.svm(payload);\n }\n throw new Error(`Unrecognized network in settlement payload: ${network}`);\n}\n","/**\n * Joins multiple Payment directives into a single WWW-Authenticate header value.\n * Per RFC 7235, multiple challenges are comma-separated.\n */\nexport function wwwAuthenticateHeader(directives: string[]): string {\n return directives.join(', ');\n}\n\nexport interface PaymentRequiredHeaderInput {\n x402Version: 1 | 2;\n accepts: unknown[];\n resource?: { url: string; mimeType?: string };\n}\n\n/**\n * Add the v1↔v2 amount-field alias to each accepts entry. Idempotent. Used by both\n * `paymentRequiredHeader` (header emit) and `build402Body` (body emit) so every\n * x402 entry on the wire carries BOTH `amount` (v2 spec) AND `maxAmountRequired`\n * (v1 spec) — strict v1-only parsers (e.g. Coinbase awal at `payments-mcp.coinbase.com`,\n * which is hardcoded to read `maxAmountRequired`) work alongside strict v2 parsers,\n * which ignore the alias.\n */\nexport function aliasAmountFields(accepts: unknown[]): unknown[] {\n return accepts.map((entry) => {\n if (entry === null || typeof entry !== 'object') return entry;\n const e = entry as Record<string, unknown>;\n const hasAmount = e.amount !== undefined;\n const hasMaxAmount = e.maxAmountRequired !== undefined;\n if (hasAmount && !hasMaxAmount) return { ...e, maxAmountRequired: e.amount };\n if (hasMaxAmount && !hasAmount) return { ...e, amount: e.maxAmountRequired };\n return e;\n });\n}\n\n/**\n * Encode the standard x402 PAYMENT-REQUIRED header (base64-encoded JSON of the\n * PaymentRequired object). Clients that recognize the header (`@x402/fetch`,\n * `@x402/core` HTTPClient, `agentscore-pay`) prefer it over body fields.\n *\n * Note: do NOT add a v1↔v2 amount-field alias here. `@x402/core`'s\n * `findMatchingRequirements` uses `deepEqual` against the agent's signed\n * `accepted` payload — any field present on one side and missing on the other\n * (e.g. `maxAmountRequired` on the wire body but not in `buildPaymentRequirements`'s\n * output) makes the match silently fail at settle time. Keep `accepts` shape\n * identical to whatever `buildPaymentRequirements` produces server-side.\n */\nexport function paymentRequiredHeader(input: PaymentRequiredHeaderInput): string {\n return Buffer.from(JSON.stringify(input)).toString('base64');\n}\n","/**\n * Multi-rail payment header bundle — one call composes both `WWW-Authenticate` (the\n * `paymentauth.org` Payment directives) and the standard x402 `PAYMENT-REQUIRED` header\n * from a single rails declaration. Reduces ~10 lines of merchant boilerplate per 402\n * response.\n *\n * Layered on top of `paymentDirective` / `wwwAuthenticateHeader` / `paymentRequiredHeader`\n * — those primitives stay exposed for vendors who want full control.\n */\n\nimport { buildPaymentDirective, type BuildPaymentDirectiveInput } from './directive';\nimport { paymentRequiredHeader, wwwAuthenticateHeader } from './wwwauthenticate';\n\nexport interface PaymentHeadersRail {\n /** Symbolic rail name — `tempo-mainnet`, `x402-base-mainnet`, `stripe`, etc. */\n rail: string;\n /** Amount in USD as a number or string. */\n amountUsd: string | number;\n /** Recipient address (on-chain) — required for crypto rails. */\n recipient?: string;\n /** Stripe profile_id / network_id — required for `stripe` rail. */\n networkId?: string;\n /** EVM chain id override — usually inferred from rail. */\n chainId?: number;\n /** Token contract / currency override — usually inferred from rail. */\n currency?: string;\n /** Decimal precision override — usually inferred from rail (USDC=6, etc.). */\n decimals?: number;\n /** MPP method override — usually inferred from rail. */\n method?: string;\n /** MPP intent. Default `charge`. */\n intent?: string;\n /** ISO-8601 expiry. Default now + 5 min. */\n expires?: string;\n}\n\nexport interface BuildPaymentHeadersInput {\n /** Rails the merchant accepts on this 402. Each becomes one `Payment` directive. */\n rails: PaymentHeadersRail[];\n /** Order id used as the directive challenge id (per-rail it becomes `${orderId}-${rail}`). */\n orderId: string;\n /** Realm — the host of the merchant URL (e.g. `agents.merchant.example`). */\n realm: string;\n /**\n * Optional x402 `accepts` array — included as the standard PAYMENT-REQUIRED header so\n * x402 clients (`@x402/fetch`, `@x402/core` HTTPClient, `agentscore-pay`) can parse the\n * base64-encoded JSON form instead of the WWW-Authenticate text directives. Pass\n * `undefined` (or omit) to skip the PAYMENT-REQUIRED header.\n */\n x402?: { accepts: unknown[]; version?: 1 | 2; resource?: { url: string; mimeType?: string } };\n}\n\nexport interface PaymentHeadersResult {\n 'www-authenticate': string;\n 'PAYMENT-REQUIRED'?: string;\n}\n\n/**\n * Compose `WWW-Authenticate` (multi-directive) and `PAYMENT-REQUIRED` (x402 base64) headers\n * from a single rails declaration. Returns an object suitable for spreading into a\n * `Headers` constructor or the `headers` field of a `Response`.\n *\n * Example:\n * ```ts\n * const headers = buildPaymentHeaders({\n * orderId: 'ord_123',\n * realm: 'agents.merchant.example',\n * rails: [\n * { rail: 'tempo-mainnet', amountUsd: 25, recipient: TEMPO_ADDR },\n * { rail: 'x402-base-mainnet', amountUsd: 25, recipient: BASE_ADDR },\n * { rail: 'stripe', amountUsd: 25, networkId: STRIPE_PROFILE_ID },\n * ],\n * x402: { accepts: x402Accepts, version: 1 },\n * });\n * return new Response(JSON.stringify(body), { status: 402, headers });\n * ```\n */\nexport function buildPaymentHeaders(input: BuildPaymentHeadersInput): PaymentHeadersResult {\n const directives = input.rails.map((rail) => {\n const directiveInput: BuildPaymentDirectiveInput = {\n id: `${input.orderId}-${rail.rail}`,\n realm: input.realm,\n rail: rail.rail,\n amountUsd: rail.amountUsd,\n };\n if (rail.recipient !== undefined) directiveInput.recipient = rail.recipient;\n if (rail.networkId !== undefined) directiveInput.networkId = rail.networkId;\n if (rail.chainId !== undefined) directiveInput.chainId = rail.chainId;\n if (rail.currency !== undefined) directiveInput.currency = rail.currency;\n if (rail.decimals !== undefined) directiveInput.decimals = rail.decimals;\n if (rail.method !== undefined) directiveInput.method = rail.method;\n if (rail.intent !== undefined) directiveInput.intent = rail.intent;\n if (rail.expires !== undefined) directiveInput.expires = rail.expires;\n return buildPaymentDirective(directiveInput);\n });\n\n const result: PaymentHeadersResult = {\n 'www-authenticate': wwwAuthenticateHeader(directives),\n };\n\n if (input.x402) {\n result['PAYMENT-REQUIRED'] = paymentRequiredHeader({\n x402Version: input.x402.version ?? 2,\n accepts: input.x402.accepts,\n ...(input.x402.resource ? { resource: input.x402.resource } : {}),\n });\n }\n\n return result;\n}\n","/**\n * Idempotency-key composition.\n *\n * Stable per-payment keys that retries of the same logical payment can reuse, so AgentScore's\n * `/v1/credentials/wallets` capture endpoint dedupes correctly and the operator's\n * `transaction_count` doesn't inflate.\n *\n * Convention:\n * 1. Prefer the upstream payment-rail's stable identifier (Stripe PaymentIntent id, x402\n * tx hash) when one exists — those are already idempotent on their side.\n * 2. Fall back to a synthesized `pi-{orderId}-{amountCents}` key when no upstream id is\n * available (e.g. pre-creation, or rails without a PI concept).\n * 3. Server caps idempotency keys at 200 chars; this helper warns when that boundary is\n * crossed so a future caller doesn't silently get truncation collisions.\n */\n\nconst SERVER_IDEMPOTENCY_KEY_MAX = 200;\n\nexport interface BuildIdempotencyKeyInput {\n /** Upstream rail's stable payment id — Stripe PaymentIntent id, x402 tx hash, etc. Wins when present. */\n paymentIntentId?: string | null;\n /** Order id — used to compose a fallback key when no paymentIntentId exists. */\n orderId?: string | null;\n /** Amount in cents (or smallest currency unit) — added to the fallback for extra collision resistance. */\n amountCents?: number;\n /** Optional extra prefix to namespace the key (e.g. `\"refund\"`, `\"void\"`). */\n prefix?: string;\n}\n\n/**\n * Compose a stable idempotency key for AgentScore wallet capture and other retry-safe POSTs.\n *\n * Returns `undefined` when no inputs are present (caller should treat as \"no idempotency\n * key — first attempt only\", same shape as omitting the field entirely).\n *\n * Examples:\n * ```ts\n * buildIdempotencyKey({ paymentIntentId: 'pi_abc' }); // → 'pi_abc'\n * buildIdempotencyKey({ orderId: 'ord_x', amountCents: 25000 }); // → 'pi-ord_x-25000'\n * buildIdempotencyKey({ orderId: 'ord_x' }); // → 'pi-ord_x'\n * buildIdempotencyKey({ paymentIntentId: 'pi_abc', prefix: 'refund' }); // → 'refund-pi_abc'\n * buildIdempotencyKey({}); // → undefined\n * ```\n */\nexport function buildIdempotencyKey(input: BuildIdempotencyKeyInput): string | undefined {\n const prefix = input.prefix ? `${input.prefix}-` : '';\n\n if (input.paymentIntentId) {\n const key = `${prefix}${input.paymentIntentId}`;\n return clampKey(key);\n }\n\n if (input.orderId) {\n const amountSuffix = input.amountCents !== undefined ? `-${input.amountCents}` : '';\n const key = `${prefix}pi-${input.orderId}${amountSuffix}`;\n return clampKey(key);\n }\n\n return undefined;\n}\n\nfunction clampKey(key: string): string {\n if (key.length <= SERVER_IDEMPOTENCY_KEY_MAX) return key;\n // Server truncates anyway; surfacing the warning here gives callers a chance to design\n // shorter inputs. We still return the original key (server-side truncation is the source\n // of truth) — clamping client-side would change semantics for any caller already\n // depending on the full string for their own dedup.\n console.warn(\n `[agentscore-commerce] idempotency key longer than ${SERVER_IDEMPOTENCY_KEY_MAX} chars — server will truncate, may cause silent collisions if multiple keys share the first ${SERVER_IDEMPOTENCY_KEY_MAX} chars.`,\n );\n return key;\n}\n","/**\n * Payment-signer extraction.\n *\n * Shared between merchants and the gate. Three paths recover a wallet signer:\n *\n * - **Tempo MPP** — `Authorization: Payment <base64>`; credential `source` is a DID of the\n * form `did:pkh:eip155:<chain>:<address>`.\n * - **Solana MPP `solana/charge`** — `Authorization: Payment <base64>`; recovery via either\n * a `did:pkh:solana:<genesis>:<address>` source (when set by the client) or by decoding\n * the credential's signed-tx payload and reading the SPL `TransferChecked` authority\n * (pull mode only — `payload.type === 'transaction'`).\n * - **x402 EIP-3009 (EVM, e.g. Base/Sepolia)** — `payment-signature` / `x-payment`;\n * decoded payload carries `payload.authorization.from`.\n *\n * Optional peer deps: `mppx` for MPP credentials, `@solana/kit` for the Solana tx-decode\n * fallback. Both dynamic-imported; merchants who don't accept that rail don't need them.\n */\n\nexport type SignerNetwork = 'evm' | 'solana';\n\nconst TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\nconst TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';\nconst TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\ninterface SolanaKitMinimal {\n getBase64Codec: () => { encode: (s: string) => Uint8Array };\n getTransactionDecoder: () => { decode: (b: Uint8Array) => { messageBytes: Uint8Array } };\n getCompiledTransactionMessageDecoder: () => {\n decode: (b: Uint8Array) => {\n staticAccounts: ReadonlyArray<string>;\n instructions: ReadonlyArray<{\n programAddressIndex: number;\n accountIndices?: number[];\n data?: Uint8Array;\n }>;\n };\n };\n}\n\n/**\n * Decode a Solana MPP `solana/charge` credential's `payload.transaction` (base64-encoded\n * signed Solana tx) and return the SPL `TransferChecked` authority — the source-ATA owner,\n * which is the buyer's wallet. Pull mode only (`payload.type === 'transaction'`); push mode\n * (`payload.type === 'signature'`) returns null because recovery would require an RPC fetch.\n */\nasync function extractSolanaSignerFromCredential(credential: unknown): Promise<string | null> {\n const payload = (credential as { payload?: { transaction?: string; type?: string } }).payload;\n if (!payload?.transaction || payload.type !== 'transaction') return null;\n\n const moduleName = '@solana/kit';\n const kit = (await import(moduleName).catch(() => null)) as SolanaKitMinimal | null;\n if (!kit?.getBase64Codec || !kit.getTransactionDecoder || !kit.getCompiledTransactionMessageDecoder) {\n return null;\n }\n\n try {\n const txBytes = kit.getBase64Codec().encode(payload.transaction);\n const decoded = kit.getTransactionDecoder().decode(txBytes);\n const message = kit.getCompiledTransactionMessageDecoder().decode(decoded.messageBytes);\n\n // SPL TransferChecked accounts: [source ATA, mint, destination ATA, authority, ...signers].\n // Returns the FIRST matched authority. For multi-recipient `splits` txs, the buyer\n // signs ONE tx with N TransferChecked instructions all sharing the same authority,\n // so first-match is correct; if a tx ever surfaces with mismatched authorities the\n // first one wins (acceptable since both belong to whoever signed the tx).\n for (const ix of message.instructions) {\n const programId = message.staticAccounts[ix.programAddressIndex];\n if (programId !== TOKEN_PROGRAM && programId !== TOKEN_2022_PROGRAM) continue;\n const data = ix.data;\n if (!data || data.length === 0 || data[0] !== TRANSFER_CHECKED_DISCRIMINATOR) continue;\n const accountIndices = ix.accountIndices ?? [];\n const authorityIndex = accountIndices[3];\n if (authorityIndex === undefined) continue;\n // v0 transactions can carry account indices that resolve via address lookup tables;\n // staticAccounts only holds the static set. If the index is out of range, the\n // authority sits in a lookup table we'd need RPC to resolve. Skip cleanly with a\n // warning rather than returning the wrong address.\n if (authorityIndex >= message.staticAccounts.length) {\n console.warn(\n '[gate] Solana TransferChecked authority resolves through an address lookup table; ' +\n 'signer-match recovery requires the static-account form. Skipping.',\n );\n continue;\n }\n const authority = message.staticAccounts[authorityIndex];\n if (authority) return authority;\n }\n return null;\n } catch (err) {\n console.warn('[gate] Solana credential decode failed:', err instanceof Error ? err.message : err);\n return null;\n }\n}\n\nexport interface PaymentSigner {\n /** Recovered wallet address (EVM lowercased; Solana base58 preserved verbatim). */\n address: string;\n /** Network family — used by `captureWallet` and downstream cross-chain attribution. */\n network: SignerNetwork;\n}\n\n/**\n * Recover the signer wallet from the incoming payment credential, including the network\n * family. Returns `null` when no wallet signature is present (e.g. Stripe SPT, card-only\n * payments, or no credential yet).\n *\n * @param request - the inbound `Request`\n * @param x402PaymentHeader - the value of `payment-signature` or `x-payment` header, if any.\n * Extracted separately because some frameworks (Express) don't expose a web `Request` object.\n */\nexport async function extractPaymentSigner(\n request: Request,\n x402PaymentHeader?: string,\n): Promise<PaymentSigner | null> {\n // MPP — Authorization: Payment <base64>\n const authHeader = request.headers.get('authorization');\n if (authHeader) {\n try {\n const moduleName = 'mppx';\n const mppx = (await import(moduleName).catch(() => null)) as {\n Credential?: {\n extractPaymentScheme: (h: string) => unknown;\n fromRequest: (r: Request) => unknown;\n };\n } | null;\n if (mppx?.Credential?.extractPaymentScheme(authHeader)) {\n const credential = mppx.Credential.fromRequest(request);\n const source = (credential as { source?: string }).source;\n const evmMatch = source?.match(/^did:pkh:eip155:\\d+:(0x[0-9a-fA-F]{40})$/);\n if (evmMatch) return { address: evmMatch[1]!.toLowerCase(), network: 'evm' };\n // Solana CAIP-10: did:pkh:solana:<genesis-base58>:<address-base58>\n const solMatch = source?.match(/^did:pkh:solana:[1-9A-HJ-NP-Za-km-z]{32,44}:([1-9A-HJ-NP-Za-km-z]{32,44})$/);\n if (solMatch) return { address: solMatch[1]!, network: 'solana' };\n // Fallback: source not set by upstream client. Decode the credential's signed-tx\n // payload to find the SPL TransferChecked authority (= source-ATA owner = buyer\n // wallet). Pull mode only.\n const solanaFromTx = await extractSolanaSignerFromCredential(credential);\n if (solanaFromTx) return { address: solanaFromTx, network: 'solana' };\n }\n } catch (err) {\n console.warn('[gate] MPP signer extraction failed:', err instanceof Error ? err.message : err);\n }\n }\n\n // x402 — base64 JSON, EIP-3009 only. EVM `payload.authorization.from` is the signer.\n if (x402PaymentHeader) {\n try {\n const decoded = atob(x402PaymentHeader);\n const parsed = JSON.parse(decoded) as {\n payload?: { authorization?: { from?: string } };\n };\n const from = parsed?.payload?.authorization?.from;\n if (typeof from === 'string' && /^0x[0-9a-fA-F]{40}$/.test(from)) {\n return { address: from.toLowerCase(), network: 'evm' };\n }\n } catch (err) {\n console.warn('[gate] x402 signer extraction failed:', err instanceof Error ? err.message : err);\n }\n }\n\n return null;\n}\n\n/**\n * Headers-only variant for adapters that don't natively expose a Web Fetch `Request`\n * (Express, Fastify, ASGI-bridged frameworks). Constructs a synthetic Request carrying\n * only the `authorization` header and delegates to {@link extractPaymentSigner}. Works\n * because the MPP and x402 paths only read `request.headers.get('authorization')` and\n * the explicit `x402PaymentHeader` arg — no body, query, or method semantics needed.\n */\nexport async function extractPaymentSignerFromAuth(\n authHeader: string | null | undefined,\n x402PaymentHeader?: string,\n): Promise<PaymentSigner | null> {\n const request = new Request('http://internal.gate/', {\n headers: authHeader ? { authorization: authHeader } : {},\n });\n return extractPaymentSigner(request, x402PaymentHeader);\n}\n\n/**\n * Read the x402 payment header from a `Request`, matching the alternate names merchants might\n * use. Falls back to reading either header directly.\n */\nexport function readX402PaymentHeader(request: Request): string | undefined {\n return (\n request.headers.get('payment-signature') ??\n request.headers.get('x-payment') ??\n undefined\n );\n}\n","/**\n * x402 Settlement-Overrides header helpers — used with the `upto` scheme to specify the\n * actual amount to charge after the work is done. The header is JSON-encoded and lives\n * on the merchant's response; the facilitator settles for that amount instead of the\n * advertised maximum.\n *\n * Per the x402 docs (https://docs.x402.org/getting-started/quickstart-for-sellers), the\n * amount field accepts three formats:\n * - raw atomic units, e.g., '1000' for $0.001 USDC at 6 decimals\n * - percentage, e.g., '50%' of the authorized maximum\n * - dollar price, e.g., '$0.05' (converted to atomic via the network's default token)\n */\n\nexport const SETTLEMENT_OVERRIDES_HEADER = 'Settlement-Overrides';\n\nexport interface SettlementOverrides {\n /** Raw atomic units, '<n>%' percentage, or '$X.YZ' dollar price. */\n amount: string;\n}\n\n/**\n * Build a `{ name, value }` pair for the x402 Settlement-Overrides header. Vendors\n * set this on their response to direct the facilitator to settle for the actual amount\n * (used in the upto scheme flow):\n *\n * const { name, value } = settlementOverrideHeader({ amount: '1500' });\n * res.setHeader(name, value); // Express\n * c.header(name, value); // Hono\n */\nexport function settlementOverrideHeader(overrides: SettlementOverrides): { name: string; value: string } {\n return { name: SETTLEMENT_OVERRIDES_HEADER, value: JSON.stringify(overrides) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,IAAM,WAAW;AAAA,EACtB,MAAM;AAAA,IACJ,SAAS,EAAE,OAAO,eAAwB,SAAS,KAAK;AAAA,IACx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