@babylonlabs-io/ts-sdk 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/README.md +56 -12
  2. package/dist/bitcoin-CNnPFU6Y.cjs +2 -0
  3. package/dist/bitcoin-CNnPFU6Y.cjs.map +1 -0
  4. package/dist/{constants-Q7v2O7Ps.js → bitcoin-nOOgeRyl.js} +64 -76
  5. package/dist/bitcoin-nOOgeRyl.js.map +1 -0
  6. package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs +2 -0
  7. package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs.map +1 -0
  8. package/dist/buildAndBroadcastRefund-DnTQkCgG.js +1331 -0
  9. package/dist/buildAndBroadcastRefund-DnTQkCgG.js.map +1 -0
  10. package/dist/challengeAssert-D1lpvuMv.js +283 -0
  11. package/dist/challengeAssert-D1lpvuMv.js.map +1 -0
  12. package/dist/challengeAssert-nYlgeAI8.cjs +2 -0
  13. package/dist/challengeAssert-nYlgeAI8.cjs.map +1 -0
  14. package/dist/errors-BZON3Wmn.cjs +2 -0
  15. package/dist/errors-BZON3Wmn.cjs.map +1 -0
  16. package/dist/errors-CHY4WNi-.js +1226 -0
  17. package/dist/errors-CHY4WNi-.js.map +1 -0
  18. package/dist/fundPeginTransaction-BLYXxLBv.js +70 -0
  19. package/dist/fundPeginTransaction-BLYXxLBv.js.map +1 -0
  20. package/dist/fundPeginTransaction-DxNOeyNI.cjs +2 -0
  21. package/dist/fundPeginTransaction-DxNOeyNI.cjs.map +1 -0
  22. package/dist/index-BpXpESWu.cjs +2 -0
  23. package/dist/index-BpXpESWu.cjs.map +1 -0
  24. package/dist/index-CFwoGJNQ.js +1141 -0
  25. package/dist/index-CFwoGJNQ.js.map +1 -0
  26. package/dist/index.cjs +1 -1
  27. package/dist/index.js +134 -100
  28. package/dist/payout-DzGsAnhf.js +261 -0
  29. package/dist/payout-DzGsAnhf.js.map +1 -0
  30. package/dist/payout-RFIh7GLN.cjs +2 -0
  31. package/dist/payout-RFIh7GLN.cjs.map +1 -0
  32. package/dist/psbtInputFields-C-zYR1z7.cjs +2 -0
  33. package/dist/psbtInputFields-C-zYR1z7.cjs.map +1 -0
  34. package/dist/psbtInputFields-Dx41_IoI.js +229 -0
  35. package/dist/psbtInputFields-Dx41_IoI.js.map +1 -0
  36. package/dist/signing-DeWVBl7m.js +64 -0
  37. package/dist/signing-DeWVBl7m.js.map +1 -0
  38. package/dist/signing-cl-lowxV.cjs +2 -0
  39. package/dist/signing-cl-lowxV.cjs.map +1 -0
  40. package/dist/tbv/core/clients/eth/__tests__/protocol-params-reader.test.d.ts +2 -0
  41. package/dist/tbv/core/clients/eth/__tests__/protocol-params-reader.test.d.ts.map +1 -0
  42. package/dist/tbv/core/clients/eth/__tests__/signer-set-reader.test.d.ts +2 -0
  43. package/dist/tbv/core/clients/eth/__tests__/signer-set-reader.test.d.ts.map +1 -0
  44. package/dist/tbv/core/clients/eth/contract-address-resolver.d.ts +18 -0
  45. package/dist/tbv/core/clients/eth/contract-address-resolver.d.ts.map +1 -0
  46. package/dist/tbv/core/clients/eth/index.d.ts +4 -1
  47. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
  48. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +27 -0
  49. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -0
  50. package/dist/tbv/core/clients/eth/signer-set-reader.d.ts +37 -0
  51. package/dist/tbv/core/clients/eth/signer-set-reader.d.ts.map +1 -0
  52. package/dist/tbv/core/clients/eth/types.d.ts +80 -0
  53. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  54. package/dist/tbv/core/clients/index.cjs +1 -1
  55. package/dist/tbv/core/clients/index.js +25 -21
  56. package/dist/tbv/core/contracts/abis/ApplicationRegistry.abi.d.ts +74 -0
  57. package/dist/tbv/core/contracts/abis/ApplicationRegistry.abi.d.ts.map +1 -0
  58. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +20 -0
  59. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  60. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +233 -0
  61. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts.map +1 -0
  62. package/dist/tbv/core/contracts/index.d.ts +2 -0
  63. package/dist/tbv/core/contracts/index.d.ts.map +1 -1
  64. package/dist/tbv/core/index.cjs +1 -1
  65. package/dist/tbv/core/index.d.ts +3 -1
  66. package/dist/tbv/core/index.d.ts.map +1 -1
  67. package/dist/tbv/core/index.js +129 -95
  68. package/dist/tbv/core/managers/PeginManager.d.ts +1 -1
  69. package/dist/tbv/core/primitives/index.cjs +1 -1
  70. package/dist/tbv/core/primitives/index.d.ts +3 -2
  71. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  72. package/dist/tbv/core/primitives/index.js +24 -23
  73. package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts +1 -1
  74. package/dist/tbv/core/primitives/psbt/index.d.ts +1 -1
  75. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  76. package/dist/tbv/core/primitives/psbt/pegin.d.ts +2 -3
  77. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  78. package/dist/tbv/core/primitives/utils/bitcoin.d.ts +4 -0
  79. package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
  80. package/dist/tbv/core/primitives/utils/index.d.ts +1 -1
  81. package/dist/tbv/core/primitives/utils/index.d.ts.map +1 -1
  82. package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts +2 -0
  83. package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts.map +1 -0
  84. package/dist/tbv/core/services/activation/activateVault.d.ts +77 -0
  85. package/dist/tbv/core/services/activation/activateVault.d.ts.map +1 -0
  86. package/dist/tbv/core/services/activation/index.d.ts +7 -0
  87. package/dist/tbv/core/services/activation/index.d.ts.map +1 -0
  88. package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts +2 -0
  89. package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts.map +1 -0
  90. package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts +5 -0
  91. package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts.map +1 -0
  92. package/dist/tbv/core/services/deposit/index.d.ts +4 -0
  93. package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
  94. package/dist/tbv/core/services/deposit/peginState.d.ts +93 -0
  95. package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -0
  96. package/dist/tbv/core/services/deposit/validation.d.ts +114 -0
  97. package/dist/tbv/core/services/deposit/validation.d.ts.map +1 -0
  98. package/dist/tbv/core/services/htlc/__tests__/htlc.test.d.ts +2 -0
  99. package/dist/tbv/core/services/htlc/__tests__/htlc.test.d.ts.map +1 -0
  100. package/dist/tbv/core/services/htlc/index.d.ts +25 -0
  101. package/dist/tbv/core/services/htlc/index.d.ts.map +1 -0
  102. package/dist/tbv/core/services/index.cjs +1 -1
  103. package/dist/tbv/core/services/index.d.ts +4 -0
  104. package/dist/tbv/core/services/index.d.ts.map +1 -1
  105. package/dist/tbv/core/services/index.js +25 -5
  106. package/dist/tbv/core/services/index.js.map +1 -1
  107. package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts +2 -0
  108. package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts.map +1 -0
  109. package/dist/tbv/core/services/pegout/index.d.ts +2 -0
  110. package/dist/tbv/core/services/pegout/index.d.ts.map +1 -0
  111. package/dist/tbv/core/services/pegout/state.d.ts +30 -0
  112. package/dist/tbv/core/services/pegout/state.d.ts.map +1 -0
  113. package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts +2 -0
  114. package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts.map +1 -0
  115. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +103 -0
  116. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -0
  117. package/dist/tbv/core/services/refund/errors.d.ts +13 -0
  118. package/dist/tbv/core/services/refund/errors.d.ts.map +1 -0
  119. package/dist/tbv/core/services/refund/index.d.ts +8 -0
  120. package/dist/tbv/core/services/refund/index.d.ts.map +1 -0
  121. package/dist/tbv/core/utils/index.cjs +1 -1
  122. package/dist/tbv/core/utils/index.js +30 -24
  123. package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts +1 -1
  124. package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts +3 -0
  125. package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts.map +1 -0
  126. package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts +3 -0
  127. package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts.map +1 -0
  128. package/dist/tbv/core/utils/utxo/availability.d.ts +62 -0
  129. package/dist/tbv/core/utils/utxo/availability.d.ts.map +1 -0
  130. package/dist/tbv/core/utils/utxo/index.d.ts +2 -0
  131. package/dist/tbv/core/utils/utxo/index.d.ts.map +1 -1
  132. package/dist/tbv/core/utils/utxo/reservation.d.ts +65 -0
  133. package/dist/tbv/core/utils/utxo/reservation.d.ts.map +1 -0
  134. package/dist/tbv/core/wots/__tests__/blockDerivation.test.d.ts +2 -0
  135. package/dist/tbv/core/wots/__tests__/blockDerivation.test.d.ts.map +1 -0
  136. package/dist/tbv/core/wots/blockDerivation.d.ts +36 -0
  137. package/dist/tbv/core/wots/blockDerivation.d.ts.map +1 -0
  138. package/dist/tbv/core/wots/index.d.ts +1 -0
  139. package/dist/tbv/core/wots/index.d.ts.map +1 -1
  140. package/dist/tbv/index.cjs +1 -1
  141. package/dist/tbv/index.js +129 -95
  142. package/dist/tbv/integrations/aave/index.cjs +1 -1
  143. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  144. package/dist/tbv/integrations/aave/index.d.ts +3 -3
  145. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  146. package/dist/tbv/integrations/aave/index.js +145 -169
  147. package/dist/tbv/integrations/aave/index.js.map +1 -1
  148. package/dist/tbv/integrations/aave/utils/healthFactor.d.ts +0 -30
  149. package/dist/tbv/integrations/aave/utils/healthFactor.d.ts.map +1 -1
  150. package/dist/tbv/integrations/aave/utils/index.d.ts +2 -2
  151. package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
  152. package/dist/types-B-p4dhEH.cjs +2 -0
  153. package/dist/types-B-p4dhEH.cjs.map +1 -0
  154. package/dist/types-DWjaqVfP.js +608 -0
  155. package/dist/types-DWjaqVfP.js.map +1 -0
  156. package/package.json +5 -1
  157. package/dist/challengeAssert-D_k_ADgP.cjs +0 -2
  158. package/dist/challengeAssert-D_k_ADgP.cjs.map +0 -1
  159. package/dist/challengeAssert-k5_LWUtO.js +0 -362
  160. package/dist/challengeAssert-k5_LWUtO.js.map +0 -1
  161. package/dist/constants-EiyZkXce.cjs +0 -2
  162. package/dist/constants-EiyZkXce.cjs.map +0 -1
  163. package/dist/constants-Q7v2O7Ps.js.map +0 -1
  164. package/dist/errors-DAKpPfl7.cjs +0 -2
  165. package/dist/errors-DAKpPfl7.cjs.map +0 -1
  166. package/dist/errors-DARTQrP3.js +0 -1510
  167. package/dist/errors-DARTQrP3.js.map +0 -1
  168. package/dist/fundPeginTransaction-DpwnDslW.js +0 -50
  169. package/dist/fundPeginTransaction-DpwnDslW.js.map +0 -1
  170. package/dist/fundPeginTransaction-EbrZzlrh.cjs +0 -2
  171. package/dist/fundPeginTransaction-EbrZzlrh.cjs.map +0 -1
  172. package/dist/index-DKfhZvdn.cjs +0 -2
  173. package/dist/index-DKfhZvdn.cjs.map +0 -1
  174. package/dist/index-qIcjkxLw.js +0 -911
  175. package/dist/index-qIcjkxLw.js.map +0 -1
  176. package/dist/payout-Ce9vSs9e.js +0 -164
  177. package/dist/payout-Ce9vSs9e.js.map +0 -1
  178. package/dist/payout-CfsDnjKI.cjs +0 -2
  179. package/dist/payout-CfsDnjKI.cjs.map +0 -1
  180. package/dist/psbtInputFields-C0nKn_GD.cjs +0 -2
  181. package/dist/psbtInputFields-C0nKn_GD.cjs.map +0 -1
  182. package/dist/psbtInputFields-DO0ELwiv.js +0 -116
  183. package/dist/psbtInputFields-DO0ELwiv.js.map +0 -1
  184. package/dist/signAndSubmitPayouts-CAOEAQp9.js +0 -490
  185. package/dist/signAndSubmitPayouts-CAOEAQp9.js.map +0 -1
  186. package/dist/signAndSubmitPayouts-CSJmcPQN.cjs +0 -2
  187. package/dist/signAndSubmitPayouts-CSJmcPQN.cjs.map +0 -1
  188. package/dist/signing-Deg5lCoC.cjs +0 -2
  189. package/dist/signing-Deg5lCoC.cjs.map +0 -1
  190. package/dist/signing-Drwr3bXB.js +0 -16
  191. package/dist/signing-Drwr3bXB.js.map +0 -1
  192. package/dist/types-D1rYwwCu.js +0 -235
  193. package/dist/types-D1rYwwCu.js.map +0 -1
  194. package/dist/types-DEWiqXYp.cjs +0 -2
  195. package/dist/types-DEWiqXYp.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"psbtInputFields-DO0ELwiv.js","sources":["../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 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 * 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 // 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":["selectUtxosForPegin","availableUTXOs","peginAmount","feeRate","numOutputs","validUTXOs","utxo","script","Buffer","bitcoinScript","sortedUTXOs","a","b","selectedUTXOs","accumulatedValue","estimatedFee","inputSize","P2TR_INPUT_SIZE","outputSize","MAX_NON_LEGACY_OUTPUT_SIZE","baseTxSize","TX_BUFFER_SIZE_OVERHEAD","rateBasedTxBufferFee","DUST_THRESHOLD","changeOutputFee","finalChangeAmount","shouldAddChangeOutput","changeAmount","getDustThreshold","BTC_DUST_SAT","calculateBtcTxHash","txHex","cleanHex","Transaction","BitcoinScriptType","getScriptType","scriptPubKey","length","getPsbtInputFields","publicKeyNoCoord","type"],"mappings":";;;AAqEO,SAASA,EACdC,GACAC,GACAC,GACAC,GACqB;AACrB,MAAI,CAAC,OAAO,UAAUA,CAAU,KAAKA,IAAa;AAChD,UAAM,IAAI;AAAA,MACR,wDAAwDA,CAAU;AAAA,IAAA;AAItE,MAAIH,EAAe,WAAW;AAC5B,UAAM,IAAI,MAAM,wCAAwC;AAK1D,QAAMI,IAAaJ,EAAe,OAAO,CAACK,MAAS;AACjD,UAAMC,IAASC,EAAO,KAAKF,EAAK,cAAc,KAAK;AAEnD,WAAO,CAAC,CADiBG,EAAc,UAAUF,CAAM;AAAA,EAEzD,CAAC;AAED,MAAIF,EAAW,WAAW;AACxB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAMJ,QAAMK,IAAc,CAAC,GAAGL,CAAU,EAAE,KAAK,CAACM,GAAGC,MAAMA,EAAE,QAAQD,EAAE,KAAK,GAE9DE,IAAwB,CAAA;AAC9B,MAAIC,IAAmB,IACnBC,IAAe;AAGnB,aAAWT,KAAQI,GAAa;AAC9B,IAAAG,EAAc,KAAKP,CAAI,GACvBQ,KAAoB,OAAOR,EAAK,KAAK;AAGrC,UAAMU,IAAYH,EAAc,SAASI,GACnCC,IAAad,IAAae,GAC1BC,IAAaJ,IAAYE,IAAaG;AAW5C,QARAN,IACE,OAAO,KAAK,KAAKK,IAAajB,CAAO,CAAC,IACtC,OAAOmB,EAAqBnB,CAAO,CAAC,GAGjBW,IAAmBZ,IAAca,IAGnCQ,GAA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AC,MAAM,KAEb,WAKPC,MAAW,MACXD,EAAa,CAAC,MAAM;AAAA,EACpBA,EAAa,CAAC,MAAM,KAEb,UAKPC,MAAW,MACXD,EAAa,CAAC,MAAM;AAAA,EACpBA,EAAa,CAAC,MAAM,KAEb,SAGF;AACT;ACnCO,SAASE,EACdhC,GACAiC,GACiB;AACjB,QAAMH,IAAe5B,EAAO,KAAKF,EAAK,cAAc,KAAK,GACnDkC,IAAOL,EAAcC,CAAY;AAEvC,UAAQI,GAAA;AAAA,IACN,KAAKN,EAAkB;AACrB,aAAO;AAAA,QACL,aAAa;AAAA,UACX,QAAQE;AAAA,UACR,OAAO9B,EAAK;AAAA,QAAA;AAAA,MACd;AAAA,IAIJ,KAAK4B,EAAkB,OAAO;AAC5B,UAAI,CAAC5B,EAAK;AACR,cAAM,IAAI,MAAM,uCAAuC;AAEzD,aAAO;AAAA,QACL,aAAa;AAAA,UACX,QAAQ8B;AAAA,UACR,OAAO9B,EAAK;AAAA,QAAA;AAAA,QAEd,eAAeE,EAAO,KAAKF,EAAK,eAAe,KAAK;AAAA,MAAA;AAAA,IAExD;AAAA,IAEA,KAAK4B,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,OAAO9B,EAAK;AAAA,QAAA;AAAA;AAAA,QAGd,GAAIiC,KAAoB,EAAE,gBAAgBA,EAAA;AAAA,MAAiB;AAAA,IAE/D;AAAA,IAEA;AACE,YAAM,IAAI,MAAM,4BAA4BC,CAAI,EAAE;AAAA,EAAA;AAExD;"}
@@ -1,490 +0,0 @@
1
- var C = Object.defineProperty;
2
- var N = (s, t, e) => t in s ? C(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
- var T = (s, t, e) => N(s, typeof t != "symbol" ? t + "" : t, e);
4
- import { c as D, a as $, R as L, D as P, d as _ } from "./types-D1rYwwCu.js";
5
- import * as R from "bitcoinjs-lib";
6
- import { Transaction as M, Psbt as m } from "bitcoinjs-lib";
7
- import { Buffer as v } from "buffer";
8
- import { c as b } from "./signing-Drwr3bXB.js";
9
- import { v as w, b as U, s as l, p as d } from "./constants-Q7v2O7Ps.js";
10
- import "@babylonlabs-io/babylon-tbv-rust-wasm";
11
- import { b as x, e as g } from "./payout-Ce9vSs9e.js";
12
- class W {
13
- /**
14
- * Creates a new PayoutManager instance.
15
- *
16
- * @param config - Manager configuration including wallet
17
- */
18
- constructor(t) {
19
- T(this, "config");
20
- this.config = t;
21
- }
22
- /**
23
- * Signs a Payout transaction and extracts the Schnorr signature.
24
- *
25
- * Flow:
26
- * 1. Vault provider submits Claim transaction
27
- * 2. Claimer submits Assert transaction to prove validity
28
- * 3. Payout can be executed (references Assert tx)
29
- *
30
- * This method orchestrates the following steps:
31
- * 1. Get wallet's public key and convert to x-only format
32
- * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)
33
- * 3. Build unsigned PSBT using primitives
34
- * 4. Sign PSBT via btcWallet.signPsbt()
35
- * 5. Extract 64-byte Schnorr signature using primitives
36
- *
37
- * The returned signature can be submitted to the vault provider API.
38
- *
39
- * @param params - Payout signing parameters
40
- * @returns Signature result with 64-byte Schnorr signature and depositor pubkey
41
- * @throws Error if wallet pubkey doesn't match depositor pubkey
42
- * @throws Error if wallet operations fail or signature extraction fails
43
- */
44
- async signPayoutTransaction(t) {
45
- this.validatePayoutOutputs(
46
- t.payoutTxHex,
47
- t.registeredPayoutScriptPubKey
48
- );
49
- const e = await this.config.btcWallet.getPublicKeyHex(), { depositorPubkey: r } = w(
50
- e,
51
- t.depositorBtcPubkey
52
- ), n = await x({
53
- payoutTxHex: t.payoutTxHex,
54
- peginTxHex: t.peginTxHex,
55
- assertTxHex: t.assertTxHex,
56
- depositorBtcPubkey: r,
57
- vaultProviderBtcPubkey: t.vaultProviderBtcPubkey,
58
- vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys,
59
- universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys,
60
- timelockPegin: t.timelockPegin,
61
- network: this.config.network
62
- }), a = await this.config.btcWallet.signPsbt(
63
- n.psbtHex,
64
- b(e, 1)
65
- );
66
- return {
67
- signature: g(a, r),
68
- depositorBtcPubkey: r
69
- };
70
- }
71
- /**
72
- * Gets the configured Bitcoin network.
73
- *
74
- * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
75
- */
76
- getNetwork() {
77
- return this.config.network;
78
- }
79
- /**
80
- * Checks if the wallet supports batch signing (signPsbts).
81
- *
82
- * @returns true if batch signing is supported
83
- */
84
- supportsBatchSigning() {
85
- return typeof this.config.btcWallet.signPsbts == "function";
86
- }
87
- /**
88
- * Batch signs multiple payout transactions (1 per claimer).
89
- * This allows signing all transactions with a single wallet interaction.
90
- *
91
- * @param transactions - Array of payout params to sign
92
- * @returns Array of signature results matching input order
93
- * @throws Error if wallet doesn't support batch signing
94
- * @throws Error if any signing operation fails
95
- */
96
- async signPayoutTransactionsBatch(t) {
97
- if (!this.supportsBatchSigning())
98
- throw new Error(
99
- "Wallet does not support batch signing (signPsbts method not available)"
100
- );
101
- const e = await this.config.btcWallet.getPublicKeyHex(), r = [], n = [], a = [];
102
- for (const o of t) {
103
- this.validatePayoutOutputs(
104
- o.payoutTxHex,
105
- o.registeredPayoutScriptPubKey
106
- );
107
- const { depositorPubkey: c } = w(
108
- e,
109
- o.depositorBtcPubkey
110
- );
111
- a.push(c);
112
- const p = await x({
113
- payoutTxHex: o.payoutTxHex,
114
- peginTxHex: o.peginTxHex,
115
- assertTxHex: o.assertTxHex,
116
- depositorBtcPubkey: c,
117
- vaultProviderBtcPubkey: o.vaultProviderBtcPubkey,
118
- vaultKeeperBtcPubkeys: o.vaultKeeperBtcPubkeys,
119
- universalChallengerBtcPubkeys: o.universalChallengerBtcPubkeys,
120
- timelockPegin: o.timelockPegin,
121
- network: this.config.network
122
- });
123
- r.push(p.psbtHex), n.push(b(e, 1));
124
- }
125
- const i = await this.config.btcWallet.signPsbts(
126
- r,
127
- n
128
- );
129
- if (i.length !== t.length)
130
- throw new Error(
131
- `Expected ${t.length} signed PSBTs but received ${i.length}`
132
- );
133
- const u = [];
134
- for (let o = 0; o < t.length; o++) {
135
- const c = a[o], p = g(
136
- i[o],
137
- c
138
- );
139
- u.push({
140
- payoutSignature: p,
141
- depositorBtcPubkey: c
142
- });
143
- }
144
- return u;
145
- }
146
- /**
147
- * Validates that the payout transaction's largest output pays to the
148
- * registered depositor payout address (scriptPubKey).
149
- *
150
- * This prevents two attack vectors from a malicious vault provider:
151
- * 1. Substituting a completely different payout address
152
- * 2. Including a dust output to the correct address while routing
153
- * the actual funds to an attacker-controlled address
154
- *
155
- * @param payoutTxHex - Raw payout transaction hex
156
- * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)
157
- * @throws Error if scriptPubKey is invalid hex
158
- * @throws Error if the largest output does not pay to the registered address
159
- */
160
- validatePayoutOutputs(t, e) {
161
- if (!U(e))
162
- throw new Error(
163
- "Invalid registeredPayoutScriptPubKey: not valid hex"
164
- );
165
- const r = v.from(
166
- l(e),
167
- "hex"
168
- ), n = M.fromHex(l(t));
169
- if (n.outs.length === 0)
170
- throw new Error("Payout transaction has no outputs");
171
- if (!n.outs.reduce(
172
- (i, u) => u.value > i.value ? u : i
173
- ).script.equals(r))
174
- throw new Error(
175
- "Payout transaction does not pay to the registered depositor payout address"
176
- );
177
- }
178
- }
179
- const G = 1e4;
180
- async function B(s) {
181
- const {
182
- statusReader: t,
183
- peginTxid: e,
184
- targetStatuses: r,
185
- timeoutMs: n,
186
- pollIntervalMs: a = G,
187
- signal: i
188
- } = s, u = Date.now();
189
- for (; ; ) {
190
- if (i != null && i.aborted)
191
- throw new Error(
192
- `Polling aborted for pegin ${e.slice(0, 8)}… (target: ${[...r].join(", ")})`
193
- );
194
- if (Date.now() - u >= n)
195
- throw new Error(
196
- `Polling timeout after ${n}ms for pegin ${e.slice(0, 8)}… (target: ${[...r].join(", ")})`
197
- );
198
- try {
199
- const c = (await t.getPeginStatus(
200
- { pegin_txid: e },
201
- i
202
- )).status;
203
- if (r.has(c))
204
- return c;
205
- if (D.has(c) && !r.has(c))
206
- throw new Error(
207
- `Pegin ${e.slice(0, 8)}… reached terminal status "${c}" while waiting for ${[...r].join(", ")}`
208
- );
209
- } catch (o) {
210
- if (!(o instanceof $ && o.code === L.NOT_FOUND || o instanceof Error && o.message.includes("PegIn not found")))
211
- throw o;
212
- }
213
- await new Promise((o, c) => {
214
- const p = () => {
215
- clearTimeout(y), c(
216
- new Error(
217
- `Polling aborted for pegin ${e.slice(0, 8)}… (target: ${[...r].join(", ")})`
218
- )
219
- );
220
- }, y = setTimeout(() => {
221
- i == null || i.removeEventListener("abort", p), o();
222
- }, a);
223
- i == null || i.addEventListener("abort", p, { once: !0 });
224
- });
225
- }
226
- }
227
- const F = 300 * 1e3, V = /* @__PURE__ */ new Set([
228
- P.PENDING_DEPOSITOR_WOTS_PK,
229
- ..._
230
- ]);
231
- async function yt(s) {
232
- const {
233
- statusReader: t,
234
- wotsSubmitter: e,
235
- peginTxid: r,
236
- depositorPk: n,
237
- wotsPublicKeys: a,
238
- timeoutMs: i = F,
239
- signal: u
240
- } = s;
241
- u == null || u.throwIfAborted();
242
- const o = await B({
243
- statusReader: t,
244
- peginTxid: r,
245
- targetStatuses: V,
246
- timeoutMs: i,
247
- signal: u
248
- });
249
- _.has(o) || (u == null || u.throwIfAborted(), await e.submitDepositorWotsKey(
250
- {
251
- pegin_txid: r,
252
- depositor_pk: n,
253
- wots_public_keys: a
254
- },
255
- u
256
- ));
257
- }
258
- const z = 1;
259
- function X(s, t, e) {
260
- const r = m.fromBase64(s), n = r.data.getTransaction().toString("hex").toLowerCase(), a = l(t).toLowerCase();
261
- if (n !== a)
262
- throw new Error(
263
- `PSBT integrity check failed for ${e}: unsigned transaction does not match tx_hex`
264
- );
265
- return r;
266
- }
267
- function j(s) {
268
- const t = m.fromHex(s.toHex());
269
- for (const e of t.data.inputs)
270
- delete e.tapBip32Derivation, delete e.tapMerkleRoot;
271
- return t;
272
- }
273
- function k(s, t, e) {
274
- if (!s)
275
- throw new Error(`Missing ${e} PSBT`);
276
- const r = X(s, t, e);
277
- return j(r).toHex();
278
- }
279
- function q(s, t) {
280
- const e = [], r = [], n = [], a = b(
281
- t,
282
- z
283
- ), i = k(
284
- s.payout_psbt,
285
- s.payout_tx.tx_hex,
286
- "depositor payout"
287
- );
288
- e.push(i), r.push(a);
289
- for (const u of s.challenger_presign_data) {
290
- const o = l(u.challenger_pubkey), c = e.length, p = k(
291
- u.nopayout_psbt,
292
- u.nopayout_tx.tx_hex,
293
- `nopayout (challenger ${o})`
294
- );
295
- e.push(p), r.push(a), n.push({
296
- challengerPubkey: o,
297
- noPayoutIdx: c
298
- });
299
- }
300
- return { psbtHexes: e, signOptions: r, challengerEntries: n };
301
- }
302
- function J(s, t, e) {
303
- const r = g(
304
- s[0],
305
- e
306
- ), n = {};
307
- for (const a of t)
308
- n[a.challengerPubkey] = {
309
- nopayout_signature: g(
310
- s[a.noPayoutIdx],
311
- e
312
- )
313
- };
314
- return {
315
- payout_signatures: {
316
- payout_signature: r
317
- },
318
- per_challenger: n
319
- };
320
- }
321
- async function Y(s, t, e) {
322
- if (typeof s.signPsbts == "function")
323
- return s.signPsbts(t, e);
324
- const r = [];
325
- for (let n = 0; n < t.length; n++)
326
- r.push(await s.signPsbt(t[n], e == null ? void 0 : e[n]));
327
- return r;
328
- }
329
- async function Q(s) {
330
- const { depositorGraph: t, depositorBtcPubkey: e, btcWallet: r } = s, n = l(e), a = await r.getPublicKeyHex(), { psbtHexes: i, signOptions: u, challengerEntries: o } = q(t, a), c = await Y(
331
- r,
332
- i,
333
- u
334
- );
335
- if (c.length !== i.length)
336
- throw new Error(
337
- `Wallet returned ${c.length} signed PSBTs, expected ${i.length}`
338
- );
339
- return J(
340
- c,
341
- o,
342
- n
343
- );
344
- }
345
- const Z = 1200 * 1e3, E = /* @__PURE__ */ new Set([
346
- P.PENDING_ACKS,
347
- P.PENDING_ACTIVATION,
348
- P.ACTIVATED
349
- ]), tt = /* @__PURE__ */ new Set([
350
- P.PENDING_DEPOSITOR_SIGNATURES,
351
- ...E
352
- ]);
353
- function et(s) {
354
- return s.map((t) => ({
355
- claimerPubkeyXOnly: d(t.claimer_pubkey),
356
- payoutTxHex: t.payout_tx.tx_hex,
357
- assertTxHex: t.assert_tx.tx_hex
358
- }));
359
- }
360
- function ot(s) {
361
- const { output: t } = R.payments.p2tr({
362
- internalPubkey: v.from(s, "hex")
363
- });
364
- if (!t)
365
- throw new Error("Failed to derive BIP-86 P2TR scriptPubKey");
366
- return t.toString("hex");
367
- }
368
- function rt(s, t) {
369
- const e = l(s).toLowerCase(), r = l(
370
- t.vaultProviderBtcPubkey
371
- ).toLowerCase(), n = l(
372
- t.depositorBtcPubkey
373
- ).toLowerCase();
374
- if (e === r || e === n)
375
- return t.registeredPayoutScriptPubKey;
376
- if (!t.vaultKeeperBtcPubkeys.some(
377
- (u) => l(u).toLowerCase() === e
378
- ))
379
- throw new Error(
380
- `Unknown claimer pubkey ${e}: not VP, depositor, or a registered vault keeper`
381
- );
382
- return `0x${ot(e)}`;
383
- }
384
- function S(s, t) {
385
- return {
386
- payoutTxHex: s.payoutTxHex,
387
- peginTxHex: t.peginTxHex,
388
- assertTxHex: s.assertTxHex,
389
- vaultProviderBtcPubkey: t.vaultProviderBtcPubkey,
390
- vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys,
391
- universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys,
392
- depositorBtcPubkey: t.depositorBtcPubkey,
393
- timelockPegin: t.timelockPegin,
394
- registeredPayoutScriptPubKey: rt(
395
- s.claimerPubkeyXOnly,
396
- t
397
- )
398
- };
399
- }
400
- async function st(s, t, e, r) {
401
- const n = new W({
402
- network: t.network,
403
- btcWallet: s
404
- }), a = e.length;
405
- r == null || r(0, a);
406
- let i;
407
- if (n.supportsBatchSigning())
408
- i = (await n.signPayoutTransactionsBatch(
409
- e.map((c) => S(c, t))
410
- )).map((c) => c.payoutSignature);
411
- else {
412
- i = [];
413
- for (let o = 0; o < e.length; o++) {
414
- r == null || r(o, a);
415
- const c = await n.signPayoutTransaction(
416
- S(e[o], t)
417
- );
418
- i.push(c.signature);
419
- }
420
- }
421
- const u = {};
422
- for (let o = 0; o < e.length; o++)
423
- u[e[o].claimerPubkeyXOnly] = {
424
- payout_signature: i[o]
425
- };
426
- return r == null || r(a, a), u;
427
- }
428
- async function gt(s) {
429
- const {
430
- statusReader: t,
431
- presignClient: e,
432
- btcWallet: r,
433
- peginTxid: n,
434
- depositorPk: a,
435
- signingContext: i,
436
- timeoutMs: u = Z,
437
- signal: o,
438
- onProgress: c
439
- } = s, p = await B({
440
- statusReader: t,
441
- peginTxid: n,
442
- targetStatuses: tt,
443
- timeoutMs: u,
444
- signal: o
445
- });
446
- if (E.has(p))
447
- return;
448
- o == null || o.throwIfAborted();
449
- const y = await e.requestDepositorPresignTransactions(
450
- {
451
- pegin_txid: n,
452
- depositor_pk: a
453
- },
454
- o
455
- );
456
- o == null || o.throwIfAborted();
457
- const H = d(a), I = y.txs.filter(
458
- (K) => d(K.claimer_pubkey) !== H
459
- ), O = et(I), A = await st(
460
- r,
461
- i,
462
- O,
463
- c
464
- );
465
- o == null || o.throwIfAborted();
466
- const h = await Q({
467
- depositorGraph: y.depositor_graph,
468
- depositorBtcPubkey: a,
469
- btcWallet: r
470
- });
471
- o == null || o.throwIfAborted();
472
- const f = { ...A };
473
- f[l(a)] = h.payout_signatures, await e.submitDepositorPresignatures(
474
- {
475
- pegin_txid: n,
476
- depositor_pk: a,
477
- signatures: f,
478
- depositor_claimer_presignatures: h
479
- },
480
- o
481
- );
482
- }
483
- export {
484
- W as P,
485
- Q as a,
486
- gt as p,
487
- yt as s,
488
- B as w
489
- };
490
- //# sourceMappingURL=signAndSubmitPayouts-CAOEAQp9.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"signAndSubmitPayouts-CAOEAQp9.js","sources":["../src/tbv/core/managers/PayoutManager.ts","../src/tbv/core/services/deposit/waitForPeginStatus.ts","../src/tbv/core/services/deposit/submitWotsPublicKey.ts","../src/tbv/core/services/deposit/signDepositorGraph.ts","../src/tbv/core/services/deposit/signAndSubmitPayouts.ts"],"sourcesContent":["/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1, 2, and 4 of peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { Transaction } from \"bitcoinjs-lib\";\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../shared/wallets\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\nimport {\n buildPayoutPsbt,\n extractPayoutSignature,\n isValidHex,\n stripHexPrefix,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex).\n * This should be the public key that was used when creating the vault,\n * as stored on-chain. If not provided, will be fetched from the wallet.\n */\n depositorBtcPubkey?: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 2), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate payout TX outputs pay to the registered depositor payout address\n this.validatePayoutOutputs(\n params.payoutTxHex,\n params.registeredPayoutScriptPubKey,\n );\n\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx)\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: this.config.network,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(walletPubkeyRaw, 1),\n );\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(\n transactions: SignPayoutParams[],\n ): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate payout TX outputs pay to the registered depositor payout address\n this.validatePayoutOutputs(\n tx.payoutTxHex,\n tx.registeredPayoutScriptPubKey,\n );\n\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n network: this.config.network,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(createTaprootScriptPathSignOptions(walletPubkeyRaw, 1));\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n\n /**\n * Validates that the payout transaction's largest output pays to the\n * registered depositor payout address (scriptPubKey).\n *\n * This prevents two attack vectors from a malicious vault provider:\n * 1. Substituting a completely different payout address\n * 2. Including a dust output to the correct address while routing\n * the actual funds to an attacker-controlled address\n *\n * @param payoutTxHex - Raw payout transaction hex\n * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)\n * @throws Error if scriptPubKey is invalid hex\n * @throws Error if the largest output does not pay to the registered address\n */\n private validatePayoutOutputs(\n payoutTxHex: string,\n registeredPayoutScriptPubKey: string,\n ): void {\n if (!isValidHex(registeredPayoutScriptPubKey)) {\n throw new Error(\n \"Invalid registeredPayoutScriptPubKey: not valid hex\",\n );\n }\n\n const expectedScript = Buffer.from(\n stripHexPrefix(registeredPayoutScriptPubKey),\n \"hex\",\n );\n const payoutTx = Transaction.fromHex(stripHexPrefix(payoutTxHex));\n\n if (payoutTx.outs.length === 0) {\n throw new Error(\"Payout transaction has no outputs\");\n }\n\n // Find the largest output by value — this must pay to the registered address.\n // A dust output to the correct address with funds routed elsewhere is rejected.\n const largestOutput = payoutTx.outs.reduce((max, output) =>\n output.value > max.value ? output : max,\n );\n\n if (!largestOutput.script.equals(expectedScript)) {\n throw new Error(\n \"Payout transaction does not pay to the registered depositor payout address\",\n );\n }\n }\n}\n","/**\n * Poll `getPeginStatus` until the VP reaches one of the target statuses.\n *\n * Pure polling utility with no framework dependencies (no localStorage, no React).\n * Handles \"PegIn not found\" as transient (VP hasn't ingested yet).\n */\n\nimport { JsonRpcError } from \"../../clients/vault-provider/json-rpc-client\";\nimport {\n RpcErrorCode,\n VP_TERMINAL_STATUSES,\n type DaemonStatus,\n} from \"../../clients/vault-provider/types\";\nimport type { PeginStatusReader } from \"./interfaces\";\n\n/** Default polling interval (10 seconds). */\nconst DEFAULT_POLL_INTERVAL_MS = 10_000;\n\nexport interface WaitForPeginStatusParams {\n /** VP client implementing the status reader interface */\n statusReader: PeginStatusReader;\n /** BTC pegin transaction ID (unprefixed hex, 64 chars) */\n peginTxid: string;\n /** Set of acceptable statuses — polling stops when the VP reports one of these */\n targetStatuses: ReadonlySet<DaemonStatus>;\n /** Maximum time to wait in milliseconds */\n timeoutMs: number;\n /** Polling interval in milliseconds (default: 10s) */\n pollIntervalMs?: number;\n /** AbortSignal for cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * Poll `getPeginStatus` until the VP reaches one of the target statuses.\n *\n * @returns The DaemonStatus string that matched one of the targets\n * @throws Error on timeout, abort, or non-transient RPC error\n */\nexport async function waitForPeginStatus(\n params: WaitForPeginStatusParams,\n): Promise<DaemonStatus> {\n const {\n statusReader,\n peginTxid,\n targetStatuses,\n timeoutMs,\n pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,\n signal,\n } = params;\n\n const startTime = Date.now();\n\n while (true) {\n if (signal?.aborted) {\n throw new Error(\n `Polling aborted for pegin ${peginTxid.slice(0, 8)}… (target: ${[...targetStatuses].join(\", \")})`,\n );\n }\n\n if (Date.now() - startTime >= timeoutMs) {\n throw new Error(\n `Polling timeout after ${timeoutMs}ms for pegin ${peginTxid.slice(0, 8)}… (target: ${[...targetStatuses].join(\", \")})`,\n );\n }\n\n try {\n const response = await statusReader.getPeginStatus(\n { pegin_txid: peginTxid },\n signal,\n );\n\n const status = response.status as DaemonStatus;\n if (targetStatuses.has(status)) {\n return status;\n }\n // Fail fast on terminal statuses to avoid waiting for timeout\n if (VP_TERMINAL_STATUSES.has(status) && !targetStatuses.has(status)) {\n throw new Error(\n `Pegin ${peginTxid.slice(0, 8)}… reached terminal status \"${status}\" while waiting for ${[...targetStatuses].join(\", \")}`,\n );\n }\n } catch (error) {\n // \"PegIn not found\" is transient — VP hasn't ingested the pegin yet.\n // Check structured error code first, fall back to message matching.\n const isNotFound =\n (error instanceof JsonRpcError &&\n error.code === RpcErrorCode.NOT_FOUND) ||\n (error instanceof Error && error.message.includes(\"PegIn not found\"));\n if (!isNotFound) {\n throw error;\n }\n }\n\n // Wait before next poll, with abort support\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(\n new Error(\n `Polling aborted for pegin ${peginTxid.slice(0, 8)}… (target: ${[...targetStatuses].join(\", \")})`,\n ),\n );\n };\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, pollIntervalMs);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n}\n","/**\n * Submit pre-derived WOTS public keys to the vault provider.\n *\n * Polls `getPeginStatus` until the VP reaches `PendingDepositorWotsPK`,\n * then submits the keys. If the VP has already moved past WOTS step\n * (e.g., resume flow), submission is skipped.\n *\n * The caller is responsible for deriving WOTS keys externally using\n * `mnemonicToWotsSeed` + `deriveWotsBlockPublicKeys` from the SDK's\n * `tbv/core/wots` module.\n */\n\nimport {\n DaemonStatus,\n POST_WOTS_STATUSES,\n type WotsBlockPublicKey,\n} from \"../../clients/vault-provider/types\";\nimport type { PeginStatusReader, WotsKeySubmitter } from \"./interfaces\";\nimport { waitForPeginStatus } from \"./waitForPeginStatus\";\n\n/** Maximum time to wait for VP to reach PendingDepositorWotsPK (5 min). */\nconst STATUS_POLL_TIMEOUT_MS = 5 * 60 * 1000;\n\n/** All statuses we accept — either ready for submission or already past it. */\nconst TARGET_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.PENDING_DEPOSITOR_WOTS_PK,\n ...POST_WOTS_STATUSES,\n]);\n\nexport interface SubmitWotsPublicKeyParams {\n /** VP client implementing the status reader interface */\n statusReader: PeginStatusReader;\n /** VP client implementing the WOTS key submission interface */\n wotsSubmitter: WotsKeySubmitter;\n /** BTC pegin transaction ID (unprefixed hex, 64 chars) */\n peginTxid: string;\n /** Depositor's x-only BTC public key (unprefixed hex, 64 chars) */\n depositorPk: string;\n /** Pre-derived WOTS block public keys (one per assert block) */\n wotsPublicKeys: WotsBlockPublicKey[];\n /** Maximum time to wait for VP to be ready (default: 5 min) */\n timeoutMs?: number;\n /** AbortSignal for cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * Submit WOTS public keys to the vault provider.\n *\n * @throws Error on timeout, abort, or RPC error\n */\nexport async function submitWotsPublicKey(\n params: SubmitWotsPublicKeyParams,\n): Promise<void> {\n const {\n statusReader,\n wotsSubmitter,\n peginTxid,\n depositorPk,\n wotsPublicKeys,\n timeoutMs = STATUS_POLL_TIMEOUT_MS,\n signal,\n } = params;\n\n signal?.throwIfAborted();\n\n // Wait until VP has ingested the pegin and is ready for the WOTS key.\n const status = await waitForPeginStatus({\n statusReader,\n peginTxid,\n targetStatuses: TARGET_STATUSES,\n timeoutMs,\n signal,\n });\n\n // Key was already submitted in a previous session (e.g. resume flow)\n if (POST_WOTS_STATUSES.has(status)) {\n return;\n }\n\n signal?.throwIfAborted();\n\n await wotsSubmitter.submitDepositorWotsKey(\n {\n pegin_txid: peginTxid,\n depositor_pk: depositorPk,\n wots_public_keys: wotsPublicKeys,\n },\n signal,\n );\n}\n","/**\n * Depositor Graph Signing Service\n *\n * Signs the depositor's own graph transactions (Payout, NoPayout per challenger)\n * using pre-built PSBTs from the vault provider.\n *\n * The VP returns unsigned PSBTs with prevouts, scripts, and taproot metadata\n * already embedded (BIP 174), so any standard PSBT-compatible signer can\n * produce signatures without extra context.\n *\n * Transaction counts: 1 Payout + N NoPayout = 1 + N total PSBTs\n *\n * @see btc-vault docs/pegin.md — \"Automatic Graph Creation & Presigning\"\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\n\nimport type { BitcoinWallet, SignPsbtOptions } from \"../../../../shared/wallets/interfaces\";\nimport type {\n DepositorAsClaimerPresignatures,\n DepositorGraphTransactions,\n DepositorPreSigsPerChallenger,\n} from \"../../clients/vault-provider/types\";\nimport { extractPayoutSignature } from \"../../primitives/psbt/payout\";\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { createTaprootScriptPathSignOptions } from \"../../utils/signing\";\n\n/**\n * Each payout/nopayout PSBT has exactly one input that needs signing.\n * Used to construct SignPsbtOptions for wallet.signPsbt().\n */\nconst SINGLE_PSBT_INPUT_COUNT = 1;\n\n/** Tracks which indices in the flat PSBT array belong to which challenger */\ninterface ChallengerEntry {\n challengerPubkey: string;\n noPayoutIdx: number;\n}\n\n/** Result of the collect phase — flat PSBT array with index mapping */\ninterface CollectedDepositorGraphPsbts {\n psbtHexes: string[];\n signOptions: SignPsbtOptions[];\n challengerEntries: ChallengerEntry[];\n}\n\n// ============================================================================\n// PSBT verification — ensure pre-built PSBTs match advertised tx_hex\n// ============================================================================\n\n/**\n * Parse a base64-encoded PSBT and verify its unsigned transaction matches\n * the expected transaction hex. Catches VP serialization bugs.\n */\nfunction verifyAndParsePsbt(\n psbtBase64: string,\n expectedTxHex: string,\n label: string,\n): Psbt {\n const psbt = Psbt.fromBase64(psbtBase64);\n const unsignedTxHex = psbt.data\n .getTransaction()\n .toString(\"hex\")\n .toLowerCase();\n const normalizedExpected = stripHexPrefix(expectedTxHex).toLowerCase();\n if (unsignedTxHex !== normalizedExpected) {\n throw new Error(\n `PSBT integrity check failed for ${label}: unsigned transaction does not match tx_hex`,\n );\n }\n return psbt;\n}\n\n/**\n * Sanitize a parsed PSBT for Taproot script-path signing.\n *\n * VP-provided PSBTs include tapBip32Derivation and tapMerkleRoot metadata\n * that causes some wallets (notably OKX) to ignore disableTweakSigner and\n * sign with a tweaked key. Stripping these fields forces the wallet to\n * rely solely on tapLeafScript for script-path signing.\n */\nfunction sanitizePsbtForScriptPathSigning(psbt: Psbt): Psbt {\n const clone = Psbt.fromHex(psbt.toHex());\n for (const input of clone.data.inputs) {\n delete input.tapBip32Derivation;\n delete input.tapMerkleRoot;\n }\n return clone;\n}\n\n/**\n * Validate, verify integrity, sanitize, and convert a PSBT to hex.\n */\nfunction validateAndConvertPsbt(\n psbtBase64: string | undefined,\n expectedTxHex: string,\n label: string,\n): string {\n if (!psbtBase64) {\n throw new Error(`Missing ${label} PSBT`);\n }\n const psbt = verifyAndParsePsbt(psbtBase64, expectedTxHex, label);\n const sanitized = sanitizePsbtForScriptPathSigning(psbt);\n return sanitized.toHex();\n}\n\n// ============================================================================\n// Collect phase — decode pre-built PSBTs from VP response\n// ============================================================================\n\n/**\n * Collect all pre-built PSBTs from the depositor graph and track their indices.\n * Layout: [Payout, NoPayout_0, NoPayout_1, ...]\n */\nfunction collectDepositorGraphPsbts(\n depositorGraph: DepositorGraphTransactions,\n walletPublicKey: string,\n): CollectedDepositorGraphPsbts {\n const psbtHexes: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const challengerEntries: ChallengerEntry[] = [];\n\n const singleInputOpts = createTaprootScriptPathSignOptions(\n walletPublicKey,\n SINGLE_PSBT_INPUT_COUNT,\n );\n\n // Index 0: Payout PSBT\n const payoutHex = validateAndConvertPsbt(\n depositorGraph.payout_psbt,\n depositorGraph.payout_tx.tx_hex,\n \"depositor payout\",\n );\n psbtHexes.push(payoutHex);\n signOptions.push(singleInputOpts);\n\n // Per-challenger: 1 NoPayout\n for (const challenger of depositorGraph.challenger_presign_data) {\n const challengerPubkey = stripHexPrefix(challenger.challenger_pubkey);\n\n const noPayoutIdx = psbtHexes.length;\n const noPayoutHex = validateAndConvertPsbt(\n challenger.nopayout_psbt,\n challenger.nopayout_tx.tx_hex,\n `nopayout (challenger ${challengerPubkey})`,\n );\n psbtHexes.push(noPayoutHex);\n signOptions.push(singleInputOpts);\n\n challengerEntries.push({\n challengerPubkey,\n noPayoutIdx,\n });\n }\n\n return { psbtHexes, signOptions, challengerEntries };\n}\n\n// ============================================================================\n// Extract phase\n// ============================================================================\n\n/**\n * Extract all signatures from signed PSBTs and assemble into presignatures.\n */\nfunction extractDepositorGraphSignatures(\n signedPsbtHexes: string[],\n challengerEntries: ChallengerEntry[],\n depositorPubkey: string,\n): DepositorAsClaimerPresignatures {\n const payoutSignature = extractPayoutSignature(\n signedPsbtHexes[0],\n depositorPubkey,\n );\n\n const perChallenger: Record<string, DepositorPreSigsPerChallenger> = {};\n for (const entry of challengerEntries) {\n perChallenger[entry.challengerPubkey] = {\n nopayout_signature: extractPayoutSignature(\n signedPsbtHexes[entry.noPayoutIdx],\n depositorPubkey,\n ),\n };\n }\n\n return {\n payout_signatures: {\n payout_signature: payoutSignature,\n },\n per_challenger: perChallenger,\n };\n}\n\n/**\n * Sign multiple PSBTs, using batch signing when the wallet supports it.\n * Falls back to sequential `signPsbt` calls for wallets without `signPsbts`.\n */\nasync function signPsbtsWithFallback(\n wallet: BitcoinWallet,\n psbtHexes: string[],\n options?: SignPsbtOptions[],\n): Promise<string[]> {\n if (typeof wallet.signPsbts === \"function\") {\n return wallet.signPsbts(psbtHexes, options);\n }\n\n const signed: string[] = [];\n for (let i = 0; i < psbtHexes.length; i++) {\n signed.push(await wallet.signPsbt(psbtHexes[i], options?.[i]));\n }\n return signed;\n}\n\n// ============================================================================\n// Main entry point\n// ============================================================================\n\nexport interface SignDepositorGraphParams {\n /** The depositor graph from VP response (contains pre-built PSBTs) */\n depositorGraph: DepositorGraphTransactions;\n /** Depositor's BTC public key (x-only, 64-char hex, no 0x prefix) */\n depositorBtcPubkey: string;\n /** Bitcoin wallet for signing */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Sign all depositor graph transactions and assemble into presignatures.\n *\n * Flow:\n * 1. Collect pre-built PSBTs from VP response (base64 -> hex)\n * 2. Batch sign via wallet.signPsbts() if available, else sequential signPsbt()\n * 3. Extract Schnorr signatures from each signed PSBT\n * 4. Assemble into DepositorAsClaimerPresignatures\n */\nexport async function signDepositorGraph(\n params: SignDepositorGraphParams,\n): Promise<DepositorAsClaimerPresignatures> {\n const { depositorGraph, depositorBtcPubkey, btcWallet } = params;\n\n const depositorPubkey = stripHexPrefix(depositorBtcPubkey);\n const walletPublicKey = await btcWallet.getPublicKeyHex();\n\n // 1. Collect pre-built PSBTs from VP response\n const { psbtHexes, signOptions, challengerEntries } =\n collectDepositorGraphPsbts(depositorGraph, walletPublicKey);\n\n // 2. Sign all PSBTs (batch when supported, sequential fallback for mobile)\n const signedPsbtHexes = await signPsbtsWithFallback(\n btcWallet,\n psbtHexes,\n signOptions,\n );\n\n if (signedPsbtHexes.length !== psbtHexes.length) {\n throw new Error(\n `Wallet returned ${signedPsbtHexes.length} signed PSBTs, expected ${psbtHexes.length}`,\n );\n }\n\n // 3. Extract signatures and assemble presignatures\n return extractDepositorGraphSignatures(\n signedPsbtHexes,\n challengerEntries,\n depositorPubkey,\n );\n}\n","/**\n * Payout Signing Orchestration\n *\n * Polls VP for `PendingDepositorSignatures`, fetches presign transactions,\n * signs payouts via PayoutManager, signs the depositor graph, and submits\n * all signatures back to the VP.\n *\n * This is the main deposit protocol step between registration and activation.\n */\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { BitcoinWallet } from \"../../../../shared/wallets/interfaces\";\nimport { DaemonStatus } from \"../../clients/vault-provider/types\";\nimport type {\n ClaimerSignatures,\n ClaimerTransactions,\n} from \"../../clients/vault-provider/types\";\nimport { PayoutManager } from \"../../managers/PayoutManager\";\nimport {\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../../primitives/utils/bitcoin\";\nimport type { PeginStatusReader, PresignClient } from \"./interfaces\";\nimport { signDepositorGraph } from \"./signDepositorGraph\";\nimport { waitForPeginStatus } from \"./waitForPeginStatus\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Context required for signing payout transactions.\n * Caller builds this from on-chain data (contract queries, GraphQL, config).\n */\nexport interface PayoutSigningContext {\n /** Raw pegin BTC transaction hex (for PSBT construction) */\n peginTxHex: string;\n /** Vault provider's BTC public key (x-only hex, no prefix) */\n vaultProviderBtcPubkey: string;\n /** Sorted vault keeper BTC public keys (x-only hex, no prefix) */\n vaultKeeperBtcPubkeys: string[];\n /** Sorted universal challenger BTC public keys (x-only hex, no prefix) */\n universalChallengerBtcPubkeys: string[];\n /** Depositor's BTC public key (x-only hex, no prefix) */\n depositorBtcPubkey: string;\n /** Pegin timelock from the locked offchain params version */\n timelockPegin: number;\n /** BTC network (Mainnet, Testnet, etc.) */\n network: Network;\n /** On-chain registered depositor payout scriptPubKey (hex) */\n registeredPayoutScriptPubKey: string;\n}\n\nexport interface PollAndSignPayoutsParams {\n /** VP client implementing the status reader interface */\n statusReader: PeginStatusReader;\n /** VP client implementing the presign transaction flow interface */\n presignClient: PresignClient;\n /** Bitcoin wallet for signing */\n btcWallet: BitcoinWallet;\n /** BTC pegin transaction ID (unprefixed hex, 64 chars) */\n peginTxid: string;\n /** Depositor's x-only BTC public key (unprefixed hex, 64 chars) */\n depositorPk: string;\n /** Signing context built from on-chain data */\n signingContext: PayoutSigningContext;\n /** Maximum polling timeout in milliseconds (default: 20 min) */\n timeoutMs?: number;\n /** AbortSignal for cancellation */\n signal?: AbortSignal;\n /** Optional progress callback (completed claimers, total claimers) */\n onProgress?: (completed: number, total: number) => void;\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Maximum polling timeout (20 minutes) — VP may take 15-20 min to prepare. */\nconst MAX_POLLING_TIMEOUT_MS = 20 * 60 * 1000;\n\n/** Statuses after payout signatures are submitted — if VP is already here, skip. */\nconst POST_PAYOUT_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.PENDING_ACKS,\n DaemonStatus.PENDING_ACTIVATION,\n DaemonStatus.ACTIVATED,\n]);\n\nconst TARGET_STATUS: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,\n ...POST_PAYOUT_STATUSES,\n]);\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\ninterface PreparedTransaction {\n claimerPubkeyXOnly: string;\n payoutTxHex: string;\n assertTxHex: string;\n}\n\nfunction prepareTransactionsForSigning(\n claimerTransactions: ClaimerTransactions[],\n): PreparedTransaction[] {\n return claimerTransactions.map((tx) => ({\n claimerPubkeyXOnly: processPublicKeyToXOnly(tx.claimer_pubkey),\n payoutTxHex: tx.payout_tx.tx_hex,\n assertTxHex: tx.assert_tx.tx_hex,\n }));\n}\n\n/**\n * Derive BIP-86 P2TR scriptPubKey hex from an x-only public key.\n * Requires bitcoinjs-lib ECC to be initialized by the caller.\n */\nfunction deriveBip86ScriptPubKey(xOnlyPubkeyHex: string): string {\n const { output } = bitcoin.payments.p2tr({\n internalPubkey: Buffer.from(xOnlyPubkeyHex, \"hex\"),\n });\n if (!output) {\n throw new Error(\"Failed to derive BIP-86 P2TR scriptPubKey\");\n }\n return output.toString(\"hex\");\n}\n\n/**\n * Resolve the expected payout scriptPubKey for a given claimer.\n *\n * - VP/Depositor claimer: payout goes to the depositor's registered payout address\n * - VK claimer: payout goes to a BIP-86 P2TR address derived from the VK's pubkey\n *\n * Note: BIP-86 derivation for VK claimers requires bitcoinjs-lib's ECC to be initialized.\n */\nfunction resolvePayoutScriptPubKey(\n claimerPubkeyXOnly: string,\n context: PayoutSigningContext,\n): string {\n const claimer = stripHexPrefix(claimerPubkeyXOnly).toLowerCase();\n const vpPubkey = stripHexPrefix(\n context.vaultProviderBtcPubkey,\n ).toLowerCase();\n const depositorPubkey = stripHexPrefix(\n context.depositorBtcPubkey,\n ).toLowerCase();\n\n if (claimer === vpPubkey || claimer === depositorPubkey) {\n return context.registeredPayoutScriptPubKey;\n }\n\n // Verify claimer is a known vault keeper\n const isVaultKeeper = context.vaultKeeperBtcPubkeys.some(\n (vk) => stripHexPrefix(vk).toLowerCase() === claimer,\n );\n if (!isVaultKeeper) {\n throw new Error(\n `Unknown claimer pubkey ${claimer}: not VP, depositor, or a registered vault keeper`,\n );\n }\n\n // VK claimer: derive BIP-86 P2TR scriptPubKey from the VK's x-only pubkey\n const scriptPubKey = deriveBip86ScriptPubKey(claimer);\n return `0x${scriptPubKey}`;\n}\n\nfunction buildPayoutSigningInput(\n tx: PreparedTransaction,\n context: PayoutSigningContext,\n) {\n return {\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: context.peginTxHex,\n assertTxHex: tx.assertTxHex,\n vaultProviderBtcPubkey: context.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: context.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: context.universalChallengerBtcPubkeys,\n depositorBtcPubkey: context.depositorBtcPubkey,\n timelockPegin: context.timelockPegin,\n registeredPayoutScriptPubKey: resolvePayoutScriptPubKey(\n tx.claimerPubkeyXOnly,\n context,\n ),\n };\n}\n\n/**\n * Sign all payout transactions using PayoutManager.\n * Uses batch signing when wallet supports it, sequential otherwise.\n */\nasync function signPayoutTransactions(\n btcWallet: BitcoinWallet,\n context: PayoutSigningContext,\n transactions: PreparedTransaction[],\n onProgress?: (completed: number, total: number) => void,\n): Promise<Record<string, ClaimerSignatures>> {\n const payoutManager = new PayoutManager({\n network: context.network,\n btcWallet,\n });\n\n const totalClaimers = transactions.length;\n onProgress?.(0, totalClaimers);\n\n let payoutSignatures: string[];\n\n if (payoutManager.supportsBatchSigning()) {\n const results = await payoutManager.signPayoutTransactionsBatch(\n transactions.map((tx) => buildPayoutSigningInput(tx, context)),\n );\n payoutSignatures = results.map((r) => r.payoutSignature);\n } else {\n payoutSignatures = [];\n for (let i = 0; i < transactions.length; i++) {\n onProgress?.(i, totalClaimers);\n const result = await payoutManager.signPayoutTransaction(\n buildPayoutSigningInput(transactions[i], context),\n );\n payoutSignatures.push(result.signature);\n }\n }\n\n const signatures: Record<string, ClaimerSignatures> = {};\n for (let i = 0; i < transactions.length; i++) {\n signatures[transactions[i].claimerPubkeyXOnly] = {\n payout_signature: payoutSignatures[i],\n };\n }\n\n onProgress?.(totalClaimers, totalClaimers);\n return signatures;\n}\n\n// ============================================================================\n// Main entry point\n// ============================================================================\n\n/**\n * Poll for payout transactions, sign them, sign the depositor graph,\n * and submit all signatures to the vault provider.\n *\n * This is the main deposit protocol step between registration and activation.\n *\n * @throws Error on timeout, abort, signing failure, or RPC error\n */\nexport async function pollAndSignPayouts(\n params: PollAndSignPayoutsParams,\n): Promise<void> {\n const {\n statusReader,\n presignClient,\n btcWallet,\n peginTxid,\n depositorPk,\n signingContext,\n timeoutMs = MAX_POLLING_TIMEOUT_MS,\n signal,\n onProgress,\n } = params;\n\n // Phase 1: Poll until VP is ready for depositor signatures (or already past)\n const status = await waitForPeginStatus({\n statusReader,\n peginTxid,\n targetStatuses: TARGET_STATUS,\n timeoutMs,\n signal,\n });\n\n // Resume-safe: if VP already moved past payout signing, nothing to do\n if (POST_PAYOUT_STATUSES.has(status)) {\n return;\n }\n\n signal?.throwIfAborted();\n\n // Phase 2: Fetch presign transactions\n const response = await presignClient.requestDepositorPresignTransactions(\n {\n pegin_txid: peginTxid,\n depositor_pk: depositorPk,\n },\n signal,\n );\n\n signal?.throwIfAborted();\n\n // Phase 3: Sign VP/VK claimer payout transactions\n // Filter out the depositor's own claimer entry — its payout is signed\n // separately via signDepositorGraph (Phase 4) using VP-provided PSBTs.\n // Including it here would cause a redundant wallet signing prompt whose\n // result is discarded when the depositor graph signature overwrites it.\n const depositorPkNormalized = processPublicKeyToXOnly(depositorPk);\n const nonDepositorTxs = response.txs.filter(\n (tx) => processPublicKeyToXOnly(tx.claimer_pubkey) !== depositorPkNormalized,\n );\n const preparedTransactions = prepareTransactionsForSigning(nonDepositorTxs);\n const claimerSignatures = await signPayoutTransactions(\n btcWallet,\n signingContext,\n preparedTransactions,\n onProgress,\n );\n\n signal?.throwIfAborted();\n\n // Phase 4: Sign depositor-as-claimer graph\n const depositorClaimerPresignatures = await signDepositorGraph({\n depositorGraph: response.depositor_graph,\n depositorBtcPubkey: depositorPk,\n btcWallet,\n });\n\n signal?.throwIfAborted();\n\n // Phase 5: Submit all signatures to VP\n // Include depositor's own payout signature in the signatures map\n const allSignatures = { ...claimerSignatures };\n allSignatures[stripHexPrefix(depositorPk)] =\n depositorClaimerPresignatures.payout_signatures;\n\n await presignClient.submitDepositorPresignatures(\n {\n pegin_txid: peginTxid,\n depositor_pk: depositorPk,\n signatures: allSignatures,\n depositor_claimer_presignatures: depositorClaimerPresignatures,\n },\n signal,\n );\n}\n"],"names":["PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","extractPayoutSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","tx","signedPsbts","results","i","payoutSignature","payoutTxHex","registeredPayoutScriptPubKey","isValidHex","expectedScript","Buffer","stripHexPrefix","payoutTx","Transaction","max","output","DEFAULT_POLL_INTERVAL_MS","waitForPeginStatus","statusReader","peginTxid","targetStatuses","timeoutMs","pollIntervalMs","signal","startTime","status","VP_TERMINAL_STATUSES","error","JsonRpcError","RpcErrorCode","resolve","reject","onAbort","timeoutId","STATUS_POLL_TIMEOUT_MS","TARGET_STATUSES","DaemonStatus","POST_WOTS_STATUSES","submitWotsPublicKey","wotsSubmitter","depositorPk","wotsPublicKeys","SINGLE_PSBT_INPUT_COUNT","verifyAndParsePsbt","psbtBase64","expectedTxHex","label","psbt","Psbt","unsignedTxHex","normalizedExpected","sanitizePsbtForScriptPathSigning","clone","input","validateAndConvertPsbt","collectDepositorGraphPsbts","depositorGraph","walletPublicKey","psbtHexes","challengerEntries","singleInputOpts","payoutHex","challenger","challengerPubkey","noPayoutIdx","noPayoutHex","extractDepositorGraphSignatures","signedPsbtHexes","perChallenger","entry","signPsbtsWithFallback","wallet","options","signed","signDepositorGraph","depositorBtcPubkey","btcWallet","MAX_POLLING_TIMEOUT_MS","POST_PAYOUT_STATUSES","TARGET_STATUS","prepareTransactionsForSigning","claimerTransactions","processPublicKeyToXOnly","deriveBip86ScriptPubKey","xOnlyPubkeyHex","bitcoin","resolvePayoutScriptPubKey","claimerPubkeyXOnly","context","claimer","vpPubkey","vk","buildPayoutSigningInput","signPayoutTransactions","onProgress","payoutManager","totalClaimers","payoutSignatures","r","result","signatures","pollAndSignPayouts","presignClient","signingContext","response","depositorPkNormalized","nonDepositorTxs","preparedTransactions","claimerSignatures","depositorClaimerPresignatures","allSignatures"],"mappings":";;;;;;;;;;;AAsJO,MAAMA,EAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQzB,YAAYC,GAA6B;AAPxB,IAAAC,EAAA;AAQf,SAAK,SAASD;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBA,MAAM,sBACJE,GACgC;AAEhC,SAAK;AAAA,MACHA,EAAO;AAAA,MACPA,EAAO;AAAA,IAAA;AAIT,UAAMC,IAAkB,MAAM,KAAK,OAAO,UAAU,gBAAA,GAC9C,EAAE,iBAAAC,MAAoBC;AAAA,MAC1BF;AAAA,MACAD,EAAO;AAAA,IAAA,GAIHI,IAAa,MAAMC,EAAgB;AAAA,MACvC,aAA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