@devlab.group/agent-commerce 2.4.0 → 2.5.0
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 +115 -15
- package/dist/ap2.d.ts +24 -12
- package/dist/ap2.js +31 -13
- package/dist/ap2.js.map +1 -1
- package/dist/{chunk-AITMDXKW.js → chunk-3OTCFFFT.js} +37 -4
- package/dist/chunk-3OTCFFFT.js.map +1 -0
- package/dist/{chunk-4OEXK3YG.js → chunk-4K7FIBJM.js} +25 -4
- package/dist/chunk-4K7FIBJM.js.map +1 -0
- package/dist/{chunk-WUIAUAA7.js → chunk-FKQK5XZA.js} +652 -68
- package/dist/chunk-FKQK5XZA.js.map +1 -0
- package/dist/chunk-GA3O2A7R.js +92 -0
- package/dist/chunk-GA3O2A7R.js.map +1 -0
- package/dist/{chunk-6WACRJVT.js → chunk-VUCMBGUR.js} +3 -3
- package/dist/{chunk-6WACRJVT.js.map → chunk-VUCMBGUR.js.map} +1 -1
- package/dist/cli/{ap2-QDHPRSTF.js → ap2-YAPLERSC.js} +34 -15
- package/dist/cli/ap2-YAPLERSC.js.map +1 -0
- package/dist/cli/{chunk-G2JEY7MB.js → chunk-2J2IQQ4X.js} +8 -7
- package/dist/cli/chunk-2J2IQQ4X.js.map +1 -0
- package/dist/cli/chunk-2UPPX3FJ.js +311 -0
- package/dist/cli/chunk-2UPPX3FJ.js.map +1 -0
- package/dist/cli/{chunk-WYOGIANL.js → chunk-4H2QLHQI.js} +4 -4
- package/dist/cli/{chunk-WYOGIANL.js.map → chunk-4H2QLHQI.js.map} +1 -1
- package/dist/cli/{chunk-OZ4LAWBK.js → chunk-5R7DM5LM.js} +25 -4
- package/dist/cli/chunk-5R7DM5LM.js.map +1 -0
- package/dist/cli/chunk-663ALDZA.js +92 -0
- package/dist/cli/chunk-663ALDZA.js.map +1 -0
- package/dist/cli/{chunk-QQ3WY5L3.js → chunk-IDY2735M.js} +36 -104
- package/dist/cli/chunk-IDY2735M.js.map +1 -0
- package/dist/cli/chunk-JFVRG2HH.js +107 -0
- package/dist/cli/chunk-JFVRG2HH.js.map +1 -0
- package/dist/cli/chunk-M7NXVRU5.js +8 -0
- package/dist/cli/{chunk-UXB65XCS.js.map → chunk-M7NXVRU5.js.map} +1 -1
- package/dist/cli/chunk-NIU5EMSB.js +119 -0
- package/dist/cli/chunk-NIU5EMSB.js.map +1 -0
- package/dist/cli/{chunk-AZDWFVDW.js → chunk-QA2OPHBF.js} +655 -70
- package/dist/cli/chunk-QA2OPHBF.js.map +1 -0
- package/dist/cli/{chunk-DCMW67JM.js → chunk-QLUCNPRT.js} +404 -161
- package/dist/cli/chunk-QLUCNPRT.js.map +1 -0
- package/dist/cli/chunk-SYQLJXIU.js +105 -0
- package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
- package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
- package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
- package/dist/cli/{chunk-PIMFPCNZ.js → chunk-Z34UMZBB.js} +234 -85
- package/dist/cli/chunk-Z34UMZBB.js.map +1 -0
- package/dist/cli/config-BWFMN2ZB.js +12 -0
- package/dist/cli/{config-UI4EDG4L.js.map → config-BWFMN2ZB.js.map} +1 -1
- package/dist/cli/index.js +258 -11
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-26LJMN4N.js → mcp-KZEMXLHR.js} +5 -4
- package/dist/cli/mcp-KZEMXLHR.js.map +1 -0
- package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
- package/dist/cli/near-U6365VFX.js.map +1 -0
- package/dist/cli/payment-providers-SZL36H3Y.js +6 -0
- package/dist/cli/payment-providers-SZL36H3Y.js.map +1 -0
- package/dist/cli/{provider-Z4OJNAYI.js → provider-6TKB5ADJ.js} +30 -16
- package/dist/cli/provider-6TKB5ADJ.js.map +1 -0
- package/dist/cli/receipts-ZGLJWMQG.js +8 -0
- package/dist/cli/receipts-ZGLJWMQG.js.map +1 -0
- package/dist/cli/reconcile-IC22MJD5.js +4 -0
- package/dist/cli/reconcile-IC22MJD5.js.map +1 -0
- package/dist/cli/{run-TEPYJUHG.js → run-ZTYPQI4D.js} +151 -115
- package/dist/cli/run-ZTYPQI4D.js.map +1 -0
- package/dist/cli/svm-KDSPDFJG.js +48 -0
- package/dist/cli/svm-KDSPDFJG.js.map +1 -0
- package/dist/cli/{x402-BMVONZKA.js → x402-WLYBLODI.js} +10 -9
- package/dist/cli/x402-WLYBLODI.js.map +1 -0
- package/dist/index.d.ts +112 -12
- package/dist/index.js +948 -157
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +1 -2
- package/dist/mcp.js +1 -1
- package/dist/mpp.js +24 -11
- package/dist/mpp.js.map +1 -1
- package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
- package/dist/near-FH7HPZV3.js.map +1 -0
- package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-DEXpdp8m.d.ts} +102 -48
- package/dist/{runtime-Cl_BLVZV.d.ts → runtime-Dz2fSO-P.d.ts} +220 -2
- package/dist/svm-KNC3PHMS.js +48 -0
- package/dist/svm-KNC3PHMS.js.map +1 -0
- package/dist/x402.js +5 -5
- package/package.json +1 -1
- package/dist/authorization-DjAecwuW.d.ts +0 -115
- package/dist/chunk-4OEXK3YG.js.map +0 -1
- package/dist/chunk-AITMDXKW.js.map +0 -1
- package/dist/chunk-KA2AX5FH.js +0 -44
- package/dist/chunk-KA2AX5FH.js.map +0 -1
- package/dist/chunk-WUIAUAA7.js.map +0 -1
- package/dist/cli/ap2-QDHPRSTF.js.map +0 -1
- package/dist/cli/chunk-AZDWFVDW.js.map +0 -1
- package/dist/cli/chunk-DCMW67JM.js.map +0 -1
- package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
- package/dist/cli/chunk-OSTCU6ZK.js +0 -44
- package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
- package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
- package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
- package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
- package/dist/cli/chunk-UXB65XCS.js +0 -8
- package/dist/cli/config-UI4EDG4L.js +0 -11
- package/dist/cli/mcp-26LJMN4N.js.map +0 -1
- package/dist/cli/near-5AY3HWYF.js.map +0 -1
- package/dist/cli/provider-Z4OJNAYI.js.map +0 -1
- package/dist/cli/run-TEPYJUHG.js.map +0 -1
- package/dist/cli/svm-3MMYFPC7.js +0 -33
- package/dist/cli/svm-3MMYFPC7.js.map +0 -1
- package/dist/cli/x402-BMVONZKA.js.map +0 -1
- package/dist/near-D6C42VPE.js.map +0 -1
- package/dist/svm-QEUAUNPQ.js +0 -33
- package/dist/svm-QEUAUNPQ.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/protocols/mcp/descriptor.ts","../../src/protocols/mcp/tool-mapping.ts","../../src/protocols/mcp/result-mapping.ts","../../src/protocols/mcp/adapter.ts"],"names":[],"mappings":";;;;;;;;AAUA,IAAM,kBAAA,GAAqB,CAAA,EAAG,4BAA4B,CAAA,EAAA,EAAK,uBAAuB,CAAA,CAAA;AAGtF,IAAM,gBAAA,GAAsC,CAAC,YAAA,EAAc,YAAY,CAAA;AAUhE,IAAM,eAAA,GAAqC;AAAA,EAChD,WAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,aAAA;AAAA,EACA,aAAA;AAAA,EACA,OAAA;AAAA,EACA,SAAA;AAAA,EACA,kCAAA;AAAA,EACA,OAAA;AAAA,EACA,0BAAA;AAAA,EACA,eAAA;AAAA,EACA,UAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EACA,oBAAA;AAAA;AAAA,EAEA,+CAAA;AAAA,EACA;AACF,CAAA;AAEO,SAAS,gBAAgB,qBAAA,EAAkD;AAChF,EAAA,OAAO;AAAA,IACL,IA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AAU,CAAA,EAAE;AAAA,EACvD;AACA,EAAA,OAAO,MAAA;AACT;AAEO,SAAS,iBAAiB,OAAA,EAAkD;AACjF,EAAA,OAAO,IAAI,mBAAmB,OAAO,CAAA;AACvC","file":"mcp-26LJMN4N.js","sourcesContent":["/**\n * Adapter self-description. `supportedSpec` lists the modern revision and\n * the newest 2025-era revision. The SDK's legacy fallback also accepts older\n * 2025-era revisions.\n */\nimport { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/server';\nimport type { AdapterDescriptor } from '../../core';\nimport { MCP_MODERN_PROTOCOL_REVISION } from './constants';\n\n// List the modern revision followed by the SDK's latest legacy revision\nconst MCP_SUPPORTED_SPEC = `${MCP_MODERN_PROTOCOL_REVISION}, ${LATEST_PROTOCOL_VERSION}`;\n\n// Tool-oriented capabilities this adapter implements\nconst MCP_CAPABILITIES: readonly string[] = ['tools/list', 'tools/call'];\n\n/**\n * MCP surfaces this adapter does not implement, listed so its descriptor never\n * implies blanket protocol compatibility.\n *\n * `dns-rebinding-protection` is delegated rather than missing: the gateway's\n * `onRequest` hook validates Host and Origin for `/mcp` (see adapter.ts), and\n * the adapter provides none on its own.\n */\nexport const MCP_UNSUPPORTED: readonly string[] = [\n 'resources',\n 'prompts',\n 'sampling',\n 'completions',\n 'elicitation',\n 'roots',\n 'logging',\n 'notifications/tools/list_changed',\n 'tasks',\n 'dns-rebinding-protection',\n 'authorization',\n 'sessions',\n 'subscriptions',\n 'pagination',\n 'HTTP+SSE transport',\n // mppx reads challenges and refusals from tool-result `_meta`.\n 'MPP payment-required as JSON-RPC error -32042',\n 'MPP verification failure as JSON-RPC error -32043',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'mcp',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: MCP_SUPPORTED_SPEC,\n capabilities: MCP_CAPABILITIES,\n status: 'stable',\n unsupported: MCP_UNSUPPORTED,\n };\n}\n","/**\n * Maps a canonical `CommerceResource` to an MCP `Tool`: the tool name is the\n * resource id, the description carries a price notice for a paid resource,\n * and the input schema is the canonical JSON Schema plus the reserved\n * `_payment` and `_authorization` properties the resource accepts\n */\n\nimport type { JSONObject, Tool } from '@modelcontextprotocol/server';\nimport {\n AUTHORIZATION_INPUT_FIELD,\n type CommerceResource,\n PAYMENT_INPUT_FIELD,\n type PaymentMethodName,\n} from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { MPP_MCP_CREDENTIAL_META_KEY } from '../../payments/mpp/transport';\nimport { X402_MCP_PAYMENT_META_KEY } from '../../payments/x402/transport';\nimport { MCP_TOOL_NAME_PATTERN } from './constants';\n\nexport function isValidToolName(id: string): boolean {\n return MCP_TOOL_NAME_PATTERN.test(id);\n}\n\nfunction isPaidResource(resource: CommerceResource): boolean {\n return resource.pricing.type !== 'free';\n}\n\n// The rail a `_payment` proof is labeled with (see `extractReservedInputFields`),\n// `undefined` when the resource lists none\nfunction primaryPaymentMethod(resource: CommerceResource): PaymentMethodName | undefined {\n return resource.paymentMethods[0];\n}\n\n/** Describe the selected rail's `_meta` proof and `_payment` fallback */\nexport function proofCarriers(method: PaymentMethodName | undefined): string {\n const field = `the \"${PAYMENT_INPUT_FIELD}\" argument`;\n if (method === 'x402') return `_meta[\"${X402_MCP_PAYMENT_META_KEY}\"] or ${field}`;\n if (method === 'mpp') return `_meta[\"${MPP_MCP_CREDENTIAL_META_KEY}\"] or ${field}`;\n return field;\n}\n\n// How to supply a proof, generic when the resource names no rail\nfunction paymentProofNote(resource: CommerceResource): string {\n const method = primaryPaymentMethod(resource);\n const rail = method !== undefined ? `an ${method}` : 'a';\n return `Requires ${rail} payment proof in ${proofCarriers(method)}, built from the payment-required response.`;\n}\n\n// Tell callers to omit `_payment` when a wrapper supplies `_meta`\nconst OMIT_NOTE = 'Omit it when the client sends the proof in _meta.';\n\n/**\n * Description for the reserved `_payment` input property, in the proof\n * encoding of the resource's own rail\n */\nfunction paymentInputFieldDescription(resource: CommerceResource): string {\n const method = primaryPaymentMethod(resource);\n if (method === 'x402') {\n return `x402 payment proof (base64 PAYMENT-SIGNATURE value) for a previous payment-required response. ${OMIT_NOTE}`;\n }\n if (method === 'mpp') {\n return `MPP credential (the full \"Authorization: Payment ...\" value) for the challenge in a previous payment-required response. ${OMIT_NOTE}`;\n }\n if (method !== undefined) {\n return `${method} payment proof (base64-encoded) returned from a previous payment-required response.`;\n }\n return 'Payment proof returned from a previous payment-required response.';\n}\n\n// The authorization methods the resource requires, empty when it requires none\nfunction requiredAuthorization(resource: CommerceResource): readonly string[] {\n return resource.authorization?.required ?? [];\n}\n\nfunction authorizationNote(resource: CommerceResource): string {\n const methods = requiredAuthorization(resource);\n return methods.length > 0\n ? ` Also requires ${methods.join(' and ')} authorization in the \"${AUTHORIZATION_INPUT_FIELD}\" input field.`\n : '';\n}\n\n/**\n * Tool description. A paid resource gets a price notice appended, so an agent\n * sees the cost before calling, not only in the input schema.\n */\nexport function buildToolDescription(resource: CommerceResource): string {\n const base = resource.description ?? resource.name;\n switch (resource.pricing.type) {\n case 'free':\n return base;\n case 'fixed': {\n const { amount, currency } = resource.pricing;\n return `${base} Costs ${amount} ${currency} per call. ${paymentProofNote(resource)}${authorizationNote(resource)}`;\n }\n case 'dynamic':\n return `${base} Requires payment (amount determined at request time). ${paymentProofNote(resource)}${authorizationNote(resource)}`;\n }\n}\n\n/**\n * Builds the MCP `Tool.inputSchema` from the canonical `CommerceResource.inputSchema`.\n *\n * Every keyword is carried through except that `type` is forced to the\n * `'object'` MCP requires, `properties` keeps only object-valued entries and\n * `required` only strings. A paid resource gains the optional `_payment`\n * string property, and a resource requiring authorization the optional\n * `_authorization` object. Both are declared because a resource's input schema\n * is closed by default, and a client that validates arguments against it\n * would otherwise refuse to send them.\n */\nexport function buildInputSchema(resource: CommerceResource): Tool['inputSchema'] {\n const base = resource.inputSchema;\n const baseIsObject = isRecord(base);\n\n // Keep object-valued property schemas from the resource's config JSON\n const basePropertyEntries: readonly [string, JSONObject][] =\n baseIsObject && isRecord(base.properties)\n ? Object.entries(base.properties).filter((entry): entry is [string, JSONObject] =>\n isRecord(entry[1]),\n )\n : [];\n const properties: Record<string, JSONObject> = Object.fromEntries(basePropertyEntries);\n\n // Both overwrite a resource-declared property of the same name; config\n // rejects that collision at load time\n if (isPaidResource(resource)) {\n properties[PAYMENT_INPUT_FIELD] = {\n type: 'string',\n description: paymentInputFieldDescription(resource),\n };\n }\n const methods = requiredAuthorization(resource);\n if (methods.length > 0) {\n properties[AUTHORIZATION_INPUT_FIELD] = {\n type: 'object',\n description:\n 'Authorization this resource requires in addition to payment: the method and its serialized proof.',\n properties: {\n method: { type: 'string', enum: [...methods] },\n payload: { type: 'string', minLength: 1 },\n },\n required: ['method', 'payload'],\n };\n }\n\n const required =\n baseIsObject && Array.isArray(base.required)\n ? base.required.filter((v): v is string => typeof v === 'string')\n : [];\n\n const extra = baseIsObject\n ? Object.fromEntries(\n Object.entries(base).filter(\n ([key]) => key !== 'type' && key !== 'properties' && key !== 'required',\n ),\n )\n : {};\n\n return {\n ...extra,\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n}\n","/**\n * Maps pipeline outcomes and errors to MCP tool results through the core wire\n * helpers (`toErrorEnvelope`, `toPaymentRequiredEnvelope`,\n * `toDeliverySummary`). The A2A adapter uses all three and the HTTP route the\n * two envelopes, so each shape is defined once.\n */\n\nimport type { CallToolResult } from '@modelcontextprotocol/server';\nimport {\n type CommerceError,\n DELIVERY_SUMMARY_META_KEY,\n type DeliveredOutcome,\n type ExecutionOutcome,\n type PaymentMethodName,\n type PaymentRequiredOutcome,\n toDeliverySummary,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport {\n MPP_MCP_PAYMENT_REQUIRED_META_KEY,\n MPP_MCP_RECEIPT_META_KEY,\n mcpPaymentRequired,\n receiptObject,\n} from '../../payments/mpp/transport';\nimport {\n settlementFailure,\n settlementResponse,\n settlementResponseFromDetails,\n X402_MCP_ERROR_META_KEY,\n X402_MCP_PAYMENT_RESPONSE_META_KEY,\n x402ErrorCode,\n} from '../../payments/x402/transport';\nimport { proofCarriers } from './tool-mapping';\n\nfunction toRecord(value: object): Record<string, unknown> {\n return value as Record<string, unknown>;\n}\n\nfunction deliveredResult(outcome: DeliveredOutcome): CallToolResult {\n const body = outcome.body;\n const text = typeof body === 'string' ? body : JSON.stringify(body ?? null);\n const payment = outcome.payment;\n const receipt =\n payment?.provider === 'mpp' ? receiptObject(payment.metadata?.['receipt']) : undefined;\n return {\n content: [{ type: 'text', text }],\n ...(isRecord(body) ? { structuredContent: body } : {}),\n _meta: {\n [DELIVERY_SUMMARY_META_KEY]: toRecord(toDeliverySummary(outcome)),\n ...(payment?.provider === 'x402'\n ? { [X402_MCP_PAYMENT_RESPONSE_META_KEY]: settlementResponse(payment) }\n : {}),\n ...(receipt !== undefined ? { [MPP_MCP_RECEIPT_META_KEY]: receipt } : {}),\n },\n };\n}\n\n// The x402 MCP transport requires the first text block to repeat\n// `structuredContent` as JSON; the second gives readers a short explanation\nfunction structuredError(\n structured: Record<string, unknown>,\n sentence: string,\n meta?: Record<string, unknown>,\n): CallToolResult {\n return {\n isError: true,\n content: [\n { type: 'text', text: JSON.stringify(structured) },\n { type: 'text', text: sentence },\n ],\n structuredContent: structured,\n ...(meta !== undefined ? { _meta: meta } : {}),\n };\n}\n\n// Put x402's PaymentRequired fields beside the gateway error envelope so\n// x402 clients can read the challenge from `structuredContent`\nfunction withX402Challenge(\n envelope: Record<string, unknown>,\n challenge: Record<string, unknown>,\n): Record<string, unknown> {\n return { ...challenge, ...envelope };\n}\n\nfunction paymentRequiredResult(outcome: PaymentRequiredOutcome): CallToolResult {\n const envelope = toPaymentRequiredEnvelope(outcome);\n const p = envelope.payment;\n const x402Required = p.provider === 'x402' ? p.envelope : undefined;\n const structured =\n x402Required !== undefined\n ? withX402Challenge(toRecord(envelope), x402Required)\n : toRecord(envelope);\n const mppRequired = p.provider === 'mpp' ? mcpPaymentRequired(p.envelope) : undefined;\n let meta: Record<string, unknown> | undefined;\n if (x402Required !== undefined) meta = { [X402_MCP_ERROR_META_KEY]: x402Required };\n else if (mppRequired !== undefined) meta = { [MPP_MCP_PAYMENT_REQUIRED_META_KEY]: mppRequired };\n return structuredError(\n structured,\n // A challenge with several offers names no single destination\n `Payment required: ${p.amount} ${p.currency}${p.destination !== undefined ? ` to ${p.destination}` : ''} for resource \"${outcome.resourceId}\". Retry with an ${p.provider} payment proof in ${proofCarriers(p.provider)}.`,\n meta,\n );\n}\n\n/** A tool result for an error; `rail` is the payment method the call used, if any */\nexport function errorResult(error: CommerceError, rail?: PaymentMethodName): CallToolResult {\n const envelope = toErrorEnvelope(error);\n const details = error.details;\n const challenge = details?.['challenge'];\n // Include the rail's new challenge when a 402 refusal supplies one\n const refused = error.httpStatus === 402 && isRecord(challenge);\n const x402Required =\n rail === 'x402' && refused\n ? {\n ...challenge,\n error: x402ErrorCode(error.code, details?.['reason'], details?.['network']),\n }\n : undefined;\n const structured =\n x402Required !== undefined\n ? withX402Challenge(toRecord(envelope), x402Required)\n : toRecord(envelope);\n let meta: Record<string, unknown> | undefined;\n if (rail === 'x402') {\n const settlement =\n error.code === 'PAYMENT_SETTLEMENT_FAILED'\n ? settlementFailure(details)\n : settlementResponseFromDetails(details);\n if (settlement !== undefined || x402Required !== undefined) {\n meta = {\n ...(x402Required !== undefined ? { [X402_MCP_ERROR_META_KEY]: x402Required } : {}),\n ...(settlement !== undefined ? { [X402_MCP_PAYMENT_RESPONSE_META_KEY]: settlement } : {}),\n };\n }\n } else if (rail === 'mpp' && refused) {\n // MPP error results carry a challenge but no receipt\n const required = mcpPaymentRequired(challenge, {\n code: error.code,\n reason: details?.['reason'],\n detail: error.message,\n });\n if (required !== undefined) meta = { [MPP_MCP_PAYMENT_REQUIRED_META_KEY]: required };\n }\n return structuredError(structured, `${envelope.code}: ${envelope.message}`, meta);\n}\n\nexport function mapOutcome(outcome: ExecutionOutcome): CallToolResult {\n return outcome.kind === 'delivered' ? deliveredResult(outcome) : paymentRequiredResult(outcome);\n}\n","/**\n * MCP protocol adapter.\n *\n * One MCP tool per mcp-exposed canonical resource. Every `tools/call` builds a\n * `CanonicalRequest` and goes through `context.pipeline.execute()`. This\n * adapter reads payment carriers but leaves verification, settlement and\n * merchant calls to the pipeline.\n *\n * The SDK's `createMcpHandler` serves `2026-07-28` over Streamable HTTP and\n * routes 2025-era requests through its stateless fallback. It creates a\n * low-level `Server` for each request. This adapter converts the gateway's\n * Node request and response to the web types the handler uses, without adding\n * `@modelcontextprotocol/node` as a peer.\n *\n * Tools are registered on the low-level `Server`, not through\n * `McpServer.registerTool`, whose `inputSchema` accepts only a Zod schema or\n * shape. `CommerceResource.inputSchema` and the MCP wire `Tool.inputSchema`\n * are both JSON Schema, so building `Tool` objects directly carries the schema\n * through with no lossy conversion. The SDK marks `Server` `@deprecated` but\n * still documents it for advanced cases such as this one.\n *\n * The gateway's `onRequest` hook validates Host and Origin for every route,\n * including `/mcp`. This adapter has no separate allowlist. When mounted\n * outside the gateway, it provides no Host or Origin checks; its descriptor\n * therefore lists `dns-rebinding-protection` as unsupported.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport {\n type CallToolResult,\n createMcpHandler,\n type McpHttpHandler,\n ProtocolError,\n ProtocolErrorCode,\n Server,\n type Tool,\n} from '@modelcontextprotocol/server';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type CanonicalRequest,\n CommerceError,\n type CommerceResource,\n extractReservedInputFields,\n type HttpProtocolAdapter,\n type PaymentSubmission,\n type ProtocolAdapterContext,\n toCommerceError,\n} from '../../core';\nimport { toLogInfo } from '../../core/errors';\nimport { isRecord } from '../../core/is-record';\nimport { MPP_MCP_CREDENTIAL_META_KEY } from '../../payments/mpp/transport';\nimport { X402_MCP_PAYMENT_META_KEY, x402McpPaymentSubmission } from '../../payments/x402/transport';\nimport { PACKAGE_VERSION } from '../../version';\nimport { readCappedBody } from '../http';\nimport { MCP_MODERN_PROTOCOL_REVISION, MCP_TOOL_NAME_PATTERN } from './constants';\nimport { buildDescriptor } from './descriptor';\nimport { errorResult, mapOutcome } from './result-mapping';\nimport { buildInputSchema, buildToolDescription, isValidToolName } from './tool-mapping';\n\nexport interface McpAdapterOptions {\n /** Path prefix the gateway mounts this adapter at. Default '/mcp' */\n readonly mountPath?: string;\n /** MCP `Implementation.name` reported during initialize */\n readonly serverName?: string;\n /** MCP `Implementation.version` reported during initialize. Default: this package's version */\n readonly serverVersion?: string;\n}\n\ninterface RegisteredTool {\n readonly resource: CommerceResource;\n readonly tool: Tool;\n}\n\ninterface SkippedResource {\n readonly id: string;\n readonly reason: string;\n}\n\nconst DEFAULT_MOUNT_PATH = '/mcp';\nconst DEFAULT_SERVER_NAME = 'agent-commerce';\n\n/**\n * The SDK can dispatch several `tools/call` requests in one JSON-RPC batch\n * before earlier calls settle. One POST can therefore start concurrent\n * `pipeline.execute()` calls. Limit active calls to 8 per adapter instance.\n */\nconst MAX_CONCURRENT_TOOL_CALLS = 8;\n\n// A second line behind the gateway mount's cap, bounding what this adapter\n// buffers if it is mounted without that guard\nconst MAX_REQUEST_BODY_BYTES = 256 * 1024;\n\n/**\n * Bounds the queue behind the semaphore, per adapter instance. Without it an\n * oversized batch would queue in full and then run in full. 64 is 8x\n * MAX_CONCURRENT_TOOL_CALLS, room for a legitimate burst; calls beyond it fail\n * fast with GATEWAY_BUSY and reach no backend.\n */\nconst MAX_QUEUED_TOOL_CALLS = 64;\n\n// Batch revision used by the SDK when no protocol-version header is sent\nconst MCP_BATCH_PROTOCOL_REVISION = '2025-03-26';\n\n// The tool list is public and stable until restart; cache it for a minute\nconst TOOLS_LIST_CACHE_HINT = { ttlMs: 60_000, cacheScope: 'public' } as const;\n\nclass McpProtocolAdapter implements HttpProtocolAdapter {\n readonly name = 'mcp' as const;\n readonly mountPath: string;\n readonly descriptor: AdapterDescriptor;\n\n private readonly serverName: string;\n private readonly serverVersion: string;\n\n private context: ProtocolAdapterContext | undefined;\n private started = false;\n private tools: readonly RegisteredTool[] = [];\n private toolsByResourceId: ReadonlyMap<string, CommerceResource> = new Map();\n private skipped: readonly SkippedResource[] = [];\n private handler: McpHttpHandler | undefined;\n\n // Counting semaphore on `pipeline.execute()`. It lives on the adapter, not\n // the request, so the cap holds across concurrent `/mcp` requests as well\n // as within one batch.\n private inFlightToolCalls = 0;\n private readonly toolCallWaiters: Array<() => void> = [];\n\n constructor(options: McpAdapterOptions = {}) {\n this.mountPath = options.mountPath ?? DEFAULT_MOUNT_PATH;\n this.serverName = options.serverName ?? DEFAULT_SERVER_NAME;\n this.serverVersion = options.serverVersion ?? PACKAGE_VERSION;\n this.descriptor = buildDescriptor(PACKAGE_VERSION);\n }\n\n async start(context: ProtocolAdapterContext): Promise<void> {\n this.context = context;\n this.started = false;\n\n let resources: readonly CommerceResource[] = [];\n try {\n resources = context.resources.listExposedVia('mcp');\n } catch (err) {\n context.logger.error(\n { err: toLogInfo(err) },\n 'mcp adapter: failed to list mcp-exposed resources',\n );\n resources = [];\n }\n\n const tools: RegisteredTool[] = [];\n const toolsByResourceId = new Map<string, CommerceResource>();\n const skipped: SkippedResource[] = [];\n\n for (const resource of resources) {\n try {\n if (!isValidToolName(resource.id)) {\n skipped.push({\n id: resource.id,\n reason: `resource id is not a legal MCP tool name (must match ${MCP_TOOL_NAME_PATTERN.source})`,\n });\n continue;\n }\n if (toolsByResourceId.has(resource.id)) {\n skipped.push({ id: resource.id, reason: 'duplicate tool name' });\n continue;\n }\n const tool: Tool = {\n name: resource.id,\n description: buildToolDescription(resource),\n inputSchema: buildInputSchema(resource),\n };\n tools.push({ resource, tool });\n toolsByResourceId.set(resource.id, resource);\n } catch (err) {\n skipped.push({\n id: resource.id,\n reason: `failed to build MCP tool: ${toCommerceError(err).message}`,\n });\n }\n }\n\n for (const s of skipped) {\n context.logger.warn({ resourceId: s.id, reason: s.reason }, 'mcp adapter: resource skipped');\n }\n\n this.tools = tools;\n this.toolsByResourceId = toolsByResourceId;\n this.skipped = skipped;\n // Route 2025-era requests through the SDK's stateless fallback\n this.handler = createMcpHandler(\n (ctx) => this.buildServer(ctx.requestInfo?.signal ?? new AbortController().signal),\n {\n legacy: 'stateless',\n // Reporting only: a request the SDK rejects is already answered\n onerror: (err) => context.logger.debug({ err: toLogInfo(err) }, 'mcp adapter: SDK error'),\n },\n );\n this.started = true;\n\n context.logger.info(\n {\n mountPath: this.mountPath,\n toolCount: tools.length,\n skippedCount: skipped.length,\n },\n 'mcp adapter started',\n );\n }\n\n async handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started || !this.context || !this.handler) {\n this.writeJsonRpcError(res, 503, 'MCP adapter is not running.');\n return;\n }\n if (req.method !== 'POST') {\n this.writeJsonRpcError(res, 405, 'Method not allowed. This endpoint only accepts POST.');\n return;\n }\n\n // Aborted when the response closes. `handleToolCall` checks it only\n // before `pipeline.execute()`: a call that may already have settled\n // must finish, or the buyer is charged for nothing.\n const abortController = new AbortController();\n res.once('close', () => abortController.abort());\n const read = await readCappedBody(req, MAX_REQUEST_BODY_BYTES);\n if (read.kind === 'too-large') {\n this.writeJsonRpcError(\n res,\n 413,\n `Request body exceeds the ${MAX_REQUEST_BODY_BYTES}-byte limit.`,\n );\n return;\n }\n if (read.kind !== 'ok') {\n this.writeJsonRpcError(res, 400, 'Could not read the request body.');\n return;\n }\n const body = parseJson(read.text);\n const version = req.headers['mcp-protocol-version'];\n if (Array.isArray(body) && version !== undefined && version !== MCP_BATCH_PROTOCOL_REVISION) {\n this.writeJsonRpcError(\n res,\n 400,\n `Invalid Request: JSON-RPC batches are supported only in MCP ${MCP_BATCH_PROTOCOL_REVISION}.`,\n );\n return;\n }\n const malformed = isModernRequest(req) ? undefined : malformedToolCall(body);\n if (malformed !== undefined) {\n this.writeJsonRpcError(res, 200, malformed.message, -32602, malformed.id);\n return;\n }\n const response = await this.handler.fetch(\n toWebRequest(req, read.text, abortController.signal),\n );\n await writeWebResponse(response, res);\n } catch (err) {\n this.context?.logger.error({ err: toLogInfo(err) }, 'mcp adapter: request handling failed');\n this.writeJsonRpcError(res, 500, 'Internal server error.');\n }\n }\n\n async health(): Promise<AdapterHealth> {\n const checkedAt = this.context?.clock.nowIso() ?? new Date().toISOString();\n if (!this.started || !this.context) {\n return { status: 'fail', detail: 'MCP adapter has not been started.', checkedAt };\n }\n const toolCount = this.tools.length;\n if (this.skipped.length > 0) {\n const detail = `${toolCount} tool(s) registered; ${this.skipped.length} resource(s) skipped: ${this.skipped\n .map((s) => `${s.id} (${s.reason})`)\n .join('; ')}`;\n return { status: 'warn', detail, checkedAt };\n }\n return { status: 'pass', detail: `${toolCount} tool(s) registered.`, checkedAt };\n }\n\n async stop(): Promise<void> {\n this.started = false;\n const handler = this.handler;\n this.handler = undefined;\n try {\n await handler?.close();\n } catch {\n // Best effort: stop() must be idempotent and never throw\n }\n this.context = undefined;\n }\n\n // Use general JSON-RPC codes for transport errors\n private writeJsonRpcError(\n res: ServerResponse,\n status: number,\n message: string,\n code = status >= 500 ? -32603 : -32600,\n id: string | number | null = null,\n ): void {\n if (res.headersSent) return;\n res.writeHead(status, {\n 'content-type': 'application/json',\n // RFC 9110 requires Allow on a 405, and this endpoint takes only POST\n ...(status === 405 ? { allow: 'POST' } : {}),\n });\n res.end(JSON.stringify({ jsonrpc: '2.0', error: { code, message }, id }));\n }\n\n private buildServer(signal: AbortSignal): Server {\n const server = new Server(\n { name: this.serverName, version: this.serverVersion },\n { capabilities: { tools: {} }, cacheHints: { 'tools/list': TOOLS_LIST_CACHE_HINT } },\n );\n server.setRequestHandler('tools/list', async (request) => {\n // A cursor is invalid because this list is not paginated\n if (request.params?.cursor !== undefined) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid cursor.');\n }\n return { tools: this.tools.map((t) => t.tool) };\n });\n server.setRequestHandler('tools/call', async (request) =>\n this.handleToolCall(\n request.params.name,\n request.params.arguments ?? {},\n request.params._meta,\n signal,\n ),\n );\n return server;\n }\n\n private async handleToolCall(\n resourceId: string,\n rawArgs: Record<string, unknown>,\n meta: Record<string, unknown> | undefined,\n signal: AbortSignal,\n ): Promise<CallToolResult> {\n const context = this.context;\n if (!context) {\n return errorResult(new CommerceError('INTERNAL_ERROR', 'MCP adapter is not running.'));\n }\n // Clients can call names absent from `tools/list`. Return the same MCP\n // error for unknown and non-MCP resources without revealing the latter\n const resource = this.toolsByResourceId.get(resourceId);\n if (!resource) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Unknown tool \"${resourceId}\".`);\n }\n try {\n const requestId = context.ids.next('mcp');\n const fields = extractReservedInputFields(rawArgs, resource, requestId);\n const { input, authorization } = fields;\n // Client wrappers attach proofs in `_meta`; that proof takes priority\n // over a possible `_payment` placeholder in the arguments\n const payment = paymentFromMeta(meta, resource) ?? fields.payment;\n const request: CanonicalRequest = {\n requestId,\n resourceId,\n input,\n protocol: 'mcp',\n receivedAt: context.clock.nowIso(),\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n await this.acquireToolCallSlot(signal);\n try {\n // The last cancellation point: a queued call whose caller has left\n // must not start a pipeline run, while a started one may reach\n // settle() and must finish\n if (signal.aborted) {\n // No error code names \"the caller left\". PROTOCOL_UNSUPPORTED is the\n // closest non-retryable one; GATEWAY_BUSY would invite a retry\n // nobody is left to make.\n return errorResult(\n new CommerceError(\n 'PROTOCOL_UNSUPPORTED',\n 'Client disconnected before this call started.',\n ),\n );\n }\n const outcome = await context.pipeline.execute(request);\n return mapOutcome(outcome);\n } finally {\n // Always released: a stranded permit shrinks the cap for good and\n // eventually deadlocks the adapter\n this.releaseToolCallSlot();\n }\n } catch (err) {\n const error = toCommerceError(err);\n context.logger.warn({ resourceId, err: toLogInfo(error) }, 'mcp adapter: execution failed');\n return errorResult(error, resource.paymentMethods[0]);\n }\n }\n\n /**\n * Takes a permit, or queues for one when MAX_CONCURRENT_TOOL_CALLS are in\n * flight. Throws when the queue is full or the caller disconnected while\n * queued; a throw never leaks a permit.\n */\n private async acquireToolCallSlot(signal: AbortSignal): Promise<void> {\n if (this.inFlightToolCalls < MAX_CONCURRENT_TOOL_CALLS) {\n this.inFlightToolCalls++;\n return;\n }\n if (this.toolCallWaiters.length >= MAX_QUEUED_TOOL_CALLS) {\n // Load shedding is transient, so GATEWAY_BUSY tells the caller to back\n // off and retry\n throw new CommerceError(\n 'GATEWAY_BUSY',\n 'Too many tool calls already queued on this adapter; retry later.',\n );\n }\n // Resolved by releaseToolCallSlot, which hands its permit straight to the\n // oldest waiter, so a call arriving later cannot take it first\n await new Promise<void>((resolve) => this.toolCallWaiters.push(resolve));\n if (signal.aborted) {\n // This waiter now holds a permit it will not use; pass it on\n this.releaseToolCallSlot();\n // Non-retryable, for the same reason as the check in handleToolCall\n throw new CommerceError('PROTOCOL_UNSUPPORTED', 'Client disconnected while queued.');\n }\n }\n\n private releaseToolCallSlot(): void {\n const next = this.toolCallWaiters.shift();\n // Handing the permit over leaves the in-flight count unchanged\n if (next !== undefined) next();\n else this.inFlightToolCalls--;\n }\n}\n\n// Pass the Node request body to the SDK as a stream. The gateway's socket\n// byte limit still applies, and the signal reports client disconnects.\nfunction toWebRequest(req: IncomingMessage, body: string, signal: AbortSignal): Request {\n const headers = new Headers();\n for (const [name, value] of Object.entries(req.headers)) {\n if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(', ') : value);\n }\n return new Request(new URL(req.url ?? '/', 'http://localhost'), {\n method: req.method ?? 'POST',\n headers,\n body,\n signal,\n });\n}\n\n/**\n * Let the SDK validate requests with `Mcp-Method` or a modern version header;\n * malformed headers and `_meta` may require an HTTP 400 response\n */\nfunction isModernRequest(req: IncomingMessage): boolean {\n if (req.headers['mcp-method'] !== undefined) return true;\n const version = req.headers['mcp-protocol-version'];\n // ISO revision dates sort lexically.\n return typeof version === 'string' && version >= MCP_MODERN_PROTOCOL_REVISION;\n}\n\n// Undefined for a body that is not JSON; the SDK answers that with -32700\nfunction parseJson(body: string): unknown {\n try {\n return JSON.parse(body);\n } catch {\n return undefined;\n }\n}\n\n// Give malformed tool calls without modern headers a short -32602 response\nfunction malformedToolCall(message: unknown): { id: string | number; message: string } | undefined {\n if (!isRecord(message) || message['method'] !== 'tools/call') return undefined;\n const id = message['id'];\n if (typeof id !== 'string' && typeof id !== 'number') return undefined;\n const params = message['params'];\n let problem: string | undefined;\n if (!isRecord(params)) problem = 'params must be an object';\n else if (typeof params['name'] !== 'string') problem = '\"name\" must be a string';\n else if (params['arguments'] !== undefined && !isRecord(params['arguments'])) {\n problem = '\"arguments\" must be an object';\n } else if (params['_meta'] !== undefined && !isRecord(params['_meta'])) {\n problem = '\"_meta\" must be an object';\n }\n return problem === undefined\n ? undefined\n : { id, message: `Invalid tools/call params: ${problem}.` };\n}\n\n// Stream the SDK's response body, including SSE, to the Node response\nasync function writeWebResponse(response: Response, res: ServerResponse): Promise<void> {\n res.writeHead(response.status, Object.fromEntries(response.headers));\n if (response.body !== null) {\n for await (const chunk of response.body) {\n if (res.destroyed) break;\n res.write(chunk);\n }\n }\n res.end();\n}\n\n// Read a proof from the selected rail's MCP `_meta` carrier\nfunction paymentFromMeta(\n meta: Record<string, unknown> | undefined,\n resource: CommerceResource,\n): PaymentSubmission | undefined {\n const method = resource.paymentMethods[0];\n if (method === 'x402') {\n const payload = x402McpPaymentSubmission(meta?.[X402_MCP_PAYMENT_META_KEY]);\n if (payload !== undefined) return { method, payload };\n }\n const credential = meta?.[MPP_MCP_CREDENTIAL_META_KEY];\n if (method === 'mpp' && isRecord(credential)) {\n // The MPP provider converts this object to an Authorization value\n return { method, payload: JSON.stringify(credential) };\n }\n return undefined;\n}\n\nexport function createMcpAdapter(options?: McpAdapterOptions): HttpProtocolAdapter {\n return new McpProtocolAdapter(options);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/payments/x402/near.ts"],"names":[],"mappings":";;;;AAeA,IAAM,0BAAA,GAA6B,IAAA;AAEnC,IAAM,SA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,OAAO;AAAA,IACL,OAAO,QAAA,CAAS,QAAA;AAAA,IAChB,WAAW,oBAAA,CAAqB;AAAA,MAC9B,SAAS,KAAA,CAAM,OAAA;AAAA,MACf,UAAU,QAAA,CAAS,QAAA;AAAA,MACnB,WAAW,QAAA,CAAS,SAAA;AAAA,MACpB,OAAO,QAAA,CAAS;AAAA,KACjB;AAAA,GACH;AACF;AAOA,SAAS,YAAY,OAAA,EAA0B;AAC7C,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,OAAA,EAAS,QAAQ,CAAA;AAC3C,EAAA,IAAI,KAAA,CAAM,QAAA,CAAS,QAAQ,CAAA,KAAM,SAAS,OAAO,KAAA;AACjD,EAAA,IAAI;AACF,IAAA,uBAAA,CAAwB,KAAA,CAAM,SAAS,CAAA,EAAG,KAAA,CAAM,SAAS,CAAC,CAAA,CAAE,QAAA,CAAS,QAAQ,CAAC,CAAA;AAC9E,IAAA,OAAO,KAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"near-5AY3HWYF.js","sourcesContent":["/**\n * NEAR `exact` payload inspection: bounded decoding of the NEP-366 signed\n * delegate action, the transfer it authorizes and its replay identity. The\n * provider loads this module only for a NEAR offer, so other deployments never\n * import `@x402/near`.\n *\n * The facilitator checks the signature, the access key and its nonce, the\n * delegate window and chain state. The gateway checks the transfer the buyer\n * signed against the offer, so a proof for other terms never reaches it.\n */\nimport { decodeSignedDelegateB64, parseFtTransferArgs } from '@x402/near';\nimport { isRecord } from '../../core/is-record';\nimport { computeNearReplayKey } from './replay-key';\n\n// One `ft_transfer` delegate is a few hundred bytes; this bounds the decoder\nconst MAX_SIGNED_DELEGATE_BASE64 = 4096;\n// NEP-141 requires exactly one yoctoNEAR on `ft_transfer`\nconst ONE_YOCTO = 1n;\n\nexport interface NearTransferTerms {\n readonly network: string;\n /** The NEP-141 token contract the delegate must call */\n readonly asset: string;\n readonly payTo: string;\n /** Atomic units, as the offer states them */\n readonly amount: string;\n}\n\n/**\n * Returns the payer and replay key if the NEAR `exact` payload matches the\n * offer, or a refusal reason using the SDK facilitator's codes.\n */\nexport function inspectNearPayload(\n payload: unknown,\n terms: NearTransferTerms,\n): { readonly payer: string; readonly replayKey: string } | string {\n const encoded = isRecord(payload) ? payload['signedDelegateAction'] : undefined;\n if (typeof encoded !== 'string' || encoded.length > MAX_SIGNED_DELEGATE_BASE64) {\n return 'invalid_exact_near_payload_shape';\n }\n let delegate: ReturnType<typeof decodeSignedDelegateB64>['delegate'];\n try {\n delegate = decodeSignedDelegateB64(encoded).delegate;\n } catch {\n return 'invalid_exact_near_payload_signed_delegate_action';\n }\n if (!isCanonical(encoded)) return 'invalid_exact_near_payload_signed_delegate_action';\n if (delegate.actionCount !== 1) return 'invalid_exact_near_payload_action_count';\n const call = delegate.functionCall;\n if (!call) return 'invalid_exact_near_payload_action_kind';\n if (call.methodName !== 'ft_transfer') return 'invalid_exact_near_payload_method_name';\n if (delegate.receiverId !== terms.asset) {\n return 'invalid_exact_near_payload_token_contract_mismatch';\n }\n let args: ReturnType<typeof parseFtTransferArgs>;\n try {\n args = parseFtTransferArgs(call.args);\n } catch {\n return 'invalid_exact_near_payload_ft_transfer_args';\n }\n if (args.receiver_id !== terms.payTo) return 'invalid_exact_near_payload_recipient_mismatch';\n if (args.amount !== terms.amount) return 'invalid_exact_near_payload_amount_mismatch';\n if (call.deposit !== ONE_YOCTO) return 'invalid_exact_near_payload_attached_deposit';\n return {\n payer: delegate.senderId,\n replayKey: computeNearReplayKey({\n network: terms.network,\n senderId: delegate.senderId,\n publicKey: delegate.publicKey,\n nonce: delegate.nonce,\n }),\n };\n}\n\n/**\n * One delegate, one encoding: canonical base64, and no bytes after the signed\n * delegate. The SDK decoder ignores such bytes, so the check decodes the\n * payload without its last byte: a canonical encoding then runs short.\n */\nfunction isCanonical(encoded: string): boolean {\n const bytes = Buffer.from(encoded, 'base64');\n if (bytes.toString('base64') !== encoded) return false;\n try {\n decodeSignedDelegateB64(bytes.subarray(0, bytes.length - 1).toString('base64'));\n return false;\n } catch {\n return true;\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/payments/mpp/credential.ts","../../src/payments/mpp/descriptor.ts","../../src/payments/mpp/options.ts","../../src/payments/mpp/provider.ts"],"names":["isAddress","getAddress"],"mappings":";;;;;;;;;;;;;;AASA,IAAM,oBAAA,GAA+D;AAAA,EACnE,CAAC,6CAA6C,aAAa,CAAA;AAAA,EAC3D,CAAC,wCAAwC,mBAAmB,CAAA;AAAA,EAC5D,CAAC,sCAAsC,6BAA6B,CAAA;AAAA,EACpE,CAAC,iCAAiC,uBAAuB,CAAA;AAAA,EACzD,CAAC,qCAAqC,iBAAiB,CAAA;AAAA,EACvD,CAAC,qCAAqC,cAAc,CAAA;AAAA,EACpD,CAAC,wCAAwC,iBAAiB;AAC5D,CAAA;AAEO,SAAS,mBAAmB,KAAA,EAAwB;AACzD,EAAA,IAAI,KAAA,YAAiB,MAAA,CAAO,mBAAA,EAAqB,OAAO,mBAAA;AACxD,EAAA,IAAI,KAAA,YAAiB,MAAA,CAAO,mBAAA,EAAqB,OAAO,iBAAA;AACxD,EAAA,IAAI,KAAA,YAAiB,MAAA,CAAO,qBAAA,EAAuB,OAAO,mBAAA;AAC1D,EAAA,IAAI,KAAA,YAAiB,OAAO,uBAAA,EAAyB;AACnD,IAAA,MAAM,KAAA,GAAQ,oBAAA,CAAqB,IAAA,CAAK,CAAC,CAAC,IAAI,CAAA,KAAM,KAAA,CAAM,OAAA,CAAQ,QAAA,CAAS,IAAI,CAAC,CAAA;AAChF,IAAA,IAAI,KAAA,EAAO,OAAO,KAAA,CAAM,CAAC,CAAA;AAAA,EAC3B;AACA,EAAA,OAAO,uBAAA;AACT;AAIO,SAAS,iBAAiB,OAAA,EAAwC;AACvE,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,SAAA,EAAU,CAAE,UAAA,CAAW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AAQ,QAAQ,MAAA,EAAO;AAC9F","file":"provider-Z4OJNAYI.js","sourcesContent":["// Reading an MPP credential: its decoding, its binding to the challenge, and the x402 proof it carries\nimport { type Challenge, Credential, Errors, PaymentRequest } from 'mppx';\nimport type { Types } from 'mppx/evm';\nimport { getAddress, isAddress } from 'viem';\nimport type { PaymentRequirement, PaymentSubmission } from '../../core';\n\n// mppx reports a verification failure only as message text. The pinned\n// release's wording maps to stable reasons, and the tests cover every entry;\n// unmapped text becomes `authorization_invalid`.\nconst VERIFICATION_REASONS: readonly (readonly [string, string])[] = [\n ['EVM authorization challenge hash mismatch', 'wrong_nonce'],\n ['EVM authorization signature mismatch', 'invalid_signature'],\n ['EVM authorization is not valid yet', 'authorization_not_yet_valid'],\n ['EVM authorization has expired', 'authorization_expired'],\n ['EVM authorization source mismatch', 'source_mismatch'],\n ['EVM authorization amount mismatch', 'wrong_amount'],\n ['EVM authorization recipient mismatch', 'wrong_recipient'],\n];\n\nexport function verificationReason(error: unknown): string {\n if (error instanceof Errors.PaymentExpiredError) return 'challenge_expired';\n if (error instanceof Errors.InvalidPayloadError) return 'invalid_payload';\n if (error instanceof Errors.InvalidChallengeError) return 'invalid_challenge';\n if (error instanceof Errors.VerificationFailedError) {\n const match = VERIFICATION_REASONS.find(([text]) => error.message.includes(text));\n if (match) return match[1];\n }\n return 'authorization_invalid';\n}\n\n// Accept the HTTP `Authorization: Payment ...` value or a JSON credential\n// from MCP `_meta`. Serialize the object for mppx deserialization\nexport function decodeCredential(payload: string): Credential.Credential {\n const serialized = payload.trimStart().startsWith('{')\n ? Credential.serialize(JSON.parse(payload) as Credential.Credential)\n : payload;\n return Credential.deserialize(serialized);\n}\n\n// Compares the echoed challenge with the one issued for this request. Both\n// carry a valid HMAC by now, so any difference means the credential answers a\n// challenge issued for other terms. The final comparison catches a difference\n// in any request field the named checks do not cover.\nexport function bindingMismatch(\n echoed: Challenge.Challenge,\n issued: Challenge.Challenge,\n resourceId: string,\n): string | undefined {\n if (echoed.realm !== issued.realm) return 'wrong_realm';\n if (echoed.method !== issued.method || echoed.intent !== issued.intent) {\n return 'unsupported_method';\n }\n // Only the encoded `opaque` survives the credential round trip, not `meta`,\n // so compare it with the encoding of this resource's binding\n if (echoed.opaque !== PaymentRequest.serialize({ resource: resourceId })) {\n return 'wrong_resource';\n }\n // `issued` was built for the request carrying this credential, so a\n // different body, or none, fails here. A challenge without a digest binds\n // no body, as the core draft reads it.\n if (echoed.digest !== undefined && echoed.digest !== issued.digest) {\n return 'body_digest_mismatch';\n }\n const got = echoed.request as ChargeRequest;\n const want = issued.request as ChargeRequest;\n if (got.amount !== want.amount) return 'wrong_amount';\n if (!sameAddress(got.recipient, want.recipient)) return 'wrong_recipient';\n if (got.methodDetails?.chainId !== want.methodDetails?.chainId) return 'wrong_network';\n if (!sameAddress(got.currency, want.currency)) return 'wrong_asset';\n if (canonical(got.methodDetails) !== canonical(want.methodDetails)) {\n return 'unsupported_credential';\n }\n if (canonical(got) !== canonical(want)) return 'wrong_terms';\n return undefined;\n}\n\n// Rewrap the MPP authorization as the x402 `exact` payload expected by settlement\nexport function toX402Submission(\n x402Requirement: PaymentRequirement,\n authorization: Types.AuthorizationPayload,\n): PaymentSubmission {\n const { signature, from, to, value, validAfter, validBefore, nonce } = authorization;\n const payment = {\n x402Version: 2,\n accepted: x402Requirement.challenge.accepts[0],\n payload: { signature, authorization: { from, to, value, validAfter, validBefore, nonce } },\n };\n return { method: 'x402', payload: Buffer.from(JSON.stringify(payment)).toString('base64') };\n}\n\ninterface ChargeRequest {\n readonly amount?: string;\n readonly currency?: string;\n readonly recipient?: string;\n readonly methodDetails?: { readonly chainId?: number };\n}\n\n// The encoding mppx binds into the challenge HMAC, so key order cannot\n// produce a false mismatch\nfunction canonical(value: object | undefined): string {\n return value === undefined ? '' : PaymentRequest.serialize(value as PaymentRequest.Request);\n}\n\nexport function sameAddress(a: string | undefined, b: string | undefined): boolean {\n return a !== undefined && b !== undefined && isAddress(a) && isAddress(b)\n ? getAddress(a) === getAddress(b)\n : false;\n}\n","/**\n * Describes the MPP profile and its unsupported variants.\n *\n * The protocol name alone cannot identify a compatible intent, method and\n * extension set, so the descriptor lists both the target and its gaps.\n *\n * Importing the descriptor does not load `mppx`.\n */\nimport type { AdapterDescriptor } from '../../core/public-types';\nimport { PACKAGE_VERSION } from '../../version';\nimport { MPP_NETWORKS, MPP_PROFILE, MPP_SUPPORTED_SPEC } from './constants';\n\nexport const MPP_DESCRIPTOR: AdapterDescriptor = {\n name: 'mpp',\n kind: 'payment',\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: MPP_SUPPORTED_SPEC,\n capabilities: [\n `intent=${MPP_PROFILE.intent}`,\n `method=${MPP_PROFILE.method}`,\n `credential=${MPP_PROFILE.credentialType}`,\n 'eip-3009',\n ...MPP_NETWORKS.map((network) => `network=${network}`),\n `asset=${MPP_PROFILE.assetSymbol}`,\n 'verify-before-settle',\n 'authorization-flow',\n 'upfront-flow',\n 'payment-receipt',\n // HTTP request bodies only; MCP and A2A carry the proof in the body\n 'challenge-digest-binding',\n ],\n // The pinned specs are drafts and mppx is pre-1.0; the wire format may change\n status: 'experimental',\n unsupported: [\n // Name other methods as a class instead of maintaining a second list\n 'methods other than evm',\n // This profile supports only the EIP-3009 `authorization` credential\n 'credential=permit2',\n 'credential=transaction',\n 'credential=hash',\n // The draft allows splits only with permit2 credentials\n 'splits',\n 'intent=subscription',\n // A separate EVM draft, not an option of charge\n 'evm sessions',\n 'discovery extension',\n ],\n};\n","// The MPP provider's options, checked once at construction\nimport { isAddress } from 'viem';\nimport { type Clock, CommerceError, type IdGenerator, type Logger } from '../../core';\nimport type { X402FacilitatorConfig } from '../x402/guardrails';\nimport type { X402PaymentFlow } from '../x402/payment-flow';\nimport { isMppNetwork, MPP_MIN_CHALLENGE_SECRET_LENGTH, MPP_NETWORKS } from './constants';\n\n/** Whether the token contract has recorded `nonce` as used by `payer` */\nexport type NonceUsedReader = (payer: `0x${string}`, nonce: `0x${string}`) => Promise<boolean>;\n\nexport interface MppProviderOptions {\n /** Merchant-controlled settlement destination. Never gateway-owned */\n readonly recipient: `0x${string}`;\n /** EIP-3009 token the charge is paid in */\n readonly asset: `0x${string}`;\n /** EIP-712 domain name of the asset, e.g. 'USDC' or 'MockUSDC' */\n readonly assetName: string;\n /** EIP-712 domain version of the asset, e.g. '2' */\n readonly assetVersion: string;\n /** Value of each challenge's `realm`, such as the gateway's host */\n readonly realm: string;\n /** Key that binds each challenge to this gateway. Never logged or published */\n readonly challengeSecret: string;\n /** RPC endpoint of the settlement chain */\n readonly rpcUrl: string;\n /** The x402 facilitator that verifies and broadcasts the authorization */\n readonly facilitator: X402FacilitatorConfig;\n /** Must be `true` before anything settles on a mainnet. Never a default */\n readonly allowMainnet?: boolean;\n /** Required on mainnet when facilitator auth is `none` */\n readonly allowUnauthenticatedFacilitator?: boolean;\n readonly logger?: Logger;\n /**\n * Seconds a challenge stays valid, 300 by default. The mppx client signs its\n * authorization to expire at the same moment.\n */\n readonly challengeTtlSeconds?: number;\n /**\n * CAIP-2 network: `eip155:31337` (local Anvil), `eip155:84532` (Base\n * Sepolia, the default) or `eip155:8453` (Base)\n */\n readonly network?: string;\n /**\n * Same flow values as x402. The default, `upfront`, settles before the\n * backend; `authorization` settles after it\n */\n readonly paymentFlow?: X402PaymentFlow;\n /** Per-resource overrides of `paymentFlow`, keyed by resource id */\n readonly resourcePaymentFlows?: Readonly<Record<string, X402PaymentFlow>>;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n}\n\nexport function configInvalid(message: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message);\n}\n\nexport type MppChallengeOptions = Omit<\n MppProviderOptions,\n 'rpcUrl' | 'facilitator' | 'allowMainnet' | 'allowUnauthenticatedFacilitator' | 'logger'\n>;\n\nexport function validateOptions(options: MppChallengeOptions): void {\n if (!isAddress(options.recipient)) throw configInvalid('MPP recipient is not an EVM address');\n if (!isAddress(options.asset)) throw configInvalid('MPP asset is not an EVM address');\n if (options.assetName.length === 0 || options.assetVersion.length === 0) {\n throw configInvalid('MPP asset needs its EIP-712 domain name and version');\n }\n // mppx refuses CR or LF in the quoted realm parameter, so checking here fails\n // at construction instead of on every challenge\n if (options.realm.length === 0 || /[\\r\\n]/.test(options.realm)) {\n throw configInvalid('MPP realm must be a non-empty single-line string');\n }\n if (options.challengeSecret.length < MPP_MIN_CHALLENGE_SECRET_LENGTH) {\n throw configInvalid(\n `MPP challenge secret must have length at least ${MPP_MIN_CHALLENGE_SECRET_LENGTH}`,\n );\n }\n const ttl = options.challengeTtlSeconds;\n if (ttl !== undefined && (!Number.isInteger(ttl) || ttl <= 0)) {\n throw configInvalid('MPP challenge TTL must be a positive whole number of seconds');\n }\n if (options.network !== undefined && !isMppNetwork(options.network)) {\n throw configInvalid(`MPP network must be one of ${MPP_NETWORKS.join(', ')}`);\n }\n}\n","/**\n * MPP payment provider for the `charge` intent, the `evm` method and the\n * EIP-3009 `authorization` credential.\n *\n * It issues challenges and verifies credentials without moving funds: local\n * checks first, then a read-only check by an x402 facilitator. Settlement hands\n * the same signed authorization to that facilitator through an internal x402\n * provider built from these options. The MPP layer adds no signing key.\n *\n * Under the default `upfront` flow settlement precedes the backend call; under\n * `authorization` it follows a successful one. The drafts require a confirmed\n * transaction before a `Payment-Receipt`.\n */\nimport { Challenge, type Credential, Method, Receipt } from 'mppx';\nimport { Methods, type Types } from 'mppx/evm';\nimport { charge } from 'mppx/evm/server';\nimport { createPublicClient, getAddress, http, parseAbi } from 'viem';\nimport {\n type AdapterHealth,\n CommerceError,\n type PaymentContext,\n type PaymentProvider,\n type PaymentRequirement,\n type PaymentResult,\n type PaymentSettlementContext,\n type PaymentVerificationContext,\n systemClock,\n} from '../../core';\nimport { SETTLE_AFTER_BACKEND_METADATA_KEY } from '../../core/execution/settlement-order';\nimport { parseCanonicalAmount } from '../x402/amount';\nimport { createX402PaymentProvider, DEFAULT_IDS } from '../x402/provider';\nimport { computeReplayKey } from '../x402/replay-key';\nimport {\n MPP_DEFAULT_NETWORK,\n MPP_DEFAULT_PAYMENT_FLOW,\n MPP_PROFILE,\n MPP_SPEC_DRAFTS,\n} from './constants';\nimport {\n bindingMismatch,\n decodeCredential,\n sameAddress,\n toX402Submission,\n verificationReason,\n} from './credential';\nimport { MPP_DESCRIPTOR } from './descriptor';\nimport {\n configInvalid,\n type MppChallengeOptions,\n type MppProviderOptions,\n type NonceUsedReader,\n validateOptions,\n} from './options';\nimport { CONTENT_DIGEST_METADATA_KEY } from './transport';\n\nconst DEFAULT_CHALLENGE_TTL_SECONDS = 300;\n\n// The x402 SDK's verify reason for an EIP-3009 nonce already spent on chain\nconst NONCE_ALREADY_USED = 'invalid_exact_evm_nonce_already_used';\n\nconst AUTHORIZATION_STATE_ABI = parseAbi([\n 'function authorizationState(address authorizer, bytes32 nonce) view returns (bool)',\n]);\n\nconst NONCE_READ_TIMEOUT_MS = 5_000;\n\nexport function createMppPaymentProvider(options: MppProviderOptions): PaymentProvider {\n const { rpcUrl, facilitator, allowMainnet, allowUnauthenticatedFacilitator, logger, ...rest } =\n options;\n // Checked first so a bad MPP option is reported as one, not as an x402 error\n validateOptions(rest);\n // Built from the same terms, and never registered as a rail, so an MPP-only\n // deployment needs no x402 configuration\n const settlement = createX402PaymentProvider({\n network: options.network ?? MPP_DEFAULT_NETWORK,\n rpcUrl,\n asset: options.asset,\n assetName: options.assetName,\n assetVersion: options.assetVersion,\n assetDecimals: MPP_PROFILE.assetDecimals,\n payTo: options.recipient,\n facilitator,\n ...(allowMainnet !== undefined ? { allowMainnet } : {}),\n ...(allowUnauthenticatedFacilitator !== undefined ? { allowUnauthenticatedFacilitator } : {}),\n ...(logger !== undefined ? { logger } : {}),\n ...(options.clock !== undefined ? { clock: options.clock } : {}),\n });\n // One attempt: the read only names the reason for a refusal already decided\n const chain = createPublicClient({\n transport: http(rpcUrl, { timeout: NONCE_READ_TIMEOUT_MS, retryCount: 0 }),\n });\n const nonceUsed: NonceUsedReader = (payer, nonce) =>\n chain.readContract({\n address: options.asset,\n abi: AUTHORIZATION_STATE_ABI,\n functionName: 'authorizationState',\n args: [payer, nonce],\n });\n return createMppProviderWithSettlement(rest, settlement, nonceUsed);\n}\n\n/**\n * Internal seam: tests inject a settlement provider and the nonce reader. Not\n * exported from the `./mpp` entry.\n */\nexport function createMppProviderWithSettlement(\n options: MppChallengeOptions,\n settlement: PaymentProvider,\n nonceUsed?: NonceUsedReader,\n): PaymentProvider {\n validateOptions(options);\n if (settlement.name !== 'x402') {\n throw configInvalid('MPP settlement must be an x402 payment provider');\n }\n const network = options.network ?? MPP_DEFAULT_NETWORK;\n const chainId = Number(network.split(':')[1]);\n const clock = options.clock ?? systemClock;\n const ttlSeconds = options.challengeTtlSeconds ?? DEFAULT_CHALLENGE_TTL_SECONDS;\n const recipient = getAddress(options.recipient);\n const asset = getAddress(options.asset);\n const ids = options.ids ?? DEFAULT_IDS;\n // The settlement provider's terms are fixed at construction, so one passing\n // check covers every later challenge\n let settlementTermsChecked = false;\n\n // charge() requires a callback even though this provider never invokes the\n // mppx broadcast path. Settlement is delegated to the x402 provider.\n const method = charge({\n currency: asset,\n recipient,\n chainId,\n decimals: MPP_PROFILE.assetDecimals,\n authorization: { name: options.assetName, version: options.assetVersion },\n settle: async () => {\n throw new CommerceError('INTERNAL_ERROR', 'MPP direct broadcast is disabled');\n },\n });\n\n function rejected(requirement: PaymentRequirement, reason: string): PaymentResult {\n return {\n status: 'rejected',\n provider: 'mpp',\n amount: requirement.amount,\n currency: requirement.currency,\n network,\n asset,\n rejectionReason: reason,\n };\n }\n\n async function createRequirement(context: PaymentContext): Promise<PaymentRequirement> {\n if (context.currency !== MPP_PROFILE.assetSymbol) {\n throw configInvalid(\n `Resource \"${context.resource.id}\" is priced in ${context.currency}, but MPP charges ${MPP_PROFILE.assetSymbol}`,\n );\n }\n // Strict parse first: mppx converts with viem's parseUnits, which rounds\n // excess precision instead of refusing it\n if (parseCanonicalAmount(context.amount, MPP_PROFILE.assetDecimals) <= 0n) {\n throw new CommerceError('PAYMENT_INVALID', `Amount \"${context.amount}\" must be above zero`, {\n details: { amount: context.amount },\n });\n }\n // Reject a mismatched settlement requirement before the buyer signs\n if (!settlementTermsChecked) {\n await settlementRequirement(context);\n settlementTermsChecked = true;\n }\n const paymentFlow =\n options.resourcePaymentFlows?.[context.resource.id] ??\n options.paymentFlow ??\n MPP_DEFAULT_PAYMENT_FLOW;\n // mppx signs `validBefore` at this expiry. Under `authorization`, the\n // backend must finish before then for settlement to proceed.\n const expires = new Date(clock.now().getTime() + ttlSeconds * 1000);\n const digest = context.metadata?.[CONTENT_DIGEST_METADATA_KEY];\n const challenge = Challenge.fromMethod(Methods.charge, {\n secretKey: options.challengeSecret,\n realm: options.realm,\n expires,\n // Present for an HTTP request with a body. MCP and A2A carry the proof\n // in the body itself, so their challenges bind none.\n ...(typeof digest === 'string' ? { digest } : {}),\n // Bound by the challenge HMAC, so a challenge for one resource cannot pay\n // for another at the same price\n meta: { resource: context.resource.id },\n request: {\n amount: context.amount,\n currency: asset,\n recipient,\n chainId,\n decimals: MPP_PROFILE.assetDecimals,\n credentialTypes: [MPP_PROFILE.credentialType],\n },\n });\n return {\n id: ids.next('payreq'),\n requestId: context.requestId,\n resourceId: context.resource.id,\n provider: 'mpp',\n amount: context.amount,\n currency: context.currency,\n destination: recipient,\n network,\n asset,\n expiresAt: expires.toISOString(),\n challenge: {\n provider: 'mpp',\n version: MPP_SPEC_DRAFTS.core,\n accepts: [challenge],\n // Build both carrier forms here because the HTTP route and MCP\n // adapter cannot import mppx: a header value for HTTP and challenge\n // objects for MCP\n envelope: { wwwAuthenticate: Challenge.serialize(challenge), challenges: [challenge] },\n },\n metadata: { [SETTLE_AFTER_BACKEND_METADATA_KEY]: paymentFlow === 'authorization' },\n };\n }\n\n async function verify(context: PaymentVerificationContext): Promise<PaymentResult> {\n const { requirement, resource, submission } = context;\n if (requirement.provider !== 'mpp' || requirement.challenge.provider !== 'mpp') {\n return rejected(requirement, 'wrong_provider');\n }\n const issued = requirement.challenge.accepts[0] as Challenge.Challenge | undefined;\n if (!issued) return rejected(requirement, 'missing_challenge');\n\n let credential: Credential.Credential;\n try {\n credential = decodeCredential(submission.payload);\n } catch {\n return rejected(requirement, 'malformed_credential');\n }\n const echoed = credential.challenge;\n\n // A valid HMAC means this gateway issued the challenge, not that it was\n // issued for this resource and price. The binding checks below close that gap.\n if (!Challenge.verify(echoed, { secretKey: options.challengeSecret })) {\n return rejected(requirement, 'challenge_not_issued');\n }\n const binding = bindingMismatch(echoed, issued, resource.id);\n if (binding) return rejected(requirement, binding);\n if (!echoed.expires || new Date(echoed.expires).getTime() <= clock.now().getTime()) {\n return rejected(requirement, 'challenge_expired');\n }\n if ((credential.payload as { type?: unknown } | null)?.type !== MPP_PROFILE.credentialType) {\n return rejected(requirement, 'unsupported_credential');\n }\n\n // Local checks only: signature recovery, nonce == challenge hash, the\n // validity window and payload terms. With no network call involved, any\n // failure here is a verdict on the credential, not an outage.\n let payer: `0x${string}`;\n try {\n const validation = await Method.validateCredential([method], credential);\n payer = getAddress((validation.details as { payer: string }).payer);\n } catch (error) {\n return rejected(requirement, verificationReason(error));\n }\n\n // validateCredential proved it equals the 32-byte challenge hash\n const nonce = (credential.payload as Types.AuthorizationPayload).nonce as `0x${string}`;\n // Match x402's key so the same authorization collides across both rails\n const replayKey = computeReplayKey({ chainId, asset, from: payer, nonce });\n\n // The facilitator check runs before the pipeline reserves the replay key,\n // so an outage throws the x402 provider's retryable error and uses up\n // nothing, and a refusal is an ordinary rejection\n const x402Verification = await settlement.verify(\n await toX402Context(context, credential.payload as Types.AuthorizationPayload),\n );\n if (x402Verification.status !== 'verified') {\n // A spent challenge-hash nonce means the challenge was used. Check\n // the token when the facilitator reports only a simulation failure;\n // keep its reason if the token read fails.\n const reason = x402Verification.rejectionReason;\n const spent =\n reason === NONCE_ALREADY_USED ||\n ((await nonceUsed?.(payer, nonce).catch(() => false)) ?? false);\n return rejected(\n requirement,\n spent ? 'challenge_already_used' : (reason ?? 'settlement_rejected'),\n );\n }\n // A different key would settle an authorization the pipeline did not reserve\n if (x402Verification.replayKey !== replayKey) {\n return rejected(requirement, 'settlement_mismatch');\n }\n\n return {\n status: 'verified',\n provider: 'mpp',\n payer,\n payee: recipient,\n amount: requirement.amount,\n currency: requirement.currency,\n network,\n asset,\n replayKey,\n };\n }\n\n // The same payment as an x402 requirement and `exact` submission\n async function toX402Context(\n context: PaymentVerificationContext,\n authorization: Types.AuthorizationPayload,\n ): Promise<PaymentVerificationContext> {\n const { requestId, requirement, resource } = context;\n const x402Requirement = await settlementRequirement({\n requestId,\n resource,\n amount: requirement.amount,\n currency: requirement.currency,\n requestedAt: clock.nowIso(),\n });\n return {\n requestId,\n resource,\n requirement: x402Requirement,\n submission: toX402Submission(x402Requirement, authorization),\n };\n }\n\n async function settlementRequirement(context: PaymentContext): Promise<PaymentRequirement> {\n const x402 = await settlement.createRequirement(context);\n const extra = (x402.challenge.accepts[0]?.['extra'] ?? {}) as Record<string, unknown>;\n if (\n x402.network !== network ||\n !sameAddress(x402.asset, asset) ||\n !sameAddress(x402.destination, recipient) ||\n extra['name'] !== options.assetName ||\n extra['version'] !== options.assetVersion\n ) {\n throw configInvalid(\n 'MPP settlement provider must use the same network, asset, EIP-712 domain and recipient',\n );\n }\n return x402;\n }\n\n async function settle(context: PaymentSettlementContext): Promise<PaymentResult> {\n const { requestId, requirement, resource, submission, verification } = context;\n if (verification.status !== 'verified' || verification.replayKey === undefined) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'MPP settle() called without a successful verify()',\n );\n }\n\n // verify() already ran the facilitator check, and the facilitator checks\n // again before broadcasting. A throw may follow a broadcast, so it\n // propagates and the pipeline marks the payment uncertain.\n const credential = decodeCredential(submission.payload);\n const authorization = credential.payload as Types.AuthorizationPayload;\n const settled = await settlement.settle({\n ...(await toX402Context({ requestId, requirement, resource, submission }, authorization)),\n verification: { ...verification, provider: 'x402' },\n });\n const result: PaymentResult = {\n ...settled,\n provider: 'mpp',\n amount: requirement.amount,\n currency: requirement.currency,\n replayKey: verification.replayKey,\n };\n if (settled.status !== 'settled' || settled.externalReference === undefined) return result;\n // Include the EVM method's `challengeId` and `chainId` in the receipt\n // sent through the HTTP `Payment-Receipt` header\n const fields: Receipt.Receipt & { challengeId: string; chainId: number } = {\n method: MPP_PROFILE.method,\n reference: settled.externalReference,\n status: 'success',\n timestamp: settled.settledAt ?? clock.nowIso(),\n challengeId: credential.challenge.id,\n chainId,\n };\n const receipt = Receipt.from(fields);\n return { ...result, metadata: { ...settled.metadata, receipt: Receipt.serialize(receipt) } };\n }\n\n function health(): Promise<AdapterHealth> {\n return settlement.health();\n }\n\n return { name: 'mpp', descriptor: MPP_DESCRIPTOR, createRequirement, verify, settle, health };\n}\n\nexport type { MppProviderOptions, NonceUsedReader } from './options';\n"]}
|