@t402/btc 2.7.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.
Files changed (62) hide show
  1. package/README.md +120 -0
  2. package/dist/cjs/exact/client/index.d.ts +89 -0
  3. package/dist/cjs/exact/client/index.js +145 -0
  4. package/dist/cjs/exact/client/index.js.map +1 -0
  5. package/dist/cjs/exact/facilitator/index.d.ts +114 -0
  6. package/dist/cjs/exact/facilitator/index.js +218 -0
  7. package/dist/cjs/exact/facilitator/index.js.map +1 -0
  8. package/dist/cjs/exact/server/index.d.ts +101 -0
  9. package/dist/cjs/exact/server/index.js +161 -0
  10. package/dist/cjs/exact/server/index.js.map +1 -0
  11. package/dist/cjs/index.d.ts +179 -0
  12. package/dist/cjs/index.js +849 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/lightning/client/index.d.ts +82 -0
  15. package/dist/cjs/lightning/client/index.js +114 -0
  16. package/dist/cjs/lightning/client/index.js.map +1 -0
  17. package/dist/cjs/lightning/facilitator/index.d.ts +93 -0
  18. package/dist/cjs/lightning/facilitator/index.js +211 -0
  19. package/dist/cjs/lightning/facilitator/index.js.map +1 -0
  20. package/dist/cjs/lightning/server/index.d.ts +96 -0
  21. package/dist/cjs/lightning/server/index.js +157 -0
  22. package/dist/cjs/lightning/server/index.js.map +1 -0
  23. package/dist/cjs/signer-B_Z4WGLa.d.ts +64 -0
  24. package/dist/esm/chunk-2DEKJ7ER.mjs +123 -0
  25. package/dist/esm/chunk-2DEKJ7ER.mjs.map +1 -0
  26. package/dist/esm/chunk-3IOPLDQH.mjs +74 -0
  27. package/dist/esm/chunk-3IOPLDQH.mjs.map +1 -0
  28. package/dist/esm/chunk-7IU3Z36R.mjs +103 -0
  29. package/dist/esm/chunk-7IU3Z36R.mjs.map +1 -0
  30. package/dist/esm/chunk-HNFWDITA.mjs +170 -0
  31. package/dist/esm/chunk-HNFWDITA.mjs.map +1 -0
  32. package/dist/esm/chunk-MX3PAUPJ.mjs +65 -0
  33. package/dist/esm/chunk-MX3PAUPJ.mjs.map +1 -0
  34. package/dist/esm/chunk-YJYTK2QQ.mjs +127 -0
  35. package/dist/esm/chunk-YJYTK2QQ.mjs.map +1 -0
  36. package/dist/esm/chunk-YWZC2RR7.mjs +38 -0
  37. package/dist/esm/chunk-YWZC2RR7.mjs.map +1 -0
  38. package/dist/esm/chunk-ZOL5R3HZ.mjs +177 -0
  39. package/dist/esm/chunk-ZOL5R3HZ.mjs.map +1 -0
  40. package/dist/esm/exact/client/index.d.mts +89 -0
  41. package/dist/esm/exact/client/index.mjs +11 -0
  42. package/dist/esm/exact/client/index.mjs.map +1 -0
  43. package/dist/esm/exact/facilitator/index.d.mts +114 -0
  44. package/dist/esm/exact/facilitator/index.mjs +11 -0
  45. package/dist/esm/exact/facilitator/index.mjs.map +1 -0
  46. package/dist/esm/exact/server/index.d.mts +101 -0
  47. package/dist/esm/exact/server/index.mjs +10 -0
  48. package/dist/esm/exact/server/index.mjs.map +1 -0
  49. package/dist/esm/index.d.mts +179 -0
  50. package/dist/esm/index.mjs +77 -0
  51. package/dist/esm/index.mjs.map +1 -0
  52. package/dist/esm/lightning/client/index.d.mts +82 -0
  53. package/dist/esm/lightning/client/index.mjs +11 -0
  54. package/dist/esm/lightning/client/index.mjs.map +1 -0
  55. package/dist/esm/lightning/facilitator/index.d.mts +93 -0
  56. package/dist/esm/lightning/facilitator/index.mjs +11 -0
  57. package/dist/esm/lightning/facilitator/index.mjs.map +1 -0
  58. package/dist/esm/lightning/server/index.d.mts +96 -0
  59. package/dist/esm/lightning/server/index.mjs +10 -0
  60. package/dist/esm/lightning/server/index.mjs.map +1 -0
  61. package/dist/esm/signer-B_Z4WGLa.d.mts +64 -0
  62. package/package.json +142 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts","../../src/constants.ts","../../src/utils.ts","../../src/exact/client/scheme.ts","../../src/exact/client/register.ts","../../src/lightning/client/scheme.ts","../../src/lightning/client/register.ts","../../src/exact/server/scheme.ts","../../src/exact/server/register.ts","../../src/exact/facilitator/scheme.ts","../../src/exact/facilitator/register.ts","../../src/lightning/server/scheme.ts","../../src/lightning/server/register.ts","../../src/lightning/facilitator/scheme.ts","../../src/lightning/facilitator/register.ts"],"sourcesContent":["/**\n * @module @t402/btc - t402 Payment Protocol Bitcoin & Lightning Network Implementation\n *\n * This module provides the Bitcoin-specific implementation of the t402 payment protocol.\n * Supports on-chain BTC payments (via PSBT) and Lightning Network payments (via BOLT11).\n *\n * Schemes:\n * - exact (on-chain): PSBT-based Bitcoin payments\n * - exact (lightning): BOLT11 invoice-based Lightning payments\n */\n\n// Export BTC exact scheme (client)\nexport { ExactBtcScheme } from './exact/index.js'\n\n// Export Lightning scheme (client)\nexport { LightningScheme } from './lightning/index.js'\n\n// Export register functions for easy integration\nexport { registerExactBtcScheme as registerExactBtcClientScheme } from './exact/client/index.js'\nexport type { BtcClientConfig } from './exact/client/index.js'\nexport { registerExactBtcScheme as registerExactBtcServerScheme } from './exact/server/index.js'\nexport type { BtcResourceServerConfig } from './exact/server/index.js'\nexport { registerExactBtcScheme as registerExactBtcFacilitatorScheme } from './exact/facilitator/index.js'\nexport type { BtcFacilitatorConfig } from './exact/facilitator/index.js'\n\nexport { registerLightningScheme as registerLightningClientScheme } from './lightning/client/index.js'\nexport type { LightningClientConfig } from './lightning/client/index.js'\nexport { registerLightningScheme as registerLightningServerScheme } from './lightning/server/index.js'\nexport type { LightningResourceServerConfig } from './lightning/server/index.js'\nexport { registerLightningScheme as registerLightningFacilitatorScheme } from './lightning/facilitator/index.js'\nexport type { LightningFacilitatorConfig } from './lightning/facilitator/index.js'\n\n// Export signer interfaces\nexport type { ClientBtcSigner, ClientLightningSigner } from './signer.js'\n\n// Export facilitator signer interfaces\nexport type { FacilitatorBtcSigner } from './exact/facilitator/scheme.js'\nexport type { FacilitatorLightningSigner } from './lightning/facilitator/scheme.js'\n\n// Export payload types\nexport type { BtcOnchainPayload, LightningPayload } from './types.js'\n\n// Export constants\nexport {\n BTC_MAINNET,\n BTC_TESTNET,\n LIGHTNING_MAINNET,\n LIGHTNING_TESTNET,\n BTC_NETWORKS,\n LIGHTNING_NETWORKS,\n ALL_NETWORKS,\n DUST_LIMIT,\n MIN_RELAY_FEE,\n SATS_PER_BTC,\n SCHEME_EXACT,\n DEFAULT_VALIDITY_DURATION,\n MAINNET_ADDRESS_PREFIXES,\n TESTNET_ADDRESS_PREFIXES,\n} from './constants.js'\n\nexport type { BtcNetwork, LightningNetwork } from './constants.js'\n\n// Export utility functions\nexport {\n satoshisToBtc,\n btcToSatoshis,\n validateBitcoinAddress,\n isMainnetAddress,\n isTestnetAddress,\n validateBolt11Invoice,\n isValidHex,\n} from './utils.js'\n\n// Export server scheme types\nexport type { ExactBtcSchemeConfig } from './exact/server/scheme.js'\nexport type { LightningSchemeConfig, InvoiceGenerator } from './lightning/server/scheme.js'\n","/**\n * Bitcoin & Lightning Network Constants\n *\n * CAIP-2 network identifiers, dust limits, and fee constants.\n */\n\n/**\n * CAIP-2 Network Identifiers for Bitcoin\n * Uses BIP-122 chain genesis block hashes\n */\nexport const BTC_MAINNET = 'bip122:000000000019d6689c085ae165831e93'\nexport const BTC_TESTNET = 'bip122:000000000933ea01ad0ee984209779ba'\n\n/**\n * CAIP-2 Network Identifiers for Lightning Network\n */\nexport const LIGHTNING_MAINNET = 'lightning:mainnet'\nexport const LIGHTNING_TESTNET = 'lightning:testnet'\n\n/**\n * All supported BTC on-chain networks\n */\nexport const BTC_NETWORKS = [BTC_MAINNET, BTC_TESTNET] as const\n\n/**\n * All supported Lightning networks\n */\nexport const LIGHTNING_NETWORKS = [LIGHTNING_MAINNET, LIGHTNING_TESTNET] as const\n\n/**\n * All supported networks (on-chain + Lightning)\n */\nexport const ALL_NETWORKS = [...BTC_NETWORKS, ...LIGHTNING_NETWORKS] as const\n\nexport type BtcNetwork = (typeof BTC_NETWORKS)[number]\nexport type LightningNetwork = (typeof LIGHTNING_NETWORKS)[number]\n\n/**\n * Dust limit in satoshis - minimum viable output value\n * Outputs below this threshold are rejected by Bitcoin nodes\n */\nexport const DUST_LIMIT = 546\n\n/**\n * Minimum relay fee in satoshis\n * Transactions with fees below this are not relayed by default\n */\nexport const MIN_RELAY_FEE = 1000\n\n/**\n * Satoshis per BTC\n */\nexport const SATS_PER_BTC = 100_000_000\n\n/**\n * Scheme identifiers\n */\nexport const SCHEME_EXACT = 'exact'\n\n/**\n * Default timeout for payment validity (in seconds)\n */\nexport const DEFAULT_VALIDITY_DURATION = 3600 // 1 hour\n\n/**\n * Bitcoin address prefixes for basic validation\n */\nexport const MAINNET_ADDRESS_PREFIXES = ['bc1', '1', '3']\nexport const TESTNET_ADDRESS_PREFIXES = ['tb1', 'm', 'n', '2']\n","/**\n * Bitcoin & Lightning Utility Functions\n *\n * Helper functions for address validation, unit conversion,\n * and invoice validation.\n */\n\nimport { SATS_PER_BTC, MAINNET_ADDRESS_PREFIXES, TESTNET_ADDRESS_PREFIXES } from './constants.js'\n\n/**\n * Convert satoshis to BTC\n *\n * @param sats - Amount in satoshis\n * @returns Amount in BTC as string (to avoid floating point issues)\n */\nexport function satoshisToBtc(sats: bigint | number | string): string {\n const satsBigInt = BigInt(sats)\n const whole = satsBigInt / BigInt(SATS_PER_BTC)\n const frac = satsBigInt % BigInt(SATS_PER_BTC)\n\n if (frac === 0n) {\n return whole.toString()\n }\n\n const fracStr = frac.toString().padStart(8, '0')\n return `${whole}.${fracStr}`.replace(/\\.?0+$/, '')\n}\n\n/**\n * Convert BTC to satoshis\n *\n * @param btc - Amount in BTC (string or number)\n * @returns Amount in satoshis as bigint\n */\nexport function btcToSatoshis(btc: string | number): bigint {\n const btcStr = typeof btc === 'number' ? btc.toString() : btc\n const [wholePart, fracPart = ''] = btcStr.split('.')\n const paddedFrac = fracPart.padEnd(8, '0').slice(0, 8)\n const combined = wholePart + paddedFrac\n const result = BigInt(combined.replace(/^0+/, '') || '0')\n return result\n}\n\n/**\n * Validate a Bitcoin address (basic format validation)\n *\n * Checks address prefix against known formats:\n * - Mainnet: bc1 (bech32), 1 (P2PKH), 3 (P2SH)\n * - Testnet: tb1 (bech32), m/n (P2PKH), 2 (P2SH)\n *\n * @param address - Bitcoin address to validate\n * @returns true if the address has a valid format\n */\nexport function validateBitcoinAddress(address: string): boolean {\n if (!address || address.length < 14 || address.length > 90) {\n return false\n }\n\n const allPrefixes = [...MAINNET_ADDRESS_PREFIXES, ...TESTNET_ADDRESS_PREFIXES]\n return allPrefixes.some((prefix) => address.startsWith(prefix))\n}\n\n/**\n * Check if a Bitcoin address is for mainnet\n *\n * @param address - Bitcoin address\n * @returns true if mainnet address\n */\nexport function isMainnetAddress(address: string): boolean {\n return MAINNET_ADDRESS_PREFIXES.some((prefix) => address.startsWith(prefix))\n}\n\n/**\n * Check if a Bitcoin address is for testnet\n *\n * @param address - Bitcoin address\n * @returns true if testnet address\n */\nexport function isTestnetAddress(address: string): boolean {\n return TESTNET_ADDRESS_PREFIXES.some((prefix) => address.startsWith(prefix))\n}\n\n/**\n * Validate a BOLT11 Lightning invoice (basic format validation)\n *\n * BOLT11 invoices follow the format:\n * - lnbc... for mainnet\n * - lntb... for testnet\n * - lnbcrt... for regtest\n *\n * @param invoice - BOLT11 invoice string\n * @returns true if the invoice has a valid format\n */\nexport function validateBolt11Invoice(invoice: string): boolean {\n if (!invoice || invoice.length < 20) {\n return false\n }\n\n const lower = invoice.toLowerCase()\n return lower.startsWith('lnbc') || lower.startsWith('lntb') || lower.startsWith('lnbcrt')\n}\n\n/**\n * Validate a hex-encoded string\n *\n * @param hex - String to validate\n * @param expectedLength - Expected byte length (hex length / 2)\n * @returns true if valid hex of expected length\n */\nexport function isValidHex(hex: string, expectedLength?: number): boolean {\n if (!/^[0-9a-fA-F]+$/.test(hex)) {\n return false\n }\n if (expectedLength !== undefined && hex.length !== expectedLength * 2) {\n return false\n }\n return true\n}\n","/**\n * Bitcoin On-chain Client Scheme Implementation\n *\n * Creates payment payloads for Bitcoin on-chain transfers using the exact scheme.\n * Builds PSBTs (Partially Signed Bitcoin Transactions) and signs them with the client's wallet.\n */\n\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from '@t402/core/types'\nimport type { ClientBtcSigner } from '../../signer.js'\nimport type { BtcOnchainPayload } from '../../types.js'\nimport { SCHEME_EXACT, DUST_LIMIT } from '../../constants.js'\nimport { validateBitcoinAddress } from '../../utils.js'\n\n/**\n * Bitcoin client implementation for the Exact payment scheme.\n *\n * Creates signed PSBTs for on-chain Bitcoin payments that can be\n * finalized and broadcast by a facilitator.\n */\nexport class ExactBtcScheme implements SchemeNetworkClient {\n readonly scheme = SCHEME_EXACT\n\n /**\n * Creates a new ExactBtcScheme instance.\n *\n * @param signer - The Bitcoin signer for client operations\n */\n constructor(private readonly signer: ClientBtcSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n *\n * The payload contains a signed PSBT with a single output\n * paying the required amount to the payTo address.\n *\n * @param t402Version - The t402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n t402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, 't402Version' | 'payload'>> {\n // Validate required fields\n if (!paymentRequirements.payTo) {\n throw new Error('PayTo address is required')\n }\n if (!paymentRequirements.amount) {\n throw new Error('Amount is required')\n }\n\n // Validate address format\n if (!validateBitcoinAddress(paymentRequirements.payTo)) {\n throw new Error(`Invalid Bitcoin address: ${paymentRequirements.payTo}`)\n }\n\n // Validate amount is above dust limit\n const amountSats = BigInt(paymentRequirements.amount)\n if (amountSats < BigInt(DUST_LIMIT)) {\n throw new Error(`Amount ${amountSats} satoshis is below dust limit (${DUST_LIMIT})`)\n }\n\n // Build an unsigned PSBT\n // The PSBT contains: output to payTo address for the required amount\n // Input selection and fee calculation are handled by the signer\n const unsignedPsbt = this.buildUnsignedPsbt(paymentRequirements)\n\n // Sign the PSBT\n const signedPsbt = await this.signer.signPsbt(unsignedPsbt)\n\n // Create payload\n const payload: BtcOnchainPayload = {\n signedPsbt,\n }\n\n return {\n t402Version,\n payload,\n }\n }\n\n /**\n * Build an unsigned PSBT for the payment.\n *\n * Creates a minimal PSBT representation with the required output.\n * The actual UTXO selection and fee calculation should be handled\n * by the signer implementation (which typically has wallet context).\n *\n * @param requirements - Payment requirements\n * @returns Base64-encoded unsigned PSBT\n */\n private buildUnsignedPsbt(requirements: PaymentRequirements): string {\n // Encode payment details as a JSON payload in the PSBT\n // The signer is responsible for building the full PSBT\n // with proper UTXO selection and fee estimation\n const psbtData = {\n outputs: [\n {\n address: requirements.payTo,\n value: requirements.amount,\n },\n ],\n network: requirements.network,\n fromAddress: this.signer.getAddress(),\n fromPubKey: this.signer.getPublicKey(),\n }\n\n // Encode as base64 for transport\n return Buffer.from(JSON.stringify(psbtData)).toString('base64')\n }\n}\n","import { t402Client, PaymentPolicy } from '@t402/core/client'\nimport { Network } from '@t402/core/types'\nimport { ClientBtcSigner } from '../../signer.js'\nimport { ExactBtcScheme } from './scheme.js'\n\n/**\n * Configuration options for registering BTC schemes to an t402Client\n */\nexport interface BtcClientConfig {\n /**\n * The Bitcoin signer to use for creating payment payloads\n */\n signer: ClientBtcSigner\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[]\n\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (bip122:*)\n */\n networks?: Network[]\n}\n\n/**\n * Registers Bitcoin exact payment schemes to an t402Client instance.\n *\n * @param client - The t402Client instance to register schemes to\n * @param config - Configuration for BTC client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactBtcScheme } from \"@t402/btc/exact/client\";\n * import { t402Client } from \"@t402/core/client\";\n *\n * const client = new t402Client();\n * registerExactBtcScheme(client, {\n * signer: myBtcSigner,\n * });\n * ```\n */\nexport function registerExactBtcScheme(client: t402Client, config: BtcClientConfig): t402Client {\n const scheme = new ExactBtcScheme(config.signer)\n\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach((network) => {\n client.register(network, scheme)\n })\n } else {\n client.register('bip122:*', scheme)\n }\n\n if (config.policies) {\n config.policies.forEach((policy) => {\n client.registerPolicy(policy)\n })\n }\n\n return client\n}\n","/**\n * Lightning Network Client Scheme Implementation\n *\n * Creates payment payloads for Lightning Network payments.\n * Pays BOLT11 invoices and returns preimage as proof of payment.\n */\n\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from '@t402/core/types'\nimport type { ClientLightningSigner } from '../../signer.js'\nimport type { LightningPayload } from '../../types.js'\nimport { SCHEME_EXACT } from '../../constants.js'\nimport { validateBolt11Invoice } from '../../utils.js'\n\n/**\n * Lightning Network client implementation for the Exact payment scheme.\n *\n * Pays BOLT11 invoices using a Lightning node and returns the\n * payment preimage as proof of payment.\n *\n * Note: The scheme is 'exact' because Lightning payments are always\n * for the exact invoice amount.\n */\nexport class LightningScheme implements SchemeNetworkClient {\n readonly scheme = SCHEME_EXACT\n\n /**\n * Creates a new LightningScheme instance.\n *\n * @param signer - The Lightning signer for client operations\n */\n constructor(private readonly signer: ClientLightningSigner) {}\n\n /**\n * Creates a payment payload for the Lightning scheme.\n *\n * 1. Extracts the BOLT11 invoice from requirements.extra.bolt11Invoice\n * 2. Pays the invoice using the Lightning signer\n * 3. Returns the preimage and payment hash as proof of payment\n *\n * @param t402Version - The t402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n t402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, 't402Version' | 'payload'>> {\n // Extract BOLT11 invoice from requirements\n const bolt11Invoice = paymentRequirements.extra?.bolt11Invoice as string | undefined\n\n if (!bolt11Invoice) {\n throw new Error('BOLT11 invoice is required in requirements.extra.bolt11Invoice')\n }\n\n // Validate invoice format\n if (!validateBolt11Invoice(bolt11Invoice)) {\n throw new Error(`Invalid BOLT11 invoice format: ${bolt11Invoice.slice(0, 20)}...`)\n }\n\n // Pay the invoice\n const { preimage, paymentHash } = await this.signer.payInvoice(bolt11Invoice)\n\n // Create payload with proof of payment\n const payload: LightningPayload = {\n paymentHash,\n preimage,\n bolt11Invoice,\n }\n\n return {\n t402Version,\n payload,\n }\n }\n}\n","import { t402Client, PaymentPolicy } from '@t402/core/client'\nimport { Network } from '@t402/core/types'\nimport { ClientLightningSigner } from '../../signer.js'\nimport { LightningScheme } from './scheme.js'\n\n/**\n * Configuration options for registering Lightning schemes to an t402Client\n */\nexport interface LightningClientConfig {\n /**\n * The Lightning signer to use for paying invoices\n */\n signer: ClientLightningSigner\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[]\n\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (lightning:*)\n */\n networks?: Network[]\n}\n\n/**\n * Registers Lightning payment schemes to an t402Client instance.\n *\n * @param client - The t402Client instance to register schemes to\n * @param config - Configuration for Lightning client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerLightningScheme } from \"@t402/btc/lightning/client\";\n * import { t402Client } from \"@t402/core/client\";\n *\n * const client = new t402Client();\n * registerLightningScheme(client, {\n * signer: myLnSigner,\n * });\n * ```\n */\nexport function registerLightningScheme(\n client: t402Client,\n config: LightningClientConfig,\n): t402Client {\n const scheme = new LightningScheme(config.signer)\n\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach((network) => {\n client.register(network, scheme)\n })\n } else {\n client.register('lightning:*', scheme)\n }\n\n if (config.policies) {\n config.policies.forEach((policy) => {\n client.registerPolicy(policy)\n })\n }\n\n return client\n}\n","/**\n * Bitcoin On-chain Server Scheme Implementation\n *\n * Handles price parsing and payment requirement enhancement for\n * Bitcoin on-chain payments using the exact scheme.\n */\n\nimport type {\n AssetAmount,\n Network,\n PaymentRequirements,\n Price,\n SchemeNetworkServer,\n MoneyParser,\n} from '@t402/core/types'\nimport { SCHEME_EXACT, SATS_PER_BTC } from '../../constants.js'\n\n/**\n * Configuration options for ExactBtcScheme server\n */\nexport interface ExactBtcSchemeConfig {\n /**\n * The Bitcoin address to receive payments\n */\n payTo: string\n}\n\n/**\n * Bitcoin server implementation for the Exact payment scheme.\n * Handles price parsing and converts user-friendly amounts to satoshis.\n *\n * For Bitcoin, the asset is always \"BTC\" and amounts are in satoshis.\n */\nexport class ExactBtcScheme implements SchemeNetworkServer {\n readonly scheme = SCHEME_EXACT\n private moneyParsers: MoneyParser[] = []\n private config: ExactBtcSchemeConfig\n\n constructor(config: ExactBtcSchemeConfig) {\n this.config = config\n }\n\n /**\n * Register a custom money parser in the parser chain.\n *\n * @param parser - Custom function to convert amount to AssetAmount (or null to skip)\n * @returns The server instance for chaining\n */\n registerMoneyParser(parser: MoneyParser): ExactBtcScheme {\n this.moneyParsers.push(parser)\n return this\n }\n\n /**\n * Parses a price into an asset amount in satoshis.\n *\n * Accepts:\n * - Number: treated as USD, converted to satoshis at a default rate\n * - String with $: treated as USD\n * - AssetAmount: returned directly\n *\n * For Bitcoin, amounts are always in satoshis and the asset is \"BTC\".\n *\n * @param price - The price to parse\n * @param network - The network to use\n * @returns Promise that resolves to the parsed asset amount\n */\n async parsePrice(price: Price, network: Network): Promise<AssetAmount> {\n // If already an AssetAmount, return it directly\n if (typeof price === 'object' && price !== null && 'amount' in price) {\n if (!price.asset) {\n throw new Error(`Asset must be specified for AssetAmount on network ${network}`)\n }\n return {\n amount: price.amount,\n asset: price.asset,\n extra: price.extra || {},\n }\n }\n\n // Parse Money to decimal number\n const amount = this.parseMoneyToDecimal(price)\n\n // Try each custom money parser in order\n for (const parser of this.moneyParsers) {\n const result = await parser(amount, network)\n if (result !== null) {\n return result\n }\n }\n\n // Default: treat amount as satoshis directly\n return this.defaultMoneyConversion(amount)\n }\n\n /**\n * Build payment requirements for this scheme/network combination.\n *\n * @param paymentRequirements - Base payment requirements with amount/asset already set\n * @param supportedKind - The supported kind from facilitator\n * @param extensionKeys - Extensions supported by the facilitator\n * @returns Enhanced payment requirements\n */\n async enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n t402Version: number\n scheme: string\n network: Network\n extra?: Record<string, unknown>\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n void supportedKind\n void extensionKeys\n\n return {\n ...paymentRequirements,\n payTo: paymentRequirements.payTo || this.config.payTo,\n asset: paymentRequirements.asset || 'BTC',\n }\n }\n\n /**\n * Parse Money (string | number) to a decimal number.\n */\n private parseMoneyToDecimal(money: string | number): number {\n if (typeof money === 'number') {\n if (!Number.isFinite(money)) {\n throw new Error(`Invalid money value: ${money}`)\n }\n return money\n }\n\n const cleanMoney = money.replace(/^\\$/, '').trim()\n const amount = parseFloat(cleanMoney)\n\n if (isNaN(amount)) {\n throw new Error(`Invalid money format: ${money}`)\n }\n\n return amount\n }\n\n /**\n * Default money conversion: treat amount as satoshis.\n * For direct satoshi amounts, the amount is used as-is.\n */\n private defaultMoneyConversion(amount: number): AssetAmount {\n // Amount is treated as satoshis directly\n const sats = Math.floor(amount * SATS_PER_BTC)\n\n return {\n amount: sats.toString(),\n asset: 'BTC',\n extra: {\n symbol: 'BTC',\n decimals: 8,\n },\n }\n }\n}\n","import { t402ResourceServer } from '@t402/core/server'\nimport { Network } from '@t402/core/types'\nimport { ExactBtcScheme, ExactBtcSchemeConfig } from './scheme.js'\n\n/**\n * Configuration options for registering BTC schemes to an t402ResourceServer\n */\nexport interface BtcResourceServerConfig {\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (bip122:*)\n */\n networks?: Network[]\n\n /**\n * Scheme configuration (payTo address, etc.)\n */\n schemeConfig: ExactBtcSchemeConfig\n}\n\n/**\n * Registers Bitcoin exact payment schemes to an t402ResourceServer instance.\n *\n * @param server - The t402ResourceServer instance to register schemes to\n * @param config - Configuration for BTC resource server registration\n * @returns The server instance for chaining\n */\nexport function registerExactBtcScheme(\n server: t402ResourceServer,\n config: BtcResourceServerConfig,\n): t402ResourceServer {\n const scheme = new ExactBtcScheme(config.schemeConfig)\n\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach((network) => {\n server.register(network, scheme)\n })\n } else {\n server.register('bip122:*', scheme)\n }\n\n return server\n}\n","/**\n * Bitcoin On-chain Facilitator Scheme Implementation\n *\n * Verifies and settles Bitcoin on-chain payments using the exact scheme.\n * Validates signed PSBTs and broadcasts transactions to the Bitcoin network.\n */\n\nimport type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from '@t402/core/types'\nimport type { BtcOnchainPayload } from '../../types.js'\nimport { SCHEME_EXACT, DUST_LIMIT, BTC_NETWORKS } from '../../constants.js'\nimport { validateBitcoinAddress } from '../../utils.js'\n\n/**\n * Facilitator BTC signer interface for verify and settle operations\n */\nexport interface FacilitatorBtcSigner {\n /**\n * Get all addresses this facilitator can use\n */\n getAddresses(): readonly string[]\n\n /**\n * Verify a signed PSBT\n * Checks that outputs match expected values and signatures are valid\n *\n * @param params - Verification parameters\n * @returns Verification result\n */\n verifyPsbt(params: {\n signedPsbt: string\n expectedPayTo: string\n expectedAmount: string\n }): Promise<{\n valid: boolean\n reason?: string\n payer?: string\n }>\n\n /**\n * Finalize and broadcast a signed PSBT\n *\n * @param signedPsbt - Base64-encoded signed PSBT\n * @returns Transaction ID\n */\n broadcastPsbt(signedPsbt: string): Promise<string>\n\n /**\n * Wait for a transaction to be confirmed\n *\n * @param txId - Transaction ID\n * @param confirmations - Number of confirmations to wait for\n * @returns Confirmation result\n */\n waitForConfirmation(\n txId: string,\n confirmations?: number,\n ): Promise<{\n confirmed: boolean\n txId: string\n blockHash?: string\n confirmations: number\n }>\n}\n\n/**\n * Bitcoin facilitator implementation for the Exact payment scheme.\n *\n * Verifies signed PSBTs and broadcasts transactions to settle payments.\n */\nexport class ExactBtcScheme implements SchemeNetworkFacilitator {\n readonly scheme = SCHEME_EXACT\n readonly caipFamily = 'bip122:*'\n\n constructor(private readonly signer: FacilitatorBtcSigner) {}\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * Bitcoin on-chain has no extra data.\n */\n getExtra(_network: string): Record<string, unknown> | undefined {\n return undefined\n }\n\n /**\n * Get signer addresses used by this facilitator.\n */\n getSigners(_network: string): string[] {\n return [...this.signer.getAddresses()]\n }\n\n /**\n * Verifies a payment payload.\n *\n * Validates:\n * 1. Scheme and network matching\n * 2. PSBT structure and signatures\n * 3. Output matches (payTo, amount)\n * 4. Amount above dust limit\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const btcPayload = payload.payload as BtcOnchainPayload | undefined\n\n // Validate payload structure\n if (!btcPayload?.signedPsbt) {\n return {\n isValid: false,\n invalidReason: 'invalid_payload_structure',\n payer: undefined,\n }\n }\n\n // Verify scheme matches\n if (payload.accepted.scheme !== SCHEME_EXACT || requirements.scheme !== SCHEME_EXACT) {\n return {\n isValid: false,\n invalidReason: 'unsupported_scheme',\n payer: undefined,\n }\n }\n\n // Verify network is a valid BTC network\n const validNetworks: readonly string[] = BTC_NETWORKS\n if (!validNetworks.includes(requirements.network)) {\n return {\n isValid: false,\n invalidReason: 'unsupported_network',\n payer: undefined,\n }\n }\n\n // Verify network matches\n if (payload.accepted.network !== requirements.network) {\n return {\n isValid: false,\n invalidReason: 'network_mismatch',\n payer: undefined,\n }\n }\n\n // Validate payTo address\n if (!validateBitcoinAddress(requirements.payTo)) {\n return {\n isValid: false,\n invalidReason: 'invalid_pay_to_address',\n payer: undefined,\n }\n }\n\n // Validate amount above dust limit\n if (BigInt(requirements.amount) < BigInt(DUST_LIMIT)) {\n return {\n isValid: false,\n invalidReason: 'amount_below_dust_limit',\n payer: undefined,\n }\n }\n\n // Verify the PSBT\n try {\n const result = await this.signer.verifyPsbt({\n signedPsbt: btcPayload.signedPsbt,\n expectedPayTo: requirements.payTo,\n expectedAmount: requirements.amount,\n })\n\n if (!result.valid) {\n return {\n isValid: false,\n invalidReason: result.reason || 'psbt_verification_failed',\n payer: result.payer,\n }\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer: result.payer,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n return {\n isValid: false,\n invalidReason: `verification_error: ${errorMessage}`,\n payer: undefined,\n }\n }\n }\n\n /**\n * Settles a payment by finalizing and broadcasting the PSBT.\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n const btcPayload = payload.payload as BtcOnchainPayload | undefined\n\n if (!btcPayload?.signedPsbt) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: '',\n errorReason: 'invalid_payload_structure',\n payer: undefined,\n }\n }\n\n // Re-verify before settling\n const verifyResult = await this.verify(payload, requirements)\n if (!verifyResult.isValid) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: '',\n errorReason: verifyResult.invalidReason ?? 'verification_failed',\n payer: verifyResult.payer,\n }\n }\n\n try {\n // Broadcast the signed transaction\n const txId = await this.signer.broadcastPsbt(btcPayload.signedPsbt)\n\n // Wait for at least 1 confirmation\n const confirmation = await this.signer.waitForConfirmation(txId, 1)\n\n if (!confirmation.confirmed) {\n return {\n success: false,\n errorReason: 'transaction_not_confirmed',\n transaction: txId,\n network: payload.accepted.network,\n payer: verifyResult.payer,\n }\n }\n\n return {\n success: true,\n transaction: txId,\n network: payload.accepted.network,\n payer: verifyResult.payer,\n }\n } catch (error) {\n console.error('Failed to settle Bitcoin transaction:', error)\n return {\n success: false,\n errorReason: 'transaction_failed',\n transaction: '',\n network: payload.accepted.network,\n payer: verifyResult.payer,\n }\n }\n }\n}\n","import { t402Facilitator } from '@t402/core/facilitator'\nimport { Network } from '@t402/core/types'\nimport { FacilitatorBtcSigner, ExactBtcScheme } from './scheme.js'\n\n/**\n * Configuration options for registering BTC schemes to an t402Facilitator\n */\nexport interface BtcFacilitatorConfig {\n /**\n * The Bitcoin signer for facilitator operations (verify and settle)\n */\n signer: FacilitatorBtcSigner\n\n /**\n * Networks to register (single network or array of networks)\n * Examples: \"bip122:000000000019d6689c085ae165831e93\"\n */\n networks: Network | Network[]\n}\n\n/**\n * Registers Bitcoin exact payment schemes to an t402Facilitator instance.\n *\n * @param facilitator - The t402Facilitator instance to register schemes to\n * @param config - Configuration for BTC facilitator registration\n * @returns The facilitator instance for chaining\n */\nexport function registerExactBtcScheme(\n facilitator: t402Facilitator,\n config: BtcFacilitatorConfig,\n): t402Facilitator {\n facilitator.register(config.networks, new ExactBtcScheme(config.signer))\n return facilitator\n}\n","/**\n * Lightning Network Server Scheme Implementation\n *\n * Handles price parsing and payment requirement enhancement for\n * Lightning Network payments.\n */\n\nimport type {\n AssetAmount,\n Network,\n PaymentRequirements,\n Price,\n SchemeNetworkServer,\n MoneyParser,\n} from '@t402/core/types'\nimport { SCHEME_EXACT, SATS_PER_BTC } from '../../constants.js'\n\n/**\n * Lightning invoice generator function\n * Used to create BOLT11 invoices for payment requirements\n */\nexport type InvoiceGenerator = (\n amountSats: string,\n description: string,\n expiry: number,\n) => Promise<{\n bolt11Invoice: string\n paymentHash: string\n}>\n\n/**\n * Configuration options for Lightning server scheme\n */\nexport interface LightningSchemeConfig {\n /**\n * Function to generate BOLT11 invoices\n */\n generateInvoice: InvoiceGenerator\n}\n\n/**\n * Lightning Network server implementation for the Exact payment scheme.\n * Generates BOLT11 invoices and enhances payment requirements.\n */\nexport class LightningScheme implements SchemeNetworkServer {\n readonly scheme = SCHEME_EXACT\n private moneyParsers: MoneyParser[] = []\n private config: LightningSchemeConfig\n\n constructor(config: LightningSchemeConfig) {\n this.config = config\n }\n\n /**\n * Register a custom money parser in the parser chain.\n *\n * @param parser - Custom function to convert amount to AssetAmount (or null to skip)\n * @returns The server instance for chaining\n */\n registerMoneyParser(parser: MoneyParser): LightningScheme {\n this.moneyParsers.push(parser)\n return this\n }\n\n /**\n * Parses a price into an asset amount in satoshis.\n *\n * @param price - The price to parse\n * @param network - The network to use\n * @returns Promise that resolves to the parsed asset amount\n */\n async parsePrice(price: Price, network: Network): Promise<AssetAmount> {\n // If already an AssetAmount, return it directly\n if (typeof price === 'object' && price !== null && 'amount' in price) {\n if (!price.asset) {\n throw new Error(`Asset must be specified for AssetAmount on network ${network}`)\n }\n return {\n amount: price.amount,\n asset: price.asset,\n extra: price.extra || {},\n }\n }\n\n // Parse Money to decimal number\n const amount = this.parseMoneyToDecimal(price)\n\n // Try each custom money parser in order\n for (const parser of this.moneyParsers) {\n const result = await parser(amount, network)\n if (result !== null) {\n return result\n }\n }\n\n // Default: convert to satoshis\n return this.defaultMoneyConversion(amount)\n }\n\n /**\n * Build payment requirements for Lightning Network.\n *\n * Generates a BOLT11 invoice and adds it to the extra field.\n */\n async enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n t402Version: number\n scheme: string\n network: Network\n extra?: Record<string, unknown>\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n void extensionKeys\n\n const extra = { ...paymentRequirements.extra }\n\n // Generate a BOLT11 invoice for the payment\n const invoice = await this.config.generateInvoice(\n paymentRequirements.amount,\n `t402 payment on ${supportedKind.network}`,\n paymentRequirements.maxTimeoutSeconds,\n )\n\n extra.bolt11Invoice = invoice.bolt11Invoice\n extra.paymentHash = invoice.paymentHash\n\n return {\n ...paymentRequirements,\n asset: paymentRequirements.asset || 'BTC',\n extra,\n }\n }\n\n /**\n * Parse Money (string | number) to a decimal number.\n */\n private parseMoneyToDecimal(money: string | number): number {\n if (typeof money === 'number') {\n if (!Number.isFinite(money)) {\n throw new Error(`Invalid money value: ${money}`)\n }\n return money\n }\n\n const cleanMoney = money.replace(/^\\$/, '').trim()\n const amount = parseFloat(cleanMoney)\n\n if (isNaN(amount)) {\n throw new Error(`Invalid money format: ${money}`)\n }\n\n return amount\n }\n\n /**\n * Default money conversion: treat amount as BTC, convert to satoshis.\n */\n private defaultMoneyConversion(amount: number): AssetAmount {\n const sats = Math.floor(amount * SATS_PER_BTC)\n\n return {\n amount: sats.toString(),\n asset: 'BTC',\n extra: {\n symbol: 'BTC',\n decimals: 8,\n },\n }\n }\n}\n","import { t402ResourceServer } from '@t402/core/server'\nimport { Network } from '@t402/core/types'\nimport { LightningScheme, LightningSchemeConfig } from './scheme.js'\n\n/**\n * Configuration options for registering Lightning schemes to an t402ResourceServer\n */\nexport interface LightningResourceServerConfig {\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (lightning:*)\n */\n networks?: Network[]\n\n /**\n * Scheme configuration (invoice generator, etc.)\n */\n schemeConfig: LightningSchemeConfig\n}\n\n/**\n * Registers Lightning payment schemes to an t402ResourceServer instance.\n *\n * @param server - The t402ResourceServer instance to register schemes to\n * @param config - Configuration for Lightning resource server registration\n * @returns The server instance for chaining\n */\nexport function registerLightningScheme(\n server: t402ResourceServer,\n config: LightningResourceServerConfig,\n): t402ResourceServer {\n const scheme = new LightningScheme(config.schemeConfig)\n\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach((network) => {\n server.register(network, scheme)\n })\n } else {\n server.register('lightning:*', scheme)\n }\n\n return server\n}\n","/**\n * Lightning Network Facilitator Scheme Implementation\n *\n * Verifies Lightning Network payments using preimage verification.\n * Lightning payments are atomic (settle-on-pay), so settlement is a no-op.\n */\n\nimport type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from '@t402/core/types'\nimport type { LightningPayload } from '../../types.js'\nimport { SCHEME_EXACT, LIGHTNING_NETWORKS } from '../../constants.js'\nimport { isValidHex } from '../../utils.js'\n\n/**\n * Facilitator Lightning signer interface\n */\nexport interface FacilitatorLightningSigner {\n /**\n * Get all node public keys this facilitator manages\n */\n getAddresses(): readonly string[]\n\n /**\n * Look up a payment by its payment hash\n *\n * @param paymentHash - Hex-encoded payment hash\n * @returns Payment status\n */\n lookupPayment(paymentHash: string): Promise<{\n settled: boolean\n amountSats?: string\n preimage?: string\n }>\n}\n\n/**\n * Compute SHA-256 hash of a hex-encoded preimage\n *\n * @param preimageHex - Hex-encoded preimage\n * @returns Hex-encoded SHA-256 hash\n */\nasync function sha256Hex(preimageHex: string): Promise<string> {\n const bytes = new Uint8Array(preimageHex.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16)))\n const hashBuffer = await globalThis.crypto.subtle.digest('SHA-256', bytes)\n const hashArray = new Uint8Array(hashBuffer)\n return Array.from(hashArray)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Lightning Network facilitator implementation for the Exact payment scheme.\n *\n * Verification is done by checking that SHA-256(preimage) === paymentHash.\n * Lightning payments are atomic, so settle is a confirmation-only operation.\n */\nexport class LightningScheme implements SchemeNetworkFacilitator {\n readonly scheme = SCHEME_EXACT\n readonly caipFamily = 'lightning:*'\n\n constructor(private readonly signer: FacilitatorLightningSigner) {}\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * Lightning has no extra data.\n */\n getExtra(_network: string): Record<string, unknown> | undefined {\n return undefined\n }\n\n /**\n * Get signer addresses (node public keys) for this facilitator.\n */\n getSigners(_network: string): string[] {\n return [...this.signer.getAddresses()]\n }\n\n /**\n * Verifies a Lightning payment payload.\n *\n * Validates:\n * 1. Payload structure (paymentHash, preimage, bolt11Invoice)\n * 2. Preimage verification: SHA-256(preimage) === paymentHash\n * 3. Payment lookup on the Lightning node\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const lnPayload = payload.payload as LightningPayload | undefined\n\n // Validate payload structure\n if (!lnPayload?.paymentHash || !lnPayload?.preimage || !lnPayload?.bolt11Invoice) {\n return {\n isValid: false,\n invalidReason: 'invalid_payload_structure',\n payer: undefined,\n }\n }\n\n // Verify scheme matches\n if (payload.accepted.scheme !== SCHEME_EXACT || requirements.scheme !== SCHEME_EXACT) {\n return {\n isValid: false,\n invalidReason: 'unsupported_scheme',\n payer: undefined,\n }\n }\n\n // Verify network is a valid Lightning network\n const validNetworks: readonly string[] = LIGHTNING_NETWORKS\n if (!validNetworks.includes(requirements.network)) {\n return {\n isValid: false,\n invalidReason: 'unsupported_network',\n payer: undefined,\n }\n }\n\n // Validate preimage format (32 bytes hex)\n if (!isValidHex(lnPayload.preimage, 32)) {\n return {\n isValid: false,\n invalidReason: 'invalid_preimage_format',\n payer: undefined,\n }\n }\n\n // Validate payment hash format (32 bytes hex)\n if (!isValidHex(lnPayload.paymentHash, 32)) {\n return {\n isValid: false,\n invalidReason: 'invalid_payment_hash_format',\n payer: undefined,\n }\n }\n\n // Core verification: SHA-256(preimage) must equal paymentHash\n try {\n const computedHash = await sha256Hex(lnPayload.preimage)\n\n if (computedHash !== lnPayload.paymentHash.toLowerCase()) {\n return {\n isValid: false,\n invalidReason: 'preimage_hash_mismatch',\n payer: undefined,\n }\n }\n } catch {\n return {\n isValid: false,\n invalidReason: 'preimage_verification_failed',\n payer: undefined,\n }\n }\n\n // Optionally verify with the Lightning node\n try {\n const payment = await this.signer.lookupPayment(lnPayload.paymentHash)\n\n if (!payment.settled) {\n return {\n isValid: false,\n invalidReason: 'payment_not_settled',\n payer: undefined,\n }\n }\n\n // Verify amount matches if available\n if (payment.amountSats && BigInt(payment.amountSats) < BigInt(requirements.amount)) {\n return {\n isValid: false,\n invalidReason: 'insufficient_amount',\n payer: undefined,\n }\n }\n } catch (error) {\n // If we can't verify with the node, the preimage verification is sufficient\n console.warn('Could not verify payment with Lightning node:', error)\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer: undefined,\n }\n }\n\n /**\n * Settles a Lightning payment.\n *\n * Lightning payments are atomic (settle-on-pay), so this is effectively\n * a confirmation that the payment was already completed. The actual\n * settlement happened when the client paid the invoice.\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n const lnPayload = payload.payload as LightningPayload | undefined\n\n if (!lnPayload?.paymentHash || !lnPayload?.preimage) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: '',\n errorReason: 'invalid_payload_structure',\n payer: undefined,\n }\n }\n\n // Verify the payment\n const verifyResult = await this.verify(payload, requirements)\n if (!verifyResult.isValid) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: '',\n errorReason: verifyResult.invalidReason ?? 'verification_failed',\n payer: undefined,\n }\n }\n\n // Lightning is settle-on-pay: the payment hash serves as the transaction ID\n return {\n success: true,\n transaction: lnPayload.paymentHash,\n network: payload.accepted.network,\n payer: undefined,\n }\n }\n}\n","import { t402Facilitator } from '@t402/core/facilitator'\nimport { Network } from '@t402/core/types'\nimport { FacilitatorLightningSigner, LightningScheme } from './scheme.js'\n\n/**\n * Configuration options for registering Lightning schemes to an t402Facilitator\n */\nexport interface LightningFacilitatorConfig {\n /**\n * The Lightning signer for facilitator operations\n */\n signer: FacilitatorLightningSigner\n\n /**\n * Networks to register (single network or array of networks)\n * Examples: \"lightning:mainnet\", [\"lightning:mainnet\", \"lightning:testnet\"]\n */\n networks: Network | Network[]\n}\n\n/**\n * Registers Lightning payment schemes to an t402Facilitator instance.\n *\n * @param facilitator - The t402Facilitator instance to register schemes to\n * @param config - Configuration for Lightning facilitator registration\n * @returns The facilitator instance for chaining\n */\nexport function registerLightningScheme(\n facilitator: t402Facilitator,\n config: LightningFacilitatorConfig,\n): t402Facilitator {\n facilitator.register(config.networks, new LightningScheme(config.signer))\n return facilitator\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2CAAAA;AAAA,EAAA,oCAAAA;AAAA,EAAA;AAAA,4CAAAC;AAAA,EAAA,qCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;;;ACUO,IAAM,cAAc;AACpB,IAAM,cAAc;AAKpB,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;AAK1B,IAAM,eAAe,CAAC,aAAa,WAAW;AAK9C,IAAM,qBAAqB,CAAC,mBAAmB,iBAAiB;AAKhE,IAAM,eAAe,CAAC,GAAG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aAAa,MAAM,GAAG;AAClF,eAAO;AAAA,UACL,SAAS;AAAA,UACT,eAAe;AAAA,UACf,OAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AAEd,cAAQ,KAAK,iDAAiD,KAAK;AAAA,IACrE;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,eAAe;AAAA,MACf,OAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OACJ,SACA,cACyB;AACzB,UAAM,YAAY,QAAQ;AAE1B,QAAI,CAAC,WAAW,eAAe,CAAC,WAAW,UAAU;AACnD,aAAO;AAAA,QACL,SAAS;AAAA,QACT,SAAS,QAAQ,SAAS;AAAA,QAC1B,aAAa;AAAA,QACb,aAAa;AAAA,QACb,OAAO;AAAA,MACT;AAAA,IACF;AAGA,UAAM,eAAe,MAAM,KAAK,OAAO,SAAS,YAAY;AAC5D,QAAI,CAAC,aAAa,SAAS;AACzB,aAAO;AAAA,QACL,SAAS;AAAA,QACT,SAAS,QAAQ,SAAS;AAAA,QAC1B,aAAa;AAAA,QACb,aAAa,aAAa,iBAAiB;AAAA,QAC3C,OAAO;AAAA,MACT;AAAA,IACF;AAGA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,aAAa,UAAU;AAAA,MACvB,SAAS,QAAQ,SAAS;AAAA,MAC1B,OAAO;AAAA,IACT;AAAA,EACF;AACF;;;ACjNO,SAASC,yBACd,aACA,QACiB;AACjB,cAAY,SAAS,OAAO,UAAU,IAAIC,iBAAgB,OAAO,MAAM,CAAC;AACxE,SAAO;AACT;","names":["registerExactBtcScheme","registerLightningScheme","ExactBtcScheme","registerExactBtcScheme","ExactBtcScheme","ExactBtcScheme","registerExactBtcScheme","ExactBtcScheme","LightningScheme","registerLightningScheme","LightningScheme","LightningScheme","registerLightningScheme","LightningScheme"]}
@@ -0,0 +1,82 @@
1
+ import { SchemeNetworkClient, PaymentRequirements, PaymentPayload, Network } from '@t402/core/types';
2
+ import { a as ClientLightningSigner } from '../../signer-B_Z4WGLa.js';
3
+ import { PaymentPolicy, t402Client } from '@t402/core/client';
4
+
5
+ /**
6
+ * Lightning Network Client Scheme Implementation
7
+ *
8
+ * Creates payment payloads for Lightning Network payments.
9
+ * Pays BOLT11 invoices and returns preimage as proof of payment.
10
+ */
11
+
12
+ /**
13
+ * Lightning Network client implementation for the Exact payment scheme.
14
+ *
15
+ * Pays BOLT11 invoices using a Lightning node and returns the
16
+ * payment preimage as proof of payment.
17
+ *
18
+ * Note: The scheme is 'exact' because Lightning payments are always
19
+ * for the exact invoice amount.
20
+ */
21
+ declare class LightningScheme implements SchemeNetworkClient {
22
+ private readonly signer;
23
+ readonly scheme = "exact";
24
+ /**
25
+ * Creates a new LightningScheme instance.
26
+ *
27
+ * @param signer - The Lightning signer for client operations
28
+ */
29
+ constructor(signer: ClientLightningSigner);
30
+ /**
31
+ * Creates a payment payload for the Lightning scheme.
32
+ *
33
+ * 1. Extracts the BOLT11 invoice from requirements.extra.bolt11Invoice
34
+ * 2. Pays the invoice using the Lightning signer
35
+ * 3. Returns the preimage and payment hash as proof of payment
36
+ *
37
+ * @param t402Version - The t402 protocol version
38
+ * @param paymentRequirements - The payment requirements
39
+ * @returns Promise resolving to a payment payload
40
+ */
41
+ createPaymentPayload(t402Version: number, paymentRequirements: PaymentRequirements): Promise<Pick<PaymentPayload, 't402Version' | 'payload'>>;
42
+ }
43
+
44
+ /**
45
+ * Configuration options for registering Lightning schemes to an t402Client
46
+ */
47
+ interface LightningClientConfig {
48
+ /**
49
+ * The Lightning signer to use for paying invoices
50
+ */
51
+ signer: ClientLightningSigner;
52
+ /**
53
+ * Optional policies to apply to the client
54
+ */
55
+ policies?: PaymentPolicy[];
56
+ /**
57
+ * Optional specific networks to register
58
+ * If not provided, registers wildcard support (lightning:*)
59
+ */
60
+ networks?: Network[];
61
+ }
62
+ /**
63
+ * Registers Lightning payment schemes to an t402Client instance.
64
+ *
65
+ * @param client - The t402Client instance to register schemes to
66
+ * @param config - Configuration for Lightning client registration
67
+ * @returns The client instance for chaining
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * import { registerLightningScheme } from "@t402/btc/lightning/client";
72
+ * import { t402Client } from "@t402/core/client";
73
+ *
74
+ * const client = new t402Client();
75
+ * registerLightningScheme(client, {
76
+ * signer: myLnSigner,
77
+ * });
78
+ * ```
79
+ */
80
+ declare function registerLightningScheme(client: t402Client, config: LightningClientConfig): t402Client;
81
+
82
+ export { type LightningClientConfig, LightningScheme, registerLightningScheme };
@@ -0,0 +1,114 @@
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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
21
+
22
+ // src/lightning/client/index.ts
23
+ var client_exports = {};
24
+ __export(client_exports, {
25
+ LightningScheme: () => LightningScheme,
26
+ registerLightningScheme: () => registerLightningScheme
27
+ });
28
+ module.exports = __toCommonJS(client_exports);
29
+
30
+ // src/constants.ts
31
+ var BTC_MAINNET = "bip122:000000000019d6689c085ae165831e93";
32
+ var BTC_TESTNET = "bip122:000000000933ea01ad0ee984209779ba";
33
+ var LIGHTNING_MAINNET = "lightning:mainnet";
34
+ var LIGHTNING_TESTNET = "lightning:testnet";
35
+ var BTC_NETWORKS = [BTC_MAINNET, BTC_TESTNET];
36
+ var LIGHTNING_NETWORKS = [LIGHTNING_MAINNET, LIGHTNING_TESTNET];
37
+ var ALL_NETWORKS = [...BTC_NETWORKS, ...LIGHTNING_NETWORKS];
38
+ var SCHEME_EXACT = "exact";
39
+
40
+ // src/utils.ts
41
+ function validateBolt11Invoice(invoice) {
42
+ if (!invoice || invoice.length < 20) {
43
+ return false;
44
+ }
45
+ const lower = invoice.toLowerCase();
46
+ return lower.startsWith("lnbc") || lower.startsWith("lntb") || lower.startsWith("lnbcrt");
47
+ }
48
+
49
+ // src/lightning/client/scheme.ts
50
+ var LightningScheme = class {
51
+ /**
52
+ * Creates a new LightningScheme instance.
53
+ *
54
+ * @param signer - The Lightning signer for client operations
55
+ */
56
+ constructor(signer) {
57
+ this.signer = signer;
58
+ __publicField(this, "scheme", SCHEME_EXACT);
59
+ }
60
+ /**
61
+ * Creates a payment payload for the Lightning scheme.
62
+ *
63
+ * 1. Extracts the BOLT11 invoice from requirements.extra.bolt11Invoice
64
+ * 2. Pays the invoice using the Lightning signer
65
+ * 3. Returns the preimage and payment hash as proof of payment
66
+ *
67
+ * @param t402Version - The t402 protocol version
68
+ * @param paymentRequirements - The payment requirements
69
+ * @returns Promise resolving to a payment payload
70
+ */
71
+ async createPaymentPayload(t402Version, paymentRequirements) {
72
+ const bolt11Invoice = paymentRequirements.extra?.bolt11Invoice;
73
+ if (!bolt11Invoice) {
74
+ throw new Error("BOLT11 invoice is required in requirements.extra.bolt11Invoice");
75
+ }
76
+ if (!validateBolt11Invoice(bolt11Invoice)) {
77
+ throw new Error(`Invalid BOLT11 invoice format: ${bolt11Invoice.slice(0, 20)}...`);
78
+ }
79
+ const { preimage, paymentHash } = await this.signer.payInvoice(bolt11Invoice);
80
+ const payload = {
81
+ paymentHash,
82
+ preimage,
83
+ bolt11Invoice
84
+ };
85
+ return {
86
+ t402Version,
87
+ payload
88
+ };
89
+ }
90
+ };
91
+
92
+ // src/lightning/client/register.ts
93
+ function registerLightningScheme(client, config) {
94
+ const scheme = new LightningScheme(config.signer);
95
+ if (config.networks && config.networks.length > 0) {
96
+ config.networks.forEach((network) => {
97
+ client.register(network, scheme);
98
+ });
99
+ } else {
100
+ client.register("lightning:*", scheme);
101
+ }
102
+ if (config.policies) {
103
+ config.policies.forEach((policy) => {
104
+ client.registerPolicy(policy);
105
+ });
106
+ }
107
+ return client;
108
+ }
109
+ // Annotate the CommonJS export names for ESM import in node:
110
+ 0 && (module.exports = {
111
+ LightningScheme,
112
+ registerLightningScheme
113
+ });
114
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/lightning/client/index.ts","../../../../src/constants.ts","../../../../src/utils.ts","../../../../src/lightning/client/scheme.ts","../../../../src/lightning/client/register.ts"],"sourcesContent":["export { LightningScheme } from './scheme.js'\nexport { registerLightningScheme } from './register.js'\nexport type { LightningClientConfig } from './register.js'\n","/**\n * Bitcoin & Lightning Network Constants\n *\n * CAIP-2 network identifiers, dust limits, and fee constants.\n */\n\n/**\n * CAIP-2 Network Identifiers for Bitcoin\n * Uses BIP-122 chain genesis block hashes\n */\nexport const BTC_MAINNET = 'bip122:000000000019d6689c085ae165831e93'\nexport const BTC_TESTNET = 'bip122:000000000933ea01ad0ee984209779ba'\n\n/**\n * CAIP-2 Network Identifiers for Lightning Network\n */\nexport const LIGHTNING_MAINNET = 'lightning:mainnet'\nexport const LIGHTNING_TESTNET = 'lightning:testnet'\n\n/**\n * All supported BTC on-chain networks\n */\nexport const BTC_NETWORKS = [BTC_MAINNET, BTC_TESTNET] as const\n\n/**\n * All supported Lightning networks\n */\nexport const LIGHTNING_NETWORKS = [LIGHTNING_MAINNET, LIGHTNING_TESTNET] as const\n\n/**\n * All supported networks (on-chain + Lightning)\n */\nexport const ALL_NETWORKS = [...BTC_NETWORKS, ...LIGHTNING_NETWORKS] as const\n\nexport type BtcNetwork = (typeof BTC_NETWORKS)[number]\nexport type LightningNetwork = (typeof LIGHTNING_NETWORKS)[number]\n\n/**\n * Dust limit in satoshis - minimum viable output value\n * Outputs below this threshold are rejected by Bitcoin nodes\n */\nexport const DUST_LIMIT = 546\n\n/**\n * Minimum relay fee in satoshis\n * Transactions with fees below this are not relayed by default\n */\nexport const MIN_RELAY_FEE = 1000\n\n/**\n * Satoshis per BTC\n */\nexport const SATS_PER_BTC = 100_000_000\n\n/**\n * Scheme identifiers\n */\nexport const SCHEME_EXACT = 'exact'\n\n/**\n * Default timeout for payment validity (in seconds)\n */\nexport const DEFAULT_VALIDITY_DURATION = 3600 // 1 hour\n\n/**\n * Bitcoin address prefixes for basic validation\n */\nexport const MAINNET_ADDRESS_PREFIXES = ['bc1', '1', '3']\nexport const TESTNET_ADDRESS_PREFIXES = ['tb1', 'm', 'n', '2']\n","/**\n * Bitcoin & Lightning Utility Functions\n *\n * Helper functions for address validation, unit conversion,\n * and invoice validation.\n */\n\nimport { SATS_PER_BTC, MAINNET_ADDRESS_PREFIXES, TESTNET_ADDRESS_PREFIXES } from './constants.js'\n\n/**\n * Convert satoshis to BTC\n *\n * @param sats - Amount in satoshis\n * @returns Amount in BTC as string (to avoid floating point issues)\n */\nexport function satoshisToBtc(sats: bigint | number | string): string {\n const satsBigInt = BigInt(sats)\n const whole = satsBigInt / BigInt(SATS_PER_BTC)\n const frac = satsBigInt % BigInt(SATS_PER_BTC)\n\n if (frac === 0n) {\n return whole.toString()\n }\n\n const fracStr = frac.toString().padStart(8, '0')\n return `${whole}.${fracStr}`.replace(/\\.?0+$/, '')\n}\n\n/**\n * Convert BTC to satoshis\n *\n * @param btc - Amount in BTC (string or number)\n * @returns Amount in satoshis as bigint\n */\nexport function btcToSatoshis(btc: string | number): bigint {\n const btcStr = typeof btc === 'number' ? btc.toString() : btc\n const [wholePart, fracPart = ''] = btcStr.split('.')\n const paddedFrac = fracPart.padEnd(8, '0').slice(0, 8)\n const combined = wholePart + paddedFrac\n const result = BigInt(combined.replace(/^0+/, '') || '0')\n return result\n}\n\n/**\n * Validate a Bitcoin address (basic format validation)\n *\n * Checks address prefix against known formats:\n * - Mainnet: bc1 (bech32), 1 (P2PKH), 3 (P2SH)\n * - Testnet: tb1 (bech32), m/n (P2PKH), 2 (P2SH)\n *\n * @param address - Bitcoin address to validate\n * @returns true if the address has a valid format\n */\nexport function validateBitcoinAddress(address: string): boolean {\n if (!address || address.length < 14 || address.length > 90) {\n return false\n }\n\n const allPrefixes = [...MAINNET_ADDRESS_PREFIXES, ...TESTNET_ADDRESS_PREFIXES]\n return allPrefixes.some((prefix) => address.startsWith(prefix))\n}\n\n/**\n * Check if a Bitcoin address is for mainnet\n *\n * @param address - Bitcoin address\n * @returns true if mainnet address\n */\nexport function isMainnetAddress(address: string): boolean {\n return MAINNET_ADDRESS_PREFIXES.some((prefix) => address.startsWith(prefix))\n}\n\n/**\n * Check if a Bitcoin address is for testnet\n *\n * @param address - Bitcoin address\n * @returns true if testnet address\n */\nexport function isTestnetAddress(address: string): boolean {\n return TESTNET_ADDRESS_PREFIXES.some((prefix) => address.startsWith(prefix))\n}\n\n/**\n * Validate a BOLT11 Lightning invoice (basic format validation)\n *\n * BOLT11 invoices follow the format:\n * - lnbc... for mainnet\n * - lntb... for testnet\n * - lnbcrt... for regtest\n *\n * @param invoice - BOLT11 invoice string\n * @returns true if the invoice has a valid format\n */\nexport function validateBolt11Invoice(invoice: string): boolean {\n if (!invoice || invoice.length < 20) {\n return false\n }\n\n const lower = invoice.toLowerCase()\n return lower.startsWith('lnbc') || lower.startsWith('lntb') || lower.startsWith('lnbcrt')\n}\n\n/**\n * Validate a hex-encoded string\n *\n * @param hex - String to validate\n * @param expectedLength - Expected byte length (hex length / 2)\n * @returns true if valid hex of expected length\n */\nexport function isValidHex(hex: string, expectedLength?: number): boolean {\n if (!/^[0-9a-fA-F]+$/.test(hex)) {\n return false\n }\n if (expectedLength !== undefined && hex.length !== expectedLength * 2) {\n return false\n }\n return true\n}\n","/**\n * Lightning Network Client Scheme Implementation\n *\n * Creates payment payloads for Lightning Network payments.\n * Pays BOLT11 invoices and returns preimage as proof of payment.\n */\n\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from '@t402/core/types'\nimport type { ClientLightningSigner } from '../../signer.js'\nimport type { LightningPayload } from '../../types.js'\nimport { SCHEME_EXACT } from '../../constants.js'\nimport { validateBolt11Invoice } from '../../utils.js'\n\n/**\n * Lightning Network client implementation for the Exact payment scheme.\n *\n * Pays BOLT11 invoices using a Lightning node and returns the\n * payment preimage as proof of payment.\n *\n * Note: The scheme is 'exact' because Lightning payments are always\n * for the exact invoice amount.\n */\nexport class LightningScheme implements SchemeNetworkClient {\n readonly scheme = SCHEME_EXACT\n\n /**\n * Creates a new LightningScheme instance.\n *\n * @param signer - The Lightning signer for client operations\n */\n constructor(private readonly signer: ClientLightningSigner) {}\n\n /**\n * Creates a payment payload for the Lightning scheme.\n *\n * 1. Extracts the BOLT11 invoice from requirements.extra.bolt11Invoice\n * 2. Pays the invoice using the Lightning signer\n * 3. Returns the preimage and payment hash as proof of payment\n *\n * @param t402Version - The t402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n t402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, 't402Version' | 'payload'>> {\n // Extract BOLT11 invoice from requirements\n const bolt11Invoice = paymentRequirements.extra?.bolt11Invoice as string | undefined\n\n if (!bolt11Invoice) {\n throw new Error('BOLT11 invoice is required in requirements.extra.bolt11Invoice')\n }\n\n // Validate invoice format\n if (!validateBolt11Invoice(bolt11Invoice)) {\n throw new Error(`Invalid BOLT11 invoice format: ${bolt11Invoice.slice(0, 20)}...`)\n }\n\n // Pay the invoice\n const { preimage, paymentHash } = await this.signer.payInvoice(bolt11Invoice)\n\n // Create payload with proof of payment\n const payload: LightningPayload = {\n paymentHash,\n preimage,\n bolt11Invoice,\n }\n\n return {\n t402Version,\n payload,\n }\n }\n}\n","import { t402Client, PaymentPolicy } from '@t402/core/client'\nimport { Network } from '@t402/core/types'\nimport { ClientLightningSigner } from '../../signer.js'\nimport { LightningScheme } from './scheme.js'\n\n/**\n * Configuration options for registering Lightning schemes to an t402Client\n */\nexport interface LightningClientConfig {\n /**\n * The Lightning signer to use for paying invoices\n */\n signer: ClientLightningSigner\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[]\n\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (lightning:*)\n */\n networks?: Network[]\n}\n\n/**\n * Registers Lightning payment schemes to an t402Client instance.\n *\n * @param client - The t402Client instance to register schemes to\n * @param config - Configuration for Lightning client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerLightningScheme } from \"@t402/btc/lightning/client\";\n * import { t402Client } from \"@t402/core/client\";\n *\n * const client = new t402Client();\n * registerLightningScheme(client, {\n * signer: myLnSigner,\n * });\n * ```\n */\nexport function registerLightningScheme(\n client: t402Client,\n config: LightningClientConfig,\n): t402Client {\n const scheme = new LightningScheme(config.signer)\n\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach((network) => {\n client.register(network, scheme)\n })\n } else {\n client.register('lightning:*', scheme)\n }\n\n if (config.policies) {\n config.policies.forEach((policy) => {\n client.registerPolicy(policy)\n })\n }\n\n return client\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUO,IAAM,cAAc;AACpB,IAAM,cAAc;AAKpB,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;AAK1B,IAAM,eAAe,CAAC,aAAa,WAAW;AAK9C,IAAM,qBAAqB,CAAC,mBAAmB,iBAAiB;AAKhE,IAAM,eAAe,CAAC,GAAG,cAAc,GAAG,kBAAkB;AAyB5D,IAAM,eAAe;;;ACoCrB,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;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,93 @@
1
+ import { SchemeNetworkFacilitator, PaymentPayload, PaymentRequirements, VerifyResponse, SettleResponse, Network } from '@t402/core/types';
2
+ import { t402Facilitator } from '@t402/core/facilitator';
3
+
4
+ /**
5
+ * Lightning Network Facilitator Scheme Implementation
6
+ *
7
+ * Verifies Lightning Network payments using preimage verification.
8
+ * Lightning payments are atomic (settle-on-pay), so settlement is a no-op.
9
+ */
10
+
11
+ /**
12
+ * Facilitator Lightning signer interface
13
+ */
14
+ interface FacilitatorLightningSigner {
15
+ /**
16
+ * Get all node public keys this facilitator manages
17
+ */
18
+ getAddresses(): readonly string[];
19
+ /**
20
+ * Look up a payment by its payment hash
21
+ *
22
+ * @param paymentHash - Hex-encoded payment hash
23
+ * @returns Payment status
24
+ */
25
+ lookupPayment(paymentHash: string): Promise<{
26
+ settled: boolean;
27
+ amountSats?: string;
28
+ preimage?: string;
29
+ }>;
30
+ }
31
+ /**
32
+ * Lightning Network facilitator implementation for the Exact payment scheme.
33
+ *
34
+ * Verification is done by checking that SHA-256(preimage) === paymentHash.
35
+ * Lightning payments are atomic, so settle is a confirmation-only operation.
36
+ */
37
+ declare class LightningScheme implements SchemeNetworkFacilitator {
38
+ private readonly signer;
39
+ readonly scheme = "exact";
40
+ readonly caipFamily = "lightning:*";
41
+ constructor(signer: FacilitatorLightningSigner);
42
+ /**
43
+ * Get mechanism-specific extra data for the supported kinds endpoint.
44
+ * Lightning has no extra data.
45
+ */
46
+ getExtra(_network: string): Record<string, unknown> | undefined;
47
+ /**
48
+ * Get signer addresses (node public keys) for this facilitator.
49
+ */
50
+ getSigners(_network: string): string[];
51
+ /**
52
+ * Verifies a Lightning payment payload.
53
+ *
54
+ * Validates:
55
+ * 1. Payload structure (paymentHash, preimage, bolt11Invoice)
56
+ * 2. Preimage verification: SHA-256(preimage) === paymentHash
57
+ * 3. Payment lookup on the Lightning node
58
+ */
59
+ verify(payload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
60
+ /**
61
+ * Settles a Lightning payment.
62
+ *
63
+ * Lightning payments are atomic (settle-on-pay), so this is effectively
64
+ * a confirmation that the payment was already completed. The actual
65
+ * settlement happened when the client paid the invoice.
66
+ */
67
+ settle(payload: PaymentPayload, requirements: PaymentRequirements): Promise<SettleResponse>;
68
+ }
69
+
70
+ /**
71
+ * Configuration options for registering Lightning schemes to an t402Facilitator
72
+ */
73
+ interface LightningFacilitatorConfig {
74
+ /**
75
+ * The Lightning signer for facilitator operations
76
+ */
77
+ signer: FacilitatorLightningSigner;
78
+ /**
79
+ * Networks to register (single network or array of networks)
80
+ * Examples: "lightning:mainnet", ["lightning:mainnet", "lightning:testnet"]
81
+ */
82
+ networks: Network | Network[];
83
+ }
84
+ /**
85
+ * Registers Lightning payment schemes to an t402Facilitator instance.
86
+ *
87
+ * @param facilitator - The t402Facilitator instance to register schemes to
88
+ * @param config - Configuration for Lightning facilitator registration
89
+ * @returns The facilitator instance for chaining
90
+ */
91
+ declare function registerLightningScheme(facilitator: t402Facilitator, config: LightningFacilitatorConfig): t402Facilitator;
92
+
93
+ export { type FacilitatorLightningSigner, type LightningFacilitatorConfig, LightningScheme, registerLightningScheme };