@babylonlabs-io/ts-sdk 0.33.2 → 0.33.4

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 (147) hide show
  1. package/dist/BTCVaultRegistry.abi-DbJ5lsFJ.js +417 -0
  2. package/dist/BTCVaultRegistry.abi-DbJ5lsFJ.js.map +1 -0
  3. package/dist/BTCVaultRegistry.abi-ZdPpION2.cjs +2 -0
  4. package/dist/BTCVaultRegistry.abi-ZdPpION2.cjs.map +1 -0
  5. package/dist/PayoutManager-C9XHKZ5j.js +200 -0
  6. package/dist/PayoutManager-C9XHKZ5j.js.map +1 -0
  7. package/dist/PayoutManager-DDnNB0mj.cjs +2 -0
  8. package/dist/PayoutManager-DDnNB0mj.cjs.map +1 -0
  9. package/dist/PeginManager-BXg2S1mH.cjs +2 -0
  10. package/dist/PeginManager-BXg2S1mH.cjs.map +1 -0
  11. package/dist/{PeginManager-BtXhdqkm.js → PeginManager-C5HaMAcw.js} +367 -480
  12. package/dist/PeginManager-C5HaMAcw.js.map +1 -0
  13. package/dist/ProtocolParams.abi-BmvHwQJV.cjs +2 -0
  14. package/dist/ProtocolParams.abi-BmvHwQJV.cjs.map +1 -0
  15. package/dist/ProtocolParams.abi-DXu8L0Fn.js +382 -0
  16. package/dist/ProtocolParams.abi-DXu8L0Fn.js.map +1 -0
  17. package/dist/{bitcoin-0_T6KJON.js → bitcoin-B0S8SHCX.js} +24 -20
  18. package/dist/bitcoin-B0S8SHCX.js.map +1 -0
  19. package/dist/bitcoin-B3aqjuMP.cjs +2 -0
  20. package/dist/bitcoin-B3aqjuMP.cjs.map +1 -0
  21. package/dist/buildAndBroadcastRefund-CIPPpchL.cjs +2 -0
  22. package/dist/buildAndBroadcastRefund-CIPPpchL.cjs.map +1 -0
  23. package/dist/buildAndBroadcastRefund-D_QlvCsw.js +777 -0
  24. package/dist/buildAndBroadcastRefund-D_QlvCsw.js.map +1 -0
  25. package/dist/challengeAssert-BzxQmdZy.js +128 -0
  26. package/dist/challengeAssert-BzxQmdZy.js.map +1 -0
  27. package/dist/challengeAssert-Yyyj-EdR.cjs +2 -0
  28. package/dist/challengeAssert-Yyyj-EdR.cjs.map +1 -0
  29. package/dist/errors-9AkghWyk.js +22 -0
  30. package/dist/errors-9AkghWyk.js.map +1 -0
  31. package/dist/errors-BP73_stm.cjs +2 -0
  32. package/dist/errors-BP73_stm.cjs.map +1 -0
  33. package/dist/errors-Bu0H-dZD.cjs +2 -0
  34. package/dist/errors-Bu0H-dZD.cjs.map +1 -0
  35. package/dist/errors-CznAK5NB.js +96 -0
  36. package/dist/errors-CznAK5NB.js.map +1 -0
  37. package/dist/index.cjs +1 -1
  38. package/dist/index.js +156 -146
  39. package/dist/index.js.map +1 -1
  40. package/dist/mempoolApi-CAIge7Nj.js +205 -0
  41. package/dist/mempoolApi-CAIge7Nj.js.map +1 -0
  42. package/dist/mempoolApi-YNkKjQCU.cjs +2 -0
  43. package/dist/mempoolApi-YNkKjQCU.cjs.map +1 -0
  44. package/dist/noPayout-BXeUw0Qq.cjs +2 -0
  45. package/dist/noPayout-BXeUw0Qq.cjs.map +1 -0
  46. package/dist/noPayout-DBX6G96_.js +141 -0
  47. package/dist/noPayout-DBX6G96_.js.map +1 -0
  48. package/dist/payout-BNFMBXS6.js +193 -0
  49. package/dist/payout-BNFMBXS6.js.map +1 -0
  50. package/dist/payout-DQ_fmJUA.cjs +2 -0
  51. package/dist/payout-DQ_fmJUA.cjs.map +1 -0
  52. package/dist/peginInput-C2QPvuhR.js +177 -0
  53. package/dist/peginInput-C2QPvuhR.js.map +1 -0
  54. package/dist/peginInput-tbw9BpZy.cjs +2 -0
  55. package/dist/peginInput-tbw9BpZy.cjs.map +1 -0
  56. package/dist/peginState-BijNNT15.cjs +2 -0
  57. package/dist/peginState-BijNNT15.cjs.map +1 -0
  58. package/dist/peginState-CBAlxgXk.js +51 -0
  59. package/dist/peginState-CBAlxgXk.js.map +1 -0
  60. package/dist/psbtInputFields-2224j2ZY.js +128 -0
  61. package/dist/psbtInputFields-2224j2ZY.js.map +1 -0
  62. package/dist/psbtInputFields-B1lrwYzH.cjs +2 -0
  63. package/dist/psbtInputFields-B1lrwYzH.cjs.map +1 -0
  64. package/dist/reservation-CHUGW0F_.js +142 -0
  65. package/dist/reservation-CHUGW0F_.js.map +1 -0
  66. package/dist/reservation-ho7mjW3X.cjs +2 -0
  67. package/dist/reservation-ho7mjW3X.cjs.map +1 -0
  68. package/dist/signing-Bnsro0hE.cjs +2 -0
  69. package/dist/signing-Bnsro0hE.cjs.map +1 -0
  70. package/dist/signing-DaLvGwQe.js +16 -0
  71. package/dist/signing-DaLvGwQe.js.map +1 -0
  72. package/dist/tbv/core/clients/index.cjs +1 -1
  73. package/dist/tbv/core/clients/index.js +31 -30
  74. package/dist/tbv/core/clients/index.js.map +1 -1
  75. package/dist/tbv/core/contracts/index.cjs +2 -0
  76. package/dist/tbv/core/contracts/index.cjs.map +1 -0
  77. package/dist/tbv/core/contracts/index.js +14 -0
  78. package/dist/tbv/core/contracts/index.js.map +1 -0
  79. package/dist/tbv/core/index.cjs +1 -1
  80. package/dist/tbv/core/index.js +156 -146
  81. package/dist/tbv/core/index.js.map +1 -1
  82. package/dist/tbv/core/managers/PayoutManager.d.ts +8 -4
  83. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  84. package/dist/tbv/core/managers/PeginManager.d.ts +15 -1
  85. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  86. package/dist/tbv/core/managers/index.cjs +2 -0
  87. package/dist/tbv/core/managers/index.cjs.map +1 -0
  88. package/dist/tbv/core/managers/index.js +7 -0
  89. package/dist/tbv/core/managers/index.js.map +1 -0
  90. package/dist/tbv/core/primitives/index.cjs +1 -1
  91. package/dist/tbv/core/primitives/index.js +31 -29
  92. package/dist/tbv/core/primitives/index.js.map +1 -1
  93. package/dist/tbv/core/primitives/utils/bitcoin.d.ts +6 -4
  94. package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
  95. package/dist/tbv/core/services/index.cjs +1 -1
  96. package/dist/tbv/core/services/index.js +28 -27
  97. package/dist/tbv/core/services/index.js.map +1 -1
  98. package/dist/tbv/core/utils/index.cjs +1 -1
  99. package/dist/tbv/core/utils/index.js +21 -20
  100. package/dist/tbv/core/utils/index.js.map +1 -1
  101. package/dist/tbv/index.cjs +1 -1
  102. package/dist/tbv/index.js +156 -146
  103. package/dist/tbv/index.js.map +1 -1
  104. package/dist/testing/index.cjs +1 -1
  105. package/dist/testing/index.js +1 -1
  106. package/dist/types-ByW6nSLj.js +318 -0
  107. package/dist/types-ByW6nSLj.js.map +1 -0
  108. package/dist/types-CfCZyfid.cjs +2 -0
  109. package/dist/types-CfCZyfid.cjs.map +1 -0
  110. package/dist/vault-registry-reader-OK2V08tk.cjs +2 -0
  111. package/dist/vault-registry-reader-OK2V08tk.cjs.map +1 -0
  112. package/dist/{vault-registry-reader-eiBfG4uQ.js → vault-registry-reader-WiNVOsnD.js} +263 -840
  113. package/dist/vault-registry-reader-WiNVOsnD.js.map +1 -0
  114. package/package.json +11 -1
  115. package/dist/PeginManager-BtXhdqkm.js.map +0 -1
  116. package/dist/PeginManager-ztgWQqza.cjs +0 -2
  117. package/dist/PeginManager-ztgWQqza.cjs.map +0 -1
  118. package/dist/bitcoin-0_T6KJON.js.map +0 -1
  119. package/dist/bitcoin-EYBKDtEW.cjs +0 -2
  120. package/dist/bitcoin-EYBKDtEW.cjs.map +0 -1
  121. package/dist/buildAndBroadcastRefund-Ci_pVTNu.js +0 -965
  122. package/dist/buildAndBroadcastRefund-Ci_pVTNu.js.map +0 -1
  123. package/dist/buildAndBroadcastRefund-DKr9hbDn.cjs +0 -2
  124. package/dist/buildAndBroadcastRefund-DKr9hbDn.cjs.map +0 -1
  125. package/dist/challengeAssert-06GLZtV8.cjs +0 -2
  126. package/dist/challengeAssert-06GLZtV8.cjs.map +0 -1
  127. package/dist/challengeAssert-KGVKQh0J.js +0 -298
  128. package/dist/challengeAssert-KGVKQh0J.js.map +0 -1
  129. package/dist/noPayout-BmMd4NNH.js +0 -327
  130. package/dist/noPayout-BmMd4NNH.js.map +0 -1
  131. package/dist/noPayout-Bp2TYA_X.cjs +0 -2
  132. package/dist/noPayout-Bp2TYA_X.cjs.map +0 -1
  133. package/dist/psbtInputFields-BLi7Ta-T.cjs +0 -2
  134. package/dist/psbtInputFields-BLi7Ta-T.cjs.map +0 -1
  135. package/dist/psbtInputFields-DPCFHgGd.js +0 -264
  136. package/dist/psbtInputFields-DPCFHgGd.js.map +0 -1
  137. package/dist/signing-BZigafm0.js +0 -64
  138. package/dist/signing-BZigafm0.js.map +0 -1
  139. package/dist/signing-DHSXjhLM.cjs +0 -2
  140. package/dist/signing-DHSXjhLM.cjs.map +0 -1
  141. package/dist/types-PthVHz5q.cjs +0 -2
  142. package/dist/types-PthVHz5q.cjs.map +0 -1
  143. package/dist/types-SYvSQWnc.js +0 -732
  144. package/dist/types-SYvSQWnc.js.map +0 -1
  145. package/dist/vault-registry-reader-CmDdymw4.cjs +0 -2
  146. package/dist/vault-registry-reader-CmDdymw4.cjs.map +0 -1
  147. package/dist/vault-registry-reader-eiBfG4uQ.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"psbtInputFields-BLi7Ta-T.cjs","sources":["../src/tbv/core/utils/utxo/availability.ts","../src/tbv/core/utils/utxo/reservation.ts","../src/tbv/core/utils/utxo/selectUtxos.ts","../src/tbv/core/utils/transaction/btcTxHash.ts","../src/tbv/core/utils/btc/scriptType.ts","../src/tbv/core/utils/btc/psbtInputFields.ts"],"sourcesContent":["/**\n * UTXO Availability Validation\n *\n * Validates that UTXOs referenced in a pre-pegin transaction are still unspent\n * BEFORE asking the user to sign. This prevents wasted signing effort when\n * UTXOs have already been spent by unrelated transactions.\n *\n * These functions are pure — they accept pre-fetched UTXOs and perform no I/O.\n * The vault service wrapper is responsible for fetching UTXOs from the mempool.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { UtxoRef } from \"./reservation\";\n\n/**\n * Information about a missing/spent UTXO.\n */\nexport interface MissingUtxoInfo {\n /** Transaction ID of the missing UTXO */\n txid: string;\n /** Output index of the missing UTXO */\n vout: number;\n}\n\n/**\n * Result of UTXO validation.\n */\nexport interface UtxoValidationResult {\n /** Whether all UTXOs are still available */\n allAvailable: boolean;\n /** List of missing UTXOs (if any) */\n missingUtxos: MissingUtxoInfo[];\n /** Total number of inputs checked */\n totalInputs: number;\n}\n\n/**\n * Error thrown when UTXOs are not available.\n */\nexport class UtxoNotAvailableError extends Error {\n public readonly missingUtxos: MissingUtxoInfo[];\n\n constructor(missingUtxos: MissingUtxoInfo[]) {\n const count = missingUtxos.length;\n const message =\n count === 1\n ? \"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.\"\n : `${count} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;\n\n super(message);\n this.name = \"UtxoNotAvailableError\";\n this.missingUtxos = missingUtxos;\n }\n}\n\n/**\n * Extract input references (txid:vout) from an unsigned transaction.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @returns Array of input references\n */\nexport function extractInputsFromTransaction(\n unsignedTxHex: string,\n): Array<{ txid: string; vout: number }> {\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n\n let tx: Transaction;\n try {\n tx = Transaction.fromHex(cleanHex);\n } catch (error) {\n throw new Error(\n `Failed to parse BTC transaction: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n return tx.ins.map((input) => ({\n // Bitcoin stores txid in reverse byte order\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n}\n\n/**\n * Validate that all UTXOs in a transaction are still available.\n *\n * Pure function — accepts pre-fetched UTXOs instead of making network calls.\n * This should be called BEFORE signing to avoid wasting user effort\n * signing a transaction that will fail to broadcast.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @returns Validation result with missing UTXO details\n */\nexport function validateUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): UtxoValidationResult {\n const inputs = extractInputsFromTransaction(unsignedTxHex);\n\n if (inputs.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Detect duplicate inputs (same txid:vout referenced more than once).\n // This would produce an invalid Bitcoin transaction.\n const inputKeys = new Set<string>();\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (inputKeys.has(key)) {\n throw new Error(\n `Transaction contains duplicate input ${input.txid}:${input.vout}. ` +\n `This would produce an invalid Bitcoin transaction.`,\n );\n }\n inputKeys.add(key);\n }\n\n // Create a set of available UTXOs for O(1) lookup (lowercase for consistency with reservation.ts)\n const availableSet = new Set(\n availableUtxos.map((utxo) => `${utxo.txid.toLowerCase()}:${utxo.vout}`),\n );\n\n // Check which inputs are missing\n const missingUtxos: MissingUtxoInfo[] = [];\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (!availableSet.has(key)) {\n missingUtxos.push({\n txid: input.txid,\n vout: input.vout,\n });\n }\n }\n\n return {\n allAvailable: missingUtxos.length === 0,\n missingUtxos,\n totalInputs: inputs.length,\n };\n}\n\n/**\n * Validate UTXOs and throw if any are not available.\n *\n * Pure convenience function that combines validation and error throwing.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @throws UtxoNotAvailableError if any UTXOs are not available\n * @throws Error if validation fails\n */\nexport function assertUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): void {\n const result = validateUtxosAvailable(unsignedTxHex, availableUtxos);\n\n if (!result.allAvailable) {\n throw new UtxoNotAvailableError(result.missingUtxos);\n }\n}\n","/**\n * UTXO reservation utilities for vault deposits.\n *\n * Handles tracking which UTXOs are already in use by pending deposits\n * and selecting available UTXOs with smart fallback logic.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { ContractStatus } from \"../../services/deposit/peginState\";\nimport {\n FEE_SAFETY_MARGIN,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"../fee/constants\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** A txid:vout pair uniquely identifying a UTXO (outpoint). */\nexport interface UtxoRef {\n txid: string;\n vout: number;\n}\n\n/** Narrow structural type for pending pegin data. */\nexport interface PendingPeginLike {\n /**\n * Optional vault id. When present, used to skip pending pegins that are\n * already indexed on-chain so the canonical vault copy wins over a\n * tamperable off-chain entry.\n */\n id?: string;\n selectedUTXOs?: Array<{ txid: string; vout: number }>;\n unsignedTxHex?: string;\n}\n\n/** Narrow structural type for vault data. */\nexport interface VaultLike {\n /**\n * Optional vault id. When present, enables on-chain correlation with\n * pending pegins sharing the same id.\n */\n id?: string;\n status: number;\n unsignedPrePeginTx: string;\n}\n\nexport interface SelectUtxosForDepositParams<\n T extends { txid: string; vout: number; value: number },\n> {\n /** All available UTXOs from the wallet. */\n availableUtxos: T[];\n /** UTXOs that are reserved/in-flight and should be avoided if possible. */\n reservedUtxoRefs: UtxoRef[];\n /** Required deposit amount in satoshis (excluding fees). */\n requiredAmount: bigint;\n /** Fee rate in sat/vB. Used to estimate fee buffer for sufficiency check. */\n feeRate: number;\n}\n\n/** Narrow structural type for early UTXO reservations (pre-ETH-registration). */\nexport interface UtxoReservationLike {\n unsignedTxHex: string;\n}\n\nexport interface CollectReservedUtxoRefsParams {\n vaults?: VaultLike[];\n pendingPegins?: PendingPeginLike[];\n utxoReservations?: UtxoReservationLike[];\n}\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n/**\n * Parse a transaction hex and return the UTXO references of all inputs.\n *\n * Parse failures are logged and yield no refs. A malformed hex from an\n * untrusted source (e.g. off-chain storage) must not silently collapse the\n * reservation set — logging makes tampering visible in telemetry instead\n * of swallowing the error.\n */\nfunction extractInputUtxoRefs(txHex: string): UtxoRef[] {\n try {\n const tx = Transaction.fromHex(stripHexPrefix(txHex));\n return tx.ins.map((input) => {\n const txid = Buffer.from(input.hash).reverse().toString(\"hex\");\n return { txid, vout: input.index };\n });\n } catch (error) {\n console.warn(\n \"[utxoReservation] Failed to parse transaction hex; skipping inputs\",\n {\n category: \"utxoReservation\",\n error: error instanceof Error ? error.message : String(error),\n },\n );\n return [];\n }\n}\n\n/** Check if a UTXO matches any reserved ref (case-insensitive txid comparison). */\nfunction isUtxoReserved(\n utxo: { txid: string; vout: number },\n reservedRefs: UtxoRef[],\n): boolean {\n const txidLower = utxo.txid.toLowerCase();\n return reservedRefs.some(\n (ref) => ref.txid.toLowerCase() === txidLower && ref.vout === utxo.vout,\n );\n}\n\n/**\n * Estimate minimum fee buffer for UTXO pre-selection.\n *\n * WARNING: This is a ROUGH ESTIMATE used only to check if unreserved UTXOs\n * are likely sufficient BEFORE the actual signing flow begins. The actual\n * fee calculation happens in the SDK's `selectUtxosForPegin` during signing.\n *\n * Assumptions:\n * - 2 inputs (conservative estimate for most deposits)\n * - 1 vault output (P2TR, 43 vBytes)\n * - 1 change output (P2TR, 43 vBytes)\n * - Transaction overhead (11 vBytes)\n * - 10% safety margin\n */\nfunction estimateMinimumFeeBuffer(feeRate: number): bigint {\n const ASSUMED_INPUTS = 2;\n\n const estimatedTxSize =\n ASSUMED_INPUTS * P2TR_INPUT_SIZE +\n MAX_NON_LEGACY_OUTPUT_SIZE + // vault output\n MAX_NON_LEGACY_OUTPUT_SIZE + // change output\n TX_BUFFER_SIZE_OVERHEAD;\n\n const estimatedFee = Math.ceil(estimatedTxSize * feeRate * FEE_SAFETY_MARGIN);\n return BigInt(estimatedFee);\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Collect UTXO refs from in-flight deposits (PENDING/VERIFIED vaults and\n * pending pegins).\n *\n * On-chain vault data is canonical: for any pending pegin whose `id` matches\n * an indexed on-chain vault, the pending-pegin copy is ignored entirely —\n * the `vaults` branch below extracts refs from the indexer-supplied\n * `unsignedPrePeginTx` so tampered off-chain data cannot poison the\n * reservation set once the vault is indexed.\n *\n * For pegins not yet indexed, refs are derived from the stored\n * `unsignedTxHex` only. The `selectedUTXOs` sidecar is NOT used for\n * reservation: if it disagreed with the transaction's inputs (e.g. because\n * the off-chain source was tampered), trusting it would poison the reserved\n * set. The transaction hex must be validated at the source boundary before\n * being handed to this function; parsing and using its inputs is the single\n * source of truth here.\n */\nexport function collectReservedUtxoRefs(\n params: CollectReservedUtxoRefsParams,\n): UtxoRef[] {\n const reserved: UtxoRef[] = [];\n const {\n vaults = [],\n pendingPegins = [],\n utxoReservations = [],\n } = params;\n\n const onChainVaultIds = new Set(\n vaults\n .map((v) => v.id?.toLowerCase())\n .filter((id): id is string => id !== undefined),\n );\n\n for (const pending of pendingPegins) {\n if (pending.id && onChainVaultIds.has(pending.id.toLowerCase())) {\n continue;\n }\n if (pending.unsignedTxHex) {\n reserved.push(...extractInputUtxoRefs(pending.unsignedTxHex));\n }\n }\n\n for (const vault of vaults) {\n if (\n vault.status !== ContractStatus.PENDING &&\n vault.status !== ContractStatus.VERIFIED\n ) {\n continue;\n }\n reserved.push(...extractInputUtxoRefs(vault.unsignedPrePeginTx));\n }\n\n // Early reservations written before ETH registration to prevent cross-tab\n // UTXO conflicts. These are cleaned up when the deposit completes or fails.\n for (const reservation of utxoReservations) {\n reserved.push(...extractInputUtxoRefs(reservation.unsignedTxHex));\n }\n\n return reserved;\n}\n\n/**\n * Select UTXOs for a deposit, filtering out reserved ones.\n *\n * Logic:\n * 1. Filter out reserved UTXOs from the available pool\n * 2. If unreserved UTXOs are sufficient for the required amount + estimated fee, return them\n * 3. Otherwise, throw — never silently reuse reserved UTXOs, as this risks double-spend\n * failures that strand registered-but-unbroadcastable vaults\n *\n * @param params - Selection parameters\n * @returns Array of unreserved UTXOs to use for the deposit\n * @throws When all UTXOs are reserved or unreserved UTXOs are insufficient\n */\nexport function selectUtxosForDeposit<\n T extends { txid: string; vout: number; value: number },\n>(params: SelectUtxosForDepositParams<T>): T[] {\n const { availableUtxos, reservedUtxoRefs, requiredAmount, feeRate } = params;\n\n // Edge case: no UTXOs available\n if (!availableUtxos || availableUtxos.length === 0) {\n return [];\n }\n\n // Edge case: no reservations, return all\n if (reservedUtxoRefs.length === 0) {\n return availableUtxos;\n }\n\n // Filter out reserved UTXOs\n const unreserved = availableUtxos.filter(\n (utxo) => !isUtxoReserved(utxo, reservedUtxoRefs),\n );\n\n if (unreserved.length === 0) {\n throw new Error(\n \"All available UTXOs are reserved by pending deposits. \" +\n \"Wait for pending deposits to confirm or cancel them before starting a new deposit.\",\n );\n }\n\n const feeBuffer = estimateMinimumFeeBuffer(feeRate);\n const totalRequired = requiredAmount + feeBuffer;\n const unreservedTotal = unreserved.reduce(\n (sum, u) => sum + BigInt(u.value),\n 0n,\n );\n if (unreservedTotal < totalRequired) {\n throw new Error(\n \"Insufficient unreserved UTXOs for this deposit amount. \" +\n \"Wait for pending deposits to confirm or cancel them.\",\n );\n }\n\n return unreserved;\n}\n","/**\n * UTXO selection utilities for peg-in transactions.\n * Follows btc-staking-ts methodology with iterative fee calculation.\n */\n\nimport { script as bitcoinScript } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport {\n BTC_DUST_SAT,\n DUST_THRESHOLD,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n rateBasedTxBufferFee,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"../fee/constants\";\n\n/**\n * Unspent Transaction Output (UTXO) for funding peg-in transactions.\n */\nexport interface UTXO {\n /**\n * Transaction ID of the UTXO (64-char hex without 0x prefix).\n */\n txid: string;\n\n /**\n * Output index within the transaction.\n */\n vout: number;\n\n /**\n * Value in satoshis.\n */\n value: number;\n\n /**\n * Script public key hex.\n */\n scriptPubKey: string;\n}\n\nexport interface UTXOSelectionResult {\n selectedUTXOs: UTXO[];\n totalValue: bigint;\n fee: bigint;\n changeAmount: bigint;\n}\n\n/**\n * Assert that no two UTXOs share the same txid:vout outpoint.\n * Duplicates from a buggy or compromised UTXO source would produce\n * an invalid Bitcoin transaction that double-spends the same outpoint.\n */\nfunction assertNoDuplicateUtxos(utxos: UTXO[]): void {\n const seen = new Set<string>();\n for (const utxo of utxos) {\n const key = `${utxo.txid.toLowerCase()}:${utxo.vout}`;\n if (seen.has(key)) {\n throw new Error(\n `Duplicate UTXO detected: ${utxo.txid}:${utxo.vout}. ` +\n `This indicates a data integrity issue with the UTXO source.`,\n );\n }\n seen.add(key);\n }\n}\n\n/**\n * Selects UTXOs to fund a peg-in transaction with iterative fee calculation.\n *\n * This function implements the btc-staking-ts approach:\n * 1. Filter UTXOs for script validity (no minimum value filter)\n * 2. Sort by value (largest first) to minimize number of inputs\n * 3. Iteratively add UTXOs and recalculate fee until we have enough\n *\n * The fee recalculation is critical because:\n * - Each UTXO added increases transaction size → increases fee\n * - More fee needed might require another UTXO\n * - Change output detection affects fee (adds output size if needed)\n *\n * @param availableUTXOs - All available UTXOs from wallet\n * @param peginAmount - Amount to peg in (satoshis)\n * @param feeRate - Fee rate (sat/vbyte)\n * @param numOutputs - Number of outputs in the unfunded transaction (HTLC + CPFP anchor, before change)\n * @returns Selected UTXOs, total value, calculated fee, and change amount\n * @throws Error if insufficient funds or no valid UTXOs\n */\nexport function selectUtxosForPegin(\n availableUTXOs: UTXO[],\n peginAmount: bigint,\n feeRate: number,\n numOutputs: number,\n): UTXOSelectionResult {\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `Invalid numOutputs: expected a positive integer, got ${numOutputs}`,\n );\n }\n\n if (availableUTXOs.length === 0) {\n throw new Error(\"Insufficient funds: no UTXOs available\");\n }\n\n assertNoDuplicateUtxos(availableUTXOs);\n\n // Filter for script validity ONLY (matching btc-staking-ts approach)\n // No minimum value filter - we accept any UTXO with valid script\n const validUTXOs = availableUTXOs.filter((utxo) => {\n const script = Buffer.from(utxo.scriptPubKey, \"hex\");\n const decompiledScript = bitcoinScript.decompile(script);\n return !!decompiledScript;\n });\n\n if (validUTXOs.length === 0) {\n throw new Error(\n \"Insufficient funds: no valid UTXOs available (all have invalid scripts)\",\n );\n }\n\n // Sort by value: HIGHEST to LOWEST (use big UTXOs first)\n // Use spread to avoid mutating the original array\n const sortedUTXOs = [...validUTXOs].sort((a, b) => b.value - a.value);\n\n const selectedUTXOs: UTXO[] = [];\n let accumulatedValue = 0n;\n let estimatedFee = 0n;\n\n // Iteratively select UTXOs and recalculate fee\n for (const utxo of sortedUTXOs) {\n selectedUTXOs.push(utxo);\n accumulatedValue += BigInt(utxo.value);\n\n // Recalculate fee based on CURRENT number of inputs\n const inputSize = selectedUTXOs.length * P2TR_INPUT_SIZE;\n const outputSize = numOutputs * MAX_NON_LEGACY_OUTPUT_SIZE;\n const baseTxSize = inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD;\n\n // Calculate base fee with buffer\n estimatedFee =\n BigInt(Math.ceil(baseTxSize * feeRate)) +\n BigInt(rateBasedTxBufferFee(feeRate));\n\n // Check if there will be change left after pegin amount and fee\n const changeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n // If change is above dust, add fee for change output\n if (changeAmount > DUST_THRESHOLD) {\n const changeOutputFee = BigInt(\n Math.ceil(MAX_NON_LEGACY_OUTPUT_SIZE * feeRate),\n );\n estimatedFee += changeOutputFee;\n }\n\n // Check if we have enough to cover pegin amount + fees\n if (accumulatedValue >= peginAmount + estimatedFee) {\n // Success! We have enough funds\n const finalChangeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n return {\n selectedUTXOs,\n totalValue: accumulatedValue,\n fee: estimatedFee,\n changeAmount: finalChangeAmount,\n };\n }\n }\n\n // If we get here, we don't have enough funds\n throw new Error(\n `Insufficient funds: need ${peginAmount + estimatedFee} sats (${peginAmount} pegin + ${estimatedFee} fee), have ${accumulatedValue} sats`,\n );\n}\n\n/**\n * Checks if change amount is above dust threshold.\n *\n * @param changeAmount - Change amount in satoshis\n * @returns true if change should be added as output, false if it should go to miners\n */\nexport function shouldAddChangeOutput(changeAmount: bigint): boolean {\n return changeAmount > DUST_THRESHOLD;\n}\n\n/**\n * Gets the dust threshold value.\n *\n * @returns Dust threshold in satoshis\n */\nexport function getDustThreshold(): number {\n return BTC_DUST_SAT;\n}\n","/**\n * Bitcoin Transaction Hash Utilities\n *\n * Provides utilities for calculating Bitcoin transaction hashes in a way that matches\n * the contract's BtcUtils.hashBtcTx() implementation.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport type { Hex } from \"viem\";\n\n/**\n * Calculate Bitcoin transaction hash\n *\n * This matches the contract's BtcUtils.hashBtcTx() implementation:\n * 1. Double SHA256 the transaction bytes\n * 2. Reverse the byte order (Bitcoin convention)\n *\n * The resulting hash is used as the unique vault identifier in the BTCVaultRegistry contract.\n *\n * @param txHex - Transaction hex (with or without 0x prefix)\n * @returns The transaction hash as Hex (with 0x prefix)\n */\nexport function calculateBtcTxHash(txHex: string): Hex {\n // Remove 0x prefix if present\n const cleanHex = txHex.startsWith(\"0x\") ? txHex.slice(2) : txHex;\n\n // Use bitcoinjs-lib to calculate transaction ID (already does double SHA256 + reverse)\n const tx = Transaction.fromHex(cleanHex);\n const txid = tx.getId();\n\n // Return with 0x prefix to match Ethereum hex format\n return `0x${txid}` as Hex;\n}\n","/**\n * Bitcoin Script Type Detection\n *\n * Utilities to detect Bitcoin script types for proper PSBT input construction.\n *\n * @module utils/btc/scriptType\n */\n\n/**\n * Bitcoin script types.\n */\nexport enum BitcoinScriptType {\n P2PKH = \"P2PKH\",\n P2SH = \"P2SH\",\n P2WPKH = \"P2WPKH\",\n P2WSH = \"P2WSH\",\n P2TR = \"P2TR\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/**\n * Detect the type of a Bitcoin script.\n *\n * @param scriptPubKey - The script public key buffer\n * @returns The detected script type\n *\n * @example\n * ```typescript\n * const scriptType = getScriptType(Buffer.from(scriptPubKeyHex, 'hex'));\n * if (scriptType === BitcoinScriptType.P2TR) {\n * // Handle Taproot input\n * }\n * ```\n */\nexport function getScriptType(scriptPubKey: Buffer): BitcoinScriptType {\n const length = scriptPubKey.length;\n\n // P2PKH: OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG (25 bytes)\n if (\n length === 25 &&\n scriptPubKey[0] === 0x76 && // OP_DUP\n scriptPubKey[1] === 0xa9 && // OP_HASH160\n scriptPubKey[2] === 0x14 && // Push 20 bytes\n scriptPubKey[23] === 0x88 && // OP_EQUALVERIFY\n scriptPubKey[24] === 0xac // OP_CHECKSIG\n ) {\n return BitcoinScriptType.P2PKH;\n }\n\n // P2SH: OP_HASH160 <20 bytes> OP_EQUAL (23 bytes)\n if (\n length === 23 &&\n scriptPubKey[0] === 0xa9 && // OP_HASH160\n scriptPubKey[1] === 0x14 && // Push 20 bytes\n scriptPubKey[22] === 0x87 // OP_EQUAL\n ) {\n return BitcoinScriptType.P2SH;\n }\n\n // P2WPKH: OP_0 <20 bytes> (22 bytes)\n if (\n length === 22 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x14 // Push 20 bytes\n ) {\n return BitcoinScriptType.P2WPKH;\n }\n\n // P2WSH: OP_0 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2WSH;\n }\n\n // P2TR (Taproot): OP_1 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x51 && // OP_1\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2TR;\n }\n\n return BitcoinScriptType.UNKNOWN;\n}\n\n","/**\n * PSBT Input Field Construction\n *\n * Constructs the correct PSBT input fields for a given UTXO based on its script type.\n *\n * @module utils/btc/psbtInputFields\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { BitcoinScriptType, getScriptType } from \"./scriptType\";\n\n/**\n * PSBT input fields for supported script types (P2TR, P2WPKH, P2WSH).\n */\nexport interface PsbtInputFields {\n witnessUtxo?: {\n script: Buffer;\n value: number;\n };\n witnessScript?: Buffer;\n tapInternalKey?: Buffer;\n}\n\n/**\n * UTXO information for PSBT construction.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n */\nexport interface UtxoForPsbt {\n /** Transaction ID of the UTXO */\n txid: string;\n /** Output index (vout) of the UTXO */\n vout: number;\n /** Value of the UTXO in satoshis */\n value: number;\n /** ScriptPubKey of the UTXO (hex string) */\n scriptPubKey: string;\n /** Witness script (required for P2WSH) */\n witnessScript?: string;\n}\n\n/**\n * Get PSBT input fields for a given UTXO based on its script type.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param utxo - The unspent transaction output to process\n * @param publicKeyNoCoord - The x-only public key (32 bytes) for Taproot signing\n * @returns PSBT input fields object containing the necessary data\n * @throws Error if required input data is missing or unsupported script type\n */\nexport function getPsbtInputFields(\n utxo: UtxoForPsbt,\n publicKeyNoCoord?: Buffer,\n): PsbtInputFields {\n const scriptPubKey = Buffer.from(utxo.scriptPubKey, \"hex\");\n const type = getScriptType(scriptPubKey);\n\n switch (type) {\n case BitcoinScriptType.P2WPKH: {\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n };\n }\n\n case BitcoinScriptType.P2WSH: {\n if (!utxo.witnessScript) {\n throw new Error(\"Missing witnessScript for P2WSH input\");\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n witnessScript: Buffer.from(utxo.witnessScript, \"hex\"),\n };\n }\n\n case BitcoinScriptType.P2TR: {\n if (publicKeyNoCoord && publicKeyNoCoord.length !== 32) {\n throw new Error(\n `Invalid tapInternalKey length: expected 32 bytes, got ${publicKeyNoCoord.length}`,\n );\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n // tapInternalKey is needed for Taproot signing\n ...(publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }),\n };\n }\n\n default:\n throw new Error(`Unsupported script type: ${type}`);\n }\n}\n\n"],"names":["UtxoNotAvailableError","missingUtxos","count","message","__publicField","extractInputsFromTransaction","unsignedTxHex","cleanHex","tx","Transaction","error","input","Buffer","validateUtxosAvailable","availableUtxos","inputs","inputKeys","key","availableSet","utxo","assertUtxosAvailable","result","extractInputUtxoRefs","txHex","stripHexPrefix","isUtxoReserved","reservedRefs","txidLower","ref","estimateMinimumFeeBuffer","feeRate","estimatedTxSize","P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","estimatedFee","FEE_SAFETY_MARGIN","collectReservedUtxoRefs","params","reserved","vaults","pendingPegins","utxoReservations","onChainVaultIds","v","_a","id","pending","vault","ContractStatus","reservation","selectUtxosForDeposit","reservedUtxoRefs","requiredAmount","unreserved","feeBuffer","totalRequired","sum","u","assertNoDuplicateUtxos","utxos","seen","selectUtxosForPegin","availableUTXOs","peginAmount","numOutputs","validUTXOs","script","bitcoinScript","sortedUTXOs","a","b","selectedUTXOs","accumulatedValue","inputSize","outputSize","baseTxSize","rateBasedTxBufferFee","DUST_THRESHOLD","changeOutputFee","finalChangeAmount","shouldAddChangeOutput","changeAmount","getDustThreshold","BTC_DUST_SAT","calculateBtcTxHash","BitcoinScriptType","getScriptType","scriptPubKey","length","getPsbtInputFields","publicKeyNoCoord","type"],"mappings":"+VAyCO,MAAMA,UAA8B,KAAM,CAG/C,YAAYC,EAAiC,CAC3C,MAAMC,EAAQD,EAAa,OACrBE,EACJD,IAAU,EACN,4JACA,GAAGA,CAAK,qIAEd,MAAMC,CAAO,EATCC,EAAA,qBAUd,KAAK,KAAO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AO,CAC5B,GAAI,CAACnE,EAAK,cACR,MAAM,IAAI,MAAM,uCAAuC,EAEzD,MAAO,CACL,YAAa,CACX,OAAQqE,EACR,MAAOrE,EAAK,KAAA,EAEd,cAAeP,EAAAA,OAAO,KAAKO,EAAK,cAAe,KAAK,CAAA,CAExD,CAEA,KAAKmE,EAAkB,KAAM,CAC3B,GAAIK,GAAoBA,EAAiB,SAAW,GAClD,MAAM,IAAI,MACR,yDAAyDA,EAAiB,MAAM,EAAA,EAGpF,MAAO,CACL,YAAa,CACX,OAAQH,EACR,MAAOrE,EAAK,KAAA,EAGd,GAAIwE,GAAoB,CAAE,eAAgBA,CAAA,CAAiB,CAE/D,CAEA,QACE,MAAM,IAAI,MAAM,4BAA4BC,CAAI,EAAE,CAAA,CAExD"}
@@ -1,264 +0,0 @@
1
- var I = Object.defineProperty;
2
- var P = (t, e, n) => e in t ? I(t, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[e] = n;
3
- var p = (t, e, n) => P(t, typeof e != "symbol" ? e + "" : e, n);
4
- import { Transaction as x, script as H } from "bitcoinjs-lib";
5
- import { Buffer as f } from "buffer";
6
- import { s as $ } from "./bitcoin-0_T6KJON.js";
7
- import { C as m } from "./signing-BZigafm0.js";
8
- import { F as O, P as U, M as h, T, r as R, D as S, B as A } from "./fundPeginTransaction-oV-dNJOU.js";
9
- class F extends Error {
10
- constructor(n) {
11
- const s = n.length, a = s === 1 ? "The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO." : `${s} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;
12
- super(a);
13
- p(this, "missingUtxos");
14
- this.name = "UtxoNotAvailableError", this.missingUtxos = n;
15
- }
16
- }
17
- function N(t) {
18
- const e = t.startsWith("0x") ? t.slice(2) : t;
19
- let n;
20
- try {
21
- n = x.fromHex(e);
22
- } catch (s) {
23
- throw new Error(
24
- `Failed to parse BTC transaction: ${s instanceof Error ? s.message : String(s)}`
25
- );
26
- }
27
- return n.ins.map((s) => ({
28
- // Bitcoin stores txid in reverse byte order
29
- txid: f.from(s.hash).reverse().toString("hex"),
30
- vout: s.index
31
- }));
32
- }
33
- function W(t, e) {
34
- const n = N(t);
35
- if (n.length === 0)
36
- throw new Error("Transaction has no inputs");
37
- const s = /* @__PURE__ */ new Set();
38
- for (const r of n) {
39
- const o = `${r.txid.toLowerCase()}:${r.vout}`;
40
- if (s.has(o))
41
- throw new Error(
42
- `Transaction contains duplicate input ${r.txid}:${r.vout}. This would produce an invalid Bitcoin transaction.`
43
- );
44
- s.add(o);
45
- }
46
- const a = new Set(
47
- e.map((r) => `${r.txid.toLowerCase()}:${r.vout}`)
48
- ), i = [];
49
- for (const r of n) {
50
- const o = `${r.txid.toLowerCase()}:${r.vout}`;
51
- a.has(o) || i.push({
52
- txid: r.txid,
53
- vout: r.vout
54
- });
55
- }
56
- return {
57
- allAvailable: i.length === 0,
58
- missingUtxos: i,
59
- totalInputs: n.length
60
- };
61
- }
62
- function z(t, e) {
63
- const n = W(t, e);
64
- if (!n.allAvailable)
65
- throw new F(n.missingUtxos);
66
- }
67
- function g(t) {
68
- try {
69
- return x.fromHex($(t)).ins.map((n) => ({ txid: f.from(n.hash).reverse().toString("hex"), vout: n.index }));
70
- } catch (e) {
71
- return console.warn(
72
- "[utxoReservation] Failed to parse transaction hex; skipping inputs",
73
- {
74
- category: "utxoReservation",
75
- error: e instanceof Error ? e.message : String(e)
76
- }
77
- ), [];
78
- }
79
- }
80
- function _(t, e) {
81
- const n = t.txid.toLowerCase();
82
- return e.some(
83
- (s) => s.txid.toLowerCase() === n && s.vout === t.vout
84
- );
85
- }
86
- function B(t) {
87
- const n = 2 * U + h + // vault output
88
- h + // change output
89
- T, s = Math.ceil(n * t * O);
90
- return BigInt(s);
91
- }
92
- function G(t) {
93
- const e = [], {
94
- vaults: n = [],
95
- pendingPegins: s = [],
96
- utxoReservations: a = []
97
- } = t, i = new Set(
98
- n.map((r) => {
99
- var o;
100
- return (o = r.id) == null ? void 0 : o.toLowerCase();
101
- }).filter((r) => r !== void 0)
102
- );
103
- for (const r of s)
104
- r.id && i.has(r.id.toLowerCase()) || r.unsignedTxHex && e.push(...g(r.unsignedTxHex));
105
- for (const r of n)
106
- r.status !== m.PENDING && r.status !== m.VERIFIED || e.push(...g(r.unsignedPrePeginTx));
107
- for (const r of a)
108
- e.push(...g(r.unsignedTxHex));
109
- return e;
110
- }
111
- function Z(t) {
112
- const { availableUtxos: e, reservedUtxoRefs: n, requiredAmount: s, feeRate: a } = t;
113
- if (!e || e.length === 0)
114
- return [];
115
- if (n.length === 0)
116
- return e;
117
- const i = e.filter(
118
- (c) => !_(c, n)
119
- );
120
- if (i.length === 0)
121
- throw new Error(
122
- "All available UTXOs are reserved by pending deposits. Wait for pending deposits to confirm or cancel them before starting a new deposit."
123
- );
124
- const r = B(a), o = s + r;
125
- if (i.reduce(
126
- (c, l) => c + BigInt(l.value),
127
- 0n
128
- ) < o)
129
- throw new Error(
130
- "Insufficient unreserved UTXOs for this deposit amount. Wait for pending deposits to confirm or cancel them."
131
- );
132
- return i;
133
- }
134
- function D(t) {
135
- const e = /* @__PURE__ */ new Set();
136
- for (const n of t) {
137
- const s = `${n.txid.toLowerCase()}:${n.vout}`;
138
- if (e.has(s))
139
- throw new Error(
140
- `Duplicate UTXO detected: ${n.txid}:${n.vout}. This indicates a data integrity issue with the UTXO source.`
141
- );
142
- e.add(s);
143
- }
144
- }
145
- function Y(t, e, n, s) {
146
- if (!Number.isInteger(s) || s < 1)
147
- throw new Error(
148
- `Invalid numOutputs: expected a positive integer, got ${s}`
149
- );
150
- if (t.length === 0)
151
- throw new Error("Insufficient funds: no UTXOs available");
152
- D(t);
153
- const a = t.filter((c) => {
154
- const l = f.from(c.scriptPubKey, "hex");
155
- return !!H.decompile(l);
156
- });
157
- if (a.length === 0)
158
- throw new Error(
159
- "Insufficient funds: no valid UTXOs available (all have invalid scripts)"
160
- );
161
- const i = [...a].sort((c, l) => l.value - c.value), r = [];
162
- let o = 0n, u = 0n;
163
- for (const c of i) {
164
- r.push(c), o += BigInt(c.value);
165
- const l = r.length * U, w = s * h, E = l + w + T;
166
- if (u = BigInt(Math.ceil(E * n)) + BigInt(R(n)), o - e - u > S) {
167
- const v = BigInt(
168
- Math.ceil(h * n)
169
- );
170
- u += v;
171
- }
172
- if (o >= e + u) {
173
- const v = o - e - u;
174
- return {
175
- selectedUTXOs: r,
176
- totalValue: o,
177
- fee: u,
178
- changeAmount: v
179
- };
180
- }
181
- }
182
- throw new Error(
183
- `Insufficient funds: need ${e + u} sats (${e} pegin + ${u} fee), have ${o} sats`
184
- );
185
- }
186
- function j(t) {
187
- return t > S;
188
- }
189
- function J() {
190
- return A;
191
- }
192
- function Q(t) {
193
- const e = t.startsWith("0x") ? t.slice(2) : t;
194
- return `0x${x.fromHex(e).getId()}`;
195
- }
196
- var d = /* @__PURE__ */ ((t) => (t.P2PKH = "P2PKH", t.P2SH = "P2SH", t.P2WPKH = "P2WPKH", t.P2WSH = "P2WSH", t.P2TR = "P2TR", t.UNKNOWN = "UNKNOWN", t))(d || {});
197
- function X(t) {
198
- const e = t.length;
199
- return e === 25 && t[0] === 118 && // OP_DUP
200
- t[1] === 169 && // OP_HASH160
201
- t[2] === 20 && // Push 20 bytes
202
- t[23] === 136 && // OP_EQUALVERIFY
203
- t[24] === 172 ? "P2PKH" : e === 23 && t[0] === 169 && // OP_HASH160
204
- t[1] === 20 && // Push 20 bytes
205
- t[22] === 135 ? "P2SH" : e === 22 && t[0] === 0 && // OP_0
206
- t[1] === 20 ? "P2WPKH" : e === 34 && t[0] === 0 && // OP_0
207
- t[1] === 32 ? "P2WSH" : e === 34 && t[0] === 81 && // OP_1
208
- t[1] === 32 ? "P2TR" : "UNKNOWN";
209
- }
210
- function y(t, e) {
211
- const n = f.from(t.scriptPubKey, "hex"), s = X(n);
212
- switch (s) {
213
- case d.P2WPKH:
214
- return {
215
- witnessUtxo: {
216
- script: n,
217
- value: t.value
218
- }
219
- };
220
- case d.P2WSH: {
221
- if (!t.witnessScript)
222
- throw new Error("Missing witnessScript for P2WSH input");
223
- return {
224
- witnessUtxo: {
225
- script: n,
226
- value: t.value
227
- },
228
- witnessScript: f.from(t.witnessScript, "hex")
229
- };
230
- }
231
- case d.P2TR: {
232
- if (e && e.length !== 32)
233
- throw new Error(
234
- `Invalid tapInternalKey length: expected 32 bytes, got ${e.length}`
235
- );
236
- return {
237
- witnessUtxo: {
238
- script: n,
239
- value: t.value
240
- },
241
- // tapInternalKey is needed for Taproot signing
242
- ...e && { tapInternalKey: e }
243
- };
244
- }
245
- default:
246
- throw new Error(`Unsupported script type: ${s}`);
247
- }
248
- }
249
- export {
250
- d as B,
251
- F as U,
252
- z as a,
253
- Y as b,
254
- G as c,
255
- j as d,
256
- N as e,
257
- Q as f,
258
- J as g,
259
- X as h,
260
- y as i,
261
- Z as s,
262
- W as v
263
- };
264
- //# sourceMappingURL=psbtInputFields-DPCFHgGd.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"psbtInputFields-DPCFHgGd.js","sources":["../src/tbv/core/utils/utxo/availability.ts","../src/tbv/core/utils/utxo/reservation.ts","../src/tbv/core/utils/utxo/selectUtxos.ts","../src/tbv/core/utils/transaction/btcTxHash.ts","../src/tbv/core/utils/btc/scriptType.ts","../src/tbv/core/utils/btc/psbtInputFields.ts"],"sourcesContent":["/**\n * UTXO Availability Validation\n *\n * Validates that UTXOs referenced in a pre-pegin transaction are still unspent\n * BEFORE asking the user to sign. This prevents wasted signing effort when\n * UTXOs have already been spent by unrelated transactions.\n *\n * These functions are pure — they accept pre-fetched UTXOs and perform no I/O.\n * The vault service wrapper is responsible for fetching UTXOs from the mempool.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { UtxoRef } from \"./reservation\";\n\n/**\n * Information about a missing/spent UTXO.\n */\nexport interface MissingUtxoInfo {\n /** Transaction ID of the missing UTXO */\n txid: string;\n /** Output index of the missing UTXO */\n vout: number;\n}\n\n/**\n * Result of UTXO validation.\n */\nexport interface UtxoValidationResult {\n /** Whether all UTXOs are still available */\n allAvailable: boolean;\n /** List of missing UTXOs (if any) */\n missingUtxos: MissingUtxoInfo[];\n /** Total number of inputs checked */\n totalInputs: number;\n}\n\n/**\n * Error thrown when UTXOs are not available.\n */\nexport class UtxoNotAvailableError extends Error {\n public readonly missingUtxos: MissingUtxoInfo[];\n\n constructor(missingUtxos: MissingUtxoInfo[]) {\n const count = missingUtxos.length;\n const message =\n count === 1\n ? \"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.\"\n : `${count} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;\n\n super(message);\n this.name = \"UtxoNotAvailableError\";\n this.missingUtxos = missingUtxos;\n }\n}\n\n/**\n * Extract input references (txid:vout) from an unsigned transaction.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @returns Array of input references\n */\nexport function extractInputsFromTransaction(\n unsignedTxHex: string,\n): Array<{ txid: string; vout: number }> {\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n\n let tx: Transaction;\n try {\n tx = Transaction.fromHex(cleanHex);\n } catch (error) {\n throw new Error(\n `Failed to parse BTC transaction: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n return tx.ins.map((input) => ({\n // Bitcoin stores txid in reverse byte order\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n}\n\n/**\n * Validate that all UTXOs in a transaction are still available.\n *\n * Pure function — accepts pre-fetched UTXOs instead of making network calls.\n * This should be called BEFORE signing to avoid wasting user effort\n * signing a transaction that will fail to broadcast.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @returns Validation result with missing UTXO details\n */\nexport function validateUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): UtxoValidationResult {\n const inputs = extractInputsFromTransaction(unsignedTxHex);\n\n if (inputs.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Detect duplicate inputs (same txid:vout referenced more than once).\n // This would produce an invalid Bitcoin transaction.\n const inputKeys = new Set<string>();\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (inputKeys.has(key)) {\n throw new Error(\n `Transaction contains duplicate input ${input.txid}:${input.vout}. ` +\n `This would produce an invalid Bitcoin transaction.`,\n );\n }\n inputKeys.add(key);\n }\n\n // Create a set of available UTXOs for O(1) lookup (lowercase for consistency with reservation.ts)\n const availableSet = new Set(\n availableUtxos.map((utxo) => `${utxo.txid.toLowerCase()}:${utxo.vout}`),\n );\n\n // Check which inputs are missing\n const missingUtxos: MissingUtxoInfo[] = [];\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (!availableSet.has(key)) {\n missingUtxos.push({\n txid: input.txid,\n vout: input.vout,\n });\n }\n }\n\n return {\n allAvailable: missingUtxos.length === 0,\n missingUtxos,\n totalInputs: inputs.length,\n };\n}\n\n/**\n * Validate UTXOs and throw if any are not available.\n *\n * Pure convenience function that combines validation and error throwing.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @throws UtxoNotAvailableError if any UTXOs are not available\n * @throws Error if validation fails\n */\nexport function assertUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): void {\n const result = validateUtxosAvailable(unsignedTxHex, availableUtxos);\n\n if (!result.allAvailable) {\n throw new UtxoNotAvailableError(result.missingUtxos);\n }\n}\n","/**\n * UTXO reservation utilities for vault deposits.\n *\n * Handles tracking which UTXOs are already in use by pending deposits\n * and selecting available UTXOs with smart fallback logic.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { ContractStatus } from \"../../services/deposit/peginState\";\nimport {\n FEE_SAFETY_MARGIN,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"../fee/constants\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** A txid:vout pair uniquely identifying a UTXO (outpoint). */\nexport interface UtxoRef {\n txid: string;\n vout: number;\n}\n\n/** Narrow structural type for pending pegin data. */\nexport interface PendingPeginLike {\n /**\n * Optional vault id. When present, used to skip pending pegins that are\n * already indexed on-chain so the canonical vault copy wins over a\n * tamperable off-chain entry.\n */\n id?: string;\n selectedUTXOs?: Array<{ txid: string; vout: number }>;\n unsignedTxHex?: string;\n}\n\n/** Narrow structural type for vault data. */\nexport interface VaultLike {\n /**\n * Optional vault id. When present, enables on-chain correlation with\n * pending pegins sharing the same id.\n */\n id?: string;\n status: number;\n unsignedPrePeginTx: string;\n}\n\nexport interface SelectUtxosForDepositParams<\n T extends { txid: string; vout: number; value: number },\n> {\n /** All available UTXOs from the wallet. */\n availableUtxos: T[];\n /** UTXOs that are reserved/in-flight and should be avoided if possible. */\n reservedUtxoRefs: UtxoRef[];\n /** Required deposit amount in satoshis (excluding fees). */\n requiredAmount: bigint;\n /** Fee rate in sat/vB. Used to estimate fee buffer for sufficiency check. */\n feeRate: number;\n}\n\n/** Narrow structural type for early UTXO reservations (pre-ETH-registration). */\nexport interface UtxoReservationLike {\n unsignedTxHex: string;\n}\n\nexport interface CollectReservedUtxoRefsParams {\n vaults?: VaultLike[];\n pendingPegins?: PendingPeginLike[];\n utxoReservations?: UtxoReservationLike[];\n}\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n/**\n * Parse a transaction hex and return the UTXO references of all inputs.\n *\n * Parse failures are logged and yield no refs. A malformed hex from an\n * untrusted source (e.g. off-chain storage) must not silently collapse the\n * reservation set — logging makes tampering visible in telemetry instead\n * of swallowing the error.\n */\nfunction extractInputUtxoRefs(txHex: string): UtxoRef[] {\n try {\n const tx = Transaction.fromHex(stripHexPrefix(txHex));\n return tx.ins.map((input) => {\n const txid = Buffer.from(input.hash).reverse().toString(\"hex\");\n return { txid, vout: input.index };\n });\n } catch (error) {\n console.warn(\n \"[utxoReservation] Failed to parse transaction hex; skipping inputs\",\n {\n category: \"utxoReservation\",\n error: error instanceof Error ? error.message : String(error),\n },\n );\n return [];\n }\n}\n\n/** Check if a UTXO matches any reserved ref (case-insensitive txid comparison). */\nfunction isUtxoReserved(\n utxo: { txid: string; vout: number },\n reservedRefs: UtxoRef[],\n): boolean {\n const txidLower = utxo.txid.toLowerCase();\n return reservedRefs.some(\n (ref) => ref.txid.toLowerCase() === txidLower && ref.vout === utxo.vout,\n );\n}\n\n/**\n * Estimate minimum fee buffer for UTXO pre-selection.\n *\n * WARNING: This is a ROUGH ESTIMATE used only to check if unreserved UTXOs\n * are likely sufficient BEFORE the actual signing flow begins. The actual\n * fee calculation happens in the SDK's `selectUtxosForPegin` during signing.\n *\n * Assumptions:\n * - 2 inputs (conservative estimate for most deposits)\n * - 1 vault output (P2TR, 43 vBytes)\n * - 1 change output (P2TR, 43 vBytes)\n * - Transaction overhead (11 vBytes)\n * - 10% safety margin\n */\nfunction estimateMinimumFeeBuffer(feeRate: number): bigint {\n const ASSUMED_INPUTS = 2;\n\n const estimatedTxSize =\n ASSUMED_INPUTS * P2TR_INPUT_SIZE +\n MAX_NON_LEGACY_OUTPUT_SIZE + // vault output\n MAX_NON_LEGACY_OUTPUT_SIZE + // change output\n TX_BUFFER_SIZE_OVERHEAD;\n\n const estimatedFee = Math.ceil(estimatedTxSize * feeRate * FEE_SAFETY_MARGIN);\n return BigInt(estimatedFee);\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Collect UTXO refs from in-flight deposits (PENDING/VERIFIED vaults and\n * pending pegins).\n *\n * On-chain vault data is canonical: for any pending pegin whose `id` matches\n * an indexed on-chain vault, the pending-pegin copy is ignored entirely —\n * the `vaults` branch below extracts refs from the indexer-supplied\n * `unsignedPrePeginTx` so tampered off-chain data cannot poison the\n * reservation set once the vault is indexed.\n *\n * For pegins not yet indexed, refs are derived from the stored\n * `unsignedTxHex` only. The `selectedUTXOs` sidecar is NOT used for\n * reservation: if it disagreed with the transaction's inputs (e.g. because\n * the off-chain source was tampered), trusting it would poison the reserved\n * set. The transaction hex must be validated at the source boundary before\n * being handed to this function; parsing and using its inputs is the single\n * source of truth here.\n */\nexport function collectReservedUtxoRefs(\n params: CollectReservedUtxoRefsParams,\n): UtxoRef[] {\n const reserved: UtxoRef[] = [];\n const {\n vaults = [],\n pendingPegins = [],\n utxoReservations = [],\n } = params;\n\n const onChainVaultIds = new Set(\n vaults\n .map((v) => v.id?.toLowerCase())\n .filter((id): id is string => id !== undefined),\n );\n\n for (const pending of pendingPegins) {\n if (pending.id && onChainVaultIds.has(pending.id.toLowerCase())) {\n continue;\n }\n if (pending.unsignedTxHex) {\n reserved.push(...extractInputUtxoRefs(pending.unsignedTxHex));\n }\n }\n\n for (const vault of vaults) {\n if (\n vault.status !== ContractStatus.PENDING &&\n vault.status !== ContractStatus.VERIFIED\n ) {\n continue;\n }\n reserved.push(...extractInputUtxoRefs(vault.unsignedPrePeginTx));\n }\n\n // Early reservations written before ETH registration to prevent cross-tab\n // UTXO conflicts. These are cleaned up when the deposit completes or fails.\n for (const reservation of utxoReservations) {\n reserved.push(...extractInputUtxoRefs(reservation.unsignedTxHex));\n }\n\n return reserved;\n}\n\n/**\n * Select UTXOs for a deposit, filtering out reserved ones.\n *\n * Logic:\n * 1. Filter out reserved UTXOs from the available pool\n * 2. If unreserved UTXOs are sufficient for the required amount + estimated fee, return them\n * 3. Otherwise, throw — never silently reuse reserved UTXOs, as this risks double-spend\n * failures that strand registered-but-unbroadcastable vaults\n *\n * @param params - Selection parameters\n * @returns Array of unreserved UTXOs to use for the deposit\n * @throws When all UTXOs are reserved or unreserved UTXOs are insufficient\n */\nexport function selectUtxosForDeposit<\n T extends { txid: string; vout: number; value: number },\n>(params: SelectUtxosForDepositParams<T>): T[] {\n const { availableUtxos, reservedUtxoRefs, requiredAmount, feeRate } = params;\n\n // Edge case: no UTXOs available\n if (!availableUtxos || availableUtxos.length === 0) {\n return [];\n }\n\n // Edge case: no reservations, return all\n if (reservedUtxoRefs.length === 0) {\n return availableUtxos;\n }\n\n // Filter out reserved UTXOs\n const unreserved = availableUtxos.filter(\n (utxo) => !isUtxoReserved(utxo, reservedUtxoRefs),\n );\n\n if (unreserved.length === 0) {\n throw new Error(\n \"All available UTXOs are reserved by pending deposits. \" +\n \"Wait for pending deposits to confirm or cancel them before starting a new deposit.\",\n );\n }\n\n const feeBuffer = estimateMinimumFeeBuffer(feeRate);\n const totalRequired = requiredAmount + feeBuffer;\n const unreservedTotal = unreserved.reduce(\n (sum, u) => sum + BigInt(u.value),\n 0n,\n );\n if (unreservedTotal < totalRequired) {\n throw new Error(\n \"Insufficient unreserved UTXOs for this deposit amount. \" +\n \"Wait for pending deposits to confirm or cancel them.\",\n );\n }\n\n return unreserved;\n}\n","/**\n * UTXO selection utilities for peg-in transactions.\n * Follows btc-staking-ts methodology with iterative fee calculation.\n */\n\nimport { script as bitcoinScript } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport {\n BTC_DUST_SAT,\n DUST_THRESHOLD,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n rateBasedTxBufferFee,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"../fee/constants\";\n\n/**\n * Unspent Transaction Output (UTXO) for funding peg-in transactions.\n */\nexport interface UTXO {\n /**\n * Transaction ID of the UTXO (64-char hex without 0x prefix).\n */\n txid: string;\n\n /**\n * Output index within the transaction.\n */\n vout: number;\n\n /**\n * Value in satoshis.\n */\n value: number;\n\n /**\n * Script public key hex.\n */\n scriptPubKey: string;\n}\n\nexport interface UTXOSelectionResult {\n selectedUTXOs: UTXO[];\n totalValue: bigint;\n fee: bigint;\n changeAmount: bigint;\n}\n\n/**\n * Assert that no two UTXOs share the same txid:vout outpoint.\n * Duplicates from a buggy or compromised UTXO source would produce\n * an invalid Bitcoin transaction that double-spends the same outpoint.\n */\nfunction assertNoDuplicateUtxos(utxos: UTXO[]): void {\n const seen = new Set<string>();\n for (const utxo of utxos) {\n const key = `${utxo.txid.toLowerCase()}:${utxo.vout}`;\n if (seen.has(key)) {\n throw new Error(\n `Duplicate UTXO detected: ${utxo.txid}:${utxo.vout}. ` +\n `This indicates a data integrity issue with the UTXO source.`,\n );\n }\n seen.add(key);\n }\n}\n\n/**\n * Selects UTXOs to fund a peg-in transaction with iterative fee calculation.\n *\n * This function implements the btc-staking-ts approach:\n * 1. Filter UTXOs for script validity (no minimum value filter)\n * 2. Sort by value (largest first) to minimize number of inputs\n * 3. Iteratively add UTXOs and recalculate fee until we have enough\n *\n * The fee recalculation is critical because:\n * - Each UTXO added increases transaction size → increases fee\n * - More fee needed might require another UTXO\n * - Change output detection affects fee (adds output size if needed)\n *\n * @param availableUTXOs - All available UTXOs from wallet\n * @param peginAmount - Amount to peg in (satoshis)\n * @param feeRate - Fee rate (sat/vbyte)\n * @param numOutputs - Number of outputs in the unfunded transaction (HTLC + CPFP anchor, before change)\n * @returns Selected UTXOs, total value, calculated fee, and change amount\n * @throws Error if insufficient funds or no valid UTXOs\n */\nexport function selectUtxosForPegin(\n availableUTXOs: UTXO[],\n peginAmount: bigint,\n feeRate: number,\n numOutputs: number,\n): UTXOSelectionResult {\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `Invalid numOutputs: expected a positive integer, got ${numOutputs}`,\n );\n }\n\n if (availableUTXOs.length === 0) {\n throw new Error(\"Insufficient funds: no UTXOs available\");\n }\n\n assertNoDuplicateUtxos(availableUTXOs);\n\n // Filter for script validity ONLY (matching btc-staking-ts approach)\n // No minimum value filter - we accept any UTXO with valid script\n const validUTXOs = availableUTXOs.filter((utxo) => {\n const script = Buffer.from(utxo.scriptPubKey, \"hex\");\n const decompiledScript = bitcoinScript.decompile(script);\n return !!decompiledScript;\n });\n\n if (validUTXOs.length === 0) {\n throw new Error(\n \"Insufficient funds: no valid UTXOs available (all have invalid scripts)\",\n );\n }\n\n // Sort by value: HIGHEST to LOWEST (use big UTXOs first)\n // Use spread to avoid mutating the original array\n const sortedUTXOs = [...validUTXOs].sort((a, b) => b.value - a.value);\n\n const selectedUTXOs: UTXO[] = [];\n let accumulatedValue = 0n;\n let estimatedFee = 0n;\n\n // Iteratively select UTXOs and recalculate fee\n for (const utxo of sortedUTXOs) {\n selectedUTXOs.push(utxo);\n accumulatedValue += BigInt(utxo.value);\n\n // Recalculate fee based on CURRENT number of inputs\n const inputSize = selectedUTXOs.length * P2TR_INPUT_SIZE;\n const outputSize = numOutputs * MAX_NON_LEGACY_OUTPUT_SIZE;\n const baseTxSize = inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD;\n\n // Calculate base fee with buffer\n estimatedFee =\n BigInt(Math.ceil(baseTxSize * feeRate)) +\n BigInt(rateBasedTxBufferFee(feeRate));\n\n // Check if there will be change left after pegin amount and fee\n const changeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n // If change is above dust, add fee for change output\n if (changeAmount > DUST_THRESHOLD) {\n const changeOutputFee = BigInt(\n Math.ceil(MAX_NON_LEGACY_OUTPUT_SIZE * feeRate),\n );\n estimatedFee += changeOutputFee;\n }\n\n // Check if we have enough to cover pegin amount + fees\n if (accumulatedValue >= peginAmount + estimatedFee) {\n // Success! We have enough funds\n const finalChangeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n return {\n selectedUTXOs,\n totalValue: accumulatedValue,\n fee: estimatedFee,\n changeAmount: finalChangeAmount,\n };\n }\n }\n\n // If we get here, we don't have enough funds\n throw new Error(\n `Insufficient funds: need ${peginAmount + estimatedFee} sats (${peginAmount} pegin + ${estimatedFee} fee), have ${accumulatedValue} sats`,\n );\n}\n\n/**\n * Checks if change amount is above dust threshold.\n *\n * @param changeAmount - Change amount in satoshis\n * @returns true if change should be added as output, false if it should go to miners\n */\nexport function shouldAddChangeOutput(changeAmount: bigint): boolean {\n return changeAmount > DUST_THRESHOLD;\n}\n\n/**\n * Gets the dust threshold value.\n *\n * @returns Dust threshold in satoshis\n */\nexport function getDustThreshold(): number {\n return BTC_DUST_SAT;\n}\n","/**\n * Bitcoin Transaction Hash Utilities\n *\n * Provides utilities for calculating Bitcoin transaction hashes in a way that matches\n * the contract's BtcUtils.hashBtcTx() implementation.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport type { Hex } from \"viem\";\n\n/**\n * Calculate Bitcoin transaction hash\n *\n * This matches the contract's BtcUtils.hashBtcTx() implementation:\n * 1. Double SHA256 the transaction bytes\n * 2. Reverse the byte order (Bitcoin convention)\n *\n * The resulting hash is used as the unique vault identifier in the BTCVaultRegistry contract.\n *\n * @param txHex - Transaction hex (with or without 0x prefix)\n * @returns The transaction hash as Hex (with 0x prefix)\n */\nexport function calculateBtcTxHash(txHex: string): Hex {\n // Remove 0x prefix if present\n const cleanHex = txHex.startsWith(\"0x\") ? txHex.slice(2) : txHex;\n\n // Use bitcoinjs-lib to calculate transaction ID (already does double SHA256 + reverse)\n const tx = Transaction.fromHex(cleanHex);\n const txid = tx.getId();\n\n // Return with 0x prefix to match Ethereum hex format\n return `0x${txid}` as Hex;\n}\n","/**\n * Bitcoin Script Type Detection\n *\n * Utilities to detect Bitcoin script types for proper PSBT input construction.\n *\n * @module utils/btc/scriptType\n */\n\n/**\n * Bitcoin script types.\n */\nexport enum BitcoinScriptType {\n P2PKH = \"P2PKH\",\n P2SH = \"P2SH\",\n P2WPKH = \"P2WPKH\",\n P2WSH = \"P2WSH\",\n P2TR = \"P2TR\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/**\n * Detect the type of a Bitcoin script.\n *\n * @param scriptPubKey - The script public key buffer\n * @returns The detected script type\n *\n * @example\n * ```typescript\n * const scriptType = getScriptType(Buffer.from(scriptPubKeyHex, 'hex'));\n * if (scriptType === BitcoinScriptType.P2TR) {\n * // Handle Taproot input\n * }\n * ```\n */\nexport function getScriptType(scriptPubKey: Buffer): BitcoinScriptType {\n const length = scriptPubKey.length;\n\n // P2PKH: OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG (25 bytes)\n if (\n length === 25 &&\n scriptPubKey[0] === 0x76 && // OP_DUP\n scriptPubKey[1] === 0xa9 && // OP_HASH160\n scriptPubKey[2] === 0x14 && // Push 20 bytes\n scriptPubKey[23] === 0x88 && // OP_EQUALVERIFY\n scriptPubKey[24] === 0xac // OP_CHECKSIG\n ) {\n return BitcoinScriptType.P2PKH;\n }\n\n // P2SH: OP_HASH160 <20 bytes> OP_EQUAL (23 bytes)\n if (\n length === 23 &&\n scriptPubKey[0] === 0xa9 && // OP_HASH160\n scriptPubKey[1] === 0x14 && // Push 20 bytes\n scriptPubKey[22] === 0x87 // OP_EQUAL\n ) {\n return BitcoinScriptType.P2SH;\n }\n\n // P2WPKH: OP_0 <20 bytes> (22 bytes)\n if (\n length === 22 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x14 // Push 20 bytes\n ) {\n return BitcoinScriptType.P2WPKH;\n }\n\n // P2WSH: OP_0 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2WSH;\n }\n\n // P2TR (Taproot): OP_1 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x51 && // OP_1\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2TR;\n }\n\n return BitcoinScriptType.UNKNOWN;\n}\n\n","/**\n * PSBT Input Field Construction\n *\n * Constructs the correct PSBT input fields for a given UTXO based on its script type.\n *\n * @module utils/btc/psbtInputFields\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { BitcoinScriptType, getScriptType } from \"./scriptType\";\n\n/**\n * PSBT input fields for supported script types (P2TR, P2WPKH, P2WSH).\n */\nexport interface PsbtInputFields {\n witnessUtxo?: {\n script: Buffer;\n value: number;\n };\n witnessScript?: Buffer;\n tapInternalKey?: Buffer;\n}\n\n/**\n * UTXO information for PSBT construction.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n */\nexport interface UtxoForPsbt {\n /** Transaction ID of the UTXO */\n txid: string;\n /** Output index (vout) of the UTXO */\n vout: number;\n /** Value of the UTXO in satoshis */\n value: number;\n /** ScriptPubKey of the UTXO (hex string) */\n scriptPubKey: string;\n /** Witness script (required for P2WSH) */\n witnessScript?: string;\n}\n\n/**\n * Get PSBT input fields for a given UTXO based on its script type.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param utxo - The unspent transaction output to process\n * @param publicKeyNoCoord - The x-only public key (32 bytes) for Taproot signing\n * @returns PSBT input fields object containing the necessary data\n * @throws Error if required input data is missing or unsupported script type\n */\nexport function getPsbtInputFields(\n utxo: UtxoForPsbt,\n publicKeyNoCoord?: Buffer,\n): PsbtInputFields {\n const scriptPubKey = Buffer.from(utxo.scriptPubKey, \"hex\");\n const type = getScriptType(scriptPubKey);\n\n switch (type) {\n case BitcoinScriptType.P2WPKH: {\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n };\n }\n\n case BitcoinScriptType.P2WSH: {\n if (!utxo.witnessScript) {\n throw new Error(\"Missing witnessScript for P2WSH input\");\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n witnessScript: Buffer.from(utxo.witnessScript, \"hex\"),\n };\n }\n\n case BitcoinScriptType.P2TR: {\n if (publicKeyNoCoord && publicKeyNoCoord.length !== 32) {\n throw new Error(\n `Invalid tapInternalKey length: expected 32 bytes, got ${publicKeyNoCoord.length}`,\n );\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n // tapInternalKey is needed for Taproot signing\n ...(publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }),\n };\n }\n\n default:\n throw new Error(`Unsupported script type: ${type}`);\n }\n}\n\n"],"names":["UtxoNotAvailableError","missingUtxos","count","message","__publicField","extractInputsFromTransaction","unsignedTxHex","cleanHex","tx","Transaction","error","input","Buffer","validateUtxosAvailable","availableUtxos","inputs","inputKeys","key","availableSet","utxo","assertUtxosAvailable","result","extractInputUtxoRefs","txHex","stripHexPrefix","isUtxoReserved","reservedRefs","txidLower","ref","estimateMinimumFeeBuffer","feeRate","estimatedTxSize","P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","estimatedFee","FEE_SAFETY_MARGIN","collectReservedUtxoRefs","params","reserved","vaults","pendingPegins","utxoReservations","onChainVaultIds","v","_a","id","pending","vault","ContractStatus","reservation","selectUtxosForDeposit","reservedUtxoRefs","requiredAmount","unreserved","feeBuffer","totalRequired","sum","u","assertNoDuplicateUtxos","utxos","seen","selectUtxosForPegin","availableUTXOs","peginAmount","numOutputs","validUTXOs","script","bitcoinScript","sortedUTXOs","a","b","selectedUTXOs","accumulatedValue","inputSize","outputSize","baseTxSize","rateBasedTxBufferFee","DUST_THRESHOLD","changeOutputFee","finalChangeAmount","shouldAddChangeOutput","changeAmount","getDustThreshold","BTC_DUST_SAT","calculateBtcTxHash","BitcoinScriptType","getScriptType","scriptPubKey","length","getPsbtInputFields","publicKeyNoCoord","type"],"mappings":";;;;;;;;AAyCO,MAAMA,UAA8B,MAAM;AAAA,EAG/C,YAAYC,GAAiC;AAC3C,UAAMC,IAAQD,EAAa,QACrBE,IACJD,MAAU,IACN,8JACA,GAAGA,CAAK;AAEd,UAAMC,CAAO;AATC,IAAAC,EAAA;AAUd,SAAK,OAAO,yBACZ,KAAK,eAAeH;AAAA,EACtB;AACF;AAQO,SAASI,EACdC,GACuC;AACvC,QAAMC,IAAWD,EAAc,WAAW,IAAI,IAC1CA,EAAc,MAA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,MAAM;AAAA,EACpBA,EAAa,CAAC,MAAM,KAEb,SAGF;AACT;ACnCO,SAASE,EACdvE,GACAwE,GACiB;AACjB,QAAMH,IAAe5E,EAAO,KAAKO,EAAK,cAAc,KAAK,GACnDyE,IAAOL,EAAcC,CAAY;AAEvC,UAAQI,GAAA;AAAA,IACN,KAAKN,EAAkB;AACrB,aAAO;AAAA,QACL,aAAa;AAAA,UACX,QAAQE;AAAA,UACR,OAAOrE,EAAK;AAAA,QAAA;AAAA,MACd;AAAA,IAIJ,KAAKmE,EAAkB,OAAO;AAC5B,UAAI,CAACnE,EAAK;AACR,cAAM,IAAI,MAAM,uCAAuC;AAEzD,aAAO;AAAA,QACL,aAAa;AAAA,UACX,QAAQqE;AAAA,UACR,OAAOrE,EAAK;AAAA,QAAA;AAAA,QAEd,eAAeP,EAAO,KAAKO,EAAK,eAAe,KAAK;AAAA,MAAA;AAAA,IAExD;AAAA,IAEA,KAAKmE,EAAkB,MAAM;AAC3B,UAAIK,KAAoBA,EAAiB,WAAW;AAClD,cAAM,IAAI;AAAA,UACR,yDAAyDA,EAAiB,MAAM;AAAA,QAAA;AAGpF,aAAO;AAAA,QACL,aAAa;AAAA,UACX,QAAQH;AAAA,UACR,OAAOrE,EAAK;AAAA,QAAA;AAAA;AAAA,QAGd,GAAIwE,KAAoB,EAAE,gBAAgBA,EAAA;AAAA,MAAiB;AAAA,IAE/D;AAAA,IAEA;AACE,YAAM,IAAI,MAAM,4BAA4BC,CAAI,EAAE;AAAA,EAAA;AAExD;"}
@@ -1,64 +0,0 @@
1
- var _ = /* @__PURE__ */ ((e) => (e[e.PENDING = 0] = "PENDING", e[e.VERIFIED = 1] = "VERIFIED", e[e.ACTIVE = 2] = "ACTIVE", e[e.REDEEMED = 3] = "REDEEMED", e[e.LIQUIDATED = 4] = "LIQUIDATED", e[e.INVALID = 5] = "INVALID", e[e.DEPOSITOR_WITHDRAWN = 6] = "DEPOSITOR_WITHDRAWN", e[e.EXPIRED = 7] = "EXPIRED", e))(_ || {}), N = /* @__PURE__ */ ((e) => (e.SUBMIT_WOTS_KEY = "SUBMIT_WOTS_KEY", e.SIGN_PAYOUT_TRANSACTIONS = "SIGN_PAYOUT_TRANSACTIONS", e.SIGN_AND_BROADCAST_TO_BITCOIN = "SIGN_AND_BROADCAST_TO_BITCOIN", e.ACTIVATE_VAULT = "ACTIVATE_VAULT", e.REFUND_HTLC = "REFUND_HTLC", e))(N || {});
2
- function D(e, i = {}) {
3
- const {
4
- transactionsReady: A,
5
- needsWotsKey: T,
6
- pendingIngestion: I,
7
- canRefund: l,
8
- hasProviderTerminalFailure: E
9
- } = i;
10
- return e === 0 ? E ? { contractStatus: e, availableActions: [] } : T ? {
11
- contractStatus: e,
12
- availableActions: [
13
- "SUBMIT_WOTS_KEY"
14
- /* SUBMIT_WOTS_KEY */
15
- ]
16
- } : I === !0 && !A ? {
17
- contractStatus: e,
18
- availableActions: [
19
- "SIGN_AND_BROADCAST_TO_BITCOIN"
20
- /* SIGN_AND_BROADCAST_TO_BITCOIN */
21
- ]
22
- } : I === void 0 && !A ? { contractStatus: e, availableActions: [] } : A ? {
23
- contractStatus: e,
24
- availableActions: [
25
- "SIGN_PAYOUT_TRANSACTIONS"
26
- /* SIGN_PAYOUT_TRANSACTIONS */
27
- ]
28
- } : { contractStatus: e, availableActions: [] } : e === 1 ? {
29
- contractStatus: e,
30
- availableActions: [
31
- "ACTIVATE_VAULT"
32
- /* ACTIVATE_VAULT */
33
- ]
34
- } : e === 2 ? { contractStatus: e, availableActions: [] } : e === 3 ? { contractStatus: e, availableActions: [] } : e === 4 ? { contractStatus: e, availableActions: [] } : e === 7 ? {
35
- contractStatus: e,
36
- availableActions: l ? [
37
- "REFUND_HTLC"
38
- /* REFUND_HTLC */
39
- ] : []
40
- } : e === 5 ? { contractStatus: e, availableActions: [] } : e === 6 ? { contractStatus: e, availableActions: [] } : { contractStatus: e, availableActions: [] };
41
- }
42
- function r(e, i) {
43
- return e.availableActions.includes(i);
44
- }
45
- function O(e, i) {
46
- if (!Number.isInteger(i) || i < 1)
47
- throw new Error(`inputCount must be a positive integer, got ${i}`);
48
- return {
49
- autoFinalized: !1,
50
- signInputs: Array.from({ length: i }, (A, T) => ({
51
- index: T,
52
- publicKey: e,
53
- useTweakedSigner: !1
54
- }))
55
- };
56
- }
57
- export {
58
- _ as C,
59
- N as P,
60
- r as a,
61
- O as c,
62
- D as g
63
- };
64
- //# sourceMappingURL=signing-BZigafm0.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"signing-BZigafm0.js","sources":["../src/tbv/core/services/deposit/peginState.ts","../src/tbv/core/utils/signing.ts"],"sourcesContent":["// ============================================================================\n// State Definitions\n// ============================================================================\n\n/**\n * Vault status — combines on-chain contract status (0-4) with indexer-derived\n * statuses (5-7). The contract enum (BTCVaultRegistry.sol BTCVaultStatus) only\n * has: Pending(0), Verified(1), Active(2), Redeemed(3), Expired(4).\n * The indexer maps these and adds extra statuses for UI display.\n *\n * IMPORTANT: With the new contract architecture:\n * - Core vault status (BTCVaultRegistry) does NOT change when used by applications\n * - Vaults remain at ACTIVE status even when used in DeFi positions\n * - Application usage status is tracked separately by each integration controller\n */\nexport enum ContractStatus {\n /** Status 0: Request submitted, waiting for ACKs */\n PENDING = 0,\n /** Status 1: All ACKs collected, ready for secret activation */\n VERIFIED = 1,\n /** Status 2: HTLC secret revealed, vault is active and usable (stays here even when used by apps) */\n ACTIVE = 2,\n /** Status 3: Vault has been redeemed, BTC is claimable */\n REDEEMED = 3,\n /** Status 4 (indexer-only): Vault was liquidated (collateral seized due to unpaid debt) */\n LIQUIDATED = 4,\n /** Status 5 (indexer-only): Vault is invalid — BTC UTXOs were spent in a different transaction */\n INVALID = 5,\n /** Status 6 (indexer-only): Depositor has withdrawn their BTC (redemption complete) */\n DEPOSITOR_WITHDRAWN = 6,\n /** Status 7 (indexer-only): Vault expired due to AckTimeout or ActivationTimeout */\n EXPIRED = 7,\n}\n\n/** Reason why a vault expired */\nexport type ExpirationReason =\n | \"ack_timeout\"\n | \"proof_timeout\"\n | \"activation_timeout\";\n\n// ============================================================================\n// Protocol State Model\n// ============================================================================\n\n/**\n * Available actions user can take\n */\nexport enum PeginAction {\n /** Submit WOTS key (re-derives via wallet `deriveContextHash`) */\n SUBMIT_WOTS_KEY = \"SUBMIT_WOTS_KEY\",\n /** Sign payout transactions */\n SIGN_PAYOUT_TRANSACTIONS = \"SIGN_PAYOUT_TRANSACTIONS\",\n /** Sign and broadcast peg-in transaction to Bitcoin */\n SIGN_AND_BROADCAST_TO_BITCOIN = \"SIGN_AND_BROADCAST_TO_BITCOIN\",\n /** Reveal HTLC secret on Ethereum to activate vault */\n ACTIVATE_VAULT = \"ACTIVATE_VAULT\",\n /** Sign and broadcast HTLC refund transaction for an expired vault */\n REFUND_HTLC = \"REFUND_HTLC\",\n}\n\n/**\n * Protocol-level peg-in state (framework-agnostic)\n */\nexport interface PeginProtocolState {\n /** Smart contract status (source of truth for on-chain state) */\n contractStatus: ContractStatus;\n /** Available user actions (empty array when no action is available) */\n availableActions: PeginAction[];\n}\n\n/**\n * Options for getPeginProtocolState function.\n *\n * All fields represent protocol-level state from the vault provider or\n * on-chain contracts. Client-side tracking (localStorage, polling state)\n * is NOT included — consumers handle that in their own layer.\n */\nexport interface GetPeginProtocolStateOptions {\n /** Whether claim/payout transactions are ready from VP */\n transactionsReady?: boolean;\n /** Whether the vault provider is waiting for the depositor's WOTS public key */\n needsWotsKey?: boolean;\n /** Whether the vault provider hasn't ingested this peg-in yet */\n pendingIngestion?: boolean;\n /** Whether the depositor can refund the HTLC (Pre-PegIn tx available) */\n canRefund?: boolean;\n /** Whether the vault provider reported a terminal failure */\n hasProviderTerminalFailure?: boolean;\n}\n\n// ============================================================================\n// State Machine Logic\n// ============================================================================\n\n/**\n * Determine the current protocol state and available actions based on contract\n * status and vault provider state. Framework-agnostic: returns only\n * protocol-level data with no display labels, messages, or UI concerns.\n *\n * Client-side tracking overrides (e.g. suppressing actions after the user\n * has already acted but on-chain state hasn't caught up) are the caller's\n * responsibility.\n *\n * @param contractStatus - On-chain contract status (source of truth)\n * @param options - Vault provider state\n * @returns Protocol state with available actions\n */\nexport function getPeginProtocolState(\n contractStatus: ContractStatus,\n options: GetPeginProtocolStateOptions = {},\n): PeginProtocolState {\n const {\n transactionsReady,\n needsWotsKey,\n pendingIngestion,\n canRefund,\n hasProviderTerminalFailure,\n } = options;\n\n if (contractStatus === ContractStatus.PENDING) {\n if (hasProviderTerminalFailure) {\n return { contractStatus, availableActions: [] };\n }\n\n if (needsWotsKey) {\n return {\n contractStatus,\n availableActions: [PeginAction.SUBMIT_WOTS_KEY],\n };\n }\n\n if (pendingIngestion === true && !transactionsReady) {\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_AND_BROADCAST_TO_BITCOIN],\n };\n }\n\n if (pendingIngestion === undefined && !transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n if (!transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_PAYOUT_TRANSACTIONS],\n };\n }\n\n if (contractStatus === ContractStatus.VERIFIED) {\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_VAULT],\n };\n }\n\n if (contractStatus === ContractStatus.ACTIVE) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.REDEEMED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.LIQUIDATED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.EXPIRED) {\n return {\n contractStatus,\n availableActions: canRefund ? [PeginAction.REFUND_HTLC] : [],\n };\n }\n\n if (contractStatus === ContractStatus.INVALID) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.DEPOSITOR_WITHDRAWN) {\n return { contractStatus, availableActions: [] };\n }\n\n return { contractStatus, availableActions: [] };\n}\n\n/**\n * Check if a specific action is available in the current state\n */\nexport function canPerformAction(\n state: PeginProtocolState,\n action: PeginAction,\n): boolean {\n return state.availableActions.includes(action);\n}\n","import type { SignPsbtOptions } from \"../../../shared/wallets/interfaces\";\n\n/**\n * Create SignPsbtOptions for Taproot script-path PSBT signing.\n *\n * All vault protocol signing operations are Taproot script-path spends that\n * require `useTweakedSigner: false` (untweaked key) and `autoFinalized: false`\n * (to preserve tapScriptSig for Schnorr signature extraction).\n *\n * @param publicKey - Signer's BTC public key (hex). Accepts both compressed\n * (66-char) and x-only (64-char) formats — the wallet connector handles both.\n * @param inputCount - Number of inputs to sign. Generates entries\n * for indices 0 through inputCount-1.\n */\nexport function createTaprootScriptPathSignOptions(\n publicKey: string,\n inputCount: number,\n): SignPsbtOptions {\n if (!Number.isInteger(inputCount) || inputCount < 1) {\n throw new Error(`inputCount must be a positive integer, got ${inputCount}`);\n }\n\n return {\n autoFinalized: false,\n signInputs: Array.from({ length: inputCount }, (_, i) => ({\n index: i,\n publicKey,\n useTweakedSigner: false,\n })),\n };\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","canPerformAction","state","action","createTaprootScriptPathSignOptions","publicKey","inputCount","_","i"],"mappings":"AAeO,IAAKA,sBAAAA,OAEVA,EAAAA,EAAA,UAAU,CAAA,IAAV,WAEAA,EAAAA,EAAA,WAAW,CAAA,IAAX,YAEAA,EAAAA,EAAA,SAAS,CAAA,IAAT,UAEAA,EAAAA,EAAA,WAAW,CAAA,IAAX,YAEAA,EAAAA,EAAA,aAAa,CAAA,IAAb,cAEAA,EAAAA,EAAA,UAAU,CAAA,IAAV,WAEAA,EAAAA,EAAA,sBAAsB,CAAA,IAAtB,uBAEAA,EAAAA,EAAA,UAAU,CAAA,IAAV,WAhBUA,IAAAA,KAAA,CAAA,CAAA,GAgCAC,sBAAAA,OAEVA,EAAA,kBAAkB,mBAElBA,EAAA,2BAA2B,4BAE3BA,EAAA,gCAAgC,iCAEhCA,EAAA,iBAAiB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AAgB,kBAAkB,GAAC;AAC9C;AAKO,SAASO,EACdC,GACAC,GACS;AACT,SAAOD,EAAM,iBAAiB,SAASC,CAAM;AAC/C;ACvLO,SAASC,EACdC,GACAC,GACiB;AACjB,MAAI,CAAC,OAAO,UAAUA,CAAU,KAAKA,IAAa;AAChD,UAAM,IAAI,MAAM,8CAA8CA,CAAU,EAAE;AAG5E,SAAO;AAAA,IACL,eAAe;AAAA,IACf,YAAY,MAAM,KAAK,EAAE,QAAQA,KAAc,CAACC,GAAGC,OAAO;AAAA,MACxD,OAAOA;AAAA,MACP,WAAAH;AAAA,MACA,kBAAkB;AAAA,IAAA,EAClB;AAAA,EAAA;AAEN;"}
@@ -1,2 +0,0 @@
1
- "use strict";var l=(e=>(e[e.PENDING=0]="PENDING",e[e.VERIFIED=1]="VERIFIED",e[e.ACTIVE=2]="ACTIVE",e[e.REDEEMED=3]="REDEEMED",e[e.LIQUIDATED=4]="LIQUIDATED",e[e.INVALID=5]="INVALID",e[e.DEPOSITOR_WITHDRAWN=6]="DEPOSITOR_WITHDRAWN",e[e.EXPIRED=7]="EXPIRED",e))(l||{}),E=(e=>(e.SUBMIT_WOTS_KEY="SUBMIT_WOTS_KEY",e.SIGN_PAYOUT_TRANSACTIONS="SIGN_PAYOUT_TRANSACTIONS",e.SIGN_AND_BROADCAST_TO_BITCOIN="SIGN_AND_BROADCAST_TO_BITCOIN",e.ACTIVATE_VAULT="ACTIVATE_VAULT",e.REFUND_HTLC="REFUND_HTLC",e))(E||{});function N(e,i={}){const{transactionsReady:A,needsWotsKey:T,pendingIngestion:I,canRefund:r,hasProviderTerminalFailure:_}=i;return e===0?_?{contractStatus:e,availableActions:[]}:T?{contractStatus:e,availableActions:["SUBMIT_WOTS_KEY"]}:I===!0&&!A?{contractStatus:e,availableActions:["SIGN_AND_BROADCAST_TO_BITCOIN"]}:I===void 0&&!A?{contractStatus:e,availableActions:[]}:A?{contractStatus:e,availableActions:["SIGN_PAYOUT_TRANSACTIONS"]}:{contractStatus:e,availableActions:[]}:e===1?{contractStatus:e,availableActions:["ACTIVATE_VAULT"]}:e===2?{contractStatus:e,availableActions:[]}:e===3?{contractStatus:e,availableActions:[]}:e===4?{contractStatus:e,availableActions:[]}:e===7?{contractStatus:e,availableActions:r?["REFUND_HTLC"]:[]}:e===5?{contractStatus:e,availableActions:[]}:e===6?{contractStatus:e,availableActions:[]}:{contractStatus:e,availableActions:[]}}function D(e,i){return e.availableActions.includes(i)}function n(e,i){if(!Number.isInteger(i)||i<1)throw new Error(`inputCount must be a positive integer, got ${i}`);return{autoFinalized:!1,signInputs:Array.from({length:i},(A,T)=>({index:T,publicKey:e,useTweakedSigner:!1}))}}exports.ContractStatus=l;exports.PeginAction=E;exports.canPerformAction=D;exports.createTaprootScriptPathSignOptions=n;exports.getPeginProtocolState=N;
2
- //# sourceMappingURL=signing-DHSXjhLM.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"signing-DHSXjhLM.cjs","sources":["../src/tbv/core/services/deposit/peginState.ts","../src/tbv/core/utils/signing.ts"],"sourcesContent":["// ============================================================================\n// State Definitions\n// ============================================================================\n\n/**\n * Vault status — combines on-chain contract status (0-4) with indexer-derived\n * statuses (5-7). The contract enum (BTCVaultRegistry.sol BTCVaultStatus) only\n * has: Pending(0), Verified(1), Active(2), Redeemed(3), Expired(4).\n * The indexer maps these and adds extra statuses for UI display.\n *\n * IMPORTANT: With the new contract architecture:\n * - Core vault status (BTCVaultRegistry) does NOT change when used by applications\n * - Vaults remain at ACTIVE status even when used in DeFi positions\n * - Application usage status is tracked separately by each integration controller\n */\nexport enum ContractStatus {\n /** Status 0: Request submitted, waiting for ACKs */\n PENDING = 0,\n /** Status 1: All ACKs collected, ready for secret activation */\n VERIFIED = 1,\n /** Status 2: HTLC secret revealed, vault is active and usable (stays here even when used by apps) */\n ACTIVE = 2,\n /** Status 3: Vault has been redeemed, BTC is claimable */\n REDEEMED = 3,\n /** Status 4 (indexer-only): Vault was liquidated (collateral seized due to unpaid debt) */\n LIQUIDATED = 4,\n /** Status 5 (indexer-only): Vault is invalid — BTC UTXOs were spent in a different transaction */\n INVALID = 5,\n /** Status 6 (indexer-only): Depositor has withdrawn their BTC (redemption complete) */\n DEPOSITOR_WITHDRAWN = 6,\n /** Status 7 (indexer-only): Vault expired due to AckTimeout or ActivationTimeout */\n EXPIRED = 7,\n}\n\n/** Reason why a vault expired */\nexport type ExpirationReason =\n | \"ack_timeout\"\n | \"proof_timeout\"\n | \"activation_timeout\";\n\n// ============================================================================\n// Protocol State Model\n// ============================================================================\n\n/**\n * Available actions user can take\n */\nexport enum PeginAction {\n /** Submit WOTS key (re-derives via wallet `deriveContextHash`) */\n SUBMIT_WOTS_KEY = \"SUBMIT_WOTS_KEY\",\n /** Sign payout transactions */\n SIGN_PAYOUT_TRANSACTIONS = \"SIGN_PAYOUT_TRANSACTIONS\",\n /** Sign and broadcast peg-in transaction to Bitcoin */\n SIGN_AND_BROADCAST_TO_BITCOIN = \"SIGN_AND_BROADCAST_TO_BITCOIN\",\n /** Reveal HTLC secret on Ethereum to activate vault */\n ACTIVATE_VAULT = \"ACTIVATE_VAULT\",\n /** Sign and broadcast HTLC refund transaction for an expired vault */\n REFUND_HTLC = \"REFUND_HTLC\",\n}\n\n/**\n * Protocol-level peg-in state (framework-agnostic)\n */\nexport interface PeginProtocolState {\n /** Smart contract status (source of truth for on-chain state) */\n contractStatus: ContractStatus;\n /** Available user actions (empty array when no action is available) */\n availableActions: PeginAction[];\n}\n\n/**\n * Options for getPeginProtocolState function.\n *\n * All fields represent protocol-level state from the vault provider or\n * on-chain contracts. Client-side tracking (localStorage, polling state)\n * is NOT included — consumers handle that in their own layer.\n */\nexport interface GetPeginProtocolStateOptions {\n /** Whether claim/payout transactions are ready from VP */\n transactionsReady?: boolean;\n /** Whether the vault provider is waiting for the depositor's WOTS public key */\n needsWotsKey?: boolean;\n /** Whether the vault provider hasn't ingested this peg-in yet */\n pendingIngestion?: boolean;\n /** Whether the depositor can refund the HTLC (Pre-PegIn tx available) */\n canRefund?: boolean;\n /** Whether the vault provider reported a terminal failure */\n hasProviderTerminalFailure?: boolean;\n}\n\n// ============================================================================\n// State Machine Logic\n// ============================================================================\n\n/**\n * Determine the current protocol state and available actions based on contract\n * status and vault provider state. Framework-agnostic: returns only\n * protocol-level data with no display labels, messages, or UI concerns.\n *\n * Client-side tracking overrides (e.g. suppressing actions after the user\n * has already acted but on-chain state hasn't caught up) are the caller's\n * responsibility.\n *\n * @param contractStatus - On-chain contract status (source of truth)\n * @param options - Vault provider state\n * @returns Protocol state with available actions\n */\nexport function getPeginProtocolState(\n contractStatus: ContractStatus,\n options: GetPeginProtocolStateOptions = {},\n): PeginProtocolState {\n const {\n transactionsReady,\n needsWotsKey,\n pendingIngestion,\n canRefund,\n hasProviderTerminalFailure,\n } = options;\n\n if (contractStatus === ContractStatus.PENDING) {\n if (hasProviderTerminalFailure) {\n return { contractStatus, availableActions: [] };\n }\n\n if (needsWotsKey) {\n return {\n contractStatus,\n availableActions: [PeginAction.SUBMIT_WOTS_KEY],\n };\n }\n\n if (pendingIngestion === true && !transactionsReady) {\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_AND_BROADCAST_TO_BITCOIN],\n };\n }\n\n if (pendingIngestion === undefined && !transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n if (!transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_PAYOUT_TRANSACTIONS],\n };\n }\n\n if (contractStatus === ContractStatus.VERIFIED) {\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_VAULT],\n };\n }\n\n if (contractStatus === ContractStatus.ACTIVE) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.REDEEMED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.LIQUIDATED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.EXPIRED) {\n return {\n contractStatus,\n availableActions: canRefund ? [PeginAction.REFUND_HTLC] : [],\n };\n }\n\n if (contractStatus === ContractStatus.INVALID) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.DEPOSITOR_WITHDRAWN) {\n return { contractStatus, availableActions: [] };\n }\n\n return { contractStatus, availableActions: [] };\n}\n\n/**\n * Check if a specific action is available in the current state\n */\nexport function canPerformAction(\n state: PeginProtocolState,\n action: PeginAction,\n): boolean {\n return state.availableActions.includes(action);\n}\n","import type { SignPsbtOptions } from \"../../../shared/wallets/interfaces\";\n\n/**\n * Create SignPsbtOptions for Taproot script-path PSBT signing.\n *\n * All vault protocol signing operations are Taproot script-path spends that\n * require `useTweakedSigner: false` (untweaked key) and `autoFinalized: false`\n * (to preserve tapScriptSig for Schnorr signature extraction).\n *\n * @param publicKey - Signer's BTC public key (hex). Accepts both compressed\n * (66-char) and x-only (64-char) formats — the wallet connector handles both.\n * @param inputCount - Number of inputs to sign. Generates entries\n * for indices 0 through inputCount-1.\n */\nexport function createTaprootScriptPathSignOptions(\n publicKey: string,\n inputCount: number,\n): SignPsbtOptions {\n if (!Number.isInteger(inputCount) || inputCount < 1) {\n throw new Error(`inputCount must be a positive integer, got ${inputCount}`);\n }\n\n return {\n autoFinalized: false,\n signInputs: Array.from({ length: inputCount }, (_, i) => ({\n index: i,\n publicKey,\n useTweakedSigner: false,\n })),\n };\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","canPerformAction","state","action","createTaprootScriptPathSignOptions","publicKey","inputCount","_","i"],"mappings":"aAeO,IAAKA,GAAAA,IAEVA,EAAAA,EAAA,QAAU,CAAA,EAAV,UAEAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WAEAA,EAAAA,EAAA,OAAS,CAAA,EAAT,SAEAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WAEAA,EAAAA,EAAA,WAAa,CAAA,EAAb,aAEA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AAC,EAGvC,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,CAC9C,CAKO,SAASO,EACdC,EACAC,EACS,CACT,OAAOD,EAAM,iBAAiB,SAASC,CAAM,CAC/C,CCvLO,SAASC,EACdC,EACAC,EACiB,CACjB,GAAI,CAAC,OAAO,UAAUA,CAAU,GAAKA,EAAa,EAChD,MAAM,IAAI,MAAM,8CAA8CA,CAAU,EAAE,EAG5E,MAAO,CACL,cAAe,GACf,WAAY,MAAM,KAAK,CAAE,OAAQA,GAAc,CAACC,EAAGC,KAAO,CACxD,MAAOA,EACP,UAAAH,EACA,iBAAkB,EAAA,EAClB,CAAA,CAEN"}
@@ -1,2 +0,0 @@
1
- "use strict";var _=Object.defineProperty;var N=(e,t,n)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var p=(e,t,n)=>N(e,typeof t!="symbol"?t+"":t,n);const O=[{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequestBatch",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"requests",type:"tuple[]",internalType:"struct IBTCVaultRegistry.BatchPeginRequest[]",components:[{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}]}],outputs:[{name:"vaultIds",type:"bytes32[]",internalType:"bytes32[]"}],stateMutability:"payable"},{type:"function",name:"activateVaultWithSecret",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"},{name:"s",type:"bytes32",internalType:"bytes32"},{name:"activationMetadata",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"getPegInFee",inputs:[{name:"vaultProvider",type:"address",internalType:"address"}],outputs:[{name:"totalFee",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getVaultProviderBTCKey",inputs:[{name:"vpAddr",type:"address",internalType:"address"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"getBtcVaultBasicInfo",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"vBasic",type:"tuple",internalType:"struct BTCVaultTypes.BTCVaultBasicInfo",components:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"status",type:"uint8",internalType:"enum IBTCVaultRegistry.BTCVaultStatus"},{name:"applicationEntryPoint",type:"address",internalType:"address"},{name:"createdAt",type:"uint256",internalType:"uint256"}]}],stateMutability:"view"},{type:"error",name:"InvalidPeginFee",inputs:[{name:"provided",type:"uint256",internalType:"uint256"},{name:"required",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidSecret",inputs:[]},{type:"error",name:"ActivationDeadlineExpired",inputs:[]},{type:"error",name:"InvalidHashlock",inputs:[]},{type:"error",name:"DuplicateHashlock",inputs:[]},{type:"error",name:"CapExceeded",inputs:[]},{type:"error",name:"InvalidOutputIndex",inputs:[]},{type:"error",name:"PeginSignaturesIncomplete",inputs:[]},{type:"function",name:"getBtcVaultProtocolInfo",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"vProtocol",type:"tuple",internalType:"struct BTCVaultRegistryTypes.BTCVaultProtocolInfo",components:[{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"universalChallengersVersion",type:"uint16",internalType:"uint16"},{name:"appVaultKeepersVersion",type:"uint16",internalType:"uint16"},{name:"offchainParamsVersion",type:"uint16",internalType:"uint16"},{name:"verifiedAt",type:"uint256",internalType:"uint256"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPopSignature",type:"bytes",internalType:"bytes"},{name:"prePeginTxHash",type:"bytes32",internalType:"bytes32"},{name:"vaultProviderCommissionBps",type:"uint16",internalType:"uint16"}]}],stateMutability:"view"},{type:"function",name:"protocolParams",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IProtocolParams"}],stateMutability:"view"},{type:"function",name:"applicationRegistry",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IApplicationRegistry"}],stateMutability:"view"}];class u extends Error{constructor(t,n,r="local",i){super(n),this.code=t,this.source=r,this.data=i,this.name="JsonRpcError"}}const c={TIMEOUT:-32e3,NETWORK:-32001,PROXY_TIMEOUT:-32002,PROXY_UNAVAILABLE:-32003,INVALID_RESPONSE:-32700,RESPONSE_TOO_LARGE:-32701},g="2.0",v=3,f=1e3,w=2*1024*1024,D=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),B=new Set([408,429,500,502,503,504]),L=new Set(["vaultProvider_getPeginStatus","vaultProvider_getPegoutStatus","vaultProvider_requestDepositorPresignTransactions"]);function V(e){return L.has(e)}const C="auth_expired";function U(e){if(!(e instanceof u)||e.source!=="wire")return!1;const t=e.data;return t===null||typeof t!="object"?!1:t.kind===C}class x{constructor(t){p(this,"baseUrl");p(this,"timeout");p(this,"headers");p(this,"requestId",0);p(this,"retries");p(this,"retryDelay");p(this,"maxResponseBytes");p(this,"retryableFor");p(this,"tokenProvider");if(this.baseUrl=t.baseUrl.replace(/\/$/,""),this.timeout=t.timeout,this.headers={"Content-Type":"application/json",...t.headers},this.retries=t.retries??v,this.retryDelay=t.retryDelay??f,this.maxResponseBytes=t.maxResponseBytes??w,!Number.isFinite(this.maxResponseBytes)||this.maxResponseBytes<=0)throw new Error("maxResponseBytes must be a positive finite number");this.retryableFor=t.retryableFor??V,this.tokenProvider=t.tokenProvider}async buildHeaders(t){const n={...this.headers};if(this.tokenProvider){const r=await this.tokenProvider.getToken(t);r&&(n.Authorization=`Bearer ${r}`)}return n}async call(t,n,r){try{return await this.callOnce(t,n,r)}catch(i){if(this.tokenProvider&&U(i))return this.tokenProvider.invalidate(),await this.callOnce(t,n,r);throw i}}async callOnce(t,n,r){const i=await this.fetchWithRetry(t,n,r);let s;try{const a=D.has(t)?await i.text():await k(i,this.maxResponseBytes);s=JSON.parse(a)}catch(a){throw a instanceof u?a:new u(c.INVALID_RESPONSE,"Invalid JSON-RPC response: body is not valid JSON","local")}if(s===null||typeof s!="object"||Array.isArray(s))throw new u(c.INVALID_RESPONSE,`Invalid JSON-RPC response: expected an object, got ${typeof s}`,"local");const o=s;if("error"in o&&o.error!=null){const a=o.error;throw new u(a.code??c.INVALID_RESPONSE,a.message??"Unknown RPC error","wire",a.data)}if(!("result"in o))throw new u(c.INVALID_RESPONSE,'Invalid JSON-RPC response: missing "result" field',"local");return o.result}async callRaw(t,n,r){return this.fetchWithRetry(t,n,r)}async fetchWithRetry(t,n,r){const i=++this.requestId,s=this.retryableFor(t)?this.retries:0,a=JSON.stringify({jsonrpc:g,method:t,params:[n],id:i});let P=null;for(let d=0;d<=s;d++){const b=new AbortController,E=setTimeout(()=>b.abort(),this.timeout),T=r?G(r,b.signal):null,A=T?T.signal:b.signal;try{const y=await this.buildHeaders(t),l=await fetch(this.baseUrl,{method:"POST",headers:y,body:a,signal:A});if(clearTimeout(E),T==null||T.cleanup(),!l.ok){if(d<s&&B.has(l.status)){const I=this.retryDelay*Math.pow(2,d);await this.sleep(I,r);continue}throw new Error(`HTTP error: ${l.status} ${l.statusText}`)}return l}catch(y){if(clearTimeout(E),T==null||T.cleanup(),P=y instanceof Error?y:new Error(String(y)),r!=null&&r.aborted)throw new Error("Request aborted");if(y instanceof Error&&y.name==="AbortError"){if(d<s){const l=this.retryDelay*Math.pow(2,d);await this.sleep(l,r);continue}throw new u(c.TIMEOUT,`Request timeout after ${this.timeout}ms (${s+1} attempts)`,"local")}if(y instanceof TypeError){if(d<s){const l=this.retryDelay*Math.pow(2,d);await this.sleep(l,r);continue}throw new u(c.NETWORK,`Network error: ${y.message} (${s+1} attempts)`,"local")}throw y}}throw P||new Error("Unknown error after retries")}sleep(t,n){return new Promise((r,i)=>{if(n!=null&&n.aborted){i(new Error("Request aborted"));return}const s=setTimeout(()=>{n==null||n.removeEventListener("abort",o),r()},t),o=()=>{clearTimeout(s),i(new Error("Request aborted"))};n==null||n.addEventListener("abort",o,{once:!0})})}getBaseUrl(){return this.baseUrl}}function G(e,t){if(e.aborted)return{signal:e,cleanup:()=>{}};if(t.aborted)return{signal:t,cleanup:()=>{}};const n=new AbortController,r=()=>{t.removeEventListener("abort",i),n.abort()},i=()=>{e.removeEventListener("abort",r),n.abort()};e.addEventListener("abort",r,{once:!0}),t.addEventListener("abort",i,{once:!0});const s=()=>{e.removeEventListener("abort",r),t.removeEventListener("abort",i)};return{signal:n.signal,cleanup:s}}async function k(e,t){const n=e.headers.get("content-length");if(n!==null){const a=Number(n);if(Number.isFinite(a)&&a>t)throw m(t)}if(!e.body)return"";const r=e.body.getReader(),i=new TextDecoder;let s=0,o="";try{for(;;){const{done:a,value:P}=await r.read();if(a)break;if(P){if(s+=P.byteLength,s>t)throw await r.cancel(),m(t);o+=i.decode(P,{stream:!0})}}}finally{r.releaseLock()}return o+i.decode()}function m(e){return new u(c.RESPONSE_TOO_LARGE,`JSON-RPC response exceeds maximum size of ${e} bytes`,"local")}var R=(e=>(e.PENDING_INGESTION="PendingIngestion",e.PENDING_DEPOSITOR_WOTS_PK="PendingDepositorWotsPK",e.PENDING_BABE_SETUP="PendingBabeSetup",e.PENDING_CHALLENGER_PRESIGNING="PendingChallengerPresigning",e.PENDING_PEGIN_SIGS_AVAILABILITY="PendingPeginSigsAvailability",e.PENDING_PRE_PEGIN_CONFIRMATIONS="PendingPrePegInConfirmations",e.PENDING_DEPOSITOR_SIGNATURES="PendingDepositorSignatures",e.PENDING_ACKS="PendingACKs",e.PENDING_ACTIVATION="PendingActivation",e.ACTIVATED="Activated",e.EXPIRED="Expired",e.CLAIM_POSTED="ClaimPosted",e.PEGGED_OUT="PeggedOut",e))(R||{});const M=["PendingIngestion","PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations"],H=["PendingACKs","PendingActivation","Activated"],h=new Set(["PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations",...H]),q=new Set(["Expired","ClaimPosted","PeggedOut"]),F=new Set([...h,"PendingDepositorSignatures"]);var S=(e=>(e[e.DATABASE_ERROR=-32005]="DATABASE_ERROR",e[e.PRESIGN_ERROR=-32006]="PRESIGN_ERROR",e[e.JSON_SERIALIZATION_ERROR=-32007]="JSON_SERIALIZATION_ERROR",e[e.TX_GRAPH_ERROR=-32008]="TX_GRAPH_ERROR",e[e.INVALID_GRAPH=-32009]="INVALID_GRAPH",e[e.VALIDATION_ERROR=-32010]="VALIDATION_ERROR",e[e.NOT_FOUND=-32011]="NOT_FOUND",e[e.INTERNAL_ERROR=-32603]="INTERNAL_ERROR",e))(S||{});exports.BTCVaultRegistryABI=O;exports.DaemonStatus=R;exports.JSON_RPC_ERROR_CODES=c;exports.JsonRpcClient=x;exports.JsonRpcError=u;exports.POST_WOTS_STATUSES=F;exports.PRE_DEPOSITOR_SIGNATURES_STATES=M;exports.RpcErrorCode=S;exports.VP_TERMINAL_STATUSES=q;exports.VP_TRANSIENT_STATUSES=h;
2
- //# sourceMappingURL=types-PthVHz5q.cjs.map