x402-express-mantle 1.0.0 → 1.0.2

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.
Files changed (125) hide show
  1. package/README.md +19 -1
  2. package/lib/cjs/index.d.ts +119 -81
  3. package/lib/cjs/index.js +3 -3
  4. package/lib/esm/index.d.mts +5 -5
  5. package/lib/esm/index.mjs +3 -3
  6. package/package.json +4 -3
  7. package/lib/cjs/client/index.d.ts +0 -243
  8. package/lib/cjs/client/index.js +0 -413
  9. package/lib/cjs/client/index.js.map +0 -1
  10. package/lib/cjs/exact/client/index.d.ts +0 -37
  11. package/lib/cjs/exact/client/index.js +0 -281
  12. package/lib/cjs/exact/client/index.js.map +0 -1
  13. package/lib/cjs/exact/facilitator/index.d.ts +0 -110
  14. package/lib/cjs/exact/facilitator/index.js +0 -714
  15. package/lib/cjs/exact/facilitator/index.js.map +0 -1
  16. package/lib/cjs/exact/server/index.d.ts +0 -87
  17. package/lib/cjs/exact/server/index.js +0 -209
  18. package/lib/cjs/exact/server/index.js.map +0 -1
  19. package/lib/cjs/exact/v1/client/index.d.ts +0 -33
  20. package/lib/cjs/exact/v1/client/index.js +0 -169
  21. package/lib/cjs/exact/v1/client/index.js.map +0 -1
  22. package/lib/cjs/exact/v1/facilitator/index.d.ts +0 -71
  23. package/lib/cjs/exact/v1/facilitator/index.js +0 -384
  24. package/lib/cjs/exact/v1/facilitator/index.js.map +0 -1
  25. package/lib/cjs/facilitator/index.d.ts +0 -192
  26. package/lib/cjs/facilitator/index.js +0 -398
  27. package/lib/cjs/facilitator/index.js.map +0 -1
  28. package/lib/cjs/http/index.d.ts +0 -52
  29. package/lib/cjs/http/index.js +0 -827
  30. package/lib/cjs/http/index.js.map +0 -1
  31. package/lib/cjs/mechanisms-CzuGzYsS.d.ts +0 -270
  32. package/lib/cjs/scheme-MoBRXFM8.d.ts +0 -29
  33. package/lib/cjs/server/index.d.ts +0 -2
  34. package/lib/cjs/server/index.js +0 -1305
  35. package/lib/cjs/server/index.js.map +0 -1
  36. package/lib/cjs/signer-5OVDxViv.d.ts +0 -79
  37. package/lib/cjs/signer-BMkbhFYE.d.ts +0 -123
  38. package/lib/cjs/types/index.d.ts +0 -1
  39. package/lib/cjs/types/index.js +0 -66
  40. package/lib/cjs/types/index.js.map +0 -1
  41. package/lib/cjs/types/v1/index.d.ts +0 -1
  42. package/lib/cjs/types/v1/index.js +0 -19
  43. package/lib/cjs/types/v1/index.js.map +0 -1
  44. package/lib/cjs/utils/index.d.ts +0 -48
  45. package/lib/cjs/utils/index.js +0 -116
  46. package/lib/cjs/utils/index.js.map +0 -1
  47. package/lib/cjs/v1/index.d.ts +0 -12
  48. package/lib/cjs/v1/index.js +0 -180
  49. package/lib/cjs/v1/index.js.map +0 -1
  50. package/lib/cjs/x402HTTPResourceServer-D1YtlH_r.d.ts +0 -719
  51. package/lib/esm/chunk-3CEIVWNN.mjs +0 -339
  52. package/lib/esm/chunk-3CEIVWNN.mjs.map +0 -1
  53. package/lib/esm/chunk-BJTO5JO5.mjs +0 -11
  54. package/lib/esm/chunk-BJTO5JO5.mjs.map +0 -1
  55. package/lib/esm/chunk-EEA7DKZI.mjs +0 -111
  56. package/lib/esm/chunk-EEA7DKZI.mjs.map +0 -1
  57. package/lib/esm/chunk-FOUXRQAV.mjs +0 -88
  58. package/lib/esm/chunk-FOUXRQAV.mjs.map +0 -1
  59. package/lib/esm/chunk-IKSTWKEM.mjs +0 -157
  60. package/lib/esm/chunk-IKSTWKEM.mjs.map +0 -1
  61. package/lib/esm/chunk-JYZWCLMP.mjs +0 -305
  62. package/lib/esm/chunk-JYZWCLMP.mjs.map +0 -1
  63. package/lib/esm/chunk-PNSAJQCF.mjs +0 -108
  64. package/lib/esm/chunk-PNSAJQCF.mjs.map +0 -1
  65. package/lib/esm/chunk-PSA4YVU2.mjs +0 -92
  66. package/lib/esm/chunk-PSA4YVU2.mjs.map +0 -1
  67. package/lib/esm/chunk-QLXM7BIB.mjs +0 -23
  68. package/lib/esm/chunk-QLXM7BIB.mjs.map +0 -1
  69. package/lib/esm/chunk-TDLQZ6MP.mjs +0 -86
  70. package/lib/esm/chunk-TDLQZ6MP.mjs.map +0 -1
  71. package/lib/esm/chunk-VE37GDG2.mjs +0 -7
  72. package/lib/esm/chunk-VE37GDG2.mjs.map +0 -1
  73. package/lib/esm/chunk-WWACQNRQ.mjs +0 -7
  74. package/lib/esm/chunk-WWACQNRQ.mjs.map +0 -1
  75. package/lib/esm/chunk-X4W4S5RB.mjs +0 -39
  76. package/lib/esm/chunk-X4W4S5RB.mjs.map +0 -1
  77. package/lib/esm/chunk-Z4QX3O5V.mjs +0 -748
  78. package/lib/esm/chunk-Z4QX3O5V.mjs.map +0 -1
  79. package/lib/esm/chunk-ZYXTTU74.mjs +0 -88
  80. package/lib/esm/chunk-ZYXTTU74.mjs.map +0 -1
  81. package/lib/esm/client/index.d.mts +0 -243
  82. package/lib/esm/client/index.mjs +0 -260
  83. package/lib/esm/client/index.mjs.map +0 -1
  84. package/lib/esm/exact/client/index.d.mts +0 -37
  85. package/lib/esm/exact/client/index.mjs +0 -36
  86. package/lib/esm/exact/client/index.mjs.map +0 -1
  87. package/lib/esm/exact/facilitator/index.d.mts +0 -110
  88. package/lib/esm/exact/facilitator/index.mjs +0 -350
  89. package/lib/esm/exact/facilitator/index.mjs.map +0 -1
  90. package/lib/esm/exact/server/index.d.mts +0 -87
  91. package/lib/esm/exact/server/index.mjs +0 -129
  92. package/lib/esm/exact/server/index.mjs.map +0 -1
  93. package/lib/esm/exact/v1/client/index.d.mts +0 -33
  94. package/lib/esm/exact/v1/client/index.mjs +0 -8
  95. package/lib/esm/exact/v1/client/index.mjs.map +0 -1
  96. package/lib/esm/exact/v1/facilitator/index.d.mts +0 -71
  97. package/lib/esm/exact/v1/facilitator/index.mjs +0 -8
  98. package/lib/esm/exact/v1/facilitator/index.mjs.map +0 -1
  99. package/lib/esm/facilitator/index.d.mts +0 -192
  100. package/lib/esm/facilitator/index.mjs +0 -373
  101. package/lib/esm/facilitator/index.mjs.map +0 -1
  102. package/lib/esm/http/index.d.mts +0 -52
  103. package/lib/esm/http/index.mjs +0 -29
  104. package/lib/esm/http/index.mjs.map +0 -1
  105. package/lib/esm/mechanisms-CzuGzYsS.d.mts +0 -270
  106. package/lib/esm/scheme-fjF-9LhT.d.mts +0 -29
  107. package/lib/esm/server/index.d.mts +0 -2
  108. package/lib/esm/server/index.mjs +0 -563
  109. package/lib/esm/server/index.mjs.map +0 -1
  110. package/lib/esm/signer-5OVDxViv.d.mts +0 -79
  111. package/lib/esm/signer-BMkbhFYE.d.mts +0 -123
  112. package/lib/esm/types/index.d.mts +0 -1
  113. package/lib/esm/types/index.mjs +0 -10
  114. package/lib/esm/types/index.mjs.map +0 -1
  115. package/lib/esm/types/v1/index.d.mts +0 -1
  116. package/lib/esm/types/v1/index.mjs +0 -1
  117. package/lib/esm/types/v1/index.mjs.map +0 -1
  118. package/lib/esm/utils/index.d.mts +0 -48
  119. package/lib/esm/utils/index.mjs +0 -20
  120. package/lib/esm/utils/index.mjs.map +0 -1
  121. package/lib/esm/v1/index.d.mts +0 -12
  122. package/lib/esm/v1/index.mjs +0 -13
  123. package/lib/esm/v1/index.mjs.map +0 -1
  124. package/lib/esm/x402HTTPResourceServer-BIfIK5HS.d.mts +0 -719
  125. package/src/index.js +0 -4
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../../src/exact/v1/facilitator/index.ts","../../../../../src/exact/v1/facilitator/scheme.ts","../../../../../src/constants.ts","../../../../../src/utils.ts"],"sourcesContent":["export { ExactSvmSchemeV1 } from \"./scheme\";\n","import {\n COMPUTE_BUDGET_PROGRAM_ADDRESS,\n parseSetComputeUnitLimitInstruction,\n parseSetComputeUnitPriceInstruction,\n} from \"@solana-program/compute-budget\";\nimport {\n parseTransferCheckedInstruction as parseTransferCheckedInstructionToken,\n TOKEN_PROGRAM_ADDRESS,\n} from \"@solana-program/token\";\nimport {\n findAssociatedTokenPda,\n parseTransferCheckedInstruction as parseTransferCheckedInstruction2022,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from \"@solana-program/token-2022\";\nimport {\n decompileTransactionMessage,\n getCompiledTransactionMessageDecoder,\n type Address,\n} from \"@solana/kit\";\nimport type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from \"@x402/core/types\";\nimport type { PaymentPayloadV1, PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS } from \"../../../constants\";\nimport type { FacilitatorSvmSigner } from \"../../../signer\";\nimport type { ExactSvmPayloadV1 } from \"../../../types\";\nimport { decodeTransactionFromPayload, getTokenPayerFromTransaction } from \"../../../utils\";\n\n/**\n * SVM facilitator implementation for the Exact payment scheme (V1).\n */\nexport class ExactSvmSchemeV1 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"solana:*\";\n\n /**\n * Creates a new ExactSvmFacilitatorV1 instance.\n *\n * @param signer - The SVM RPC client for facilitator operations\n * @returns ExactSvmFacilitatorV1 instance\n */\n constructor(private readonly signer: FacilitatorSvmSigner) {}\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * For SVM, this includes a randomly selected fee payer address.\n * Random selection distributes load across multiple signers.\n *\n * @param _ - The network identifier (unused for SVM)\n * @returns Extra data with feePayer address\n */\n getExtra(_: string): Record<string, unknown> | undefined {\n // Randomly select from available signers to distribute load\n const addresses = this.signer.getAddresses();\n const randomIndex = Math.floor(Math.random() * addresses.length);\n\n return {\n feePayer: addresses[randomIndex],\n };\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * For SVM, returns all available fee payer addresses.\n *\n * @param _ - The network identifier (unused for SVM)\n * @returns Array of fee payer addresses\n */\n getSigners(_: string): string[] {\n return [...this.signer.getAddresses()];\n }\n\n /**\n * Verifies a payment payload (V1).\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const requirementsV1 = requirements as unknown as PaymentRequirementsV1;\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactSvmPayload = payload.payload as ExactSvmPayloadV1;\n\n // Step 1: Validate Payment Requirements\n if (payloadV1.scheme !== \"exact\" || requirements.scheme !== \"exact\") {\n return {\n isValid: false,\n invalidReason: \"unsupported_scheme\",\n payer: \"\",\n };\n }\n\n if (payloadV1.network !== requirements.network) {\n return {\n isValid: false,\n invalidReason: \"network_mismatch\",\n payer: \"\",\n };\n }\n\n if (!requirementsV1.extra?.feePayer || typeof requirementsV1.extra.feePayer !== \"string\") {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_missing_fee_payer\",\n payer: \"\",\n };\n }\n\n // Verify that the requested feePayer is managed by this facilitator\n const signerAddresses = this.signer.getAddresses().map(addr => addr.toString());\n if (!signerAddresses.includes(requirementsV1.extra.feePayer)) {\n return {\n isValid: false,\n invalidReason: \"fee_payer_not_managed_by_facilitator\",\n payer: \"\",\n };\n }\n\n // Step 2: Parse and Validate Transaction Structure\n let transaction;\n try {\n transaction = decodeTransactionFromPayload(exactSvmPayload);\n } catch {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_transaction_could_not_be_decoded\",\n payer: \"\",\n };\n }\n\n const compiled = getCompiledTransactionMessageDecoder().decode(transaction.messageBytes);\n const decompiled = decompileTransactionMessage(compiled);\n const instructions = decompiled.instructions ?? [];\n\n // 3 instructions: ComputeLimit + ComputePrice + TransferChecked\n if (instructions.length !== 3) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_transaction_instructions_length\",\n payer: \"\",\n };\n }\n\n // Step 3: Verify Compute Budget Instructions\n try {\n this.verifyComputeLimitInstruction(instructions[0] as never);\n this.verifyComputePriceInstruction(instructions[1] as never);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n isValid: false,\n invalidReason: errorMessage,\n payer: \"\",\n };\n }\n\n const payer = getTokenPayerFromTransaction(transaction);\n if (!payer) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_no_transfer_instruction\",\n payer: \"\",\n };\n }\n\n // Step 4: Verify Transfer Instruction\n const transferIx = instructions[2];\n const programAddress = transferIx.programAddress.toString();\n\n if (\n programAddress !== TOKEN_PROGRAM_ADDRESS.toString() &&\n programAddress !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_no_transfer_instruction\",\n payer,\n };\n }\n\n // Parse the transfer instruction using the appropriate library helper\n let parsedTransfer;\n try {\n if (programAddress === TOKEN_PROGRAM_ADDRESS.toString()) {\n parsedTransfer = parseTransferCheckedInstructionToken(transferIx as never);\n } else {\n parsedTransfer = parseTransferCheckedInstruction2022(transferIx as never);\n }\n } catch {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_no_transfer_instruction\",\n payer,\n };\n }\n\n // Verify that the facilitator's signers are not transferring their own funds\n // SECURITY: Prevent facilitator from signing away their own tokens\n const authorityAddress = parsedTransfer.accounts.authority.address.toString();\n if (signerAddresses.includes(authorityAddress)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_transaction_fee_payer_transferring_funds\",\n payer,\n };\n }\n\n // Verify mint address matches requirements\n const mintAddress = parsedTransfer.accounts.mint.address.toString();\n if (mintAddress !== requirements.asset) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_mint_mismatch\",\n payer,\n };\n }\n\n // Verify destination ATA matches expected ATA for payTo address\n const destATA = parsedTransfer.accounts.destination.address.toString();\n try {\n const [expectedDestATA] = await findAssociatedTokenPda({\n mint: requirements.asset as Address,\n owner: requirements.payTo as Address,\n tokenProgram:\n programAddress === TOKEN_PROGRAM_ADDRESS.toString()\n ? (TOKEN_PROGRAM_ADDRESS as Address)\n : (TOKEN_2022_PROGRAM_ADDRESS as Address),\n });\n\n if (destATA !== expectedDestATA.toString()) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_recipient_mismatch\",\n payer,\n };\n }\n } catch {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_recipient_mismatch\",\n payer,\n };\n }\n\n // Verify transfer amount meets requirements\n const amount = parsedTransfer.data.amount;\n if (amount < BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_svm_payload_amount_insufficient\",\n payer,\n };\n }\n\n // Step 5: Sign and Simulate Transaction\n // CRITICAL: Simulation proves transaction will succeed (catches insufficient balance, invalid accounts, etc)\n try {\n const feePayer = requirementsV1.extra.feePayer as Address;\n\n // Sign transaction with the feePayer's signer\n const fullySignedTransaction = await this.signer.signTransaction(\n exactSvmPayload.transaction,\n feePayer,\n requirements.network,\n );\n\n // Simulate to verify transaction would succeed\n await this.signer.simulateTransaction(fullySignedTransaction, requirements.network);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n isValid: false,\n invalidReason: `transaction_simulation_failed: ${errorMessage}`,\n payer,\n };\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer,\n };\n }\n\n /**\n * Settles a payment by submitting the transaction (V1).\n * Ensures the correct signer is used based on the feePayer specified in requirements.\n *\n * @param payload - The payment payload to settle\n * @param requirements - The payment requirements\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactSvmPayload = payload.payload as ExactSvmPayloadV1;\n\n const valid = await this.verify(payload, requirements);\n if (!valid.isValid) {\n return {\n success: false,\n network: payloadV1.network,\n transaction: \"\",\n errorReason: valid.invalidReason ?? \"verification_failed\",\n payer: valid.payer || \"\",\n };\n }\n\n try {\n // Extract feePayer from requirements (already validated in verify)\n const feePayer = requirements.extra.feePayer as Address;\n\n // Sign transaction with the feePayer's signer\n const fullySignedTransaction = await this.signer.signTransaction(\n exactSvmPayload.transaction,\n feePayer,\n requirements.network,\n );\n\n // Send transaction to network\n const signature = await this.signer.sendTransaction(\n fullySignedTransaction,\n requirements.network,\n );\n\n // Wait for confirmation\n await this.signer.confirmTransaction(signature, requirements.network);\n\n return {\n success: true,\n transaction: signature,\n network: payloadV1.network,\n payer: valid.payer,\n };\n } catch (error) {\n console.error(\"Failed to settle transaction:\", error);\n return {\n success: false,\n errorReason: \"transaction_failed\",\n transaction: \"\",\n network: payloadV1.network,\n payer: valid.payer || \"\",\n };\n }\n }\n\n /**\n * Verify compute limit instruction\n *\n * @param instruction - The compute limit instruction\n * @param instruction.programAddress - Program address\n * @param instruction.data - Instruction data bytes\n */\n private verifyComputeLimitInstruction(instruction: {\n programAddress: Address;\n data?: Readonly<Uint8Array>;\n }): void {\n const programAddress = instruction.programAddress.toString();\n\n if (\n programAddress !== COMPUTE_BUDGET_PROGRAM_ADDRESS.toString() ||\n !instruction.data ||\n instruction.data[0] !== 2\n ) {\n throw new Error(\n \"invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction\",\n );\n }\n\n try {\n parseSetComputeUnitLimitInstruction(instruction as never);\n } catch {\n throw new Error(\n \"invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction\",\n );\n }\n }\n\n /**\n * Verify compute price instruction\n *\n * @param instruction - The compute price instruction\n * @param instruction.programAddress - Program address\n * @param instruction.data - Instruction data bytes\n */\n private verifyComputePriceInstruction(instruction: {\n programAddress: Address;\n data?: Readonly<Uint8Array>;\n }): void {\n const programAddress = instruction.programAddress.toString();\n\n if (\n programAddress !== COMPUTE_BUDGET_PROGRAM_ADDRESS.toString() ||\n !instruction.data ||\n instruction.data[0] !== 3\n ) {\n throw new Error(\n \"invalid_exact_svm_payload_transaction_instructions_compute_price_instruction\",\n );\n }\n\n try {\n const parsedInstruction = parseSetComputeUnitPriceInstruction(instruction as never);\n\n // Check if price exceeds maximum (5 lamports per compute unit)\n if (\n (parsedInstruction as unknown as { microLamports: bigint }).microLamports >\n BigInt(MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS)\n ) {\n throw new Error(\n \"invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high\",\n );\n }\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"too_high\")) {\n throw error;\n }\n throw new Error(\n \"invalid_exact_svm_payload_transaction_instructions_compute_price_instruction\",\n );\n }\n }\n}\n","/**\n * Token program addresses for SPL Token and Token-2022\n * These addresses are the same across all Solana networks (mainnet, devnet, testnet)\n */\nexport const TOKEN_PROGRAM_ADDRESS = \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\";\nexport const TOKEN_2022_PROGRAM_ADDRESS = \"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb\";\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS = \"ComputeBudget111111111111111111111111111111\";\n\n/**\n * Default RPC URLs for Solana networks\n */\nexport const DEVNET_RPC_URL = \"https://api.devnet.solana.com\";\nexport const TESTNET_RPC_URL = \"https://api.testnet.solana.com\";\nexport const MAINNET_RPC_URL = \"https://api.mainnet-beta.solana.com\";\nexport const DEVNET_WS_URL = \"wss://api.devnet.solana.com\";\nexport const TESTNET_WS_URL = \"wss://api.testnet.solana.com\";\nexport const MAINNET_WS_URL = \"wss://api.mainnet-beta.solana.com\";\n\n/**\n * USDC token mint addresses (default stablecoin)\n */\nexport const USDC_MAINNET_ADDRESS = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\";\nexport const USDC_DEVNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\";\nexport const USDC_TESTNET_ADDRESS = \"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU\"; // Same as devnet\n\n/**\n * Compute budget configuration\n * All prices are in microlamports (1 lamport = 1,000,000 microlamports)\n */\nexport const DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;\nexport const MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 5_000_000; // 5 lamports\nexport const DEFAULT_COMPUTE_UNIT_LIMIT = 6500;\n\n/**\n * Solana address validation regex (base58, 32-44 characters)\n */\nexport const SVM_ADDRESS_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * CAIP-2 network identifiers for Solana (V2)\n */\nexport const SOLANA_MAINNET_CAIP2 = \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\";\nexport const SOLANA_DEVNET_CAIP2 = \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\";\nexport const SOLANA_TESTNET_CAIP2 = \"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z\";\n\n/**\n * V1 to V2 network identifier mappings (for backwards compatibility)\n * V1 used simple names like solana, V2 uses CAIP-2\n */\nexport const V1_TO_V2_NETWORK_MAP: Record<string, string> = {\n solana: SOLANA_MAINNET_CAIP2,\n \"solana-devnet\": SOLANA_DEVNET_CAIP2,\n \"solana-testnet\": SOLANA_TESTNET_CAIP2,\n};\n","import {\n getBase64Encoder,\n getTransactionDecoder,\n getCompiledTransactionMessageDecoder,\n type Transaction,\n createSolanaRpc,\n devnet,\n testnet,\n mainnet,\n type RpcDevnet,\n type SolanaRpcApiDevnet,\n type RpcTestnet,\n type SolanaRpcApiTestnet,\n type RpcMainnet,\n type SolanaRpcApiMainnet,\n} from \"@solana/kit\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport { TOKEN_2022_PROGRAM_ADDRESS } from \"@solana-program/token-2022\";\nimport type { Network } from \"@x402/core/types\";\nimport {\n SVM_ADDRESS_REGEX,\n DEVNET_RPC_URL,\n TESTNET_RPC_URL,\n MAINNET_RPC_URL,\n USDC_MAINNET_ADDRESS,\n USDC_DEVNET_ADDRESS,\n USDC_TESTNET_ADDRESS,\n SOLANA_MAINNET_CAIP2,\n SOLANA_DEVNET_CAIP2,\n SOLANA_TESTNET_CAIP2,\n V1_TO_V2_NETWORK_MAP,\n} from \"./constants\";\nimport type { ExactSvmPayloadV1 } from \"./types\";\n\n/**\n * Normalize network identifier to CAIP-2 format\n * Handles both V1 names (solana, solana-devnet) and V2 CAIP-2 format\n *\n * @param network - Network identifier (V1 or V2 format)\n * @returns CAIP-2 network identifier\n */\nexport function normalizeNetwork(network: Network): string {\n // If it's already CAIP-2 format (contains \":\"), validate it's supported\n if (network.includes(\":\")) {\n const supported = [SOLANA_MAINNET_CAIP2, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2];\n if (!supported.includes(network)) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return network;\n }\n\n // Otherwise, it's a V1 network name, convert to CAIP-2\n const caip2Network = V1_TO_V2_NETWORK_MAP[network];\n if (!caip2Network) {\n throw new Error(`Unsupported SVM network: ${network}`);\n }\n return caip2Network;\n}\n\n/**\n * Validate Solana address format\n *\n * @param address - Base58 encoded address string\n * @returns true if address is valid, false otherwise\n */\nexport function validateSvmAddress(address: string): boolean {\n return SVM_ADDRESS_REGEX.test(address);\n}\n\n/**\n * Decode a base64 encoded transaction from an SVM payload\n *\n * @param svmPayload - The SVM payload containing a base64 encoded transaction\n * @returns Decoded Transaction object\n */\nexport function decodeTransactionFromPayload(svmPayload: ExactSvmPayloadV1): Transaction {\n try {\n const base64Encoder = getBase64Encoder();\n const transactionBytes = base64Encoder.encode(svmPayload.transaction);\n const transactionDecoder = getTransactionDecoder();\n return transactionDecoder.decode(transactionBytes);\n } catch (error) {\n console.error(\"Error decoding transaction:\", error);\n throw new Error(\"invalid_exact_svm_payload_transaction\");\n }\n}\n\n/**\n * Extract the token sender (owner of the source token account) from a TransferChecked instruction\n *\n * @param transaction - The decoded transaction\n * @returns The token payer address as a base58 string\n */\nexport function getTokenPayerFromTransaction(transaction: Transaction): string {\n const compiled = getCompiledTransactionMessageDecoder().decode(transaction.messageBytes);\n const staticAccounts = compiled.staticAccounts ?? [];\n const instructions = compiled.instructions ?? [];\n\n for (const ix of instructions) {\n const programIndex = ix.programAddressIndex;\n const programAddress = staticAccounts[programIndex].toString();\n\n // Check if this is a token program instruction\n if (\n programAddress === TOKEN_PROGRAM_ADDRESS.toString() ||\n programAddress === TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n const accountIndices: number[] = ix.accountIndices ?? [];\n // TransferChecked account order: [source, mint, destination, owner, ...]\n if (accountIndices.length >= 4) {\n const ownerIndex = accountIndices[3];\n const ownerAddress = staticAccounts[ownerIndex].toString();\n if (ownerAddress) return ownerAddress;\n }\n }\n }\n\n return \"\";\n}\n\n/**\n * Create an RPC client for the specified network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @param customRpcUrl - Optional custom RPC URL\n * @returns RPC client for the specified network\n */\nexport function createRpcClient(\n network: Network,\n customRpcUrl?: string,\n):\n | RpcDevnet<SolanaRpcApiDevnet>\n | RpcTestnet<SolanaRpcApiTestnet>\n | RpcMainnet<SolanaRpcApiMainnet> {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_DEVNET_CAIP2: {\n const url = customRpcUrl || DEVNET_RPC_URL;\n return createSolanaRpc(devnet(url)) as RpcDevnet<SolanaRpcApiDevnet>;\n }\n case SOLANA_TESTNET_CAIP2: {\n const url = customRpcUrl || TESTNET_RPC_URL;\n return createSolanaRpc(testnet(url)) as RpcTestnet<SolanaRpcApiTestnet>;\n }\n case SOLANA_MAINNET_CAIP2: {\n const url = customRpcUrl || MAINNET_RPC_URL;\n return createSolanaRpc(mainnet(url)) as RpcMainnet<SolanaRpcApiMainnet>;\n }\n default:\n throw new Error(`Unsupported network: ${network}`);\n }\n}\n\n/**\n * Get the default USDC mint address for a network\n *\n * @param network - Network identifier (CAIP-2 or V1 format)\n * @returns USDC mint address for the network\n */\nexport function getUsdcAddress(network: Network): string {\n const caip2Network = normalizeNetwork(network);\n\n switch (caip2Network) {\n case SOLANA_MAINNET_CAIP2:\n return USDC_MAINNET_ADDRESS;\n case SOLANA_DEVNET_CAIP2:\n return USDC_DEVNET_ADDRESS;\n case SOLANA_TESTNET_CAIP2:\n return USDC_TESTNET_ADDRESS;\n default:\n throw new Error(`No USDC address configured for network: ${network}`);\n }\n}\n\n/**\n * Convert a decimal amount to token smallest units\n *\n * @param decimalAmount - The decimal amount (e.g., \"0.10\")\n * @param decimals - The number of decimals for the token (e.g., 6 for USDC)\n * @returns The amount in smallest units as a string\n */\nexport function convertToTokenAmount(decimalAmount: string, decimals: number): string {\n const amount = parseFloat(decimalAmount);\n if (isNaN(amount)) {\n throw new Error(`Invalid amount: ${decimalAmount}`);\n }\n // Convert to smallest unit (e.g., for USDC with 6 decimals: 0.10 * 10^6 = 100000)\n const [intPart, decPart = \"\"] = String(amount).split(\".\");\n const paddedDec = decPart.padEnd(decimals, \"0\").slice(0, decimals);\n const tokenAmount = (intPart + paddedDec).replace(/^0+/, \"\") || \"0\";\n return tokenAmount;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,4BAIO;AACP,IAAAA,gBAGO;AACP,IAAAC,qBAIO;AACP,IAAAC,cAIO;;;ACYA,IAAM,uCAAuC;;;AC9BpD,iBAeO;AACP,mBAAsC;AACtC,wBAA2C;AA0DpC,SAAS,6BAA6B,YAA4C;AACvF,MAAI;AACF,UAAM,oBAAgB,6BAAiB;AACvC,UAAM,mBAAmB,cAAc,OAAO,WAAW,WAAW;AACpE,UAAM,yBAAqB,kCAAsB;AACjD,WAAO,mBAAmB,OAAO,gBAAgB;AAAA,EACnD,SAAS,OAAO;AACd,YAAQ,MAAM,+BAA+B,KAAK;AAClD,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AACF;AAQO,SAAS,6BAA6B,aAAkC;AAC7E,QAAM,eAAW,iDAAqC,EAAE,OAAO,YAAY,YAAY;AACvF,QAAM,iBAAiB,SAAS,kBAAkB,CAAC;AACnD,QA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,QACR;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["import_token","import_token_2022","import_kit","parseTransferCheckedInstructionToken","parseTransferCheckedInstruction2022"]}
@@ -1,192 +0,0 @@
1
- import { P as PaymentPayload, a as PaymentRequirements, V as VerifyResponse, S as SettleResponse, N as Network, b as SchemeNetworkFacilitator } from '../mechanisms-CzuGzYsS.js';
2
-
3
- /**
4
- * Facilitator Hook Context Interfaces
5
- */
6
- interface FacilitatorVerifyContext {
7
- paymentPayload: PaymentPayload;
8
- requirements: PaymentRequirements;
9
- }
10
- interface FacilitatorVerifyResultContext extends FacilitatorVerifyContext {
11
- result: VerifyResponse;
12
- }
13
- interface FacilitatorVerifyFailureContext extends FacilitatorVerifyContext {
14
- error: Error;
15
- }
16
- interface FacilitatorSettleContext {
17
- paymentPayload: PaymentPayload;
18
- requirements: PaymentRequirements;
19
- }
20
- interface FacilitatorSettleResultContext extends FacilitatorSettleContext {
21
- result: SettleResponse;
22
- }
23
- interface FacilitatorSettleFailureContext extends FacilitatorSettleContext {
24
- error: Error;
25
- }
26
- /**
27
- * Facilitator Hook Type Definitions
28
- */
29
- type FacilitatorBeforeVerifyHook = (context: FacilitatorVerifyContext) => Promise<void | {
30
- abort: true;
31
- reason: string;
32
- }>;
33
- type FacilitatorAfterVerifyHook = (context: FacilitatorVerifyResultContext) => Promise<void>;
34
- type FacilitatorOnVerifyFailureHook = (context: FacilitatorVerifyFailureContext) => Promise<void | {
35
- recovered: true;
36
- result: VerifyResponse;
37
- }>;
38
- type FacilitatorBeforeSettleHook = (context: FacilitatorSettleContext) => Promise<void | {
39
- abort: true;
40
- reason: string;
41
- }>;
42
- type FacilitatorAfterSettleHook = (context: FacilitatorSettleResultContext) => Promise<void>;
43
- type FacilitatorOnSettleFailureHook = (context: FacilitatorSettleFailureContext) => Promise<void | {
44
- recovered: true;
45
- result: SettleResponse;
46
- }>;
47
- /**
48
- * Facilitator client for the x402 payment protocol.
49
- * Manages payment scheme registration, verification, and settlement.
50
- */
51
- declare class x402Facilitator {
52
- private readonly registeredFacilitatorSchemes;
53
- private readonly extensions;
54
- private beforeVerifyHooks;
55
- private afterVerifyHooks;
56
- private onVerifyFailureHooks;
57
- private beforeSettleHooks;
58
- private afterSettleHooks;
59
- private onSettleFailureHooks;
60
- /**
61
- * Registers a scheme facilitator for the current x402 version.
62
- * Networks are stored and used for getSupported() - no need to specify them later.
63
- *
64
- * @param networks - Single network or array of networks this facilitator supports
65
- * @param facilitator - The scheme network facilitator to register
66
- * @returns The x402Facilitator instance for chaining
67
- */
68
- register(networks: Network | Network[], facilitator: SchemeNetworkFacilitator): x402Facilitator;
69
- /**
70
- * Registers a scheme facilitator for x402 version 1.
71
- * Networks are stored and used for getSupported() - no need to specify them later.
72
- *
73
- * @param networks - Single network or array of networks this facilitator supports
74
- * @param facilitator - The scheme network facilitator to register
75
- * @returns The x402Facilitator instance for chaining
76
- */
77
- registerV1(networks: Network | Network[], facilitator: SchemeNetworkFacilitator): x402Facilitator;
78
- /**
79
- * Registers a protocol extension.
80
- *
81
- * @param extension - The extension name to register (e.g., "bazaar", "sign_in_with_x")
82
- * @returns The x402Facilitator instance for chaining
83
- */
84
- registerExtension(extension: string): x402Facilitator;
85
- /**
86
- * Gets the list of registered extensions.
87
- *
88
- * @returns Array of extension names
89
- */
90
- getExtensions(): string[];
91
- /**
92
- * Register a hook to execute before facilitator payment verification.
93
- * Can abort verification by returning { abort: true, reason: string }
94
- *
95
- * @param hook - The hook function to register
96
- * @returns The x402Facilitator instance for chaining
97
- */
98
- onBeforeVerify(hook: FacilitatorBeforeVerifyHook): x402Facilitator;
99
- /**
100
- * Register a hook to execute after successful facilitator payment verification (isValid: true).
101
- * This hook is NOT called when verification fails (isValid: false) - use onVerifyFailure for that.
102
- *
103
- * @param hook - The hook function to register
104
- * @returns The x402Facilitator instance for chaining
105
- */
106
- onAfterVerify(hook: FacilitatorAfterVerifyHook): x402Facilitator;
107
- /**
108
- * Register a hook to execute when facilitator payment verification fails.
109
- * Called when: verification returns isValid: false, or an exception is thrown during verification.
110
- * Can recover from failure by returning { recovered: true, result: VerifyResponse }
111
- *
112
- * @param hook - The hook function to register
113
- * @returns The x402Facilitator instance for chaining
114
- */
115
- onVerifyFailure(hook: FacilitatorOnVerifyFailureHook): x402Facilitator;
116
- /**
117
- * Register a hook to execute before facilitator payment settlement.
118
- * Can abort settlement by returning { abort: true, reason: string }
119
- *
120
- * @param hook - The hook function to register
121
- * @returns The x402Facilitator instance for chaining
122
- */
123
- onBeforeSettle(hook: FacilitatorBeforeSettleHook): x402Facilitator;
124
- /**
125
- * Register a hook to execute after successful facilitator payment settlement.
126
- *
127
- * @param hook - The hook function to register
128
- * @returns The x402Facilitator instance for chaining
129
- */
130
- onAfterSettle(hook: FacilitatorAfterSettleHook): x402Facilitator;
131
- /**
132
- * Register a hook to execute when facilitator payment settlement fails.
133
- * Can recover from failure by returning { recovered: true, result: SettleResponse }
134
- *
135
- * @param hook - The hook function to register
136
- * @returns The x402Facilitator instance for chaining
137
- */
138
- onSettleFailure(hook: FacilitatorOnSettleFailureHook): x402Facilitator;
139
- /**
140
- * Gets supported payment kinds, extensions, and signers.
141
- * Uses networks registered during register() calls - no parameters needed.
142
- * Returns flat array format for backward compatibility with V1 clients.
143
- *
144
- * @returns Supported response with kinds as array (with version in each element), extensions, and signers
145
- */
146
- getSupported(): {
147
- kinds: Array<{
148
- x402Version: number;
149
- scheme: string;
150
- network: string;
151
- extra?: Record<string, unknown>;
152
- }>;
153
- extensions: string[];
154
- signers: Record<string, string[]>;
155
- };
156
- /**
157
- * Verifies a payment payload against requirements.
158
- *
159
- * @param paymentPayload - The payment payload to verify
160
- * @param paymentRequirements - The payment requirements to verify against
161
- * @returns Promise resolving to the verification response
162
- */
163
- verify(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<VerifyResponse>;
164
- /**
165
- * Settles a payment based on the payload and requirements.
166
- *
167
- * @param paymentPayload - The payment payload to settle
168
- * @param paymentRequirements - The payment requirements for settlement
169
- * @returns Promise resolving to the settlement response
170
- */
171
- settle(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements): Promise<SettleResponse>;
172
- /**
173
- * Internal method to register a scheme facilitator.
174
- *
175
- * @param x402Version - The x402 protocol version
176
- * @param networks - Array of concrete networks this facilitator supports
177
- * @param facilitator - The scheme network facilitator to register
178
- * @returns The x402Facilitator instance for chaining
179
- */
180
- private _registerScheme;
181
- /**
182
- * Derives a wildcard pattern from an array of networks.
183
- * If all networks share the same namespace, returns wildcard pattern.
184
- * Otherwise returns the first network for exact matching.
185
- *
186
- * @param networks - Array of networks
187
- * @returns Derived pattern for matching
188
- */
189
- private derivePattern;
190
- }
191
-
192
- export { type FacilitatorAfterSettleHook, type FacilitatorAfterVerifyHook, type FacilitatorBeforeSettleHook, type FacilitatorBeforeVerifyHook, type FacilitatorOnSettleFailureHook, type FacilitatorOnVerifyFailureHook, type FacilitatorSettleContext, type FacilitatorSettleFailureContext, type FacilitatorSettleResultContext, type FacilitatorVerifyContext, type FacilitatorVerifyFailureContext, type FacilitatorVerifyResultContext, x402Facilitator };
@@ -1,398 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/facilitator/index.ts
21
- var facilitator_exports = {};
22
- __export(facilitator_exports, {
23
- x402Facilitator: () => x402Facilitator
24
- });
25
- module.exports = __toCommonJS(facilitator_exports);
26
-
27
- // src/index.ts
28
- var x402Version = 2;
29
-
30
- // src/facilitator/x402Facilitator.ts
31
- var x402Facilitator = class {
32
- constructor() {
33
- this.registeredFacilitatorSchemes = /* @__PURE__ */ new Map();
34
- this.extensions = [];
35
- this.beforeVerifyHooks = [];
36
- this.afterVerifyHooks = [];
37
- this.onVerifyFailureHooks = [];
38
- this.beforeSettleHooks = [];
39
- this.afterSettleHooks = [];
40
- this.onSettleFailureHooks = [];
41
- }
42
- /**
43
- * Registers a scheme facilitator for the current x402 version.
44
- * Networks are stored and used for getSupported() - no need to specify them later.
45
- *
46
- * @param networks - Single network or array of networks this facilitator supports
47
- * @param facilitator - The scheme network facilitator to register
48
- * @returns The x402Facilitator instance for chaining
49
- */
50
- register(networks, facilitator) {
51
- const networksArray = Array.isArray(networks) ? networks : [networks];
52
- return this._registerScheme(x402Version, networksArray, facilitator);
53
- }
54
- /**
55
- * Registers a scheme facilitator for x402 version 1.
56
- * Networks are stored and used for getSupported() - no need to specify them later.
57
- *
58
- * @param networks - Single network or array of networks this facilitator supports
59
- * @param facilitator - The scheme network facilitator to register
60
- * @returns The x402Facilitator instance for chaining
61
- */
62
- registerV1(networks, facilitator) {
63
- const networksArray = Array.isArray(networks) ? networks : [networks];
64
- return this._registerScheme(1, networksArray, facilitator);
65
- }
66
- /**
67
- * Registers a protocol extension.
68
- *
69
- * @param extension - The extension name to register (e.g., "bazaar", "sign_in_with_x")
70
- * @returns The x402Facilitator instance for chaining
71
- */
72
- registerExtension(extension) {
73
- if (!this.extensions.includes(extension)) {
74
- this.extensions.push(extension);
75
- }
76
- return this;
77
- }
78
- /**
79
- * Gets the list of registered extensions.
80
- *
81
- * @returns Array of extension names
82
- */
83
- getExtensions() {
84
- return [...this.extensions];
85
- }
86
- /**
87
- * Register a hook to execute before facilitator payment verification.
88
- * Can abort verification by returning { abort: true, reason: string }
89
- *
90
- * @param hook - The hook function to register
91
- * @returns The x402Facilitator instance for chaining
92
- */
93
- onBeforeVerify(hook) {
94
- this.beforeVerifyHooks.push(hook);
95
- return this;
96
- }
97
- /**
98
- * Register a hook to execute after successful facilitator payment verification (isValid: true).
99
- * This hook is NOT called when verification fails (isValid: false) - use onVerifyFailure for that.
100
- *
101
- * @param hook - The hook function to register
102
- * @returns The x402Facilitator instance for chaining
103
- */
104
- onAfterVerify(hook) {
105
- this.afterVerifyHooks.push(hook);
106
- return this;
107
- }
108
- /**
109
- * Register a hook to execute when facilitator payment verification fails.
110
- * Called when: verification returns isValid: false, or an exception is thrown during verification.
111
- * Can recover from failure by returning { recovered: true, result: VerifyResponse }
112
- *
113
- * @param hook - The hook function to register
114
- * @returns The x402Facilitator instance for chaining
115
- */
116
- onVerifyFailure(hook) {
117
- this.onVerifyFailureHooks.push(hook);
118
- return this;
119
- }
120
- /**
121
- * Register a hook to execute before facilitator payment settlement.
122
- * Can abort settlement by returning { abort: true, reason: string }
123
- *
124
- * @param hook - The hook function to register
125
- * @returns The x402Facilitator instance for chaining
126
- */
127
- onBeforeSettle(hook) {
128
- this.beforeSettleHooks.push(hook);
129
- return this;
130
- }
131
- /**
132
- * Register a hook to execute after successful facilitator payment settlement.
133
- *
134
- * @param hook - The hook function to register
135
- * @returns The x402Facilitator instance for chaining
136
- */
137
- onAfterSettle(hook) {
138
- this.afterSettleHooks.push(hook);
139
- return this;
140
- }
141
- /**
142
- * Register a hook to execute when facilitator payment settlement fails.
143
- * Can recover from failure by returning { recovered: true, result: SettleResponse }
144
- *
145
- * @param hook - The hook function to register
146
- * @returns The x402Facilitator instance for chaining
147
- */
148
- onSettleFailure(hook) {
149
- this.onSettleFailureHooks.push(hook);
150
- return this;
151
- }
152
- /**
153
- * Gets supported payment kinds, extensions, and signers.
154
- * Uses networks registered during register() calls - no parameters needed.
155
- * Returns flat array format for backward compatibility with V1 clients.
156
- *
157
- * @returns Supported response with kinds as array (with version in each element), extensions, and signers
158
- */
159
- getSupported() {
160
- const kinds = [];
161
- const signersByFamily = {};
162
- for (const [version, schemeDataArray] of this.registeredFacilitatorSchemes) {
163
- for (const schemeData of schemeDataArray) {
164
- const { facilitator, networks } = schemeData;
165
- const scheme = facilitator.scheme;
166
- for (const network of networks) {
167
- const extra = facilitator.getExtra(network);
168
- kinds.push({
169
- x402Version: version,
170
- scheme,
171
- network,
172
- ...extra && { extra }
173
- });
174
- const family = facilitator.caipFamily;
175
- if (!signersByFamily[family]) {
176
- signersByFamily[family] = /* @__PURE__ */ new Set();
177
- }
178
- facilitator.getSigners(network).forEach((signer) => signersByFamily[family].add(signer));
179
- }
180
- }
181
- }
182
- const signers = {};
183
- for (const [family, signerSet] of Object.entries(signersByFamily)) {
184
- signers[family] = Array.from(signerSet);
185
- }
186
- return {
187
- kinds,
188
- extensions: this.extensions,
189
- signers
190
- };
191
- }
192
- /**
193
- * Verifies a payment payload against requirements.
194
- *
195
- * @param paymentPayload - The payment payload to verify
196
- * @param paymentRequirements - The payment requirements to verify against
197
- * @returns Promise resolving to the verification response
198
- */
199
- async verify(paymentPayload, paymentRequirements) {
200
- const context = {
201
- paymentPayload,
202
- requirements: paymentRequirements
203
- };
204
- for (const hook of this.beforeVerifyHooks) {
205
- const result = await hook(context);
206
- if (result && "abort" in result && result.abort) {
207
- return {
208
- isValid: false,
209
- invalidReason: result.reason
210
- };
211
- }
212
- }
213
- try {
214
- const schemeDataArray = this.registeredFacilitatorSchemes.get(paymentPayload.x402Version);
215
- if (!schemeDataArray) {
216
- throw new Error(
217
- `No facilitator registered for x402 version: ${paymentPayload.x402Version}`
218
- );
219
- }
220
- let schemeNetworkFacilitator;
221
- for (const schemeData of schemeDataArray) {
222
- if (schemeData.facilitator.scheme === paymentRequirements.scheme) {
223
- if (schemeData.networks.has(paymentRequirements.network)) {
224
- schemeNetworkFacilitator = schemeData.facilitator;
225
- break;
226
- }
227
- const patternRegex = new RegExp("^" + schemeData.pattern.replace("*", ".*") + "$");
228
- if (patternRegex.test(paymentRequirements.network)) {
229
- schemeNetworkFacilitator = schemeData.facilitator;
230
- break;
231
- }
232
- }
233
- }
234
- if (!schemeNetworkFacilitator) {
235
- throw new Error(
236
- `No facilitator registered for scheme: ${paymentRequirements.scheme} and network: ${paymentRequirements.network}`
237
- );
238
- }
239
- const verifyResult = await schemeNetworkFacilitator.verify(
240
- paymentPayload,
241
- paymentRequirements
242
- );
243
- if (!verifyResult.isValid) {
244
- const failureContext = {
245
- ...context,
246
- error: new Error(verifyResult.invalidReason || "Verification failed")
247
- };
248
- for (const hook of this.onVerifyFailureHooks) {
249
- const result = await hook(failureContext);
250
- if (result && "recovered" in result && result.recovered) {
251
- const recoveredContext = {
252
- ...context,
253
- result: result.result
254
- };
255
- for (const hook2 of this.afterVerifyHooks) {
256
- await hook2(recoveredContext);
257
- }
258
- return result.result;
259
- }
260
- }
261
- return verifyResult;
262
- }
263
- const resultContext = {
264
- ...context,
265
- result: verifyResult
266
- };
267
- for (const hook of this.afterVerifyHooks) {
268
- await hook(resultContext);
269
- }
270
- return verifyResult;
271
- } catch (error) {
272
- const failureContext = {
273
- ...context,
274
- error
275
- };
276
- for (const hook of this.onVerifyFailureHooks) {
277
- const result = await hook(failureContext);
278
- if (result && "recovered" in result && result.recovered) {
279
- return result.result;
280
- }
281
- }
282
- throw error;
283
- }
284
- }
285
- /**
286
- * Settles a payment based on the payload and requirements.
287
- *
288
- * @param paymentPayload - The payment payload to settle
289
- * @param paymentRequirements - The payment requirements for settlement
290
- * @returns Promise resolving to the settlement response
291
- */
292
- async settle(paymentPayload, paymentRequirements) {
293
- const context = {
294
- paymentPayload,
295
- requirements: paymentRequirements
296
- };
297
- for (const hook of this.beforeSettleHooks) {
298
- const result = await hook(context);
299
- if (result && "abort" in result && result.abort) {
300
- throw new Error(`Settlement aborted: ${result.reason}`);
301
- }
302
- }
303
- try {
304
- const schemeDataArray = this.registeredFacilitatorSchemes.get(paymentPayload.x402Version);
305
- if (!schemeDataArray) {
306
- throw new Error(
307
- `No facilitator registered for x402 version: ${paymentPayload.x402Version}`
308
- );
309
- }
310
- let schemeNetworkFacilitator;
311
- for (const schemeData of schemeDataArray) {
312
- if (schemeData.facilitator.scheme === paymentRequirements.scheme) {
313
- if (schemeData.networks.has(paymentRequirements.network)) {
314
- schemeNetworkFacilitator = schemeData.facilitator;
315
- break;
316
- }
317
- const patternRegex = new RegExp("^" + schemeData.pattern.replace("*", ".*") + "$");
318
- if (patternRegex.test(paymentRequirements.network)) {
319
- schemeNetworkFacilitator = schemeData.facilitator;
320
- break;
321
- }
322
- }
323
- }
324
- if (!schemeNetworkFacilitator) {
325
- throw new Error(
326
- `No facilitator registered for scheme: ${paymentRequirements.scheme} and network: ${paymentRequirements.network}`
327
- );
328
- }
329
- const settleResult = await schemeNetworkFacilitator.settle(
330
- paymentPayload,
331
- paymentRequirements
332
- );
333
- const resultContext = {
334
- ...context,
335
- result: settleResult
336
- };
337
- for (const hook of this.afterSettleHooks) {
338
- await hook(resultContext);
339
- }
340
- return settleResult;
341
- } catch (error) {
342
- const failureContext = {
343
- ...context,
344
- error
345
- };
346
- for (const hook of this.onSettleFailureHooks) {
347
- const result = await hook(failureContext);
348
- if (result && "recovered" in result && result.recovered) {
349
- return result.result;
350
- }
351
- }
352
- throw error;
353
- }
354
- }
355
- /**
356
- * Internal method to register a scheme facilitator.
357
- *
358
- * @param x402Version - The x402 protocol version
359
- * @param networks - Array of concrete networks this facilitator supports
360
- * @param facilitator - The scheme network facilitator to register
361
- * @returns The x402Facilitator instance for chaining
362
- */
363
- _registerScheme(x402Version2, networks, facilitator) {
364
- if (!this.registeredFacilitatorSchemes.has(x402Version2)) {
365
- this.registeredFacilitatorSchemes.set(x402Version2, []);
366
- }
367
- const schemeDataArray = this.registeredFacilitatorSchemes.get(x402Version2);
368
- schemeDataArray.push({
369
- facilitator,
370
- networks: new Set(networks),
371
- pattern: this.derivePattern(networks)
372
- });
373
- return this;
374
- }
375
- /**
376
- * Derives a wildcard pattern from an array of networks.
377
- * If all networks share the same namespace, returns wildcard pattern.
378
- * Otherwise returns the first network for exact matching.
379
- *
380
- * @param networks - Array of networks
381
- * @returns Derived pattern for matching
382
- */
383
- derivePattern(networks) {
384
- if (networks.length === 0) return "";
385
- if (networks.length === 1) return networks[0];
386
- const namespaces = networks.map((n) => n.split(":")[0]);
387
- const uniqueNamespaces = new Set(namespaces);
388
- if (uniqueNamespaces.size === 1) {
389
- return `${namespaces[0]}:*`;
390
- }
391
- return networks[0];
392
- }
393
- };
394
- // Annotate the CommonJS export names for ESM import in node:
395
- 0 && (module.exports = {
396
- x402Facilitator
397
- });
398
- //# sourceMappingURL=index.js.map