@babylonlabs-io/ts-sdk 3.0.2 → 3.1.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 (261) hide show
  1. package/dist/ApplicationRegistry.abi-s8cQ1ooR.js +160 -0
  2. package/dist/ApplicationRegistry.abi-s8cQ1ooR.js.map +1 -0
  3. package/dist/ApplicationRegistry.abi-sMiTWmnL.cjs +2 -0
  4. package/dist/ApplicationRegistry.abi-sMiTWmnL.cjs.map +1 -0
  5. package/dist/{BTCVaultRegistry.abi-BQ5tFNSu.cjs → BTCVaultRegistry.abi-CohlJX7c.cjs} +2 -2
  6. package/dist/{BTCVaultRegistry.abi-BQ5tFNSu.cjs.map → BTCVaultRegistry.abi-CohlJX7c.cjs.map} +1 -1
  7. package/dist/{BTCVaultRegistry.abi-B0x9_Bza.js → BTCVaultRegistry.abi-DBW0dyqH.js} +63 -1
  8. package/dist/{BTCVaultRegistry.abi-B0x9_Bza.js.map → BTCVaultRegistry.abi-DBW0dyqH.js.map} +1 -1
  9. package/dist/{PayoutManager-BSwbUQeF.js → PayoutManager-BZ212yml.js} +124 -123
  10. package/dist/PayoutManager-BZ212yml.js.map +1 -0
  11. package/dist/PayoutManager-DOdsgcUR.cjs +2 -0
  12. package/dist/PayoutManager-DOdsgcUR.cjs.map +1 -0
  13. package/dist/PeginManager-8EUlm10F.cjs +2 -0
  14. package/dist/{PeginManager-IgDHy_eU.cjs.map → PeginManager-8EUlm10F.cjs.map} +1 -1
  15. package/dist/{PeginManager-D8WGB8eN.js → PeginManager-QRwMUxZg.js} +45 -43
  16. package/dist/{PeginManager-D8WGB8eN.js.map → PeginManager-QRwMUxZg.js.map} +1 -1
  17. package/dist/{ProtocolParams.abi-q0AidvYX.js → ProtocolParams.abi-CKOVqFJP.js} +2 -158
  18. package/dist/ProtocolParams.abi-CKOVqFJP.js.map +1 -0
  19. package/dist/ProtocolParams.abi-CjrT0545.cjs +2 -0
  20. package/dist/ProtocolParams.abi-CjrT0545.cjs.map +1 -0
  21. package/dist/btcTxHash-BRZ8_EZq.js +9 -0
  22. package/dist/btcTxHash-BRZ8_EZq.js.map +1 -0
  23. package/dist/btcTxHash-CGb5BqFL.cjs +2 -0
  24. package/dist/btcTxHash-CGb5BqFL.cjs.map +1 -0
  25. package/dist/buildAndBroadcastReclaim-DjX7wVb2.cjs +2 -0
  26. package/dist/buildAndBroadcastReclaim-DjX7wVb2.cjs.map +1 -0
  27. package/dist/buildAndBroadcastReclaim-DoprHX7o.js +3077 -0
  28. package/dist/buildAndBroadcastReclaim-DoprHX7o.js.map +1 -0
  29. package/dist/buildVaultContextInputForClaim-9XZaqIiw.cjs +2 -0
  30. package/dist/buildVaultContextInputForClaim-9XZaqIiw.cjs.map +1 -0
  31. package/dist/buildVaultContextInputForClaim-DhBoQKyN.js +25 -0
  32. package/dist/buildVaultContextInputForClaim-DhBoQKyN.js.map +1 -0
  33. package/dist/constants-BeYquVd-.js +36 -0
  34. package/dist/constants-BeYquVd-.js.map +1 -0
  35. package/dist/constants-BwCg5K6R.cjs +2 -0
  36. package/dist/constants-BwCg5K6R.cjs.map +1 -0
  37. package/dist/{index-D2mybjXD.js → index-CVBtBjQ5.js} +2 -2
  38. package/dist/{index-D2mybjXD.js.map → index-CVBtBjQ5.js.map} +1 -1
  39. package/dist/{index-MRdle0fs.cjs → index-DpjYs5yr.cjs} +2 -2
  40. package/dist/{index-MRdle0fs.cjs.map → index-DpjYs5yr.cjs.map} +1 -1
  41. package/dist/index.cjs +1 -1
  42. package/dist/index.js +288 -260
  43. package/dist/index.js.map +1 -1
  44. package/dist/{noPayout-qBXWKwav.js → noPayout-B-vGXJ-V.js} +3 -3
  45. package/dist/{noPayout-qBXWKwav.js.map → noPayout-B-vGXJ-V.js.map} +1 -1
  46. package/dist/{noPayout-DAWBQ0eG.cjs → noPayout-DOHak0ui.cjs} +2 -2
  47. package/dist/{noPayout-DAWBQ0eG.cjs.map → noPayout-DOHak0ui.cjs.map} +1 -1
  48. package/dist/pegin-registration-client-BWMwxtr8.js +718 -0
  49. package/dist/pegin-registration-client-BWMwxtr8.js.map +1 -0
  50. package/dist/pegin-registration-client-D4EguWaz.cjs +2 -0
  51. package/dist/pegin-registration-client-D4EguWaz.cjs.map +1 -0
  52. package/dist/{primeVpAuth-BDWBKYhv.cjs → primeVpAuth-BPj2TPdD.cjs} +2 -2
  53. package/dist/{primeVpAuth-BDWBKYhv.cjs.map → primeVpAuth-BPj2TPdD.cjs.map} +1 -1
  54. package/dist/{primeVpAuth-D0ZnsjRi.js → primeVpAuth-CiCdRNGf.js} +2 -2
  55. package/dist/{primeVpAuth-D0ZnsjRi.js.map → primeVpAuth-CiCdRNGf.js.map} +1 -1
  56. package/dist/registration-records-CKLAv3gw.js +447 -0
  57. package/dist/registration-records-CKLAv3gw.js.map +1 -0
  58. package/dist/registration-records-DFQgBaYi.cjs +2 -0
  59. package/dist/registration-records-DFQgBaYi.cjs.map +1 -0
  60. package/dist/{secp256k1-D-H9jmd7.js → secp256k1-BuxBFUHm.js} +3 -3
  61. package/dist/{secp256k1-D-H9jmd7.js.map → secp256k1-BuxBFUHm.js.map} +1 -1
  62. package/dist/signer-set-reader-C1VmC9_U.js +264 -0
  63. package/dist/signer-set-reader-C1VmC9_U.js.map +1 -0
  64. package/dist/signer-set-reader-C6g47hdk.cjs +2 -0
  65. package/dist/signer-set-reader-C6g47hdk.cjs.map +1 -0
  66. package/dist/{signing-Dhr2t0Z6.js → signing-C1rR4tqs.js} +9 -15
  67. package/dist/signing-C1rR4tqs.js.map +1 -0
  68. package/dist/signing-DvISftFk.cjs +2 -0
  69. package/dist/signing-DvISftFk.cjs.map +1 -0
  70. package/dist/tbv/core/clients/eth/__tests__/registration-records.test.d.ts +2 -0
  71. package/dist/tbv/core/clients/eth/__tests__/registration-records.test.d.ts.map +1 -0
  72. package/dist/tbv/core/clients/eth/claimable-event-error.d.ts +14 -0
  73. package/dist/tbv/core/clients/eth/claimable-event-error.d.ts.map +1 -0
  74. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  75. package/dist/tbv/core/clients/eth/index.d.ts +3 -1
  76. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
  77. package/dist/tbv/core/clients/eth/index.js +27 -21
  78. package/dist/tbv/core/clients/eth/index.js.map +1 -1
  79. package/dist/tbv/core/clients/eth/payout-script.d.ts +8 -0
  80. package/dist/tbv/core/clients/eth/payout-script.d.ts.map +1 -1
  81. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +13 -0
  82. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
  83. package/dist/tbv/core/clients/eth/registration-logs-error.d.ts +11 -1
  84. package/dist/tbv/core/clients/eth/registration-logs-error.d.ts.map +1 -1
  85. package/dist/tbv/core/clients/eth/registration-records.d.ts +29 -0
  86. package/dist/tbv/core/clients/eth/registration-records.d.ts.map +1 -0
  87. package/dist/tbv/core/clients/eth/types.d.ts +120 -3
  88. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  89. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +9 -10
  90. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  91. package/dist/tbv/core/clients/index.cjs +1 -1
  92. package/dist/tbv/core/clients/index.js +56 -50
  93. package/dist/tbv/core/clients/index.js.map +1 -1
  94. package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
  95. package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
  96. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +45 -0
  97. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  98. package/dist/tbv/core/contracts/index.cjs +1 -1
  99. package/dist/tbv/core/contracts/index.js +16 -15
  100. package/dist/tbv/core/contracts/index.js.map +1 -1
  101. package/dist/tbv/core/deposit-terms/__tests__/claimSiblings.test.d.ts +2 -0
  102. package/dist/tbv/core/deposit-terms/__tests__/claimSiblings.test.d.ts.map +1 -0
  103. package/dist/tbv/core/deposit-terms/__tests__/fixtures/realFundedPrePegin.d.ts +29 -0
  104. package/dist/tbv/core/deposit-terms/__tests__/fixtures/realFundedPrePegin.d.ts.map +1 -0
  105. package/dist/tbv/core/deposit-terms/__tests__/fundedPrePeginFee.test.d.ts +2 -0
  106. package/dist/tbv/core/deposit-terms/__tests__/fundedPrePeginFee.test.d.ts.map +1 -0
  107. package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.golden.test.d.ts +2 -0
  108. package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.golden.test.d.ts.map +1 -0
  109. package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.test.d.ts +2 -0
  110. package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.test.d.ts.map +1 -0
  111. package/dist/tbv/core/deposit-terms/claimSiblings.d.ts +23 -0
  112. package/dist/tbv/core/deposit-terms/claimSiblings.d.ts.map +1 -0
  113. package/dist/tbv/core/deposit-terms/fundedPrePeginFee.d.ts +15 -0
  114. package/dist/tbv/core/deposit-terms/fundedPrePeginFee.d.ts.map +1 -0
  115. package/dist/tbv/core/deposit-terms/index.d.ts +3 -0
  116. package/dist/tbv/core/deposit-terms/index.d.ts.map +1 -1
  117. package/dist/tbv/core/deposit-terms/rebuildDepositTermsForClaim.d.ts +40 -0
  118. package/dist/tbv/core/deposit-terms/rebuildDepositTermsForClaim.d.ts.map +1 -0
  119. package/dist/tbv/core/index.cjs +1 -1
  120. package/dist/tbv/core/index.js +287 -259
  121. package/dist/tbv/core/index.js.map +1 -1
  122. package/dist/tbv/core/managers/index.cjs +1 -1
  123. package/dist/tbv/core/managers/index.js +2 -2
  124. package/dist/tbv/core/managers/pegin/signPsbtsWithFallback.d.ts +6 -2
  125. package/dist/tbv/core/managers/pegin/signPsbtsWithFallback.d.ts.map +1 -1
  126. package/dist/tbv/core/primitives/index.cjs +1 -1
  127. package/dist/tbv/core/primitives/index.js +4 -4
  128. package/dist/tbv/core/primitives/psbt/constants.d.ts +54 -6
  129. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  130. package/dist/tbv/core/services/delegated-claim/__tests__/assembleWatchtowerArtifactsFromSignatures.test.d.ts +2 -0
  131. package/dist/tbv/core/services/delegated-claim/__tests__/assembleWatchtowerArtifactsFromSignatures.test.d.ts.map +1 -0
  132. package/dist/tbv/core/services/delegated-claim/__tests__/assertBinding.test.d.ts +2 -0
  133. package/dist/tbv/core/services/delegated-claim/__tests__/assertBinding.test.d.ts.map +1 -0
  134. package/dist/tbv/core/services/delegated-claim/__tests__/assertPayoutFeeAndTimelocks.test.d.ts +2 -0
  135. package/dist/tbv/core/services/delegated-claim/__tests__/assertPayoutFeeAndTimelocks.test.d.ts.map +1 -0
  136. package/dist/tbv/core/services/delegated-claim/__tests__/fixtures/delegatedClaimPsbts.d.ts +49 -0
  137. package/dist/tbv/core/services/delegated-claim/__tests__/fixtures/delegatedClaimPsbts.d.ts.map +1 -0
  138. package/dist/tbv/core/services/delegated-claim/__tests__/payoutBinding.test.d.ts +2 -0
  139. package/dist/tbv/core/services/delegated-claim/__tests__/payoutBinding.test.d.ts.map +1 -0
  140. package/dist/tbv/core/services/delegated-claim/__tests__/payoutInputLeaf.test.d.ts +2 -0
  141. package/dist/tbv/core/services/delegated-claim/__tests__/payoutInputLeaf.test.d.ts.map +1 -0
  142. package/dist/tbv/core/services/delegated-claim/__tests__/planDelegatedClaimSigning.test.d.ts +2 -0
  143. package/dist/tbv/core/services/delegated-claim/__tests__/planDelegatedClaimSigning.test.d.ts.map +1 -0
  144. package/dist/tbv/core/services/delegated-claim/__tests__/readDelegatedClaimVaultContext.test.d.ts +2 -0
  145. package/dist/tbv/core/services/delegated-claim/__tests__/readDelegatedClaimVaultContext.test.d.ts.map +1 -0
  146. package/dist/tbv/core/services/delegated-claim/__tests__/realSchnorrVerification.test.d.ts +2 -0
  147. package/dist/tbv/core/services/delegated-claim/__tests__/realSchnorrVerification.test.d.ts.map +1 -0
  148. package/dist/tbv/core/services/delegated-claim/__tests__/signDelegatedClaimPlan.test.d.ts +2 -0
  149. package/dist/tbv/core/services/delegated-claim/__tests__/signDelegatedClaimPlan.test.d.ts.map +1 -0
  150. package/dist/tbv/core/services/delegated-claim/__tests__/signingRequests.test.d.ts +2 -0
  151. package/dist/tbv/core/services/delegated-claim/__tests__/signingRequests.test.d.ts.map +1 -0
  152. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts +34 -9
  153. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts.map +1 -1
  154. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifactsFromSignatures.d.ts +36 -0
  155. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifactsFromSignatures.d.ts.map +1 -0
  156. package/dist/tbv/core/services/delegated-claim/assertBinding.d.ts +37 -0
  157. package/dist/tbv/core/services/delegated-claim/assertBinding.d.ts.map +1 -0
  158. package/dist/tbv/core/services/delegated-claim/assertPayoutFeeAndTimelocks.d.ts +35 -0
  159. package/dist/tbv/core/services/delegated-claim/assertPayoutFeeAndTimelocks.d.ts.map +1 -0
  160. package/dist/tbv/core/services/delegated-claim/index.d.ts +22 -4
  161. package/dist/tbv/core/services/delegated-claim/index.d.ts.map +1 -1
  162. package/dist/tbv/core/services/delegated-claim/payoutBinding.d.ts +10 -4
  163. package/dist/tbv/core/services/delegated-claim/payoutBinding.d.ts.map +1 -1
  164. package/dist/tbv/core/services/delegated-claim/payoutInputLeaf.d.ts +34 -0
  165. package/dist/tbv/core/services/delegated-claim/payoutInputLeaf.d.ts.map +1 -0
  166. package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts +43 -0
  167. package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts.map +1 -0
  168. package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts +70 -0
  169. package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts.map +1 -0
  170. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts +31 -2
  171. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts.map +1 -1
  172. package/dist/tbv/core/services/delegated-claim/signDelegatedClaimPlan.d.ts +110 -0
  173. package/dist/tbv/core/services/delegated-claim/signDelegatedClaimPlan.d.ts.map +1 -0
  174. package/dist/tbv/core/services/delegated-claim/signingRequests.d.ts +24 -0
  175. package/dist/tbv/core/services/delegated-claim/signingRequests.d.ts.map +1 -0
  176. package/dist/tbv/core/services/delegated-claim/types.d.ts +110 -9
  177. package/dist/tbv/core/services/delegated-claim/types.d.ts.map +1 -1
  178. package/dist/tbv/core/services/delegated-claim/vaultIdBinding.d.ts +16 -1
  179. package/dist/tbv/core/services/delegated-claim/vaultIdBinding.d.ts.map +1 -1
  180. package/dist/tbv/core/services/delegated-claim/verifySignatureForRequest.d.ts +19 -0
  181. package/dist/tbv/core/services/delegated-claim/verifySignatureForRequest.d.ts.map +1 -0
  182. package/dist/tbv/core/services/delegated-claim/verifyingKeyBinding.d.ts +40 -0
  183. package/dist/tbv/core/services/delegated-claim/verifyingKeyBinding.d.ts.map +1 -0
  184. package/dist/tbv/core/services/delegated-claim/walletIdentity.d.ts +23 -0
  185. package/dist/tbv/core/services/delegated-claim/walletIdentity.d.ts.map +1 -0
  186. package/dist/tbv/core/services/index.cjs +1 -1
  187. package/dist/tbv/core/services/index.js +89 -76
  188. package/dist/tbv/core/services/participants/__tests__/readStampedParticipantKeys.test.d.ts +2 -0
  189. package/dist/tbv/core/services/participants/__tests__/readStampedParticipantKeys.test.d.ts.map +1 -0
  190. package/dist/tbv/core/services/participants/index.d.ts +1 -0
  191. package/dist/tbv/core/services/participants/index.d.ts.map +1 -1
  192. package/dist/tbv/core/services/participants/readStampedParticipantKeys.d.ts +29 -0
  193. package/dist/tbv/core/services/participants/readStampedParticipantKeys.d.ts.map +1 -0
  194. package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts +1 -1
  195. package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts.map +1 -1
  196. package/dist/tbv/core/utils/index.cjs +1 -1
  197. package/dist/tbv/core/utils/index.js +47 -46
  198. package/dist/tbv/core/utils/index.js.map +1 -1
  199. package/dist/tbv/core/vault-secrets/__tests__/buildVaultContextInputForClaim.test.d.ts +2 -0
  200. package/dist/tbv/core/vault-secrets/__tests__/buildVaultContextInputForClaim.test.d.ts.map +1 -0
  201. package/dist/tbv/core/vault-secrets/buildVaultContextInputForClaim.d.ts +18 -0
  202. package/dist/tbv/core/vault-secrets/buildVaultContextInputForClaim.d.ts.map +1 -0
  203. package/dist/tbv/core/vault-secrets/index.cjs +1 -1
  204. package/dist/tbv/core/vault-secrets/index.d.ts +1 -0
  205. package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
  206. package/dist/tbv/core/vault-secrets/index.js +12 -10
  207. package/dist/tbv/core/vault-secrets/index.js.map +1 -1
  208. package/dist/tbv/index.cjs +1 -1
  209. package/dist/tbv/index.js +287 -259
  210. package/dist/tbv/index.js.map +1 -1
  211. package/dist/toRefundInputs-BZXvuOMY.cjs +2 -0
  212. package/dist/toRefundInputs-BZXvuOMY.cjs.map +1 -0
  213. package/dist/toRefundInputs-dKDSvpVI.js +698 -0
  214. package/dist/toRefundInputs-dKDSvpVI.js.map +1 -0
  215. package/dist/types-Bda75Od0.cjs +2 -0
  216. package/dist/types-Bda75Od0.cjs.map +1 -0
  217. package/dist/types-C5jj3Cc-.js +198 -0
  218. package/dist/types-C5jj3Cc-.js.map +1 -0
  219. package/dist/{verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs → verifyKeyPathSchnorrSignature-CQUut2-O.cjs} +2 -2
  220. package/dist/{verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs.map → verifyKeyPathSchnorrSignature-CQUut2-O.cjs.map} +1 -1
  221. package/dist/{verifyKeyPathSchnorrSignature-BQHNhRj6.js → verifyKeyPathSchnorrSignature-DxPbeSdQ.js} +2 -2
  222. package/dist/{verifyKeyPathSchnorrSignature-BQHNhRj6.js.map → verifyKeyPathSchnorrSignature-DxPbeSdQ.js.map} +1 -1
  223. package/dist/{verifyScriptPathSchnorrSignature-CpjSTfMj.js → verifyScriptPathSchnorrSignature-B3-VkvnK.js} +6 -4
  224. package/dist/{verifyScriptPathSchnorrSignature-CpjSTfMj.js.map → verifyScriptPathSchnorrSignature-B3-VkvnK.js.map} +1 -1
  225. package/dist/{verifyScriptPathSchnorrSignature-BKZihCjk.cjs → verifyScriptPathSchnorrSignature-D2t1yACC.cjs} +2 -2
  226. package/dist/{verifyScriptPathSchnorrSignature-BKZihCjk.cjs.map → verifyScriptPathSchnorrSignature-D2t1yACC.cjs.map} +1 -1
  227. package/package.json +4 -4
  228. package/dist/PayoutManager-B6GFbG3X.cjs +0 -2
  229. package/dist/PayoutManager-B6GFbG3X.cjs.map +0 -1
  230. package/dist/PayoutManager-BSwbUQeF.js.map +0 -1
  231. package/dist/PeginManager-IgDHy_eU.cjs +0 -2
  232. package/dist/ProtocolParams.abi-Db2USqQm.cjs +0 -2
  233. package/dist/ProtocolParams.abi-Db2USqQm.cjs.map +0 -1
  234. package/dist/ProtocolParams.abi-q0AidvYX.js.map +0 -1
  235. package/dist/buildAndBroadcastReclaim-B8aFMGf-.cjs +0 -2
  236. package/dist/buildAndBroadcastReclaim-B8aFMGf-.cjs.map +0 -1
  237. package/dist/buildAndBroadcastReclaim-D5520lbL.js +0 -2210
  238. package/dist/buildAndBroadcastReclaim-D5520lbL.js.map +0 -1
  239. package/dist/constants-BTZdyOuk.cjs +0 -2
  240. package/dist/constants-BTZdyOuk.cjs.map +0 -1
  241. package/dist/constants-D5vORbQE.js +0 -29
  242. package/dist/constants-D5vORbQE.js.map +0 -1
  243. package/dist/onChainBtcPubkey-BlzxYImF.cjs +0 -2
  244. package/dist/onChainBtcPubkey-BlzxYImF.cjs.map +0 -1
  245. package/dist/onChainBtcPubkey-CCTdl53s.js +0 -159
  246. package/dist/onChainBtcPubkey-CCTdl53s.js.map +0 -1
  247. package/dist/pegin-registration-client-B0j6ugt9.cjs +0 -2
  248. package/dist/pegin-registration-client-B0j6ugt9.cjs.map +0 -1
  249. package/dist/pegin-registration-client-ilkV1mLP.js +0 -878
  250. package/dist/pegin-registration-client-ilkV1mLP.js.map +0 -1
  251. package/dist/signing-3l5Aqd-H.cjs +0 -2
  252. package/dist/signing-3l5Aqd-H.cjs.map +0 -1
  253. package/dist/signing-Dhr2t0Z6.js.map +0 -1
  254. package/dist/toRefundInputs-10RYIfh1.js +0 -559
  255. package/dist/toRefundInputs-10RYIfh1.js.map +0 -1
  256. package/dist/toRefundInputs-a-0HRyrl.cjs +0 -2
  257. package/dist/toRefundInputs-a-0HRyrl.cjs.map +0 -1
  258. package/dist/types-BueQoMjO.cjs +0 -2
  259. package/dist/types-BueQoMjO.cjs.map +0 -1
  260. package/dist/types-DGkejGZH.js +0 -456
  261. package/dist/types-DGkejGZH.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"buildAndBroadcastReclaim-B8aFMGf-.cjs","sources":["../src/tbv/core/services/activation/activateVault.ts","../src/tbv/core/services/delegated-claim/challengerBinding.ts","../src/tbv/core/services/delegated-claim/payoutBinding.ts","../src/tbv/core/services/delegated-claim/vaultIdBinding.ts","../src/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.ts","../src/tbv/core/services/delegated-claim/deriveClaimerWotsKeypair.ts","../src/tbv/core/services/delegated-claim/readWatchtowerArtifacts.ts","../src/tbv/core/services/deposit/peginRegistrationDepth.ts","../src/tbv/core/services/deposit/graphFingerprint.ts","../src/tbv/core/services/deposit/signDepositorGraph.ts","../src/tbv/core/services/deposit/waitForPeginStatus.ts","../src/tbv/core/services/deposit/runDepositorPresignFlow.ts","../src/tbv/core/services/deposit/submitWotsPublicKey.ts","../src/tbv/core/services/participants/indexerKeyHint.ts","../src/tbv/core/services/participants/resolveParticipantKeys.ts","../src/tbv/core/services/deposit/validateOnChainParticipantKeys.ts","../src/tbv/core/services/deposit/validation.ts","../src/tbv/core/services/deposit/verifyRegisteredParticipantKeys.ts","../src/tbv/core/services/deposit/verifyRegisteredVaultVersions.ts","../src/tbv/core/services/refund/errors.ts","../src/tbv/core/services/refund/buildAndBroadcastRefund.ts","../src/tbv/core/services/reclaim/errors.ts","../src/tbv/core/services/reclaim/buildAndBroadcastReclaim.ts"],"sourcesContent":["/**\n * Vault activation — reveal HTLC secret on Ethereum to move the vault from\n * Verified to Active. The on-chain contract validates `sha256(s) == hashlock`\n * and the activation deadline; this function pre-validates inputs (including\n * an optional hashlock check) and delegates the actual contract write to an\n * injected callback so the SDK stays transport-agnostic.\n *\n * @module services/activation\n */\n\nimport type { Abi, Address, Hash, Hex } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { ensureHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { validateSecretAgainstHashlock } from \"../htlc\";\n\nconst BYTES32_HEX_RE = /^0x[0-9a-fA-F]{64}$/;\nconst ADDRESS_HEX_RE = /^0x[0-9a-fA-F]{40}$/;\n// ETH calldata convention: 0x prefix REQUIRED, even number of hex chars, may\n// be empty (\"0x\"). Named distinctly from the BTC-hex regex in\n// buildAndBroadcastRefund.ts (which allows an optional prefix and requires\n// non-empty) to make the convention explicit at the call site.\nconst ETH_HEX_BYTES_RE = /^0x([0-9a-fA-F]{2})*$/;\n\nfunction assertBytes32(value: string, label: string): void {\n if (value.length !== 66) {\n throw new Error(\n `${label} must be 32 bytes (66 hex chars with 0x prefix), got length ${value.length}`,\n );\n }\n if (!BYTES32_HEX_RE.test(value)) {\n throw new Error(\n `${label} must contain only hex characters after the 0x prefix`,\n );\n }\n}\n\nfunction assertAddress(value: string, label: string): void {\n if (!ADDRESS_HEX_RE.test(value)) {\n throw new Error(\n `${label} must be a 20-byte 0x-prefixed hex address (42 chars)`,\n );\n }\n}\n\nfunction assertHexBytes(value: string, label: string): void {\n if (!ETH_HEX_BYTES_RE.test(value)) {\n throw new Error(\n `${label} must be a 0x-prefixed hex string with an even number of hex chars`,\n );\n }\n}\n\n/**\n * A single ETH contract-write call. The SDK assembles these; the caller\n * executes them via viem, wagmi, a wallet provider, or any other transport.\n */\nexport interface EthContractWriteCall {\n address: Address;\n abi: Abi;\n functionName: string;\n args: readonly unknown[];\n}\n\n/**\n * Minimum shape the SDK requires from any contract-write result. Callers may\n * return richer objects (e.g. including the receipt) — the SDK propagates\n * them unchanged via the generic parameter on {@link EthContractWriter}.\n */\nexport interface EthContractWriteResult {\n transactionHash: Hash;\n}\n\n/**\n * Caller-provided contract writer. The generic `R` lets callers return any\n * transport-specific result shape (e.g. `{ transactionHash, receipt }`);\n * the SDK forwards that shape back through `activateVault`.\n */\nexport type EthContractWriter<R extends EthContractWriteResult = EthContractWriteResult> = (\n call: EthContractWriteCall,\n) => Promise<R>;\n\nexport interface ActivateVaultInput<\n R extends EthContractWriteResult = EthContractWriteResult,\n> {\n /** BTCVaultRegistry contract address (env-specific). */\n btcVaultRegistryAddress: Address;\n /** Vault ID (bytes32, 0x-prefixed). */\n vaultId: Hex;\n /**\n * HTLC secret preimage (bytes32). A missing `0x` prefix or an uppercase\n * `0X` prefix is normalised before validation.\n */\n secret: string;\n /**\n * Optional hashlock for client-side pre-validation. When provided, the SDK\n * rejects before calling `writeContract` if `sha256(secret) != hashlock`.\n */\n hashlock?: Hex;\n /**\n * Activation metadata passed through to the contract. Required to keep\n * the \"empty metadata\" convention explicit at the call site — pass `\"0x\"`\n * (empty bytes) when no metadata is needed. Must be a 0x-prefixed hex\n * string with an even number of hex chars.\n */\n activationMetadata: Hex;\n /** Caller-provided write callback — see {@link EthContractWriter}. */\n writeContract: EthContractWriter<R>;\n /**\n * Optional abort signal. Checked before validation runs; since validation\n * is fully synchronous, cancellation between validation and the write is\n * not observable and callers should rely on the transport's own\n * cancellation support for that window.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Shared pre-write validation for both activation entry points: address and\n * bytes32 shapes, plus the optional `sha256(secret) == hashlock` pre-check —\n * the last gate before the secret would enter calldata.\n *\n * @returns the 0x-normalised secret to place in calldata\n */\nfunction validateActivationInputs(input: {\n btcVaultRegistryAddress: Address;\n vaultId: Hex;\n secret: string;\n hashlock?: Hex;\n}): Hex {\n assertAddress(input.btcVaultRegistryAddress, \"btcVaultRegistryAddress\");\n assertBytes32(input.vaultId, \"vaultId\");\n\n const normalizedSecret = ensureHexPrefix(input.secret);\n assertBytes32(normalizedSecret, \"secret\");\n\n if (input.hashlock !== undefined) {\n assertBytes32(input.hashlock, \"hashlock\");\n if (!validateSecretAgainstHashlock(normalizedSecret, input.hashlock)) {\n throw new Error(\n \"Invalid secret: SHA256(secret) does not match the provided hashlock\",\n );\n }\n }\n\n return normalizedSecret;\n}\n\n/**\n * Reveal the HTLC secret on Ethereum and activate the vault.\n *\n * Validates inputs, optionally pre-checks the secret against the expected\n * hashlock, and delegates the contract write to `writeContract`. Returns\n * whatever the writer returns so callers can keep richer transport-specific\n * metadata (e.g. viem receipts) end-to-end.\n *\n * @throws `Error` if `btcVaultRegistryAddress` is not a valid 20-byte address\n * @throws `Error` if `vaultId` or `secret` is not a valid 32-byte hex\n * @throws `Error` if `hashlock` is provided and is not a valid 32-byte hex,\n * or if `sha256(secret) != hashlock`\n * @throws `Error` if `activationMetadata` is not a 0x-prefixed hex byte\n * string (must have an even number of hex chars). Pass `\"0x\"` for\n * empty metadata.\n * @throws whatever the injected `writeContract` throws\n * @throws `AbortError` / caller-provided abort reason if `signal` aborts\n */\nexport async function activateVault<\n R extends EthContractWriteResult = EthContractWriteResult,\n>(input: ActivateVaultInput<R>): Promise<R> {\n const {\n btcVaultRegistryAddress,\n vaultId,\n hashlock,\n activationMetadata,\n writeContract,\n signal,\n } = input;\n\n signal?.throwIfAborted();\n\n const normalizedSecret = validateActivationInputs({\n btcVaultRegistryAddress,\n vaultId,\n secret: input.secret,\n hashlock,\n });\n\n assertHexBytes(activationMetadata, \"activationMetadata\");\n\n return writeContract({\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"activateVaultWithSecret\",\n args: [vaultId, normalizedSecret, activationMetadata],\n });\n}\n\nexport interface ActivateVaultAndRedeemInput<\n R extends EthContractWriteResult = EthContractWriteResult,\n> {\n /** BTCVaultRegistry contract address (env-specific). */\n btcVaultRegistryAddress: Address;\n /** Vault ID (bytes32, 0x-prefixed). */\n vaultId: Hex;\n /**\n * HTLC secret preimage (bytes32). A missing `0x` prefix or an uppercase\n * `0X` prefix is normalised before validation.\n */\n secret: string;\n /**\n * Optional hashlock for client-side pre-validation. When provided, the SDK\n * rejects before calling `writeContract` if `sha256(secret) != hashlock`.\n */\n hashlock?: Hex;\n /** Caller-provided write callback — see {@link EthContractWriter}. */\n writeContract: EthContractWriter<R>;\n /**\n * Optional abort signal. Checked before validation runs; since validation\n * is fully synchronous, cancellation between validation and the write is\n * not observable and callers should rely on the transport's own\n * cancellation support for that window.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Depositor escape hatch: reveal the HTLC secret and immediately redeem the\n * vault for the depositor, without any application activation. The contract\n * (`activateVaultWithSecretAndRedeem`) runs the same activation preconditions\n * (Verified status, activation deadline, `sha256(s) == hashlock`) and then\n * marks the vault Redeemed so the vault provider pays the BTC out to the\n * depositor's committed payout address. Used when the normal activation is\n * unavailable (e.g. the application adapter is paused or its activation\n * reverts) but the secret must still be revealed to recover the swept peg-in.\n *\n * Takes no activation metadata — the application entry point is never called.\n *\n * @throws `Error` if `btcVaultRegistryAddress` is not a valid 20-byte address\n * @throws `Error` if `vaultId` or `secret` is not a valid 32-byte hex\n * @throws `Error` if `hashlock` is provided and is not a valid 32-byte hex,\n * or if `sha256(secret) != hashlock`\n * @throws whatever the injected `writeContract` throws\n * @throws `AbortError` / caller-provided abort reason if `signal` aborts\n */\nexport async function activateVaultAndRedeem<\n R extends EthContractWriteResult = EthContractWriteResult,\n>(input: ActivateVaultAndRedeemInput<R>): Promise<R> {\n const { btcVaultRegistryAddress, vaultId, hashlock, writeContract, signal } =\n input;\n\n signal?.throwIfAborted();\n\n const normalizedSecret = validateActivationInputs({\n btcVaultRegistryAddress,\n vaultId,\n secret: input.secret,\n hashlock,\n });\n\n return writeContract({\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"activateVaultWithSecretAndRedeem\",\n args: [vaultId, normalizedSecret],\n });\n}\n","/**\n * Binding between the challenger set a delegated claim signs for and the set\n * the vault actually has on chain.\n *\n * The WronglyChallenged PSBTs arrive keyed by challenger public key, and the\n * vault provider chooses those keys. Nothing downstream notices a short map:\n * the artifacts file verifies against its own graph, so a missing challenger\n * produces a file that looks complete and fails only months later, when that\n * challenger's ChallengeAssert has to be answered inside\n * `timelock_challenge_assert` and the material is not there.\n *\n * The failure is asymmetric, which is why both directions are checked.\n * Missing entries leave the depositor unable to defend the claim; extra\n * entries hand out signatures for keys the protocol does not recognize.\n *\n * This mirrors `assertChallengerSetMatchesExpected` in\n * `services/deposit/signDepositorGraph.ts`, which does the same job at\n * deposit time against the same on-chain sets.\n *\n * @module services/delegated-claim/challengerBinding\n */\n\nimport { deriveLocalChallengers } from \"../../primitives/challengers\";\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/**\n * Thrown when the graph's challengers are not the vault's challengers.\n *\n * @experimental\n */\nexport class ChallengerSetMismatchError extends Error {\n constructor(\n /** Challengers the vault has that the graph left out. */\n readonly missing: string[],\n /** Challengers the graph lists that the vault does not have. */\n readonly unexpected: string[],\n ) {\n super(\n `Transaction graph's challenger set does not match the vault's ` +\n `(local ∪ universal)` +\n (missing.length > 0 ? ` (missing: ${missing.join(\", \")})` : \"\") +\n (unexpected.length > 0\n ? ` (unexpected: ${unexpected.join(\", \")})`\n : \"\") +\n `. Refusing to sign an incomplete or padded challenger set.`,\n );\n this.name = \"ChallengerSetMismatchError\";\n }\n}\n\n/**\n * The graph's challenger keys, and the on-chain sets they must equal.\n *\n * @experimental\n */\nexport interface AssertChallengerSetMatchesVaultParams {\n /** Challenger keys the graph produced WronglyChallenged PSBTs for. */\n graphChallengerPubkeys: string[];\n /** Depositor's BTC public key, registered on chain for this vault. */\n depositorBtcPubkey: string;\n /**\n * Vault provider's BTC public key, registered on chain for this vault.\n * The depositor-as-claimer branch does not use it, but the shared\n * derivation takes it, and passing a stand-in would be a lie that the\n * next change to that function could turn into a wrong set.\n */\n vaultProviderBtcPubkey: string;\n /** Vault keepers registered on chain for this vault. */\n vaultKeeperBtcPubkeys: string[];\n /** Universal challengers registered on chain. */\n universalChallengerBtcPubkeys: string[];\n}\n\n/**\n * Throws unless the graph's challenger set equals `local ∪ universal`.\n *\n * The depositor is the claimer here, so the local set is the vault keepers,\n * derived by the same function the deposit path uses rather than restated.\n *\n * @throws {@link ChallengerSetMismatchError} on any missing or extra key, or\n * a plain error when the on-chain sets themselves are unusable.\n *\n * @experimental\n */\nexport function assertChallengerSetMatchesVault(\n params: AssertChallengerSetMatchesVaultParams,\n): void {\n const local = deriveLocalChallengers({\n claimerBtcPubkey: params.depositorBtcPubkey,\n depositorBtcPubkey: params.depositorBtcPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n });\n const universal = params.universalChallengerBtcPubkeys.map(normalizeKey);\n\n // Protocol guarantee: the two sets are disjoint. An overlap makes a\n // challenger's role ambiguous, so it is an error rather than a union.\n const overlap = local.filter((key) => universal.includes(key));\n if (overlap.length > 0) {\n throw new Error(\n `Cannot check the challenger set: vault keepers and universal ` +\n `challengers overlap (${overlap.join(\", \")}).`,\n );\n }\n\n const supplied = params.graphChallengerPubkeys.map(normalizeKey);\n const suppliedSet = new Set(supplied);\n if (suppliedSet.size !== supplied.length) {\n throw new Error(\n \"Transaction graph lists the same challenger more than once.\",\n );\n }\n\n const expected = [...local, ...universal];\n const expectedSet = new Set(expected);\n const missing = expected.filter((key) => !suppliedSet.has(key));\n const unexpected = supplied.filter((key) => !expectedSet.has(key));\n if (missing.length > 0 || unexpected.length > 0) {\n throw new ChallengerSetMismatchError(missing, unexpected);\n }\n}\n\nfunction normalizeKey(pubkey: string): string {\n return stripHexPrefix(pubkey).toLowerCase();\n}\n","/**\n * Binding between a delegated-claim Payout and the destination the vault\n * registered on chain.\n *\n * The Payout transaction is built by the vault provider and moves the whole\n * recovered peg-in. Its outputs are the one thing in this flow that decides\n * where the money lands, and nothing in the artifacts file constrains them:\n * the Rust verification proves the bundled signatures are self-consistent\n * with the same graph that named the outputs. So a graph correctly bound to\n * this vault can still carry a Payout that pays somebody else, and the\n * depositor would sign it in the same prompt as everything else.\n *\n * This is the claim-side counterpart of `assertPayoutOutputLayout` in\n * `primitives/psbt/payout.ts`, which the deposit-time path already runs for\n * the same `depositor-as-claimer` role. It pins the same four things: the\n * output count, the payout script, the CPFP anchor value, and the version\n * and locktime the depositor's signature commits to.\n *\n * @module services/delegated-claim/payoutBinding\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport {\n NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT,\n PAYOUT_ANCHOR_DUST_SATS,\n PAYOUT_TX_LOCKTIME,\n PAYOUT_TX_VERSION,\n} from \"../../primitives/psbt/constants\";\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** Output of the Payout transaction that pays the claimer. */\nconst PAYOUT_DESTINATION_OUTPUT = 0;\n\n/**\n * Thrown when a Payout does not pay the vault's registered destination.\n *\n * @experimental\n */\nexport class PayoutDestinationError extends Error {\n constructor(\n /** The vault's registered payout scriptPubKey, hex. */\n readonly expectedScriptHex: string,\n /** The scriptPubKey the Payout actually pays, hex. */\n readonly actualScriptHex: string,\n ) {\n super(\n `Payout transaction output ${PAYOUT_DESTINATION_OUTPUT} pays ` +\n `${actualScriptHex}, not the vault's registered payout script ` +\n `${expectedScriptHex}. Refusing to sign a payout to another ` +\n `destination.`,\n );\n this.name = \"PayoutDestinationError\";\n }\n}\n\n/**\n * The Payout to check, and the destination it must pay.\n *\n * @experimental\n */\nexport interface AssertPayoutPaysRegisteredScriptParams {\n /** A Payout signing PSBT, base64, as the graph produced it. */\n payoutPsbtBase64: string;\n /**\n * `depositorPayoutScriptPubKey` as the vault registered it on chain, hex.\n * The vault provider does not choose this value, which is the whole point\n * of comparing against it.\n */\n registeredPayoutScriptPubKey: string;\n}\n\n/**\n * Throws unless the Payout pays the vault's registered payout script.\n *\n * Run this on every Payout PSBT before the wallet is prompted. Both the\n * depositor and the claimer PSBT describe the same transaction, so both must\n * pass; checking only one would leave the other free to differ.\n *\n * @throws {@link PayoutDestinationError} when output 0 pays elsewhere, or a\n * plain error when the layout is not the canonical claimer layout.\n *\n * @experimental\n */\nexport function assertPayoutPaysRegisteredScript(\n params: AssertPayoutPaysRegisteredScriptParams,\n): void {\n let psbt: Psbt;\n try {\n psbt = Psbt.fromBase64(params.payoutPsbtBase64);\n } catch (cause) {\n throw new Error(\"Payout PSBT cannot be parsed.\", { cause });\n }\n\n const { version, locktime, outs } = readPayoutTx(psbt);\n\n // Version and locktime are part of every sighash the depositor is about to\n // produce, so a deviation means signing a transaction the protocol never\n // constructs.\n if (version !== PAYOUT_TX_VERSION || locktime !== PAYOUT_TX_LOCKTIME) {\n throw new Error(\n `Payout transaction has version ${version} and locktime ${locktime}, ` +\n `expected ${PAYOUT_TX_VERSION} and ${PAYOUT_TX_LOCKTIME}.`,\n );\n }\n\n if (outs.length !== NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT) {\n throw new Error(\n `Payout transaction has ${outs.length} output(s), expected exactly ` +\n `${NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT} for a depositor-as-claimer ` +\n `payout.`,\n );\n }\n\n const expected = stripHexPrefix(\n params.registeredPayoutScriptPubKey,\n ).toLowerCase();\n if (expected.length === 0) {\n throw new Error(\n \"registeredPayoutScriptPubKey is empty; the vault's on-chain payout \" +\n \"script is required to check the Payout destination.\",\n );\n }\n const actual = outs[PAYOUT_DESTINATION_OUTPUT].script\n .toString(\"hex\")\n .toLowerCase();\n if (!Buffer.from(actual, \"hex\").equals(Buffer.from(expected, \"hex\"))) {\n throw new PayoutDestinationError(expected, actual);\n }\n\n const anchor = outs[NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT - 1];\n if (anchor.value !== PAYOUT_ANCHOR_DUST_SATS) {\n throw new Error(\n `Payout CPFP anchor value ${anchor.value} sats must equal ` +\n `${PAYOUT_ANCHOR_DUST_SATS} sats.`,\n );\n }\n}\n\n/** The unsigned transaction fields this check reads, from the PSBT. */\nfunction readPayoutTx(psbt: Psbt): {\n version: number;\n locktime: number;\n outs: { script: Buffer; value: number }[];\n} {\n return {\n version: psbt.version,\n locktime: psbt.locktime,\n outs: psbt.txOutputs.map((out) => ({\n script: Buffer.from(out.script),\n value: out.value,\n })),\n };\n}\n","/**\n * Binding between a delegated-claim graph and the vault it is claimed for.\n *\n * Neither the vault provider's graph JSON nor an artifacts file is bound to a\n * vault id by construction: the Rust side only hex-normalizes the `vault_id`\n * field it is handed, so a graph for vault B carrying `vault_id` A passes\n * every other check. The binding that does exist is on chain — the vault id\n * is `keccak256(peginTxid, depositorEthAddress)` — and the Claim transaction\n * spends that PegIn output with its first input.\n *\n * Re-deriving the id from that input is therefore the only check that ties a\n * served graph, or a file the SDK did not write, to the vault the depositor\n * means to claim.\n *\n * @module services/delegated-claim/vaultIdBinding\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { derivePeginVaultId } from \"../../clients/eth/pegin-transaction\";\n\n/**\n * Input of the Claim transaction that spends the PegIn vault UTXO. Fixed by\n * the Rust graph in `btc-vault crates/vault`, not free to choose here.\n */\nconst CLAIM_PEGIN_INPUT = 0;\n\n/**\n * Thrown when a graph does not belong to the vault it is presented for.\n *\n * @experimental\n */\nexport class VaultIdBindingError extends Error {\n constructor(\n readonly expectedVaultId: string,\n readonly derivedVaultId: string,\n readonly peginTxid: string,\n ) {\n super(\n `Transaction graph does not belong to vault ${expectedVaultId}: its ` +\n `Claim spends PegIn ${peginTxid}, which derives vault ` +\n `${derivedVaultId}. Refusing to sign for a graph served for another ` +\n `vault.`,\n );\n this.name = \"VaultIdBindingError\";\n }\n}\n\n/** Display-order txid of the PegIn output the Claim PSBT spends. */\nexport function peginTxidFromClaimPsbt(claimPsbtBase64: string): string {\n let psbt: Psbt;\n try {\n psbt = Psbt.fromBase64(claimPsbtBase64);\n } catch (cause) {\n throw new Error(\"Claim PSBT cannot be parsed.\", { cause });\n }\n const input = psbt.txInputs[CLAIM_PEGIN_INPUT];\n if (!input) {\n throw new Error(\"Claim PSBT carries no PegIn input to bind the vault to.\");\n }\n return displayTxid(input.hash);\n}\n\n/**\n * Display-order txid of the PegIn output a signed Claim transaction spends.\n */\nexport function peginTxidFromClaimTx(claimTx: Transaction): string {\n const input = claimTx.ins[CLAIM_PEGIN_INPUT];\n if (!input) {\n throw new Error(\n \"Artifacts file's claim_tx carries no PegIn input to bind the vault to.\",\n );\n }\n return displayTxid(input.hash);\n}\n\n/**\n * The three values the on-chain vault id is derived from and compared with.\n *\n * @experimental\n */\nexport interface AssertClaimSpendsVaultParams {\n /** Display-order PegIn txid, from the Claim's first input. */\n peginTxid: string;\n /** Depositor's Ethereum address, the second half of the on-chain id. */\n depositorEthAddress: string;\n /** Vault id the graph or file claims to be for. */\n expectedVaultId: string;\n}\n\n/**\n * Throws unless the Claim's PegIn input derives the expected vault id.\n *\n * Experimental: this API can change in a minor release. Pin the SDK\n * version if you build on it.\n *\n * @throws {@link VaultIdBindingError} when the graph belongs to another vault.\n * @experimental\n */\nexport function assertClaimSpendsVault(\n params: AssertClaimSpendsVaultParams,\n): void {\n const derived = normalizeVaultId(\n derivePeginVaultId(params.peginTxid, params.depositorEthAddress),\n );\n const expected = normalizeVaultId(params.expectedVaultId);\n if (derived !== expected) {\n throw new VaultIdBindingError(expected, derived, params.peginTxid);\n }\n}\n\n/** Lowercase, `0x`-prefixed form of a 32-byte vault id. */\nexport function normalizeVaultId(vaultId: string): string {\n const bare = vaultId.startsWith(\"0x\") ? vaultId.slice(2) : vaultId;\n return `0x${bare.toLowerCase()}`;\n}\n\n// Bitcoin stores a prevout hash in internal byte order; a txid is the same\n// bytes reversed. Copy before reversing — the buffer belongs to the parsed\n// transaction.\nfunction displayTxid(internalHash: Uint8Array): string {\n return Buffer.from(internalHash).reverse().toString(\"hex\");\n}\n","/**\n * Watchtower artifact assembly for the delegated claim.\n *\n * Collects every claimer-side signature the `vaultd vp wt` watchtower CLI\n * will need — in one batched wallet interaction — and bundles them with the\n * vault provider's transaction graph into an `artifacts.json`.\n *\n * Do this while the vault provider is still online and the depositor is\n * still at the keyboard. The signatures are Taproot script-path signatures\n * whose sighashes do not cover witness data, so they stay valid however the\n * claim later plays out: the WOTS values, the Groth16 proof, and the hashlock\n * preimages are all witness-only. That is what lets one signing session\n * authorize a claim that runs months later without the depositor present.\n *\n * @module services/delegated-claim/assembleWatchtowerArtifacts\n */\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\n\nimport type { BitcoinWallet } from \"../../../../shared/wallets/interfaces\";\nimport { signPsbtsWithFallback } from \"../../managers/pegin/signPsbtsWithFallback\";\nimport { isAddressFromPublicKey } from \"../../primitives/utils/bitcoin\";\nimport { createTaprootScriptPathSignOptionsForInput } from \"../../utils/signing\";\nimport {\n buildAssertClaimerPsbt,\n buildClaimPsbt,\n buildPayoutClaimerPsbt,\n buildPayoutDepositorPsbt,\n buildWatchtowerArtifacts,\n buildWronglyChallengedPsbts,\n extractTapScriptSig,\n finalizeClaimTx,\n} from \"../../wasm\";\nimport type { WronglyChallengedSigs } from \"../../wasm\";\n\nimport type {\n ClaimerArtifactsSource,\n DelegatedClaimVaultContext,\n} from \"./types\";\nimport { assertChallengerSetMatchesVault } from \"./challengerBinding\";\nimport { assertPayoutPaysRegisteredScript } from \"./payoutBinding\";\nimport {\n assertClaimSpendsVault,\n peginTxidFromClaimPsbt,\n} from \"./vaultIdBinding\";\n\n/**\n * Index of the input each delegated-claim PSBT asks the wallet to sign.\n *\n * Every one of these PSBTs is built by the Rust graph, so these indices\n * mirror `btc-vault crates/vault` and are not free to choose: the Payout's\n * Assert connector is input 1 (input 0 is the PegIn UTXO), and every other\n * signing input is input 0 of its own transaction.\n */\nconst CLAIM_DEPOSITOR_INPUT = 0;\nconst ASSERT_CLAIMER_INPUT = 0;\nconst PAYOUT_CLAIMER_INPUT = 1;\nconst PAYOUT_DEPOSITOR_INPUT = 0;\nconst WRONGLY_CHALLENGED_INPUT = 0;\n\n/**\n * One PSBT in the batch, with the input the wallet must sign.\n */\ninterface PsbtSigningRequest {\n psbtBase64: string;\n inputIndex: number;\n}\n\n/**\n * Everything one delegated-claim signing session needs.\n *\n * @experimental\n */\nexport interface AssembleWatchtowerArtifactsParams {\n /** Wallet holding the depositor key the graph was built with. */\n btcWallet: BitcoinWallet;\n /** Depositor's BTC public key (compressed or x-only hex). */\n depositorPublicKey: string;\n /** Network the depositor's address is derived on, to check the signer. */\n btcNetwork: Network;\n /** Graph and verifying key as the vault provider returned them. */\n source: ClaimerArtifactsSource;\n vault: DelegatedClaimVaultContext;\n /**\n * Per-challenger BaBe sessions as `{\"<pk>\": {\"decryptor_artifacts_hex\":\n * \"...\"}}`, passed through into the file unchanged.\n *\n * Omit it for anything but a fixture. Real sessions run to hundreds of\n * megabytes per challenger, and this argument crosses the WASM boundary as\n * one string — join them into the file downstream instead.\n */\n babeSessionsJson?: string;\n}\n\n/**\n * Signs the delegated-claim set and returns the `artifacts.json` content,\n * ready to write verbatim.\n *\n * Every signature is verified against the graph before the file is produced,\n * so a wallet that signed under the wrong key fails here rather than at claim\n * time, when nothing can be re-signed.\n *\n * Experimental: this API can change in a minor release. Pin the SDK\n * version if you build on it.\n *\n * @throws If the graph is not version 3, if the wallet returns a signature\n * that does not verify, or if the graph's own presignatures are\n * incomplete.\n * @experimental\n */\nexport async function assembleWatchtowerArtifacts(\n params: AssembleWatchtowerArtifactsParams,\n): Promise<string> {\n const { txGraphVersion } = params.vault;\n const graphJson = params.source.txGraphJson;\n\n const [claimPsbt, assertPsbt, payoutClaimerPsbt, wronglyChallengedPsbts] =\n await Promise.all([\n buildClaimPsbt(txGraphVersion, graphJson),\n buildAssertClaimerPsbt(txGraphVersion, graphJson),\n buildPayoutClaimerPsbt(txGraphVersion, graphJson),\n buildWronglyChallengedPsbts(txGraphVersion, graphJson),\n ]);\n\n // The graph arrives from the vault provider and carries no proof that it\n // belongs to this vault. The Claim's first input spends the PegIn output\n // the on-chain vault id is derived from, so that input is the binding.\n assertClaimSpendsVault({\n peginTxid: peginTxidFromClaimPsbt(claimPsbt),\n depositorEthAddress: params.vault.depositorEthAddress,\n expectedVaultId: params.vault.vaultId,\n });\n\n // The depositor Payout signature is always signed fresh. The builder no\n // longer reads a presigned one off the graph, so its PSBT always joins this\n // batch rather than costing a second wallet prompt later.\n const payoutDepositorPsbt = await buildPayoutDepositorPsbt(\n txGraphVersion,\n graphJson,\n );\n\n // Where the money lands. Both PSBTs describe the same Payout transaction,\n // so both are checked: passing one and not the other would leave the\n // unchecked half free to differ.\n for (const psbtBase64 of [payoutClaimerPsbt, payoutDepositorPsbt]) {\n assertPayoutPaysRegisteredScript({\n payoutPsbtBase64: psbtBase64,\n registeredPayoutScriptPubKey: params.vault.registeredPayoutScriptPubKey,\n });\n }\n\n // Who can be answered later. A graph that omits an active challenger\n // produces a file that verifies and still loses the vault at claim time.\n assertChallengerSetMatchesVault({\n graphChallengerPubkeys: Object.keys(wronglyChallengedPsbts),\n depositorBtcPubkey: params.depositorPublicKey,\n vaultProviderBtcPubkey: params.vault.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vault.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys:\n params.vault.universalChallengerBtcPubkeys,\n });\n\n const requests: PsbtSigningRequest[] = [\n { psbtBase64: claimPsbt, inputIndex: CLAIM_DEPOSITOR_INPUT },\n { psbtBase64: assertPsbt, inputIndex: ASSERT_CLAIMER_INPUT },\n { psbtBase64: payoutClaimerPsbt, inputIndex: PAYOUT_CLAIMER_INPUT },\n {\n psbtBase64: payoutDepositorPsbt,\n inputIndex: PAYOUT_DEPOSITOR_INPUT,\n },\n ];\n\n // Challenger order is fixed here and reused when the signatures are mapped\n // back, so a wallet that reorders nothing keeps every signature with the\n // challenger and garbled-circuit index it was computed for.\n const challengerPubkeys = Object.keys(wronglyChallengedPsbts);\n for (const challengerPubkey of challengerPubkeys) {\n for (const psbtBase64 of wronglyChallengedPsbts[challengerPubkey]) {\n requests.push({ psbtBase64, inputIndex: WRONGLY_CHALLENGED_INPUT });\n }\n }\n\n const signatures = await signAndExtract(\n params.btcWallet,\n params.depositorPublicKey,\n params.btcNetwork,\n requests,\n );\n\n let cursor = 0;\n const claimSig = signatures[cursor++];\n const assertClaimerSigHex = signatures[cursor++];\n const payoutClaimerSigHex = signatures[cursor++];\n const depositorPayoutSigHex = signatures[cursor++];\n\n const wronglyChallengedSigs: WronglyChallengedSigs = {};\n for (const challengerPubkey of challengerPubkeys) {\n const count = wronglyChallengedPsbts[challengerPubkey].length;\n wronglyChallengedSigs[challengerPubkey] = signatures.slice(\n cursor,\n cursor + count,\n );\n cursor += count;\n }\n\n const signedClaimTxHex = await finalizeClaimTx(\n txGraphVersion,\n graphJson,\n claimSig,\n );\n\n return buildWatchtowerArtifacts({\n txGraphVersion,\n graphJson,\n signedClaimTxHex,\n assertClaimerSigHex,\n payoutClaimerSigHex,\n wronglyChallengedSigs,\n depositorPayoutSigHex,\n verifyingKeyHex: params.source.verifyingKeyHex,\n claimableEventBlockNumber: params.vault.claimableEventBlockNumber,\n proverCircuitVersion: params.vault.proverCircuitVersion,\n vaultIdHex: params.vault.vaultId,\n babeSessionsJson: params.babeSessionsJson,\n expectedVaultCoreVersion: params.vault.vaultCoreVersion,\n });\n}\n\n/** The 32-byte x-only form of a compressed or x-only public key, lowercase. */\nfunction xOnlyHex(publicKeyHex: string): string {\n const hex = publicKeyHex.replace(/^0x/, \"\").toLowerCase();\n if (hex.length === 66) return hex.slice(2);\n if (hex.length === 64) return hex;\n throw new Error(\n `Public key must be 33-byte compressed or 32-byte x-only hex, got ${hex.length / 2} bytes.`,\n );\n}\n\n/**\n * Returns the wallet's signing address, once both it and the wallet's public\n * key are proved to be the vault's depositor.\n *\n * Both halves matter. The public key is what the graph's scripts commit to;\n * the address is what the sign options name the signer by, and a wallet whose\n * reported address and public key belong to different accounts would\n * otherwise sign the whole batch for the wrong account.\n *\n * @throws When the wallet is on a different account than the vault's\n * depositor, or reports an address that key does not control.\n */\nasync function assertWalletMatchesDepositor(\n btcWallet: BitcoinWallet,\n depositorPublicKey: string,\n btcNetwork: Network,\n): Promise<string> {\n const walletPublicKey = await btcWallet.getPublicKeyHex();\n if (xOnlyHex(walletPublicKey) !== xOnlyHex(depositorPublicKey)) {\n throw new Error(\n \"Connected wallet does not hold the vault's depositor key. \" +\n \"Select the account that made the deposit, then try again.\",\n );\n }\n\n const signerAddress = await btcWallet.getAddress();\n if (!isAddressFromPublicKey(signerAddress, depositorPublicKey, btcNetwork)) {\n throw new Error(\n `Connected wallet reports address \"${signerAddress}\", which is not ` +\n \"derived from the vault's depositor key. Select the account that \" +\n \"made the deposit, then try again.\",\n );\n }\n return signerAddress;\n}\n\n/**\n * Signs every PSBT in one wallet interaction and extracts the 64-byte\n * script-path signatures, in the order the requests were given.\n */\nasync function signAndExtract(\n btcWallet: BitcoinWallet,\n depositorPublicKey: string,\n btcNetwork: Network,\n requests: PsbtSigningRequest[],\n): Promise<string[]> {\n // The sign options name the signer by address, because a wallet derives a\n // key-path address from a public key and then refuses any input that sits\n // elsewhere — every script-path connector. An address names the account, so\n // it must be proved to be this depositor's account first: otherwise a wallet\n // on the wrong account signs every PSBT in the batch and the mismatch\n // only surfaces\n // later, in finalizeClaimTx or verify_bundle.\n const signerAddress = await assertWalletMatchesDepositor(\n btcWallet,\n depositorPublicKey,\n btcNetwork,\n );\n const signedPsbtHexes = await signPsbtsWithFallback(\n btcWallet,\n requests.map((request) => psbtBase64ToHex(request.psbtBase64)),\n requests.map((request) =>\n createTaprootScriptPathSignOptionsForInput(\n depositorPublicKey,\n request.inputIndex,\n signerAddress,\n ),\n ),\n );\n\n return Promise.all(\n signedPsbtHexes.map((signedPsbtHex, i) =>\n extractTapScriptSig(psbtHexToBase64(signedPsbtHex), requests[i].inputIndex),\n ),\n );\n}\n\n// The WASM graph emits and reads PSBTs as base64; wallets take and return\n// them as hex. These re-encode the same bytes rather than parsing the PSBT,\n// so no field is normalized, dropped, or reordered on the way through.\nfunction psbtBase64ToHex(psbtBase64: string): string {\n return Buffer.from(psbtBase64, \"base64\").toString(\"hex\");\n}\n\nfunction psbtHexToBase64(psbtHex: string): string {\n return Buffer.from(psbtHex, \"hex\").toString(\"base64\");\n}\n","/**\n * WOTS keypair derivation for the delegated claim.\n *\n * The watchtower CLI's `start-claim` needs the depositor's secret WOTS hash\n * chains to commit π₁ into the Assert witness. They are never stored: they\n * are re-derived from the wallet on demand, through the same frozen path\n * that produced the on-chain `depositorWotsPkHash` at deposit time.\n *\n * @module services/delegated-claim/deriveClaimerWotsKeypair\n */\n\nimport type { BitcoinWallet } from \"../../../../shared/wallets/interfaces\";\nimport { deriveVaultRoot, expandWotsSeed } from \"../../vault-secrets\";\nimport type { VaultContextInput } from \"../../vault-secrets\";\nimport {\n validateWotsKeypairAgainstGraph,\n wotsKeypairFromSeed,\n} from \"../../wasm\";\n\n/**\n * Inputs for re-deriving the depositor's WOTS keypair at claim time.\n *\n * @experimental\n */\nexport interface DeriveClaimerWotsKeypairParams {\n /** Must implement `deriveContextHash` — the only wallet prompt in the claim. */\n btcWallet: BitcoinWallet;\n /** Same context that produced this vault's secrets at deposit time. */\n vaultContext: VaultContextInput;\n /** HTLC output index of this vault within the Pre-PegIn transaction. */\n htlcVout: number;\n /** JSON-serialized TxGraph the keypair must match. */\n txGraphJson: string;\n /** Graph version. Delegated claim requires 3. */\n txGraphVersion: number;\n /**\n * `depositorWotsPkHash` as the vault records it on chain, `0x`-prefixed.\n *\n * This is the only anchor here the vault provider does not supply. The\n * graph check below compares against VP-served bytes, so it cannot tell a\n * wrong `htlcVout`, a wrong wallet account, or expander drift after a\n * WASM re-pin from a correct derivation.\n */\n expectedWotsPkHash: string;\n}\n\n/**\n * The `wots_keypair.json` content and the hash it commits to.\n *\n * @experimental\n */\nexport interface ClaimerWotsKeypair {\n /**\n * Content of `wots_keypair.json`, ready to write verbatim. Secret and\n * single-use: never log it, never persist it beyond the claim, and never\n * reuse it — reuse across claims leaks the WOTS key.\n */\n wotsKeypairJson: string;\n /** `0x`-prefixed hash of the public keys, matching `depositorWotsPkHash`. */\n pkHash: string;\n}\n\n/**\n * Re-derives the depositor's WOTS keypair and checks it against the vault's\n * on-chain commitment and against the graph.\n *\n * The validation is the point of this function, not a formality: an unbound\n * keypair produces an Assert witness no verifier accepts, and that failure\n * would otherwise surface only after the Claim has been broadcast and the\n * PegIn UTXO is already spent. The on-chain hash is checked first, because\n * it is the one value here the vault provider cannot choose.\n *\n * Experimental: this API can change in a minor release. Pin the SDK\n * version if you build on it.\n *\n * @throws If the derivation does not match the vault's on-chain\n * `depositorWotsPkHash`, or the WOTS public keys the graph's Claim\n * commits to.\n * @experimental\n */\nexport async function deriveClaimerWotsKeypair(\n params: DeriveClaimerWotsKeypairParams,\n): Promise<ClaimerWotsKeypair> {\n const root = await deriveVaultRoot(params.btcWallet, params.vaultContext);\n let wotsSeed: Uint8Array;\n try {\n wotsSeed = await expandWotsSeed(root, params.htlcVout);\n } finally {\n root.fill(0);\n }\n\n let derivation;\n try {\n derivation = await wotsKeypairFromSeed(wotsSeed);\n } finally {\n wotsSeed.fill(0);\n }\n\n assertMatchesOnChainHash(derivation.pk_hash, params.expectedWotsPkHash);\n\n await validateWotsKeypairAgainstGraph(\n params.txGraphVersion,\n derivation.keypair,\n params.txGraphJson,\n );\n\n return {\n wotsKeypairJson: JSON.stringify(derivation.keypair),\n pkHash: derivation.pk_hash,\n };\n}\n\n/**\n * Throws unless the derived public-key hash is the one the vault committed\n * to on chain at deposit time.\n */\nfunction assertMatchesOnChainHash(derived: string, onChain: string): void {\n if (normalizeHash(derived) !== normalizeHash(onChain)) {\n throw new Error(\n `Derived WOTS public-key hash ${normalizeHash(derived)} does not match ` +\n `the vault's on-chain depositorWotsPkHash ${normalizeHash(onChain)}. ` +\n `The wallet, the HTLC output index, or the derivation itself is not ` +\n `the one this vault was created with.`,\n );\n }\n}\n\nfunction normalizeHash(hash: string): string {\n const bare = hash.startsWith(\"0x\") ? hash.slice(2) : hash;\n return `0x${bare.toLowerCase()}`;\n}\n","/**\n * Reading and checking a watchtower `artifacts.json` that already exists.\n *\n * An artifacts file is the depositor's only path to their funds when the\n * vault provider is gone, and nothing checks it between the day it is written\n * and the day it is used. These functions close that gap: they re-verify\n * every signature in the file against its own embedded graph, and confirm the\n * file belongs to the vault it is about to be claimed for.\n *\n * Run them before handing the file to `vaultd vp wt`, not after a claim has\n * already spent the PegIn UTXO.\n *\n * @module services/delegated-claim/readWatchtowerArtifacts\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\n\nimport { verifyWatchtowerArtifacts } from \"../../wasm\";\n\nimport type { WatchtowerArtifactsSummary } from \"./types\";\nimport {\n assertClaimSpendsVault,\n normalizeVaultId,\n peginTxidFromClaimTx,\n} from \"./vaultIdBinding\";\n\n/**\n * Graph version the delegated-claim artifacts format exists for. Vaults on\n * graph v1 and v2 predate it and have no artifacts path at all.\n *\n * @experimental\n */\nexport const DELEGATED_CLAIM_TX_GRAPH_VERSION = 3;\n\n/**\n * Thrown when an artifacts file does not describe the vault being claimed.\n *\n * @experimental\n */\nexport class ArtifactsVaultMismatchError extends Error {\n constructor(\n readonly expectedVaultId: string,\n readonly actualVaultId: string,\n ) {\n super(\n `Artifacts belong to vault ${actualVaultId}, not ${expectedVaultId}. ` +\n `Select the artifacts file saved for this vault.`,\n );\n this.name = \"ArtifactsVaultMismatchError\";\n }\n}\n\n/** Raw shape of the fields this module reads out of the file. */\ninterface ArtifactsFileFields {\n vault_core_version?: unknown;\n vault_id?: unknown;\n claim_tx?: unknown;\n prover_circuit_version?: unknown;\n claimable_event_block_number?: unknown;\n babe_sessions?: unknown;\n}\n\n/**\n * Reads the small, self-describing fields of an artifacts file.\n *\n * This parses the whole JSON, so it is bounded by whatever the file carries\n * in `babe_sessions`. Keep those sessions in their own file: a bundle with\n * real sessions runs to hundreds of megabytes per challenger and cannot be\n * parsed in a browser tab.\n *\n * Experimental: this API can change in a minor release. Pin the SDK\n * version if you build on it.\n *\n * @throws If the file is not JSON, or lacks the fields every artifacts file\n * has.\n * @experimental\n */\nexport function summarizeWatchtowerArtifacts(\n artifactsJson: string,\n): WatchtowerArtifactsSummary {\n let parsed: ArtifactsFileFields;\n try {\n parsed = JSON.parse(artifactsJson) as ArtifactsFileFields;\n } catch (cause) {\n throw new Error(\"Artifacts file is not valid JSON.\", { cause });\n }\n\n const vaultId = requireString(parsed.vault_id, \"vault_id\");\n const claimTx = parseClaimTx(requireString(parsed.claim_tx, \"claim_tx\"));\n const proverCircuitVersion = requireSafeInteger(\n parsed.prover_circuit_version,\n \"prover_circuit_version\",\n );\n // Absent on files written before the field existed; the CLI reads an\n // absent value as 0, which means \"not yet known from chain\". Anything\n // present must be a block number: `JSON.parse` has already rounded\n // anything above 2^53, and a negative or fractional value would otherwise\n // reach `BigInt` and throw without naming the field.\n const claimableEventBlockNumber =\n parsed.claimable_event_block_number === undefined\n ? 0n\n : BigInt(\n requireSafeInteger(\n parsed.claimable_event_block_number,\n \"claimable_event_block_number\",\n ),\n );\n\n return {\n vaultCoreVersion:\n parsed.vault_core_version === undefined\n ? undefined\n : requireSafeInteger(parsed.vault_core_version, \"vault_core_version\"),\n vaultId,\n claimTxid: claimTx.getId(),\n peginTxid: peginTxidFromClaimTx(claimTx),\n proverCircuitVersion,\n claimableEventBlockNumber,\n babeSessionChallengerPubkeys: Object.keys(\n requireRecord(parsed.babe_sessions, \"babe_sessions\"),\n ),\n };\n}\n\n/**\n * The file to check, and the vault it must belong to.\n *\n * @experimental\n */\nexport interface AssertArtifactsUsableParams {\n artifactsJson: string;\n /** Vault the caller intends to claim, `0x`-prefixed or bare hex. */\n expectedVaultId: string;\n /**\n * Depositor's Ethereum address, used with the file's PegIn txid to\n * re-derive the vault id. Without it the only check would be the file's\n * self-declared `vault_id`.\n */\n depositorEthAddress: string;\n /**\n * Graph version to verify under. Defaults to the only version the format\n * exists for. A file that records a different `vault_core_version` is\n * rejected rather than verified under this one.\n */\n txGraphVersion?: number;\n}\n\n/**\n * Verifies an artifacts file and confirms it is the one for this vault.\n *\n * Experimental: this API can change in a minor release. Pin the SDK\n * version if you build on it.\n *\n * @throws {@link ArtifactsVaultMismatchError} when the file names a different\n * vault, {@link VaultIdBindingError} when the graph it carries\n * belongs to another vault whatever the file says, or a verification\n * error when any bundled signature does not hold against that graph.\n * @experimental\n */\nexport async function assertArtifactsUsableForVault(\n params: AssertArtifactsUsableParams,\n): Promise<WatchtowerArtifactsSummary> {\n const summary = summarizeWatchtowerArtifacts(params.artifactsJson);\n\n const expected = normalizeVaultId(params.expectedVaultId);\n const actual = normalizeVaultId(summary.vaultId);\n if (expected !== actual) {\n throw new ArtifactsVaultMismatchError(expected, actual);\n }\n\n // `vault_id` is a field the file declares about itself, and the Rust\n // verification only hex-normalizes it. This re-derives the id from the\n // graph the file actually carries, which catches a file whose graph\n // belongs to another vault however it was produced.\n assertClaimSpendsVault({\n peginTxid: summary.peginTxid,\n depositorEthAddress: params.depositorEthAddress,\n expectedVaultId: expected,\n });\n\n // Verifying a file under a version it does not claim yields, at best, an\n // opaque Rust error. The file states its own version, so compare it.\n const resolved = params.txGraphVersion ?? DELEGATED_CLAIM_TX_GRAPH_VERSION;\n if (\n summary.vaultCoreVersion !== undefined &&\n summary.vaultCoreVersion !== resolved\n ) {\n throw new Error(\n `Artifacts record vault core version ${summary.vaultCoreVersion}, ` +\n `but verification was asked for version ${resolved}.`,\n );\n }\n\n // A file assembled before the Ethereum withdrawal was initiated carries\n // zero here. `vaultd vp wt start-claim` would then ask the prover to prove\n // the wrong block and fail before Assert, so a function named \"usable\"\n // refuses it rather than passing the problem downstream. Nothing in the SDK\n // fills the field in later — reassemble the file instead.\n if (summary.claimableEventBlockNumber === 0n) {\n throw new Error(\n \"Artifacts carry no claimable event block number. They were assembled \" +\n \"before the Ethereum withdrawal was initiated; assemble them again.\",\n );\n }\n\n await verifyWatchtowerArtifacts(resolved, params.artifactsJson);\n\n return summary;\n}\n\nfunction parseClaimTx(txHex: string): Transaction {\n try {\n return Transaction.fromHex(txHex);\n } catch (cause) {\n throw new Error(\"Artifacts file carries an unparseable claim_tx.\", {\n cause,\n });\n }\n}\n\nfunction requireString(value: unknown, field: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(`Artifacts file is missing a usable \"${field}\".`);\n }\n return value;\n}\n\n/**\n * A count or a block height: never negative, never fractional, and inside\n * the range `JSON.parse` can represent without silently rounding.\n */\nfunction requireSafeInteger(value: unknown, field: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`Artifacts file is missing a usable \"${field}\".`);\n }\n return value;\n}\n\n/**\n * A JSON object, not a string or an array — `Object.keys` on either reports\n * index positions, which would pass as challenger public keys.\n */\nfunction requireRecord(\n value: unknown,\n field: string,\n): Record<string, unknown> {\n if (value === undefined) return {};\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`Artifacts file is missing a usable \"${field}\".`);\n }\n return value as Record<string, unknown>;\n}\n","/**\n * Ethereum confirmation-depth gate for a peg-in registration.\n *\n * Between `submitPeginRequestBatch` landing on Ethereum and the Pre-PegIn\n * BTC transaction being broadcast there is a reorg window. If the block\n * carrying the registration is orphaned *after* the BTC broadcast, the vault\n * record is gone from the chain while the depositor's BTC is already locked\n * in the HTLC — the deposit is stuck, recoverable only via the HTLC refund\n * leaf after `T_refund` (~3 days). This module closes that window by proving\n * the registration is buried before any BTC is committed.\n *\n * Depth is measured from `BTCVaultBasicInfo.createdAt`, which is the Ethereum\n * **block number** the registration was mined at (see\n * {@link isActivationDeadlinePassedOnChain}, which mirrors the contract's own\n * `block.number > createdAt + pegInActivationTimeout` check). Reading it needs\n * no transaction hash, so the same primitive serves the inline deposit flow\n * and the cross-device resume flow, and every poll re-reads live contract\n * state — an orphaned registration reads back as `depositor === zeroAddress`.\n *\n * Deliberately NOT built on viem's `waitForTransactionReceipt({confirmations})`.\n * That helper fetches the receipt once and thereafter only does block-number\n * arithmetic against the cached copy; it never re-checks that the receipt's\n * block is still canonical, so it resolves happily for a transaction that has\n * been reorged out. It buys a delay, not a finality guarantee.\n *\n * @module services/deposit\n */\n\nimport { type Hex, zeroAddress } from \"viem\";\n\nimport type { VaultBasicInfo, VaultRegistryReader } from \"../../clients/eth/types\";\n\n/**\n * Ethereum block confirmations required before the Pre-PegIn BTC transaction\n * may be broadcast.\n *\n * 8 exceeds the deepest reorg ever observed on Ethereum (7, pre-merge, caused\n * by a client bug), and costs ~1.6 min at 12s slots. Deliberately not the\n * `safe` block tag: a full epoch (~12.8 min) was rejected as too slow for the\n * benefit. This is a liveness guard against an orphaned registration, not a\n * theft mitigation — every Pre-PegIn HTLC spend path requires the depositor's\n * own BTC key regardless.\n */\nexport const PEGIN_ETH_CONFIRMATIONS = 8;\n\n/** Poll cadence — half an Ethereum slot, so a new block is never missed by long. */\nconst REGISTRATION_DEPTH_POLL_INTERVAL_MS = 6_000;\n\n/**\n * Overall budget for reaching depth. Nominally ~96s (8 × 12s); the rest\n * absorbs missed slots and RPC lag. Generous on purpose: timing out discards\n * a valid registration that only needed a few more seconds, and the failure is\n * recoverable through the resume flow, so over-waiting is cheaper than\n * under-waiting.\n */\nconst REGISTRATION_DEPTH_TIMEOUT_MS = 10 * 60_000;\n\n/**\n * Consecutive absent reads tolerated before concluding the registration is\n * genuinely not on-chain. At the 6s cadence this is ~60s — five Ethereum\n * blocks — which is what absorbs a load-balanced pool member still serving\n * pre-block state moments after the receipt. Such a node answers HTTP 200\n * with a validly encoded zero struct, so no transport-level retry can see it;\n * only re-reading later can. Expressed in polls rather than milliseconds so\n * the tolerance scales with the cadence.\n */\nconst REGISTRATION_ABSENT_GRACE_POLLS = 10;\n\n/**\n * The vault is not registered on-chain, and stayed that way past the grace\n * window — long enough that a lagging backend has been ruled out. Retrying\n * will not help.\n */\nexport class PeginRegistrationMissingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PeginRegistrationMissingError\";\n }\n}\n\n/** The registration did not reach the required depth within the budget. */\nexport class PeginRegistrationNotFinalError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PeginRegistrationNotFinalError\";\n }\n}\n\n// `instanceof` alone fails across module boundaries (duplicate SDK copies,\n// test mocks). Fall back to the name field, as the other deposit-service\n// errors in this directory do.\nexport function isPeginRegistrationMissingError(\n err: unknown,\n): err is PeginRegistrationMissingError {\n return (\n err instanceof PeginRegistrationMissingError ||\n (err instanceof Error && err.name === \"PeginRegistrationMissingError\")\n );\n}\n\nexport function isPeginRegistrationNotFinalError(\n err: unknown,\n): err is PeginRegistrationNotFinalError {\n return (\n err instanceof PeginRegistrationNotFinalError ||\n (err instanceof Error && err.name === \"PeginRegistrationNotFinalError\")\n );\n}\n\nexport interface RegistrationDepthParams {\n /** Current chain tip block number. */\n currentBlock: bigint;\n /** Block number the registration was mined at (`VaultBasicInfo.createdAt`). */\n createdAtBlock: bigint;\n}\n\n/**\n * Confirmations accrued by a registration: the mining block counts as the\n * first confirmation, so `tip === createdAt` is 1.\n *\n * Clamped at 0. A reorg between the tip read and the vault read can surface a\n * `createdAt` above the tip already in hand; a negative depth must never\n * propagate into a comparison.\n */\nexport function computeRegistrationConfirmations(\n params: RegistrationDepthParams,\n): number {\n const { currentBlock, createdAtBlock } = params;\n const depth = currentBlock - createdAtBlock + 1n;\n return depth < 0n ? 0 : Number(depth);\n}\n\nexport interface RegistrationDepthProgress {\n /** Shallowest depth across every vault being waited on. */\n confirmations: number;\n required: number;\n}\n\nexport interface WaitForPeginRegistrationDepthParams {\n vaultRegistryReader: VaultRegistryReader;\n /**\n * Chain-tip reader. A thunk rather than a `PublicClient` so this module has\n * no viem-client dependency and stays testable with two plain fakes — the\n * same shape `verifyRegisteredVaultVersions` uses for its reader.\n */\n getBlockNumber: () => Promise<bigint>;\n /** Vaults registered by the same transaction; the shallowest one gates. */\n vaultIds: readonly Hex[];\n required?: number;\n pollIntervalMs?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n onProgress?: (progress: RegistrationDepthProgress) => void;\n}\n\nexport interface PeginRegistrationDepthResult {\n confirmations: number;\n /**\n * The final observation for the shallowest vault. Callers that gated on\n * `status` before the wait should re-assert it against this — the wait can\n * span minutes, and a vault can leave PENDING in that time.\n */\n basicInfo: VaultBasicInfo;\n}\n\n/**\n * Poll until every vault's registration is at least `required` blocks deep.\n *\n * A read that comes back empty is treated as \"not visible yet\", not as\n * \"absent\": both callers reach this having already proven the registration\n * exists, so an empty read means a lagging RPC backend or a reorg, and both\n * resolve on their own.\n *\n * @throws {PeginRegistrationMissingError} if no vault has ever been observed and the grace window is spent.\n * @throws {PeginRegistrationNotFinalError} on timeout.\n * @throws if aborted.\n */\nexport async function waitForPeginRegistrationDepth(\n params: WaitForPeginRegistrationDepthParams,\n): Promise<PeginRegistrationDepthResult> {\n const {\n vaultRegistryReader,\n getBlockNumber,\n vaultIds,\n required = PEGIN_ETH_CONFIRMATIONS,\n pollIntervalMs = REGISTRATION_DEPTH_POLL_INTERVAL_MS,\n timeoutMs = REGISTRATION_DEPTH_TIMEOUT_MS,\n signal,\n onProgress,\n } = params;\n\n if (vaultIds.length === 0) {\n throw new Error(\n \"waitForPeginRegistrationDepth requires at least one vault ID\",\n );\n }\n\n const startTime = Date.now();\n // Once any poll has seen the registration, a later disappearance is a reorg,\n // and re-inclusion is the expected outcome — that case polls to the full\n // budget. Before the first sighting, absence is far more likely to be a\n // lagging backend than a missing registration, so it gets a grace window.\n let hasObservedRegistration = false;\n let absentPolls = 0;\n let lastError: unknown;\n\n while (true) {\n if (signal?.aborted) {\n throw new Error(\n `Aborted while waiting for peg-in registration depth (${vaultIds.length} vault(s))`,\n );\n }\n\n if (Date.now() - startTime >= timeoutMs) {\n // Deliberately avoids the word \"broadcast\". Callers classify this by\n // type, but any surface that stringifies it would otherwise land in the\n // message-matching \"broadcast failed\" bucket and tell the user the exact\n // opposite of what happened.\n throw new PeginRegistrationNotFinalError(\n `Peg-in registration did not reach ${required} Ethereum confirmations within ${timeoutMs}ms. ` +\n `The registration transaction was submitted but is not yet final, so the Pre-PegIn ` +\n `Bitcoin transaction was never sent and no funds are at risk. ` +\n `Resume this deposit from the dashboard once the network settles.` +\n (lastError instanceof Error ? ` Last read error: ${lastError.message}` : \"\"),\n );\n }\n\n try {\n // Tip FIRST, vault state SECOND. Both read `latest`, but they are two\n // round-trips: reading the tip first means it can only be at or behind\n // the state the vault read observes, so the computed depth is an\n // under-estimate. Reversing the order could over-count by a block and\n // release the broadcast at 7 confirmations.\n //\n // That ordering only guarantees the under-count when both land on the\n // same backend. Against a load-balanced pool the tip can come from an\n // ahead node and the vault from a behind one — the same root cause as\n // the empty-read handling below, and why this is a best-effort skew\n // guard rather than a proof.\n const currentBlock = await getBlockNumber();\n const infos = await Promise.all(\n vaultIds.map((vaultId) => vaultRegistryReader.getVaultBasicInfo(vaultId)),\n );\n\n // A zero record is what an orphaned (or never-included) registration\n // reads back as. `createdAt === 0n` is checked alongside the zero\n // depositor because a partially-decoded record must never be treated as\n // block 0 — that would compute as infinitely deep and pass the gate.\n const missingIndex = infos.findIndex(\n (info) => info.depositor === zeroAddress || info.createdAt === 0n,\n );\n\n if (missingIndex !== -1) {\n absentPolls += 1;\n\n // Never seen it, and the grace window is spent: a lagging backend has\n // been ruled out, so the registration really is not there. Only ever\n // reachable for a caller that supplied a vault ID which was never\n // registered — both in-repo callers arrive here having already proven\n // the vault visible (a receipt inline, a throwing `getVaultFromChain`\n // on resume).\n if (\n !hasObservedRegistration &&\n absentPolls > REGISTRATION_ABSENT_GRACE_POLLS\n ) {\n throw new PeginRegistrationMissingError(\n `Vault ${vaultIds[missingIndex]} is still not visible on-chain after ` +\n `${absentPolls} reads — the registration does not exist.`,\n );\n }\n\n // Otherwise keep polling. Before the first sighting this is almost\n // always an RPC backend that has not caught up to the registration\n // block; after one, it is the reorg this gate exists for, where\n // re-inclusion within a block or two is the expected outcome. Both\n // resolve themselves, and both would be made worse by aborting a\n // deposit that is about to be fine.\n console.warn(\n `Peg-in registration for vault ${vaultIds[missingIndex]} is not visible in chain state ` +\n `at block ${currentBlock} — a lagging RPC backend or an Ethereum reorg. Still polling.`,\n );\n onProgress?.({ confirmations: 0, required });\n } else {\n hasObservedRegistration = true;\n absentPolls = 0;\n lastError = undefined;\n\n // The shallowest vault gates the batch: they share one registration\n // transaction, so in practice the depths are equal, but taking the\n // minimum is the fail-safe reading if they ever diverge.\n let shallowest = infos[0];\n let shallowestDepth = computeRegistrationConfirmations({\n currentBlock,\n createdAtBlock: infos[0].createdAt,\n });\n for (const info of infos.slice(1)) {\n const depth = computeRegistrationConfirmations({\n currentBlock,\n createdAtBlock: info.createdAt,\n });\n if (depth < shallowestDepth) {\n shallowestDepth = depth;\n shallowest = info;\n }\n }\n\n onProgress?.({ confirmations: shallowestDepth, required });\n\n if (shallowestDepth >= required) {\n return { confirmations: shallowestDepth, basicInfo: shallowest };\n }\n }\n } catch (error) {\n if (isPeginRegistrationMissingError(error)) {\n throw error;\n }\n // Transient RPC failure. Retry on the next tick; the outer timeout owns\n // the overall budget, so one blip must not consume it.\n console.warn(\n `Registration-depth read failed (retrying in ${pollIntervalMs}ms): ` +\n (error instanceof Error ? error.message : String(error)),\n );\n lastError = error;\n }\n\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(\n new Error(\n `Aborted while waiting for peg-in registration depth (${vaultIds.length} vault(s))`,\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 * Deterministic fingerprint over the canonical transaction set of a\n * depositor-as-claimer graph.\n *\n * `btc-vault/docs/specifications/pegin.md` §5.9 makes this the depositor's binding\n * between the two moments where it gives up leverage:\n *\n * - **Presign** — before signing the VP's PSBTs, fingerprint the transaction\n * set the VP just supplied and persist it.\n * - **Activation** — before revealing the HTLC secret, fingerprint the graph\n * the VP returns and require an exact match.\n *\n * Without this, a VP can serve one graph to sign and a different one to\n * activate against; every check in `assertBundleBoundToVault` compares the\n * bundle only against public values it also controls.\n *\n * The two moments carry the same transactions in different encodings — presign\n * hands back raw consensus `tx_hex`, activation a serde-serialized\n * `bitcoin::Transaction`. Both sides decode strictly and re-serialize through\n * `bitcoinjs-lib`, so each hashed part is exactly one canonical transaction.\n * That matters because the layout below has no length prefixes: it matches\n * `canonical_tx_set_fingerprint` in `btc-vault`\n * (`crates/depositor-cli/src/recovery_graph.rs`), which relies on the same\n * strict decode. Hashing undecoded bytes would let a VP shift bytes between\n * parts and reach the same digest with a different graph.\n *\n * Note this commits to the transaction set only. `gc_wots_keys`, the verifying\n * key, and the typed connector metadata are deliberately outside it — the spec\n * binds those at activation by other means.\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, concatBytes, hexToBytes } from \"@noble/hashes/utils.js\";\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { PEGIN_DEPOSITOR_CLAIM_VOUT } from \"../../primitives/psbt/depositorClaim\";\nimport {\n canonicalizeBtcPubkey,\n stripHexPrefix,\n} from \"../../primitives/utils/bitcoin\";\n\n/** Lowercase hex, whole bytes, no prefix: the only form serde emits. */\nconst SERDE_HEX_RE = /^(?:[0-9a-f]{2})*$/;\n/** An x-only pubkey or a SHA-256 digest in serde hex. */\nconst BYTES32_SERDE_HEX_RE = /^[0-9a-f]{64}$/;\n/** `bitcoin::OutPoint` in serde: display-order txid, `:`, decimal vout. */\nconst OUTPOINT_RE = /^([0-9a-f]{64}):(0|[1-9][0-9]*)$/;\n\nconst INT32_MIN = -0x8000_0000;\nconst INT32_MAX = 0x7fff_ffff;\nconst UINT32_MAX = 0xffff_ffff;\n\n/** A depositor Claim is always version 2 (`check_depositor_claim_shape`). */\nconst DEPOSITOR_CLAIM_TX_VERSION = 2;\n/** A depositor Claim pays the assert connector and a CPFP anchor, nothing else. */\nconst DEPOSITOR_CLAIM_OUTPUT_COUNT = 2;\n/** Every Assert spends the Claim's connector output. */\nconst CLAIM_ASSERT_VOUT = 0;\n\n/** One challenger's contribution to the fingerprint. */\nexport interface ChallengerFingerprintPart {\n /** Challenger x-only pubkey, lowercase hex, no prefix. */\n pubkey: string;\n /** The challenger's NoPayout transaction, consensus-serialized. */\n nopayoutTx: Uint8Array;\n /** Per-GC output label hashes, lowercase hex, in the order the graph lists them. */\n outputLabelHashes: string[];\n}\n\n/** The four transactions every depositor-as-claimer graph carries. */\nexport interface CanonicalTxSet {\n peginTx: Uint8Array;\n claimTx: Uint8Array;\n assertTx: Uint8Array;\n payoutTx: Uint8Array;\n challengers: ChallengerFingerprintPart[];\n}\n\nexport class GraphFingerprintError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GraphFingerprintError\";\n }\n}\n\nfunction field(node: Record<string, unknown>, name: string, path: string) {\n const value = node[name];\n if (value === undefined) {\n throw new GraphFingerprintError(`Graph tx ${path} is missing \"${name}\"`);\n }\n return value;\n}\n\nfunction asArray(value: unknown, path: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new GraphFingerprintError(`Graph tx ${path} is not an array`);\n }\n return value;\n}\n\nfunction asRecord(value: unknown, path: string): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new GraphFingerprintError(`Graph tx ${path} is not an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction asInt(value: unknown, path: string, min: number, max: number): number {\n if (\n typeof value !== \"number\" ||\n !Number.isSafeInteger(value) ||\n value < min ||\n value > max\n ) {\n throw new GraphFingerprintError(\n `Graph tx ${path} is not an integer in [${min}, ${max}]`,\n );\n }\n return value;\n}\n\nfunction asSerdeHex(value: unknown, path: string): Buffer {\n if (typeof value !== \"string\" || !SERDE_HEX_RE.test(value)) {\n throw new GraphFingerprintError(\n `Graph tx ${path} is not lowercase hex without a prefix`,\n );\n }\n return Buffer.from(value, \"hex\");\n}\n\nfunction asSerdeBytes32(value: unknown, path: string): string {\n if (typeof value !== \"string\" || !BYTES32_SERDE_HEX_RE.test(value)) {\n throw new GraphFingerprintError(\n `Graph ${path} is not 32 bytes of lowercase hex`,\n );\n }\n return value;\n}\n\n/**\n * Re-encode one serde-serialized `bitcoin::Transaction` from a `tx_graph_json`\n * node into consensus bytes.\n *\n * Every field is required and range-checked: a value that serde would reject\n * or read differently must not reach the digest, or the depositor could match\n * a graph that the recovery tooling cannot load. `previous_output` arrives in\n * display byte order, so the txid is reversed back to wire order.\n */\nexport function serializeGraphTx(txNode: unknown, path: string): Uint8Array {\n const node = asRecord(txNode, path);\n const tx = new Transaction();\n tx.version = asInt(\n field(node, \"version\", path),\n `${path}.version`,\n INT32_MIN,\n INT32_MAX,\n );\n tx.locktime = asInt(\n field(node, \"lock_time\", path),\n `${path}.lock_time`,\n 0,\n UINT32_MAX,\n );\n\n asArray(field(node, \"input\", path), `${path}.input`).forEach((input, i) => {\n const at = `${path}.input[${i}]`;\n const inputNode = asRecord(input, at);\n const outpoint = field(inputNode, \"previous_output\", at);\n const match = typeof outpoint === \"string\" && OUTPOINT_RE.exec(outpoint);\n if (!match) {\n throw new GraphFingerprintError(\n `Graph tx ${at}.previous_output is not \"<txid>:<vout>\"`,\n );\n }\n const vout = asInt(Number(match[2]), `${at}.previous_output vout`, 0, UINT32_MAX);\n tx.addInput(\n Buffer.from(match[1], \"hex\").reverse(),\n vout,\n asInt(field(inputNode, \"sequence\", at), `${at}.sequence`, 0, UINT32_MAX),\n asSerdeHex(field(inputNode, \"script_sig\", at), `${at}.script_sig`),\n );\n tx.ins[i].witness = asArray(\n field(inputNode, \"witness\", at),\n `${at}.witness`,\n ).map((item, j) => asSerdeHex(item, `${at}.witness[${j}]`));\n });\n\n asArray(field(node, \"output\", path), `${path}.output`).forEach((output, i) => {\n const at = `${path}.output[${i}]`;\n const outputNode = asRecord(output, at);\n tx.addOutput(\n asSerdeHex(field(outputNode, \"script_pubkey\", at), `${at}.script_pubkey`),\n asInt(field(outputNode, \"value\", at), `${at}.value`, 0, Number.MAX_SAFE_INTEGER),\n );\n });\n\n return new Uint8Array(tx.toBuffer());\n}\n\n/**\n * Decode one presign `tx_hex` strictly and return its canonical bytes.\n *\n * Rejects trailing bytes and any encoding that does not round-trip, so the\n * part hashed below is exactly one transaction.\n */\nfunction decodePresignTx(txHex: string, path: string): Transaction {\n const hex = stripHexPrefix(txHex).toLowerCase();\n let tx: Transaction;\n try {\n tx = Transaction.fromHex(hex);\n } catch (err) {\n throw new GraphFingerprintError(\n `Presign ${path} is not one transaction: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (tx.toHex() !== hex) {\n throw new GraphFingerprintError(\n `Presign ${path} is not a canonical transaction encoding`,\n );\n }\n return tx;\n}\n\ninterface PresignClaimAssertTransactions {\n peginTx: Transaction;\n claimTx: Transaction;\n assertTx: Transaction;\n}\n\nexport interface AssertPresignClaimAssertLinkageParams {\n /** Authoritative PegIn transaction built and signed by the depositor. */\n peginTxHex: string;\n /** VP-supplied Claim transaction. */\n claimTxHex: string;\n /** VP-supplied Assert transaction. */\n assertTxHex: string;\n /** Response path included in actionable validation errors. */\n path: string;\n}\n\nfunction readInputOutpoint(\n tx: Transaction,\n inputIndex: number,\n): { txid: string; vout: number } | undefined {\n const input = tx.ins[inputIndex];\n if (!input) {\n return undefined;\n }\n return {\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n };\n}\n\nfunction assertClaimHasAssertOutput(claimTx: Transaction, path: string): void {\n if (!claimTx.outs[CLAIM_ASSERT_VOUT]) {\n throw new GraphFingerprintError(\n `Presign ${path}.claim_tx must have output ${CLAIM_ASSERT_VOUT}`,\n );\n }\n}\n\nfunction assertClaimSpendsPegin(\n claimTx: Transaction,\n peginTxid: string,\n path: string,\n): void {\n if (claimTx.ins.length !== 1) {\n throw new GraphFingerprintError(\n `Presign ${path}.claim_tx must have exactly one input, got ${claimTx.ins.length}`,\n );\n }\n\n assertClaimHasAssertOutput(claimTx, path);\n\n const spent = readInputOutpoint(claimTx, 0);\n if (spent?.txid !== peginTxid || spent.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n const actual = spent ? `${spent.txid}:${spent.vout}` : \"no input\";\n throw new GraphFingerprintError(\n `Presign ${path}.claim_tx must spend ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}, got ${actual}`,\n );\n }\n}\n\nfunction assertAssertSpendsClaim(\n assertTx: Transaction,\n claimTxid: string,\n path: string,\n): void {\n const spent = readInputOutpoint(assertTx, 0);\n if (spent?.txid !== claimTxid || spent.vout !== CLAIM_ASSERT_VOUT) {\n const actual = spent ? `${spent.txid}:${spent.vout}` : \"no input\";\n throw new GraphFingerprintError(\n `Presign ${path}.assert_tx input 0 must spend ${claimTxid}:${CLAIM_ASSERT_VOUT}, got ${actual}`,\n );\n }\n}\n\nfunction decodePresignClaimAssertTransactions(\n args: AssertPresignClaimAssertLinkageParams,\n): PresignClaimAssertTransactions {\n const peginTx = decodePresignTx(args.peginTxHex, `${args.path}.pegin_tx`);\n const claimTx = decodePresignTx(args.claimTxHex, `${args.path}.claim_tx`);\n const assertTx = decodePresignTx(args.assertTxHex, `${args.path}.assert_tx`);\n\n return { peginTx, claimTx, assertTx };\n}\n\nexport interface AssertPresignAssertSpendsClaimParams {\n /** VP-supplied Claim transaction. */\n claimTxHex: string;\n /** VP-supplied Assert transaction. */\n assertTxHex: string;\n /** Response path included in actionable validation errors. */\n path: string;\n}\n\n/**\n * Bind a VP/VK claimer's Assert to its own Claim: Assert input 0 must spend\n * Claim output 0.\n *\n * A claimer funds its Claim from its own wallet (`ClaimTx::from_transaction`\n * in `btc-vault` tolerates that freedom), so the Claim's inputs are not\n * checked here. Only the depositor-as-claimer Claim spends PegIn output 1;\n * {@link assertPresignClaimAssertLinkage} checks that one.\n */\nexport function assertPresignAssertSpendsClaim(\n args: AssertPresignAssertSpendsClaimParams,\n): void {\n const claimTx = decodePresignTx(args.claimTxHex, `${args.path}.claim_tx`);\n const assertTx = decodePresignTx(args.assertTxHex, `${args.path}.assert_tx`);\n assertClaimHasAssertOutput(claimTx, args.path);\n assertAssertSpendsClaim(assertTx, claimTx.getId(), args.path);\n}\n\n/**\n * Bind the depositor-as-claimer Claim/Assert pair to the depositor's\n * authoritative PegIn.\n *\n * The Claim must have exactly one input spending PegIn output 1, and Assert\n * input 0 must spend Claim output 0. Call this before any wallet signing\n * prompt: otherwise the VP can obtain signatures for an unfundable graph.\n * Do not use it for VP/VK claimer entries: their Claims are wallet-funded\n * (see {@link assertPresignAssertSpendsClaim}).\n */\nexport function assertPresignClaimAssertLinkage(\n args: AssertPresignClaimAssertLinkageParams,\n): void {\n const { peginTx, claimTx, assertTx } =\n decodePresignClaimAssertTransactions(args);\n assertClaimSpendsPegin(claimTx, peginTx.getId(), args.path);\n assertAssertSpendsClaim(assertTx, claimTx.getId(), args.path);\n}\n\n/**\n * Mirror `check_depositor_claim_shape` in `btc-vault`\n * (`crates/vault/src/transactions/claim.rs`): one input spending the\n * depositor-claim output of the depositor's own PegIn, an empty witness,\n * version 2, and exactly two outputs.\n *\n * The reference also rebuilds the Claim outputs from canonical params\n * (`ClaimTx::from_transaction`). That needs a WASM binding the SDK does not\n * have yet, so output contents are not checked here.\n */\nfunction assertDepositorClaimShape(claim: Transaction, peginTxid: string): void {\n const [input, ...extra] = claim.ins;\n if (!input || extra.length > 0) {\n throw new GraphFingerprintError(\n `Presign claim_tx must have exactly one input, got ${claim.ins.length}`,\n );\n }\n const spentTxid = Buffer.from(input.hash).reverse().toString(\"hex\");\n if (spentTxid !== peginTxid || input.index !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new GraphFingerprintError(\n `Presign claim_tx must spend ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}, ` +\n `got ${spentTxid}:${input.index}`,\n );\n }\n if (claim.version !== DEPOSITOR_CLAIM_TX_VERSION) {\n throw new GraphFingerprintError(\n `Presign claim_tx version must be ${DEPOSITOR_CLAIM_TX_VERSION}, got ${claim.version}`,\n );\n }\n if (input.witness.length > 0) {\n throw new GraphFingerprintError(\n `Presign claim_tx input must have an empty witness, got ${input.witness.length} item(s)`,\n );\n }\n if (claim.outs.length !== DEPOSITOR_CLAIM_OUTPUT_COUNT) {\n throw new GraphFingerprintError(\n `Presign claim_tx must have exactly ${DEPOSITOR_CLAIM_OUTPUT_COUNT} outputs, got ${claim.outs.length}`,\n );\n }\n}\n\n/**\n * Hash the canonical transaction set.\n *\n * Challengers are sorted by pubkey so the digest does not depend on map or\n * response ordering, which neither side controls consistently. Two entries\n * for one key are rejected: with the order between them undefined, the digest\n * would follow whichever order the VP chose.\n */\nexport function canonicalTxSetFingerprint(set: CanonicalTxSet): string {\n const sorted = [...set.challengers].sort((a, b) =>\n a.pubkey < b.pubkey ? -1 : a.pubkey > b.pubkey ? 1 : 0,\n );\n const parts = [set.peginTx, set.claimTx, set.assertTx, set.payoutTx];\n sorted.forEach((challenger, i) => {\n const pubkey = asSerdeBytes32(challenger.pubkey, \"challenger pubkey\");\n if (i > 0 && sorted[i - 1].pubkey === pubkey) {\n throw new GraphFingerprintError(`Graph lists challenger ${pubkey} twice`);\n }\n parts.push(hexToBytes(pubkey), challenger.nopayoutTx);\n for (const hash of challenger.outputLabelHashes) {\n parts.push(hexToBytes(asSerdeBytes32(hash, \"output_label_hashes entry\")));\n }\n });\n\n return bytesToHex(sha256(concatBytes(...parts)));\n}\n\n/**\n * Validate the transaction set a VP supplied at presign and fingerprint it.\n *\n * `peginTxHex` comes from the depositor's own signing context, not the\n * response — the presign payload carries no PegIn transaction, and taking it\n * from the VP would let the VP choose both sides of the comparison. It must\n * hash to `peginTxid`, and the Claim must have the depositor-claim shape,\n * as in `validate_presign_response` in `btc-vault`.\n */\nexport function fingerprintPresignTxSet(args: {\n peginTxid: string;\n peginTxHex: string;\n claimTxHex: string;\n assertTxHex: string;\n payoutTxHex: string;\n challengers: {\n challenger_pubkey: string;\n nopayout_tx: { tx_hex: string };\n output_label_hashes: string[];\n }[];\n}): string {\n const peginTxid = stripHexPrefix(args.peginTxid).toLowerCase();\n const { peginTx, claimTx, assertTx } =\n decodePresignClaimAssertTransactions({\n peginTxHex: args.peginTxHex,\n claimTxHex: args.claimTxHex,\n assertTxHex: args.assertTxHex,\n path: \"depositor_graph\",\n });\n if (peginTx.getId() !== peginTxid) {\n throw new GraphFingerprintError(\n `Presign pegin_tx hashes to ${peginTx.getId()}, expected ${peginTxid}`,\n );\n }\n assertDepositorClaimShape(claimTx, peginTxid);\n assertAssertSpendsClaim(assertTx, claimTx.getId(), \"depositor_graph\");\n\n const bytes = (tx: Transaction) => new Uint8Array(tx.toBuffer());\n return canonicalTxSetFingerprint({\n peginTx: bytes(peginTx),\n claimTx: bytes(claimTx),\n assertTx: bytes(assertTx),\n payoutTx: bytes(decodePresignTx(args.payoutTxHex, \"payout_tx\")),\n challengers: args.challengers.map((c) => ({\n pubkey: canonicalizeBtcPubkey(c.challenger_pubkey),\n nopayoutTx: bytes(decodePresignTx(c.nopayout_tx.tx_hex, \"nopayout_tx\")),\n outputLabelHashes: c.output_label_hashes.map((hash) =>\n stripHexPrefix(hash).toLowerCase(),\n ),\n })),\n });\n}\n\n/**\n * Fingerprint the graph a VP returned at activation, parsed from\n * `tx_graph_json`.\n */\nexport function fingerprintReturnedGraph(\n graph: Record<string, unknown>,\n): string {\n const tx = (key: string) =>\n serializeGraphTx(asRecord(field(graph, key, \"graph\"), key).tx, key);\n\n const subgraphs = asRecord(\n field(graph, \"challenger_subgraphs\", \"graph\"),\n \"challenger_subgraphs\",\n );\n\n return canonicalTxSetFingerprint({\n peginTx: tx(\"pegin_tx\"),\n claimTx: tx(\"claim_tx\"),\n assertTx: tx(\"assert_tx\"),\n payoutTx: tx(\"payout_tx\"),\n challengers: Object.entries(subgraphs).map(([pubkey, value]) => {\n const at = `challenger_subgraphs[${pubkey}]`;\n const sub = asRecord(value, at);\n return {\n pubkey,\n nopayoutTx: serializeGraphTx(\n asRecord(field(sub, \"nopayout_tx\", at), `${at}.nopayout_tx`).tx,\n `${at}.nopayout_tx`,\n ),\n outputLabelHashes: asArray(\n field(sub, \"output_label_hashes\", at),\n `${at}.output_label_hashes`,\n ).map((h, i) =>\n asSerdeBytes32(h, `${at}.output_label_hashes[${i}]`),\n ),\n };\n }),\n });\n}\n\n/**\n * The challenger roster a returned graph declares in `challenger_pubkeys`,\n * as `local ∪ universal`. A key in both sets is rejected: the roles are\n * disjoint, and a repeat would hide a missing key from a size comparison.\n */\nfunction declaredChallengers(graph: Record<string, unknown>): Set<string> {\n const pubkeys = asRecord(\n field(graph, \"challenger_pubkeys\", \"graph\"),\n \"challenger_pubkeys\",\n );\n const declared = new Set<string>();\n for (const role of [\"local\", \"universal\"] as const) {\n asArray(\n field(pubkeys, role, \"challenger_pubkeys\"),\n `challenger_pubkeys.${role}`,\n ).forEach((key, i) => {\n const pubkey = asSerdeBytes32(key, `challenger_pubkeys.${role}[${i}]`);\n if (declared.has(pubkey)) {\n throw new GraphFingerprintError(\n `Graph declares challenger ${pubkey} more than once`,\n );\n }\n declared.add(pubkey);\n });\n }\n return declared;\n}\n\n/**\n * Check (a) of `pegin.md` §5.9: throw unless the graph a VP returned at\n * activation is the one the depositor fingerprinted at presign.\n *\n * Call this before revealing the HTLC secret, with the value that\n * `runDepositorPresignFlow` passed to `recordGraphFingerprint`. The\n * fingerprint covers the challengers in `challenger_subgraphs`, but the graph\n * also declares its roster in `challenger_pubkeys`. This also requires the\n * two to name the same keys, or a graph could match the fingerprint while its\n * declared roster adds or drops a challenger.\n *\n * @param graph Parsed `tx_graph_json` from the artifact bundle.\n * @param expectedFingerprint The fingerprint recorded at presign.\n * @throws GraphFingerprintError when the graph is malformed, does not\n * reproduce the fingerprint, or declares a different roster.\n */\nexport function assertReturnedGraphMatchesFingerprint(\n graph: Record<string, unknown>,\n expectedFingerprint: string,\n): void {\n const actual = fingerprintReturnedGraph(graph);\n if (actual !== expectedFingerprint) {\n throw new GraphFingerprintError(\n `Graph fingerprint ${actual} does not match the presign fingerprint ${expectedFingerprint}`,\n );\n }\n\n const fingerprinted = Object.keys(\n asRecord(graph.challenger_subgraphs, \"challenger_subgraphs\"),\n );\n const declared = declaredChallengers(graph);\n if (\n fingerprinted.length !== declared.size ||\n fingerprinted.some((key) => !declared.has(key))\n ) {\n throw new GraphFingerprintError(\n `Graph challenger_subgraphs keys ${fingerprinted.join(\", \")} do not match ` +\n `challenger_pubkeys ${[...declared].join(\", \")}`,\n );\n }\n}\n","/**\n * Depositor Graph Signing Service\n *\n * Signs the depositor's own graph transactions (Payout, NoPayout per challenger)\n * for the depositor-as-claimer flow.\n *\n * Both PSBTs are constructed locally from authoritative on-chain connector\n * parameters and the VP-advertised transaction hexes (which are themselves\n * cross-checked against on-chain or protocol-defined sinks). Building PSBTs\n * locally is essential: every field that enters the Taproot sighash\n * (witnessUtxo, tapLeafScript, controlBlock, tapInternalKey) must come from\n * trusted sources, otherwise a malicious VP could substitute metadata that\n * makes the depositor's signature valid for a different spend.\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 * @see btc-vault crates/vault/src/transactions/nopayout.rs - NoPayout structure\n */\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Transaction } from \"bitcoinjs-lib\";\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../../shared/wallets/interfaces\";\nimport type {\n DepositorAsClaimerPresignatures,\n DepositorGraphTransactions,\n DepositorPreSigsPerChallenger,\n PresignDataPerChallenger,\n} from \"../../clients/vault-provider/types\";\nimport { signPsbtsWithFallback } from \"../../managers/pegin/signPsbtsWithFallback\";\nimport { deriveLocalChallengers } from \"../../primitives/challengers\";\nimport {\n assertPsbtUnsignedTxMatches,\n type AssertPsbtUnsignedTxMatchesParams,\n} from \"../../primitives/psbt/assertPsbtUnsignedTxMatches\";\nimport { DEPOSITOR_SIGNED_INPUT_COUNT } from \"../../primitives/psbt/constants\";\nimport {\n assertNoPayoutOutputMatchesChallenger,\n buildNoPayoutPsbt,\n} from \"../../primitives/psbt/noPayout\";\nimport {\n buildPayoutPsbt,\n extractPayoutSignature,\n} from \"../../primitives/psbt/payout\";\nimport { assertScriptPathSchnorrSignature } from \"../../primitives/psbt/verifyScriptPathSchnorrSignature\";\nimport {\n stripHexPrefix,\n uint8ArrayToHex,\n validateWalletPubkey,\n} from \"../../primitives/utils/bitcoin\";\nimport { createTaprootScriptPathSignOptions } from \"../../utils/signing\";\nimport { assertPresignClaimAssertLinkage } from \"./graphFingerprint\";\n\n/**\n * commissionBps placeholder for the depositor-as-claimer path — `buildPayoutPsbt`\n * only consults it under the VP-claimer role, so any in-range value is inert.\n */\nconst DEPOSITOR_PATH_UNUSED_COMMISSION_BPS = 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// Helpers\n// ============================================================================\n\n/**\n * Reject VP-supplied `challenger_presign_data` whose pubkey set does not\n * exactly equal `localChallengers ∪ universalChallengers`.\n *\n * The daemon's `challenger_presign_data` contains one entry per challenger\n * in `Challengers::all_sorted() = local + universal` (per\n * btc-vault `crates/vault/src/tx_graph/graph.rs:438-458`). For the\n * depositor-as-claimer flow this is `VKs + UCs`.\n *\n * Threat model: a malicious or buggy VP could omit, duplicate, or inject\n * unrelated entries. Missing entries → depositor activates with incomplete\n * recovery material (omitted challenger later becomes unenforceable).\n * Duplicates or extras → wallet signs PSBTs for challengers the protocol\n * doesn't recognize, handing the VP signatures it shouldn't have.\n */\nfunction assertChallengerSetMatchesExpected(\n challengerPresignData: PresignDataPerChallenger[],\n localChallengers: string[],\n universalChallengerBtcPubkeys: string[],\n): void {\n const universal = universalChallengerBtcPubkeys.map((k) =>\n stripHexPrefix(k).toLowerCase(),\n );\n // Protocol guarantee: local and universal sets are disjoint. Reject\n // overlap so the depositor doesn't sign for an ambiguous challenger role.\n const overlap = localChallengers.filter((k) => universal.includes(k));\n if (overlap.length > 0) {\n throw new Error(\n `Cannot validate challenger set: vault keepers and universal challengers overlap (${overlap.join(\", \")})`,\n );\n }\n const expected = [...localChallengers, ...universal];\n\n const suppliedList = challengerPresignData.map((c) =>\n stripHexPrefix(c.challenger_pubkey).toLowerCase(),\n );\n const suppliedSet = new Set(suppliedList);\n if (suppliedSet.size !== suppliedList.length) {\n throw new Error(\n \"Depositor graph contains duplicate challenger entries in challenger_presign_data\",\n );\n }\n const expectedSet = new Set(expected);\n const missing = expected.filter((c) => !suppliedSet.has(c));\n const extra = suppliedList.filter((c) => !expectedSet.has(c));\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `Depositor graph challenger set does not match expected (local ∪ universal)` +\n (missing.length > 0 ? ` (missing: ${missing.join(\", \")})` : \"\") +\n (extra.length > 0 ? ` (unexpected: ${extra.join(\", \")})` : \"\"),\n );\n }\n}\n\n/**\n * Read the txid that the given input references in the unsigned tx, in display\n * (big-endian) hex order. bitcoinjs-lib stores `input.hash` in internal\n * little-endian byte order, which is the reverse of how txids are normally\n * displayed.\n */\nfunction readInputTxid(tx: Transaction, inputIndex: number): string {\n const input = tx.ins[inputIndex];\n return uint8ArrayToHex(new Uint8Array(input.hash).slice().reverse());\n}\n\n/**\n * Verify the noPayout transaction's input at `inputIndex` references the\n * given parent transaction at vout 0 (per nopayout.rs the layout is fixed:\n * Assert:0, ChallengeAssertX:0, ChallengeAssertY:0).\n */\nfunction assertInputReferencesParent(\n noPayoutTx: Transaction,\n inputIndex: number,\n parentTx: Transaction,\n parentLabel: string,\n challengerPubkey: string,\n): void {\n const input = noPayoutTx.ins[inputIndex];\n if (input.index !== 0) {\n throw new Error(\n `NoPayout (challenger ${challengerPubkey}) input ${inputIndex} expected to spend ${parentLabel} vout 0, got vout ${input.index}`,\n );\n }\n const parentTxid = parentTx.getId();\n const inputTxid = readInputTxid(noPayoutTx, inputIndex);\n if (inputTxid !== parentTxid) {\n throw new Error(\n `NoPayout (challenger ${challengerPubkey}) input ${inputIndex} does not reference ${parentLabel} (expected txid ${parentTxid}, got ${inputTxid})`,\n );\n }\n}\n\n// ============================================================================\n// Collect phase\n// ============================================================================\n\n/**\n * Build the depositor's payout PSBT and per-challenger NoPayout PSBTs locally\n * from authoritative connector params.\n *\n * Layout of returned arrays: [Payout, NoPayout_0, NoPayout_1, ...]\n */\nasync function collectDepositorGraphPsbts(\n depositorGraph: DepositorGraphTransactions,\n walletPublicKey: string,\n ctx: DepositorGraphSigningContext,\n): Promise<CollectedDepositorGraphPsbts> {\n const psbtHexes: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const challengerEntries: ChallengerEntry[] = [];\n\n // 1. Fail-fast on a malformed VP response BEFORE doing any PSBT-build\n // work that would be wasted if the challenger set is wrong.\n const localChallengers = deriveLocalChallengers({\n claimerBtcPubkey: ctx.depositorBtcPubkey,\n depositorBtcPubkey: ctx.depositorBtcPubkey,\n vaultProviderBtcPubkey: ctx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: ctx.vaultKeeperBtcPubkeys,\n });\n assertChallengerSetMatchesExpected(\n depositorGraph.challenger_presign_data,\n localChallengers,\n ctx.universalChallengerBtcPubkeys,\n );\n\n // 2. Build the payout PSBT locally — every sighash-relevant field is\n // derived from trusted on-chain connector params, not from the VP.\n // buildPayoutPsbt also runs the per-role output validation.\n const builtPayout = await buildPayoutPsbt({\n vaultCoreVersion: ctx.vaultCoreVersion,\n vkClaimerPayoutScriptPubKeys: ctx.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: ctx.vpCommissionScriptPubKey,\n payoutTxHex: depositorGraph.payout_tx.tx_hex,\n peginTxHex: ctx.peginTxHex,\n assertTxHex: depositorGraph.assert_tx.tx_hex,\n timelockAssert: ctx.timelockAssert,\n depositorBtcPubkey: ctx.depositorBtcPubkey,\n vaultProviderBtcPubkey: ctx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: ctx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: ctx.universalChallengerBtcPubkeys,\n timelockPegin: ctx.timelockPegin,\n network: ctx.network,\n claimerBtcPubkey: ctx.depositorBtcPubkey,\n registeredPayoutScriptPubKey: ctx.registeredPayoutScriptPubKey,\n commissionBps: DEPOSITOR_PATH_UNUSED_COMMISSION_BPS,\n protocolFeeRate: ctx.protocolFeeRate,\n councilMembers: ctx.councilMembers,\n councilQuorum: ctx.councilQuorum,\n });\n psbtHexes.push(builtPayout.psbtHex);\n signOptions.push(\n createTaprootScriptPathSignOptions(\n walletPublicKey,\n DEPOSITOR_SIGNED_INPUT_COUNT,\n ),\n );\n\n // 3. Per-challenger: build the NoPayout PSBT locally too.\n const claimerPubkey = stripHexPrefix(ctx.depositorBtcPubkey);\n const assertTxParsed = Transaction.fromHex(\n stripHexPrefix(depositorGraph.assert_tx.tx_hex),\n );\n\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 = await buildLocalNoPayoutPsbt({\n challenger,\n challengerPubkey,\n claimerPubkey,\n localChallengers,\n assertTxParsed,\n ctx,\n });\n psbtHexes.push(noPayoutHex);\n signOptions.push(\n createTaprootScriptPathSignOptions(\n walletPublicKey,\n DEPOSITOR_SIGNED_INPUT_COUNT,\n ),\n );\n\n challengerEntries.push({\n challengerPubkey,\n noPayoutIdx,\n });\n }\n\n return { psbtHexes, signOptions, challengerEntries };\n}\n\ninterface BuildLocalNoPayoutPsbtParams {\n challenger: PresignDataPerChallenger;\n challengerPubkey: string;\n claimerPubkey: string;\n localChallengers: string[];\n assertTxParsed: Transaction;\n ctx: DepositorGraphSigningContext;\n}\n\n/**\n * Build a single NoPayout PSBT for one challenger from authoritative\n * inputs. Validates the VP-supplied parent transactions match what the\n * NoPayout transaction commits to via input txids, and asserts the output\n * pays to the protocol-defined challenger sink before returning.\n *\n * NoPayout transaction layout (per\n * btc-vault crates/vault/src/transactions/nopayout.rs):\n * - 3 inputs (fixed order):\n * - Input 0: Assert tx output 0 (depositor signs - NoPayout path)\n * - Input 1: ChallengeAssertX tx output 0 (with timelock)\n * - Input 2: ChallengeAssertY tx output 0 (with timelock)\n * - 1 output: BIP-86 P2TR to the challenger\n */\nasync function buildLocalNoPayoutPsbt(\n params: BuildLocalNoPayoutPsbtParams,\n): Promise<string> {\n const {\n challenger,\n challengerPubkey,\n claimerPubkey,\n localChallengers,\n assertTxParsed,\n ctx,\n } = params;\n\n // Pin the output sink before doing any sighash-relevant work.\n assertNoPayoutOutputMatchesChallenger(\n challenger.nopayout_tx.tx_hex,\n challengerPubkey,\n ctx.network,\n );\n\n // Parse the NoPayout tx and the two ChallengeAssert parents.\n const noPayoutTx = Transaction.fromHex(\n stripHexPrefix(challenger.nopayout_tx.tx_hex),\n );\n const challengeAssertXTx = Transaction.fromHex(\n stripHexPrefix(challenger.challenge_assert_x_tx.tx_hex),\n );\n const challengeAssertYTx = Transaction.fromHex(\n stripHexPrefix(challenger.challenge_assert_y_tx.tx_hex),\n );\n\n if (noPayoutTx.ins.length !== 3) {\n throw new Error(\n `NoPayout (challenger ${challengerPubkey}) must have exactly 3 inputs, got ${noPayoutTx.ins.length}`,\n );\n }\n\n // Pin every input's parent. Each parent's outs[0] is the authoritative\n // prevout - because we verified the parent's txid matches what the NoPayout\n // tx commits to, the parent cannot be substituted without changing the\n // NoPayout txid.\n assertInputReferencesParent(\n noPayoutTx,\n 0,\n assertTxParsed,\n \"Assert\",\n challengerPubkey,\n );\n assertInputReferencesParent(\n noPayoutTx,\n 1,\n challengeAssertXTx,\n \"ChallengeAssertX\",\n challengerPubkey,\n );\n assertInputReferencesParent(\n noPayoutTx,\n 2,\n challengeAssertYTx,\n \"ChallengeAssertY\",\n challengerPubkey,\n );\n\n const prevouts = [\n assertTxParsed.outs[0],\n challengeAssertXTx.outs[0],\n challengeAssertYTx.outs[0],\n ].map((out) => ({\n script_pubkey: uint8ArrayToHex(new Uint8Array(out.script)),\n value: out.value,\n }));\n\n return buildNoPayoutPsbt({\n noPayoutTxHex: challenger.nopayout_tx.tx_hex,\n challengerPubkey,\n prevouts,\n connectorParams: {\n txGraphVersion: ctx.vaultCoreVersion,\n claimer: claimerPubkey,\n localChallengers,\n universalChallengers: ctx.universalChallengerBtcPubkeys,\n timelockAssert: ctx.timelockAssert,\n councilMembers: ctx.councilMembers,\n councilQuorum: ctx.councilQuorum,\n },\n });\n}\n\n// ============================================================================\n// Extract phase\n// ============================================================================\n\n/** A pair of a locally-built PSBT and the wallet-returned PSBT for it. */\ntype PsbtPair = AssertPsbtUnsignedTxMatchesParams;\n\n/**\n * Extract all signatures from signed PSBTs and assemble into presignatures.\n * Each pair is asserted to encode the same unsigned tx before its signature\n * is extracted — defends against a wallet that returns a signature for a\n * substituted transaction.\n */\nfunction extractDepositorGraphSignatures(\n psbtPairs: PsbtPair[],\n challengerEntries: ChallengerEntry[],\n depositorPubkey: string,\n): DepositorAsClaimerPresignatures {\n // Positional invariant: psbtPairs[0] is the payout PSBT; per-challenger\n // nopayouts live at indices recorded in `challengerEntries[].noPayoutIdx`.\n // Set up by `collectDepositorGraphPsbts` (payout pushed first, then each\n // nopayout). A future refactor that reorders the array would silently\n // extract the wrong signature for the wrong slot — Critical Path #3.\n // Payout and every NoPayout PSBT are signed on input 0 (depositor script-path).\n const DEPOSITOR_SIGNED_INPUT_INDEX = 0;\n\n assertPsbtUnsignedTxMatches(psbtPairs[0]);\n const payoutSignature = extractPayoutSignature(\n psbtPairs[0].returnedPsbtHex,\n depositorPubkey,\n );\n // Critical Path #7: verify the wallet's signature against a sighash recomputed\n // from the PSBT we built (psbtPairs[0].requestedPsbtHex), not the returned one.\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtPairs[0].requestedPsbtHex,\n signatureHex: payoutSignature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: DEPOSITOR_SIGNED_INPUT_INDEX,\n });\n\n const perChallenger: Record<string, DepositorPreSigsPerChallenger> = {};\n for (const entry of challengerEntries) {\n assertPsbtUnsignedTxMatches(psbtPairs[entry.noPayoutIdx]);\n const nopayoutSignature = extractPayoutSignature(\n psbtPairs[entry.noPayoutIdx].returnedPsbtHex,\n depositorPubkey,\n );\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtPairs[entry.noPayoutIdx].requestedPsbtHex,\n signatureHex: nopayoutSignature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: DEPOSITOR_SIGNED_INPUT_INDEX,\n });\n perChallenger[entry.challengerPubkey] = {\n nopayout_signature: nopayoutSignature,\n };\n }\n\n return {\n payout_signatures: {\n payout_signature: payoutSignature,\n },\n per_challenger: perChallenger,\n };\n}\n\n// ============================================================================\n// Main entry point\n// ============================================================================\n\n/**\n * Authoritative inputs required to construct the depositor's Payout AND every\n * per-challenger NoPayout PSBT locally. Every field here must come from\n * trusted on-chain sources, not from the vault provider response. They feed\n * directly into the Taproot sighash.\n */\nexport interface DepositorGraphSigningContext {\n /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion` from `BTCVaultRegistry`.\n * Selects which graph's connector scripts every PSBT is rebuilt with.\n */\n vaultCoreVersion: number;\n /** Raw pegin BTC transaction hex (provides the depositor's signed prevout) */\n peginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex, no 0x prefix) */\n depositorBtcPubkey: 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 /** Pegin CSV timelock from the locked offchain params version (blocks) */\n timelockPegin: number;\n /**\n * Tx-graph fee rate (sat/vB) from the locked offchain params version —\n * bounds the depositor-claimer payout's implicit fee (payout fee band).\n */\n protocolFeeRate: bigint;\n /**\n * Assert CSV timelock from the locked offchain params version (blocks).\n * Sourced from the on-chain ProtocolParams contract via\n * `ViemProtocolParamsReader.getOffchainParamsByVersion(...).timelockAssert`.\n */\n timelockAssert: number;\n /**\n * Security council member x-only public keys (hex, no prefix). Sourced from\n * the on-chain ProtocolParams contract via\n * `ViemProtocolParamsReader.getOffchainParamsByVersion(...).securityCouncilKeys`.\n */\n councilMembers: string[];\n /**\n * M-of-N council quorum threshold. Sourced from the on-chain ProtocolParams\n * contract via `ViemProtocolParamsReader.getOffchainParamsByVersion(...).councilQuorum`.\n */\n councilQuorum: number;\n /** BTC network (Mainnet, Testnet, etc.) */\n network: Network;\n /**\n * On-chain registered depositor payout scriptPubKey (hex, with or without\n * 0x prefix). Used to assert the VP-advertised payout transaction pays to\n * the depositor's registered address before the wallet produces a signature.\n */\n registeredPayoutScriptPubKey: string;\n /**\n * RFC-006 operator payout destinations. Forwarded to `buildPayoutPsbt` for\n * shape completeness only: this graph is signed under the\n * `depositor-as-claimer` role, whose payout has two outputs and reads\n * neither the keeper map nor the VP commission destination.\n */\n vkClaimerPayoutScriptPubKeys: Readonly<Record<string, string>>;\n /** See {@link vkClaimerPayoutScriptPubKeys} — unused for this role. */\n vpCommissionScriptPubKey: string;\n}\n\nexport interface SignDepositorGraphParams {\n /** The depositor graph from VP response */\n depositorGraph: DepositorGraphTransactions;\n /** Bitcoin wallet for signing */\n btcWallet: BitcoinWallet;\n /** Authoritative inputs used to rebuild every PSBT locally */\n signingContext: DepositorGraphSigningContext;\n}\n\n/**\n * Sign all depositor graph transactions and assemble into presignatures.\n *\n * Flow:\n * 1. Build payout + per-challenger nopayout PSBTs locally\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, btcWallet, signingContext } = params;\n\n // Validate the complete funding chain before even reading the wallet key.\n // The orchestrating flow performs the same check while fingerprinting, but\n // this service is also a public entry point and must be safe on its own.\n assertPresignClaimAssertLinkage({\n peginTxHex: signingContext.peginTxHex,\n claimTxHex: depositorGraph.claim_tx.tx_hex,\n assertTxHex: depositorGraph.assert_tx.tx_hex,\n path: \"depositor_graph\",\n });\n\n const walletPublicKey = await btcWallet.getPublicKeyHex();\n // Fail fast if the connected wallet doesn't match the on-chain registered\n // depositor key — otherwise extractPayoutSignature later fails after\n // multiple wallet popups with an opaque \"no signature found\" error.\n const { depositorPubkey } = validateWalletPubkey(\n walletPublicKey,\n stripHexPrefix(signingContext.depositorBtcPubkey),\n );\n\n // 1. Build all PSBTs locally\n const { psbtHexes, signOptions, challengerEntries } =\n await collectDepositorGraphPsbts(\n depositorGraph,\n walletPublicKey,\n signingContext,\n );\n\n // 2. Sign all PSBTs (batch when supported, sequential fallback for mobile)\n // signPsbtsWithFallback guarantees one signed PSBT per input (or throws), so\n // no separate arity check is needed here.\n const signedPsbtHexes = await signPsbtsWithFallback(\n btcWallet,\n psbtHexes,\n signOptions,\n );\n\n // 3. Pair requested with signed and extract signatures\n const psbtPairs: PsbtPair[] = psbtHexes.map((requestedPsbtHex, i) => ({\n requestedPsbtHex,\n returnedPsbtHex: signedPsbtHexes[i],\n }));\n return extractDepositorGraphSignatures(\n psbtPairs,\n challengerEntries,\n depositorPubkey,\n );\n}\n","/**\n * Poll `getPeginStatusByVaultId` 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 { vaultIdKey } from \"../../clients/vault-provider/batchAttribution\";\nimport { JsonRpcError } from \"../../clients/vault-provider/json-rpc-client\";\nimport {\n DaemonStatus,\n RpcErrorCode,\n VP_TERMINAL_FAILURE_STATUSES,\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\n/** Characters of a vault id shown in error text: `0x` plus 8 hex chars. */\nconst VAULT_ID_LOG_PREFIX_LEN = 10;\n\nexport interface WaitForPeginStatusParams {\n /** VP client implementing the status reader interface */\n statusReader: PeginStatusReader;\n /** On-chain vault id (hex, `0x` prefix optional) */\n vaultId: string;\n /**\n * BTC pegin transaction ID (unprefixed hex, 64 chars) of the same vault.\n * The VP builds the response `vault_id` from the request, so that field\n * alone cannot show which row answered. `pegin_txid` is a DB lookup on the\n * server, so a mismatch shows a status for a different peg-in. It cannot\n * tell apart vaults that share one peg-in txid. It is also the identifier\n * the presign and WOTS writes are addressed by.\n */\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 `getPeginStatusByVaultId` until the VP reaches one of the target statuses.\n *\n * @returns The DaemonStatus that matched one of the targets, OR\n * `DaemonStatus.ACTIVATED` if the VP raced past the requested target into the\n * happy-path terminal (success-via-overshoot — the goal is satisfied).\n * @throws Error on timeout, abort, non-transient RPC error, or any terminal status (`Expired` + `VP_TERMINAL_FAILURE_STATUSES`) not in `targetStatuses`.\n */\nexport async function waitForPeginStatus(\n params: WaitForPeginStatusParams,\n): Promise<DaemonStatus> {\n const {\n statusReader,\n vaultId,\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 vault ${vaultId.slice(0, VAULT_ID_LOG_PREFIX_LEN)}… (target: ${[...targetStatuses].join(\", \")})`,\n );\n }\n\n if (Date.now() - startTime >= timeoutMs) {\n throw new Error(\n `Polling timeout after ${timeoutMs}ms for vault ${vaultId.slice(0, VAULT_ID_LOG_PREFIX_LEN)}… (target: ${[...targetStatuses].join(\", \")})`,\n );\n }\n\n try {\n const response = await statusReader.getPeginStatusByVaultId(\n { vault_id: vaultId },\n signal,\n );\n\n // Reject responses echoing a different vault id.\n if (vaultIdKey(response.vault_id) !== vaultIdKey(vaultId)) {\n throw new Error(\n `getPeginStatusByVaultId returned status for vault ${response.vault_id.slice(0, VAULT_ID_LOG_PREFIX_LEN)}…, requested ${vaultId.slice(0, VAULT_ID_LOG_PREFIX_LEN)}…`,\n );\n }\n\n // Reject a response whose server-side pegin txid names another peg-in.\n // The vault id check above catches a mangled response; this catches a\n // status for a different peg-in.\n if (response.pegin_txid.toLowerCase() !== peginTxid.toLowerCase()) {\n throw new Error(\n `getPeginStatusByVaultId returned status for pegin ${response.pegin_txid.slice(0, 8)}…, requested ${peginTxid.slice(0, 8)}…`,\n );\n }\n\n const status = response.status as DaemonStatus;\n if (targetStatuses.has(status)) {\n return status;\n }\n // Happy-path overshoot: VP raced past the requested target to ACTIVATED.\n // The caller's goal (reach some earlier state) is satisfied — return\n // success rather than time out waiting for a state the VP already left.\n if (status === DaemonStatus.ACTIVATED) {\n return status;\n }\n // EXPIRED is included — depositor has no path forward once VP marks the pegin Expired.\n if (\n status === DaemonStatus.EXPIRED ||\n VP_TERMINAL_FAILURE_STATUSES.has(status)\n ) {\n throw new Error(\n `Vault ${vaultId.slice(0, VAULT_ID_LOG_PREFIX_LEN)}… 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 const isNotFound =\n error instanceof JsonRpcError &&\n error.code === RpcErrorCode.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 vault ${vaultId.slice(0, VAULT_ID_LOG_PREFIX_LEN)}… (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 * 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\";\n\nimport type { BitcoinWallet } from \"../../../../shared/wallets/interfaces\";\nimport type {\n ClaimerSignatures,\n ClaimerTransactions,\n} from \"../../clients/vault-provider/types\";\nimport { DaemonStatus } from \"../../clients/vault-provider/types\";\nimport {\n supportsDepositApproval,\n type DepositTerms,\n} from \"../../deposit-terms\";\nimport { PayoutManager } from \"../../managers/PayoutManager\";\nimport {\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../../primitives/utils/bitcoin\";\nimport {\n assertPresignAssertSpendsClaim,\n fingerprintPresignTxSet,\n} from \"./graphFingerprint\";\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 /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion` from `BTCVaultRegistry`.\n * Selects which graph's connector scripts every payout/nopayout PSBT is\n * rebuilt with.\n */\n vaultCoreVersion: number;\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 /**\n * Assert CSV timelock from the locked offchain params version (blocks).\n * Source: ProtocolParams contract via\n * `ViemProtocolParamsReader.getOffchainParamsByVersion(...).timelockAssert`.\n * Required for the depositor-graph NoPayout local rebuild.\n */\n timelockAssert: number;\n /**\n * Security council member x-only public keys (hex, no prefix).\n * Source: ProtocolParams contract via\n * `getOffchainParamsByVersion(...).securityCouncilKeys`.\n * Required to rebuild every Assert:0 leaf (payout and NoPayout) locally.\n */\n councilMembers: string[];\n /**\n * M-of-N council quorum threshold.\n * Source: ProtocolParams contract via\n * `getOffchainParamsByVersion(...).councilQuorum`.\n * Required to rebuild every Assert:0 leaf (payout and NoPayout) locally.\n */\n councilQuorum: number;\n /** BTC network (Mainnet, Testnet, etc.) */\n network: Network;\n /** On-chain registered depositor payout scriptPubKey (hex) */\n registeredPayoutScriptPubKey: string;\n /** VP commission (bps) from `BTCVaultRegistry`; caps the VP-claimer payout commission output. */\n commissionBps: number;\n /**\n * Tx-graph fee rate (sat/vB) from the locked offchain params version —\n * `getOffchainParamsByVersion(...).feeRate`, the rate the VP built the\n * graph with. Bounds every payout's implicit fee (payout fee band).\n */\n protocolFeeRate: bigint;\n\n /**\n * RFC-006 resolved keeper payout destinations at the vault's frozen\n * `appKeeperKeyEpoch`, keyed by lowercased x-only operation pubkey.\n */\n vkClaimerPayoutScriptPubKeys: Readonly<Record<string, string>>;\n /**\n * RFC-006 resolved VP commission destination at the vault's frozen\n * `vpKeyEpoch`.\n */\n vpCommissionScriptPubKey: string;\n}\n\nexport interface RunDepositorPresignFlowParams {\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 /** On-chain vault id (hex, `0x` prefix optional) — addresses status polling */\n vaultId: string;\n /** BTC pegin transaction ID (unprefixed hex, 64 chars) — used by the presign RPCs */\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 /**\n * Required for approval-capable wallets. Fresh flows pass\n * PreparePeginResult.depositTerms; resume flows rebuild them from\n * on-chain state (the vault app's rebuildDepositTerms).\n */\n depositTerms?: DepositTerms;\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 * Persist the fingerprint of the transaction set about to be signed.\n *\n * `pegin.md` §5.9 requires activation to refuse a bundle whose graph does\n * not reproduce this value. It is called after every check and signature\n * has passed and before the signatures are submitted, and awaited: when it\n * throws, the flow stops and no signature reaches the VP. A run that fails a\n * check, is declined, or resumes past payout signing does not call it, so an\n * earlier record stays in place.\n */\n recordGraphFingerprint: (fingerprint: string) => void | Promise<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_PENDING_BROADCAST,\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 * Canonical x-only lowercase form, used for all claimer pubkey set-equality\n * comparisons in this module. `processPublicKeyToXOnly` already strips any\n * `0x` prefix; the lowercase here removes case-sensitivity (the VP-response\n * schema validator accepts uppercase hex, and `processPublicKeyToXOnly`\n * preserves the case of already-x-only 64-char input).\n */\nfunction normalizeClaimerPubkey(pubkey: string): string {\n return processPublicKeyToXOnly(pubkey).toLowerCase();\n}\n\n/**\n * Assert the approved terms describe the graph we will actually sign. An\n * RFC-006 key rotation bumps only a key epoch, so no version comparison can\n * catch it; `verifyRegisteredParticipantKeys` is the app-side pin, and this\n * keeps the seam self-contained for external providers (#2109).\n *\n * @throws If the terms and the signing context disagree\n */\nfunction assertDepositTermsMatchSigningContext(\n terms: DepositTerms,\n context: PayoutSigningContext,\n): void {\n const refuse = (field: string, a: unknown, b: unknown): never => {\n throw new Error(\n `Deposit terms ${field} (${String(a)}) does not match the vault's ` +\n `version-locked signing context (${String(b)}); refusing to sign ` +\n `payouts against terms that describe a different graph.`,\n );\n };\n\n // Every scalar the two types share: each one shapes the graph, and the\n // timelocks are what payout.ts pins the input sequences to.\n const scalars = [\n [\"protocolFeeRate\", terms.protocolFeeRate, context.protocolFeeRate],\n [\"vaultCoreVersion\", terms.vaultCoreVersion, context.vaultCoreVersion],\n [\"timelockPegin\", terms.timelockPegin, context.timelockPegin],\n [\"timelockAssert\", terms.timelockAssert, context.timelockAssert],\n ] as const;\n for (const [field, fromTerms, fromContext] of scalars) {\n if (fromTerms !== fromContext) {\n refuse(field, fromTerms, fromContext);\n }\n }\n\n // Set, not sequence: btc-vault sorts every roster and rejects duplicates\n // (crates/vault/src/lib.rs:249, :339), so a permutation is not drift.\n const canonical = (keys: readonly string[]) =>\n keys.map(normalizeClaimerPubkey).sort();\n const sameSet = (a: readonly string[], b: readonly string[]) => {\n const x = canonical(a);\n const y = canonical(b);\n return x.length === y.length && x.every((k, i) => k === y[i]);\n };\n\n if (!sameSet(terms.vaultKeeperBtcPubkeys, context.vaultKeeperBtcPubkeys)) {\n refuse(\n \"vaultKeeperBtcPubkeys\",\n terms.vaultKeeperBtcPubkeys.join(\",\"),\n context.vaultKeeperBtcPubkeys.join(\",\"),\n );\n }\n if (\n !sameSet(\n terms.universalChallengerBtcPubkeys,\n context.universalChallengerBtcPubkeys,\n )\n ) {\n refuse(\n \"universalChallengerBtcPubkeys\",\n terms.universalChallengerBtcPubkeys.join(\",\"),\n context.universalChallengerBtcPubkeys.join(\",\"),\n );\n }\n\n // Membership, not equality: `DepositTermsVaultGroup` carries a per-vault VP\n // key, so a batch may legitimately span providers. What matters is that the\n // vault this flow signs for was covered by what the depositor approved.\n const contextVp = normalizeClaimerPubkey(context.vaultProviderBtcPubkey);\n const approvedVps = terms.vaults.map((v) =>\n normalizeClaimerPubkey(v.vaultProviderBtcPubkey),\n );\n if (!approvedVps.includes(contextVp)) {\n refuse(\n \"vaults[].vaultProviderBtcPubkey\",\n approvedVps.join(\",\") || \"<no vaults>\",\n context.vaultProviderBtcPubkey,\n );\n }\n}\n\n/**\n * Reject VP-supplied `response.txs` whose non-depositor claimer set does not\n * exactly equal `{vaultProviderBtcPubkey} ∪ vaultKeeperBtcPubkeys`.\n *\n * The expected set is derived from on-chain context (sourced by the caller\n * from the registry/contract reads that populate PayoutSigningContext). A\n * malicious or buggy VP could otherwise omit registered vault keepers from\n * the response; the depositor would sign only the supplied subset and submit\n * a partial presignature map. If the VP later disappears, the omitted\n * keepers cannot exercise their payout recovery branch and BTC can lock.\n *\n * The depositor's own claimer entry (if present in `response.txs`) is\n * filtered out before diffing — its Payout PSBT is built locally and signed\n * separately via signDepositorGraph, so its presence in `response.txs` is\n * permitted but not required. Duplicate detection runs on the full supplied\n * list *before* the depositor filter, so a response containing\n * `[VP, VK, depositor, depositor]` is rejected as malformed.\n */\nfunction assertNonDepositorClaimerSetMatches(\n suppliedTxs: ClaimerTransactions[],\n expectedVpPubkey: string,\n expectedVkPubkeys: string[],\n depositorPubkeyXOnly: string,\n): void {\n const depositor = normalizeClaimerPubkey(depositorPubkeyXOnly);\n const expectedList = [\n normalizeClaimerPubkey(expectedVpPubkey),\n ...expectedVkPubkeys.map(normalizeClaimerPubkey),\n ];\n const expected = new Set(expectedList);\n if (expected.size !== expectedList.length) {\n throw new Error(\n \"Cannot validate claimer set: signing context contains duplicate vault provider or vault keeper key\",\n );\n }\n if (expected.has(depositor)) {\n throw new Error(\n \"Cannot validate claimer set: depositor key overlaps with vault provider or vault keeper set\",\n );\n }\n\n const suppliedAll = suppliedTxs.map((tx) =>\n normalizeClaimerPubkey(tx.claimer_pubkey),\n );\n if (new Set(suppliedAll).size !== suppliedAll.length) {\n throw new Error(\"Presign response contains duplicate claimer entries\");\n }\n\n const suppliedNonDepositor = suppliedAll.filter((k) => k !== depositor);\n const suppliedSet = new Set(suppliedNonDepositor);\n const missing = expectedList.filter((c) => !suppliedSet.has(c));\n const extra = suppliedNonDepositor.filter((c) => !expected.has(c));\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `Presign response claimer set does not match expected (vault provider ∪ vault keepers)` +\n (missing.length > 0 ? ` (missing: ${missing.join(\", \")})` : \"\") +\n (extra.length > 0 ? ` (unexpected: ${extra.join(\", \")})` : \"\"),\n );\n }\n}\n\n/**\n * Build the `SignPayoutParams` for a single claimer. Role/script resolution\n * happens inside `buildPayoutPsbt`; here we only forward the claimer pubkey\n * and the per-vault context fields.\n */\nfunction buildPayoutSigningInput(\n tx: PreparedTransaction,\n context: PayoutSigningContext,\n) {\n return {\n vaultCoreVersion: context.vaultCoreVersion,\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 timelockAssert: context.timelockAssert,\n registeredPayoutScriptPubKey: context.registeredPayoutScriptPubKey,\n claimerBtcPubkey: tx.claimerPubkeyXOnly,\n commissionBps: context.commissionBps,\n protocolFeeRate: context.protocolFeeRate,\n councilMembers: context.councilMembers,\n councilQuorum: context.councilQuorum,\n vkClaimerPayoutScriptPubKeys: context.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: context.vpCommissionScriptPubKey,\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 runDepositorPresignFlow(\n params: RunDepositorPresignFlowParams,\n): Promise<void> {\n const {\n statusReader,\n presignClient,\n btcWallet,\n vaultId,\n peginTxid,\n depositorPk,\n signingContext,\n depositTerms,\n timeoutMs = MAX_POLLING_TIMEOUT_MS,\n signal,\n onProgress,\n recordGraphFingerprint,\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 vaultId,\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 // Approval-capable wallets must have terms available before the request,\n // but the approval ceremony itself waits until the VP response has passed\n // every fail-closed validation below.\n if (depositTerms !== undefined) {\n assertDepositTermsMatchSigningContext(depositTerms, signingContext);\n }\n\n const depositApprovalWallet = supportsDepositApproval(btcWallet)\n ? btcWallet\n : undefined;\n let approvedDepositTerms: DepositTerms | undefined;\n if (depositApprovalWallet) {\n if (!depositTerms) {\n throw new Error(\n \"runDepositorPresignFlow: this wallet requires approved deposit terms but none were \" +\n \"provided. Fresh deposits must pass PreparePeginResult.depositTerms; resume flows \" +\n \"must rebuild them from on-chain state (the vault app's rebuildDepositTerms).\",\n );\n }\n approvedDepositTerms = depositTerms;\n }\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 // Every claimer gets its own Claim/Assert chain. Bind each Assert to its\n // Claim before any payout signing prompt: buildPayoutPsbt uses Assert:0 as\n // a prevout but cannot prove that Assert spends this Claim without the\n // Claim transaction itself. A VP/VK Claim is funded from the claimer's own\n // wallet, so only the depositor graph's Claim is pinned to PegIn:1 (in the\n // fingerprint below).\n response.txs.forEach((tx, index) => {\n assertPresignAssertSpendsClaim({\n claimTxHex: tx.claim_tx.tx_hex,\n assertTxHex: tx.assert_tx.tx_hex,\n path: `txs[${index}]`,\n });\n });\n\n // Fingerprint the set now, so a malformed one fails before any wallet\n // prompt. It is stored only after every check and signature below has\n // passed (see Phase 5). The PegIn comes from our own signing context rather\n // than the response, so the VP does not get to pick both sides of the\n // activation comparison.\n const graphFingerprint = fingerprintPresignTxSet({\n peginTxid,\n peginTxHex: signingContext.peginTxHex,\n claimTxHex: response.depositor_graph.claim_tx.tx_hex,\n assertTxHex: response.depositor_graph.assert_tx.tx_hex,\n payoutTxHex: response.depositor_graph.payout_tx.tx_hex,\n challengers: response.depositor_graph.challenger_presign_data,\n });\n\n // Phase 3: Validate and prepare VP/VK claimer payout transactions.\n // Fail-fast: assert the supplied non-depositor claimer set exactly equals\n // the on-chain-derived {VP} ∪ {VKs} before any wallet prompts run. The\n // depositor's own entry is permitted but not required (its payout is\n // signed separately via signDepositorGraph in Phase 4).\n const depositorPkNormalized = normalizeClaimerPubkey(depositorPk);\n assertNonDepositorClaimerSetMatches(\n response.txs,\n signingContext.vaultProviderBtcPubkey,\n signingContext.vaultKeeperBtcPubkeys,\n depositorPk,\n );\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 // Compare on the normalized form so an uppercase-hex depositor entry in\n // the VP response is still filtered out consistently with the assertion.\n const nonDepositorTxs = response.txs.filter(\n (tx) => normalizeClaimerPubkey(tx.claimer_pubkey) !== depositorPkNormalized,\n );\n const preparedTransactions = prepareTransactionsForSigning(nonDepositorTxs);\n\n // Approval-capable wallets approve only after the full VP response is\n // validated, and still before any transaction-signing call they authorize.\n if (depositApprovalWallet && approvedDepositTerms) {\n // #2110 T4: providers exposing the validate-only pre-check fail an\n // envelope violation here, before the approval ceremony starts.\n if (typeof depositApprovalWallet.validateDepositTerms === \"function\") {\n await depositApprovalWallet.validateDepositTerms(approvedDepositTerms);\n }\n // The provider validates its own device envelope inside\n // approveDepositTerms (DepositTermsApprover contract, #2109).\n await depositApprovalWallet.approveDepositTerms(approvedDepositTerms);\n }\n\n // The approval prompt can stay open for a long time. A cancel during it\n // must not lead into the signing prompts below.\n signal?.throwIfAborted();\n\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. Both Payout and per-challenger\n // NoPayout PSBTs are rebuilt locally inside signDepositorGraph from these\n // authoritative connector params and the on-chain protocol parameters.\n const depositorClaimerPresignatures = await signDepositorGraph({\n depositorGraph: response.depositor_graph,\n btcWallet,\n signingContext: {\n vaultCoreVersion: signingContext.vaultCoreVersion,\n peginTxHex: signingContext.peginTxHex,\n depositorBtcPubkey: depositorPk,\n vaultProviderBtcPubkey: signingContext.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: signingContext.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys:\n signingContext.universalChallengerBtcPubkeys,\n timelockPegin: signingContext.timelockPegin,\n timelockAssert: signingContext.timelockAssert,\n councilMembers: signingContext.councilMembers,\n councilQuorum: signingContext.councilQuorum,\n network: signingContext.network,\n registeredPayoutScriptPubKey: signingContext.registeredPayoutScriptPubKey,\n protocolFeeRate: signingContext.protocolFeeRate,\n vkClaimerPayoutScriptPubKeys: signingContext.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: signingContext.vpCommissionScriptPubKey,\n },\n });\n\n signal?.throwIfAborted();\n\n // Record what was just signed, before the signatures leave the device.\n // Not earlier: a set that fails a check or a declined prompt must not\n // replace the record of a set this depositor already signed and submitted.\n // Not later: a failed write stops the flow here, so the VP never holds\n // signatures the depositor has no fingerprint for.\n await recordGraphFingerprint(graphFingerprint);\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","/**\n * Submit pre-derived WOTS public keys to the vault provider.\n *\n * Polls `getPeginStatusByVaultId` 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 * `expandWotsSeed` + `deriveWotsBlocksFromSeed` from the SDK's\n * `tbv/core/vault-secrets` and `tbv/core/wots` modules respectively.\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 /** On-chain vault id (hex, `0x` prefix optional) — addresses status polling */\n vaultId: string;\n /** BTC pegin transaction ID (unprefixed hex, 64 chars) — used by the write RPC */\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 vaultId,\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 vaultId,\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 * RFC-006 indexer-hint acceptance policy — the single definition.\n *\n * Every path that builds against a vault takes participant keys from chain and\n * treats the indexer's copy as an untrusted *hint*. The hint never supplies key\n * material; its job is to catch a wrong vault provider address, a wrong\n * application entry point, or a stale roster version.\n *\n * Under RFC-006 an operator's BTC key is an append-only history of operation\n * keys, so there are two values the indexer may legitimately be serving at any\n * moment: the **registration** key (it has not caught up to a rotation) or the\n * **current operation** key (it has). Accepting only the first hard-fails every\n * depositor of a rotated provider the day the indexer catches up — an\n * indexer-side deploy, with nothing to deploy on our side and no user\n * workaround. Hence: accept either.\n *\n * For an operator that never rotated the two candidates are identical, so this\n * is exactly the old strict check until someone rotates.\n *\n * This module exists because the policy had already been written three times —\n * deposit, payout, and (missing) refund — and drifted each time. Callers differ\n * in shape and cannot share one entry point:\n *\n * - the deposit path compares three roles as whole sets and resolves operation\n * keys **eagerly**, because it builds the Bitcoin lock with them;\n * - payout and refund compare one scalar key and must read the operation key\n * **lazily**, because on the happy path it is a second RPC for nothing.\n *\n * So what is shared is the predicate — {@link isHintAccepted} and the two\n * matchers — plus {@link assertVaultProviderHintAccepted} for the two scalar\n * callers. Anything that needs a different acceptance rule does not belong\n * here; see `vpAuthPinnedPubkey`, which is deliberately operation-key-only\n * because accepting either would hollow out the pin.\n *\n * @module services/participants/indexerKeyHint\n */\n\nimport type { Address } from \"viem\";\n\nimport { canonicalizeBtcPubkey } from \"../../primitives/utils/bitcoin\";\n\n/**\n * Which of the two legitimate on-chain candidates a role's hint matched.\n *\n * Both true means the role never rotated, so the hint constrains nothing.\n * Both false means the hint is not explainable by any state the chain is in.\n */\nexport interface HintMatch {\n registration: boolean;\n operation: boolean;\n}\n\n/**\n * The accept-either policy itself.\n *\n * Kept as a named function rather than inlined at each call site so that\n * changing the policy is a one-line change in one file, and so a reader can\n * find every path governed by it.\n */\nexport function isHintAccepted(match: HintMatch): boolean {\n return match.registration || match.operation;\n}\n\n/** Match a single hinted key against both candidates. */\nexport function matchKeyHint(\n hint: string,\n registrationKey: string,\n operationKey: string,\n): HintMatch {\n const canonicalHint = canonicalizeBtcPubkey(hint);\n return {\n registration: canonicalHint === canonicalizeBtcPubkey(registrationKey),\n operation: canonicalHint === canonicalizeBtcPubkey(operationKey),\n };\n}\n\n/**\n * Match a hinted key *set* against both candidate sets.\n *\n * Compared as whole sets, never as per-element membership of the union: a\n * roster holding one registration key and one operation key is an indexer that\n * is halfway through applying a rotation, and union membership would wave that\n * through. Order is normalized, so this is set equality and not list equality.\n */\nexport function matchKeySetHint(\n hints: readonly string[],\n registrationKeys: readonly string[],\n operationKeys: readonly string[],\n): HintMatch {\n const canonicalHints = sortedCanonical(hints);\n return {\n registration: setsEqual(canonicalHints, sortedCanonical(registrationKeys)),\n operation: setsEqual(canonicalHints, sortedCanonical(operationKeys)),\n };\n}\n\nfunction sortedCanonical(keys: readonly string[]): string[] {\n return keys.map(canonicalizeBtcPubkey).sort();\n}\n\nfunction setsEqual(a: readonly string[], b: readonly string[]): boolean {\n return a.length === b.length && a.every((key, i) => key === b[i]);\n}\n\nexport interface AssertVaultProviderHintAcceptedParams {\n /** Vault provider's admin address, named in the error. */\n vaultProviderEthAddress: Address;\n /** The untrusted hint. Absent means there is nothing to cross-check. */\n hintBtcPubkey?: string;\n /** The vault provider's registration key, already read from chain. */\n registrationBtcPubkey: string;\n /**\n * Reads the vault provider's *current* operation key.\n *\n * Invoked only when the hint fails against the registration key, so a\n * provider that never rotated — and an indexer that has not caught up — cost\n * no extra RPC. Callers must not pre-read this.\n */\n readCurrentOperationBtcPubkey: () => Promise<string>;\n /**\n * Sentence appended to the error naming what was aborted, e.g.\n * `\"Aborting refund.\"`. The shared half of the message says which keys\n * failed to match; this says which operation the user just lost.\n */\n context?: string;\n}\n\n/**\n * Assert an indexer-hinted vault provider key is one the chain can explain.\n *\n * Resolves silently when there is no hint, or when the hint matches either\n * candidate. Throws otherwise — the caller's key material is unaffected either\n * way, since resolution is chain-only.\n */\nexport async function assertVaultProviderHintAccepted(\n params: AssertVaultProviderHintAcceptedParams,\n): Promise<void> {\n const {\n vaultProviderEthAddress,\n hintBtcPubkey,\n registrationBtcPubkey,\n readCurrentOperationBtcPubkey,\n context,\n } = params;\n\n if (!hintBtcPubkey) return;\n\n const canonicalHint = canonicalizeBtcPubkey(hintBtcPubkey);\n if (canonicalHint === canonicalizeBtcPubkey(registrationBtcPubkey)) return;\n\n const canonicalOperation = canonicalizeBtcPubkey(\n await readCurrentOperationBtcPubkey(),\n );\n if (canonicalHint === canonicalOperation) return;\n\n throw new Error(\n `Vault provider BTC pubkey mismatch for ${vaultProviderEthAddress}: ` +\n `indexer hint matches neither the registration key nor the current ` +\n `operation key on-chain.${context ? ` ${context}` : \"\"}`,\n );\n}\n","/**\n * RFC-006 participant operation-key resolution.\n *\n * Under RFC-006 an operator's BTC key is no longer fixed at registration: it\n * is an append-only history of *operation* keys, rotated by the operator's\n * cold ETH admin key. Every consumer that needs \"the key this participant\n * signs with\" must resolve it, in one of two modes:\n *\n * - **current** — for a peg-in being built now, and for the VP auth pin.\n * Needs no epoch read; each registry resolves its own genesis fallback, so\n * an operator that never rotated yields its registration key.\n * - **at epochs** — for any vault that already exists. The vault froze its\n * epochs at `submitPeginRequest`, and resolving against them is what keeps\n * an old vault signable after a later rotation.\n *\n * Both modes go through the same `finalize` pass, which is where the\n * rotation-specific safety checks live.\n *\n * @module services/participants/resolveParticipantKeys\n */\n\nimport { assertOnChainBtcPubkey } from \"../../clients/eth/onChainBtcPubkey\";\nimport type {\n KeyEpochs,\n OperationKeyQuery,\n OperationKeyReader,\n RawOperationKeys,\n} from \"../../clients/eth/types\";\nimport type {\n KeyResolutionMode,\n ParticipantKeySet,\n ResolvedParticipant,\n} from \"./types\";\n\n/** Role label used in validation error messages. */\ntype Role = \"vault provider\" | \"vault keeper\" | \"universal challenger\";\n\nfunction resolveOne(\n role: Role,\n rosterEntry: { ethAddress: `0x${string}`; btcPubKey: `0x${string}` },\n rawOperationKey: `0x${string}`,\n): ResolvedParticipant {\n const label = `${role} operation key (admin=${rosterEntry.ethAddress})`;\n const genesisBtcPubkey = assertOnChainBtcPubkey(\n rosterEntry.btcPubKey,\n `${role} roster key (admin=${rosterEntry.ethAddress})`,\n );\n const operationBtcPubkey = assertOnChainBtcPubkey(rawOperationKey, label);\n\n return {\n adminAddress: rosterEntry.ethAddress,\n genesisBtcPubkey,\n operationBtcPubkey,\n rotated: operationBtcPubkey !== genesisBtcPubkey,\n };\n}\n\n/**\n * Assert no two participants resolved to the same operation key.\n *\n * The on-chain guarantees are narrower than \"registration keys are distinct\",\n * and narrower than an earlier revision of this comment claimed. Each registry\n * enforces uniqueness *within its own role*, on rotation as well as\n * registration, and a VP rotation additionally rejects any key held in the\n * current vault-keeper or universal-challenger rosters.\n *\n * What no contract checks is the cross-role direction those rules leave open:\n * a keeper or challenger rotating **onto** the VP's key (the VP-side check runs\n * at VP rotation time and does not run again when a keeper moves), a keeper and\n * a challenger colliding with each other, and keepers of different applications\n * colliding. Any of those would collapse two entries in the sorted script key\n * set and silently build a lock with the wrong participant count, so they are\n * rejected here — before any script is constructed — rather than surfacing as a\n * confusing signature mismatch much later.\n */\nfunction assertDistinctOperationKeys(\n participants: ResolvedParticipant[],\n): void {\n const seen = new Map<string, string>();\n for (const participant of participants) {\n const previousOwner = seen.get(participant.operationBtcPubkey);\n if (previousOwner) {\n throw new Error(\n `Participant operation key collision: ${previousOwner} and ` +\n `${participant.adminAddress} both resolve to operation key ` +\n `${participant.operationBtcPubkey}`,\n );\n }\n seen.set(participant.operationBtcPubkey, participant.adminAddress);\n }\n}\n\nfunction finalize(\n query: OperationKeyQuery,\n raw: RawOperationKeys,\n resolvedAt: KeyResolutionMode,\n): ParticipantKeySet {\n if (\n raw.vaultKeepers.length !== query.vaultKeepers.length ||\n raw.universalChallengers.length !== query.universalChallengers.length\n ) {\n throw new Error(\n `Operation-key resolution returned ${raw.vaultKeepers.length} keeper and ` +\n `${raw.universalChallengers.length} challenger keys for a roster of ` +\n `${query.vaultKeepers.length} keepers and ` +\n `${query.universalChallengers.length} challengers`,\n );\n }\n\n const vaultProvider = resolveOne(\n \"vault provider\",\n {\n ethAddress: query.vaultProviderEthAddress,\n btcPubKey: query.vaultProviderGenesisBtcPubkey,\n },\n raw.vaultProvider,\n );\n\n const vaultKeepers = query.vaultKeepers.map((keeper, i) =>\n resolveOne(\"vault keeper\", keeper, raw.vaultKeepers[i]),\n );\n const universalChallengers = query.universalChallengers.map((challenger, i) =>\n resolveOne(\"universal challenger\", challenger, raw.universalChallengers[i]),\n );\n\n assertDistinctOperationKeys([\n vaultProvider,\n ...vaultKeepers,\n ...universalChallengers,\n ]);\n\n return {\n vaultProvider,\n vaultKeepers,\n universalChallengers,\n // Derived from the pairs, never the reverse — see ParticipantKeySet.\n vaultKeeperOperationKeysSorted: vaultKeepers\n .map((p) => p.operationBtcPubkey as string)\n .sort(),\n universalChallengerOperationKeysSorted: universalChallengers\n .map((p) => p.operationBtcPubkey as string)\n .sort(),\n resolvedAt,\n query,\n };\n}\n\n/**\n * Resolve every participant's *current* operation key.\n *\n * Use for a peg-in being built now. Issues no epoch read, so it never touches\n * the extended `getBtcVaultProtocolInfo` ABI.\n *\n * `blockNumber` pins the resolution to one block, and is required. Pass the\n * same block the rosters in `query` were read at: the roster supplies each\n * participant's address and genesis key, and this call resolves what that\n * participant has rotated to. Reading the two at different blocks can pair a\n * roster member with a key from a different chain state, so there is no\n * correct unpinned call and no default worth having.\n */\nexport async function resolveCurrentParticipantKeys(params: {\n operationKeyReader: OperationKeyReader;\n query: OperationKeyQuery;\n blockNumber: bigint;\n}): Promise<ParticipantKeySet> {\n const raw = await params.operationKeyReader.getCurrentOperationKeys(\n params.query,\n params.blockNumber,\n );\n return finalize(params.query, raw, { mode: \"current\" });\n}\n\n/**\n * Resolve every participant's operation key bonded at a vault's frozen epochs.\n *\n * Use for every existing-vault path: resume, payout signing, refund. The\n * rosters in `query` must be read at the vault's frozen *membership* versions,\n * because those roster keys are the genesis the keeper/challenger getters fall\n * back to.\n */\nexport async function resolveParticipantKeysAtEpochs(params: {\n operationKeyReader: OperationKeyReader;\n query: OperationKeyQuery;\n epochs: KeyEpochs;\n}): Promise<ParticipantKeySet> {\n const raw = await params.operationKeyReader.getOperationKeysAtEpochs(\n params.query,\n params.epochs,\n );\n return finalize(params.query, raw, {\n mode: \"epochs\",\n epochs: params.epochs,\n });\n}\n","import { isAddress, isAddressEqual } from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport type {\n OperationKeyReader,\n UniversalChallengerReader,\n VaultKeeperReader,\n VaultRegistryReader,\n} from \"../../clients/eth/types\";\nimport { canonicalizeBtcPubkey } from \"../../primitives/utils/bitcoin\";\nimport {\n type HintMatch,\n isHintAccepted,\n matchKeyHint,\n matchKeySetHint,\n} from \"../participants/indexerKeyHint\";\nimport { resolveCurrentParticipantKeys } from \"../participants/resolveParticipantKeys\";\nimport type { ParticipantKeySet } from \"../participants/types\";\n\nexport interface ValidateOnChainParticipantKeysParams {\n vaultRegistryReader: VaultRegistryReader;\n vaultKeeperReader: VaultKeeperReader;\n universalChallengerReader: UniversalChallengerReader;\n vaultProviderEthAddress: Address;\n /**\n * The application entry point the caller believes the provider serves — a\n * *hint*, checked against the registry, in the same sense as\n * `expectedVaultProviderBtcPubkey` below.\n *\n * The registry's own `getVaultProviderApplication(vp)` is authoritative: it\n * is what the peg-in submit path resolves internally, and it selects the\n * keeper roster, the roster version and the keeper key epoch a deposit is\n * bonded to. This value comes from the dApp's configuration instead. They\n * agree today, so the check is normally a no-op — but if they ever diverge,\n * building against the configured one would bond the vault to an application\n * the caller never chose, and nothing downstream would say so.\n */\n applicationEntryPoint: Address;\n expectedVaultProviderBtcPubkey: string;\n expectedVaultKeeperBtcPubkeys: string[];\n expectedUniversalChallengerBtcPubkeys: string[];\n /**\n * RFC-006. Participant keys are resolved to their *current operation* keys,\n * and those are what the returned key fields carry.\n */\n operationKeyReader: OperationKeyReader;\n /**\n * Optional observer for the case where the indexer hint matched the\n * operation keys rather than the registration keys — i.e. the indexer is\n * ahead of us, not wrong. Called at most once.\n */\n onIndexerServingOperationKeys?: (message: string) => void;\n /**\n * Optional observer for the case where the indexer is serving a half-applied\n * view — one role explainable only by the registration keys, another only by\n * the operation keys. That blocks every deposit for the provider until the\n * indexer converges, and \"Refresh and try again\" cannot help, so the block\n * needs to be visible rather than showing up only as user reports. Called\n * immediately before the throw.\n */\n onIndexerHintsInconsistent?: (message: string) => void;\n /**\n * Block to resolve every read against, so the roster versions, the roster\n * members and their operation keys all describe one chain state.\n *\n * This function reads in four dependent rounds — the application entry point\n * and the challenger axis, then the keeper version and epoch keyed on that\n * entry point, then the roster members at those versions, then those members'\n * operation keys — because each round needs the previous round's output.\n * Left unpinned, each round lands on\n * whatever `latest` happens to be, and a rotation between rounds yields a key\n * set that no single block ever held. The Bitcoin lock built from it would\n * commit to that mixture, and no counterparty would agree with it.\n *\n * Required rather than optional, and deliberately so. This function exists\n * only for the fresh-deposit path, where an unpinned read is never correct —\n * an optional pin would be a silent fallback to `latest`-per-round on a path\n * that builds a Bitcoin lock. Callers must pass the same block to\n * `ProtocolParamsReader.getPegInConfiguration`; the reader interfaces keep\n * their pin optional because their other callers resolve against a vault's\n * already-frozen epochs, where pinning is meaningless.\n */\n blockNumber: bigint;\n}\n\nexport interface ValidatedOnChainParticipantKeys {\n /** The VP key to build with: its current operation key. */\n vaultProviderBtcPubkeyXOnly: string;\n vaultKeeperBtcPubkeysSorted: string[];\n universalChallengerBtcPubkeysSorted: string[];\n expectedAppVaultKeepersVersion: number;\n expectedUniversalChallengersVersion: number;\n /**\n * The two operation-key epochs the peg-in config fingerprint commits to, as\n * `bigint` (`uint64` on-chain).\n *\n * They live here rather than beside the protocol params because they label\n * the very keys this function resolves: `appKeeperKeyEpoch` is the epoch the\n * keeper operation keys above were read at, and `ucKeyEpoch` the same for the\n * challengers. Reading them anywhere else would create a second place for the\n * epoch and the keys it names to come from different blocks.\n */\n appKeeperKeyEpoch: bigint;\n ucKeyEpoch: bigint;\n /**\n * The registration / roster keys, sorted. These are what indexer hints are\n * compared against first, and they stay available for diagnostics after\n * resolution.\n */\n registrationKeys: {\n vaultProvider: string;\n vaultKeepers: string[];\n universalChallengers: string[];\n };\n /**\n * The full resolution, including the admin↔key pairing. Feeds the\n * post-registration read-after-mine verification.\n */\n participantKeys: ParticipantKeySet;\n}\n\n/**\n * The application entry point the caller passed cannot be used, either because\n * the registry says this vault provider serves a different one, or because the\n * value is not a well-formed address so no comparison is possible.\n *\n * Both are a deployment or configuration fault — not chain drift, and not\n * anything a depositor can act on. One class covers both because the caller's\n * recovery is identical and the distinction only matters in a bug report, which\n * the message carries.\n *\n * It is typed only so the consuming app can recognise it and show its own\n * generic copy: the messages name addresses and the protocol values at stake,\n * which belongs in that bug report rather than in front of a depositor. An\n * untyped `Error` would be rendered verbatim as the callout body by the\n * mapper's last-resort bucket.\n */\nexport class ApplicationEntryPointMismatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ApplicationEntryPointMismatchError\";\n }\n}\n\n// `instanceof` alone fails across module boundaries (duplicate copies, test\n// mocks). Fall back to the name field, as the sibling drift guards do.\nexport function isApplicationEntryPointMismatchError(\n err: unknown,\n): err is ApplicationEntryPointMismatchError {\n return (\n err instanceof ApplicationEntryPointMismatchError ||\n (err instanceof Error && err.name === \"ApplicationEntryPointMismatchError\")\n );\n}\n\nconst sortedSet = (keys: string[]) => keys.map(canonicalizeBtcPubkey).sort();\n\nexport async function validateOnChainParticipantKeys(\n params: ValidateOnChainParticipantKeysParams,\n): Promise<ValidatedOnChainParticipantKeys> {\n const {\n vaultRegistryReader,\n vaultKeeperReader,\n universalChallengerReader,\n vaultProviderEthAddress,\n applicationEntryPoint,\n expectedVaultProviderBtcPubkey,\n expectedVaultKeeperBtcPubkeys,\n expectedUniversalChallengerBtcPubkeys,\n operationKeyReader,\n onIndexerServingOperationKeys,\n onIndexerHintsInconsistent,\n blockNumber,\n } = params;\n\n // Round 1: everything that needs no other read's output. The application\n // entry point is among them because the keeper reads below key on it, and it\n // must come from the registry rather than from the caller's configuration.\n const [\n registryApplicationEntryPoint,\n onChainVpKey,\n expectedUniversalChallengersVersion,\n ucKeyEpoch,\n ] = await Promise.all([\n vaultRegistryReader.getVaultProviderApplication(\n vaultProviderEthAddress,\n blockNumber,\n ),\n vaultRegistryReader.getVaultProviderGenesisBtcPubKey(\n vaultProviderEthAddress,\n blockNumber,\n ),\n universalChallengerReader.getLatestUniversalChallengersVersion(blockNumber),\n universalChallengerReader.getCurrentUcKeyEpoch(blockNumber),\n ]);\n\n // Fail closed before any roster is read. A divergence here is a deployment or\n // configuration fault rather than something the depositor can act on, so it\n // carries a TYPED error: the app maps that to its own generic copy and keeps\n // the message below for the bug report. An untyped `Error` would be rendered\n // verbatim as the depositor-facing callout body by the mapper's last resort.\n //\n // The shape check runs first because callers reach this with a plain `string`\n // cast to `Address` — nothing validates that cast — and `isAddressEqual`\n // *parses* both sides, so a malformed value would throw viem's error instead\n // of the one written for this situation. `isAddressEqual` rather than `===`\n // because the two values arrive from different sources and need not share\n // EIP-55 casing.\n if (!isAddress(applicationEntryPoint, { strict: false })) {\n throw new ApplicationEntryPointMismatchError(\n `The application entry point this deposit was prepared for is not a ` +\n `valid address: ${applicationEntryPoint}`,\n );\n }\n if (!isAddressEqual(registryApplicationEntryPoint, applicationEntryPoint)) {\n throw new ApplicationEntryPointMismatchError(\n `Vault provider ${vaultProviderEthAddress} is registered to application ` +\n `${registryApplicationEntryPoint}, but this deposit was prepared for ` +\n `${applicationEntryPoint}. Refusing to build: the vault keeper roster, ` +\n `its version, and the keeper key epoch would all resolve against a ` +\n `different application than the one selected.`,\n );\n }\n\n // Round 2: keyed on the registry-resolved entry point. The keeper roster\n // version and the keeper key epoch are read together so the epoch labels the\n // roster it was read beside.\n const [expectedAppVaultKeepersVersion, appKeeperKeyEpoch] = await Promise.all(\n [\n vaultKeeperReader.getCurrentVaultKeepersVersion(\n registryApplicationEntryPoint,\n blockNumber,\n ),\n vaultKeeperReader.getCurrentAppKeeperKeyEpoch(\n registryApplicationEntryPoint,\n blockNumber,\n ),\n ],\n );\n\n const [onChainKeepers, onChainChallengers] = await Promise.all([\n vaultKeeperReader.getVaultKeepersByVersion(\n registryApplicationEntryPoint,\n expectedAppVaultKeepersVersion,\n blockNumber,\n ),\n universalChallengerReader.getUniversalChallengersByVersion(\n expectedUniversalChallengersVersion,\n blockNumber,\n ),\n ]);\n\n const registrationKeys = {\n vaultProvider: canonicalizeBtcPubkey(onChainVpKey),\n vaultKeepers: sortedSet(onChainKeepers.map((p) => p.btcPubKey)),\n universalChallengers: sortedSet(onChainChallengers.map((p) => p.btcPubKey)),\n };\n\n // Resolve the current operation keys. This is what we build the Bitcoin lock\n // with; the registration keys above stay only as the primary comparison\n // target for indexer hints.\n //\n // Read unconditionally, which is why this path cannot use\n // `assertVaultProviderHintAccepted` — that helper reads the operation key\n // lazily, for callers that only need it to explain a hint mismatch.\n const participantKeys: ParticipantKeySet =\n await resolveCurrentParticipantKeys({\n operationKeyReader,\n query: {\n vaultProviderEthAddress,\n vaultProviderGenesisBtcPubkey: `0x${onChainVpKey}` as Hex,\n applicationEntryPoint: registryApplicationEntryPoint,\n vaultKeepers: onChainKeepers,\n universalChallengers: onChainChallengers,\n },\n blockNumber,\n });\n\n const operationKeys = {\n vaultProvider: participantKeys.vaultProvider.operationBtcPubkey as string,\n vaultKeepers: [...participantKeys.vaultKeeperOperationKeysSorted],\n universalChallengers: [\n ...participantKeys.universalChallengerOperationKeysSorted,\n ],\n };\n\n // --- Indexer hint cross-check -----------------------------------------\n //\n // The hint never influences the resolved key — resolution is chain-only.\n // Its job is to catch a wrong VP address, a wrong application entry point,\n // or a stale roster version, and it still does that.\n //\n // Once rotation is possible the indexer may legitimately serve either the\n // registration keys (it has not caught up) or the operation keys (it has),\n // so each role is accepted against both candidates — see `indexerKeyHint`,\n // which owns that policy and the whole-set matching rule. The cross-role\n // check below closes the same hole one level up.\n const vpMatch: HintMatch = matchKeyHint(\n expectedVaultProviderBtcPubkey,\n registrationKeys.vaultProvider,\n operationKeys.vaultProvider,\n );\n const keeperMatch: HintMatch = matchKeySetHint(\n expectedVaultKeeperBtcPubkeys,\n registrationKeys.vaultKeepers,\n operationKeys.vaultKeepers,\n );\n const challengerMatch: HintMatch = matchKeySetHint(\n expectedUniversalChallengerBtcPubkeys,\n registrationKeys.universalChallengers,\n operationKeys.universalChallengers,\n );\n\n if (!isHintAccepted(vpMatch)) {\n throw new Error(\n `Vault provider BTC pubkey indexer hint does not match BTCVaultRegistry for ${vaultProviderEthAddress}. Refresh and try again.`,\n );\n }\n if (!isHintAccepted(keeperMatch)) {\n throw new Error(\n `Vault keeper BTC pubkeys (v${expectedAppVaultKeepersVersion}) indexer set does not match ApplicationRegistry on-chain set. Refresh and try again.`,\n );\n }\n if (!isHintAccepted(challengerMatch)) {\n throw new Error(\n `Universal challenger BTC pubkeys (v${expectedUniversalChallengersVersion}) indexer set does not match ProtocolParams on-chain set. Refresh and try again.`,\n );\n }\n\n // Cross-role consistency. A role whose two candidates are identical (nobody\n // in it rotated) matches both and constrains nothing. But if one role can\n // *only* be explained by the registration keys while another can *only* be\n // explained by the operation keys, the indexer is serving a half-applied\n // view — accepting that would mean building with a key set no single\n // snapshot of the indexer ever held.\n const roles = [vpMatch, keeperMatch, challengerMatch];\n const pinsRegistration = roles.some((m) => m.registration && !m.operation);\n const pinsOperation = roles.some((m) => m.operation && !m.registration);\n\n if (pinsRegistration && pinsOperation) {\n const message =\n `Indexer participant hints are internally inconsistent for vault provider ` +\n `${vaultProviderEthAddress}: some roles match the registration keys while ` +\n `others match the rotated operation keys.`;\n // Report before throwing. This state blocks every deposit for the provider\n // and clears only when the indexer converges across all three registries —\n // nothing the user does resolves it, so it has to be observable to us.\n onIndexerHintsInconsistent?.(message);\n throw new Error(`${message} Refresh and try again.`);\n }\n\n if (pinsOperation) {\n onIndexerServingOperationKeys?.(\n `Indexer is serving rotated operation keys for vault provider ${vaultProviderEthAddress}`,\n );\n }\n\n return {\n vaultProviderBtcPubkeyXOnly: operationKeys.vaultProvider,\n vaultKeeperBtcPubkeysSorted: operationKeys.vaultKeepers,\n universalChallengerBtcPubkeysSorted: operationKeys.universalChallengers,\n expectedAppVaultKeepersVersion,\n expectedUniversalChallengersVersion,\n appKeeperKeyEpoch,\n ucKeyEpoch,\n registrationKeys,\n participantKeys,\n };\n}\n","/**\n * Pure validation functions for deposit operations.\n *\n * All validations return a consistent {@link ValidationResult} format or throw\n * on critical failures (e.g. missing protocol participants).\n *\n * Business rules (single-provider limit, max vault count) and form-flow\n * checks (wallet connected) belong in the consumer layer.\n *\n * @module tbv/core/services/deposit/validation\n */\n\nimport {\n formatSatoshisToBtc,\n stripHexPrefix,\n} from \"../../primitives/utils/bitcoin\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface ValidationResult {\n valid: boolean;\n error?: string;\n warnings?: string[];\n}\n\n/**\n * Parameters for checking if a deposit form is valid.\n */\nexport interface DepositFormValidityParams {\n /** Deposit amount in satoshis */\n amountSats: bigint;\n /** Minimum deposit from protocol params */\n minDeposit: bigint;\n /** Maximum deposit from protocol params (optional) */\n maxDeposit?: bigint;\n /** User's available BTC balance in satoshis */\n btcBalance: bigint;\n /** Estimated transaction fee in satoshis */\n estimatedFeeSats?: bigint;\n /** Depositor claim value in satoshis (required output for challenge transactions) */\n depositorClaimValue?: bigint;\n}\n\nexport interface RemainingCapacityParams {\n /** Requested deposit amount in satoshis */\n amount: bigint;\n /**\n * Effective remaining capacity in satoshis (min of protocol-total and\n * per-address remaining). `null` means no cap applies.\n */\n effectiveRemaining: bigint | null;\n}\n\n/** Narrow structural type for UTXO — avoids importing vault-specific types. */\ninterface UtxoLike {\n txid: string;\n vout: number;\n value: number;\n}\n\n/**\n * Parameters for validating multi-vault deposit flow inputs.\n *\n * Callers must resolve any async loading states before calling — the SDK\n * validates resolved data, not React hook state.\n *\n * Form-flow checks (wallet connected, provider selected) are the caller's\n * responsibility and are NOT performed here.\n */\nexport interface MultiVaultDepositFlowInputs {\n vaultAmounts: bigint[];\n confirmedUTXOs: UtxoLike[];\n vaultProviderBtcPubkey: string;\n vaultKeeperBtcPubkeys: string[];\n universalChallengerBtcPubkeys: string[];\n /** Protocol minimum deposit per vault (satoshis) */\n minDeposit: bigint;\n /** Protocol maximum deposit per vault (satoshis) */\n maxDeposit?: bigint;\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\nfunction isValidXOnlyHex(hex: string): boolean {\n return /^[0-9a-fA-F]{64}$/.test(hex);\n}\n\n// ---------------------------------------------------------------------------\n// Validation functions\n// ---------------------------------------------------------------------------\n\n/**\n * Check if deposit amount is within valid range and affordable.\n *\n * Returns false when fees/claim value are not yet known (still loading),\n * and includes them in the balance check once available.\n */\nexport function isDepositAmountValid(\n params: DepositFormValidityParams,\n): boolean {\n const {\n amountSats,\n minDeposit,\n maxDeposit,\n btcBalance,\n estimatedFeeSats,\n depositorClaimValue,\n } = params;\n\n if (amountSats <= 0n) return false;\n if (amountSats < minDeposit) return false;\n if (maxDeposit && maxDeposit > 0n && amountSats > maxDeposit) return false;\n\n if (estimatedFeeSats == null || depositorClaimValue == null) return false;\n\n const totalRequired = amountSats + estimatedFeeSats + depositorClaimValue;\n if (totalRequired > btcBalance) return false;\n\n return true;\n}\n\n/**\n * Validate deposit amount against minimum and maximum constraints.\n */\nexport function validateDepositAmount(\n amount: bigint,\n minDeposit: bigint,\n maxDeposit?: bigint,\n): ValidationResult {\n if (amount <= 0n) {\n return {\n valid: false,\n error: \"Deposit amount must be greater than zero\",\n };\n }\n\n if (amount < minDeposit) {\n return {\n valid: false,\n error: `Minimum deposit is ${formatSatoshisToBtc(minDeposit)} BTC`,\n };\n }\n\n if (maxDeposit && maxDeposit > 0n && amount > maxDeposit) {\n return {\n valid: false,\n error: `Maximum deposit is ${formatSatoshisToBtc(maxDeposit)} BTC`,\n };\n }\n\n return { valid: true };\n}\n\n/**\n * Validate that the requested deposit fits within the effective remaining cap.\n */\nexport function validateRemainingCapacity(\n params: RemainingCapacityParams,\n): ValidationResult {\n const { amount, effectiveRemaining } = params;\n if (effectiveRemaining === null) return { valid: true };\n\n if (effectiveRemaining === 0n) {\n return {\n valid: false,\n error: \"Supply cap reached — deposits temporarily paused\",\n };\n }\n\n if (amount > effectiveRemaining) {\n return {\n valid: false,\n error: `Vault size exceeds remaining capacity (${formatSatoshisToBtc(effectiveRemaining)} BTC)`,\n };\n }\n\n return { valid: true };\n}\n\n/**\n * Validate that selected providers exist in the available set.\n *\n * Business rules (e.g. single-provider limit) are the caller's responsibility.\n */\nexport function validateProviderSelection(\n selectedProviders: string[],\n availableProviders: string[],\n): ValidationResult {\n if (!selectedProviders || selectedProviders.length === 0) {\n return {\n valid: false,\n error: \"At least one vault provider must be selected\",\n };\n }\n\n const availableProvidersLower = availableProviders.map((p) =>\n p.toLowerCase(),\n );\n const invalidProviders = selectedProviders.filter(\n (p) => !availableProvidersLower.includes(p.toLowerCase()),\n );\n\n if (invalidProviders.length > 0) {\n return {\n valid: false,\n error: \"Invalid vault provider selected\",\n };\n }\n\n return { valid: true };\n}\n\n/**\n * Validate vault amounts array for multi-vault deposits.\n * Checks count, positivity, and per-vault min/max protocol limits.\n *\n * Max vault count limits are the caller's responsibility.\n */\nexport function validateVaultAmounts(\n amounts: bigint[],\n minDeposit?: bigint,\n maxDeposit?: bigint,\n): ValidationResult {\n if (!amounts || amounts.length === 0) {\n return {\n valid: false,\n error: \"At least one vault amount required\",\n };\n }\n\n for (let i = 0; i < amounts.length; i++) {\n const amount = amounts[i];\n if (amount <= 0n) {\n return {\n valid: false,\n error: `Vault ${i + 1} amount must be positive`,\n };\n }\n if (minDeposit && amount < minDeposit) {\n return {\n valid: false,\n error: `Vault ${i + 1} amount ${formatSatoshisToBtc(amount)} BTC is below minimum deposit ${formatSatoshisToBtc(minDeposit)} BTC`,\n };\n }\n if (maxDeposit && amount > maxDeposit) {\n return {\n valid: false,\n error: `Vault ${i + 1} amount ${formatSatoshisToBtc(amount)} BTC exceeds maximum deposit ${formatSatoshisToBtc(maxDeposit)} BTC`,\n };\n }\n }\n\n return { valid: true };\n}\n\n/**\n * Validate vault provider BTC public key format.\n */\nexport function validateVaultProviderPubkey(pubkey: string): ValidationResult {\n const stripped = stripHexPrefix(pubkey);\n if (!isValidXOnlyHex(stripped)) {\n return {\n valid: false,\n error:\n \"Invalid pubkey format: must be 64 hex characters (32-byte x-only public key, no 0x prefix)\",\n };\n }\n return { valid: true };\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers for multi-vault validation\n// ---------------------------------------------------------------------------\n\nfunction validateVaultKeepers(vaultKeeperBtcPubkeys: string[]): void {\n if (!vaultKeeperBtcPubkeys || vaultKeeperBtcPubkeys.length === 0) {\n throw new Error(\n \"No vault keepers available. The system requires at least one vault keeper to create a deposit.\",\n );\n }\n}\n\nfunction validateUniversalChallengers(\n universalChallengerBtcPubkeys: string[],\n): void {\n if (\n !universalChallengerBtcPubkeys ||\n universalChallengerBtcPubkeys.length === 0\n ) {\n throw new Error(\n \"No universal challengers available. The system requires at least one universal challenger to create a deposit.\",\n );\n }\n}\n\nfunction validateUTXOState(confirmedUTXOs: UtxoLike[]): void {\n if (confirmedUTXOs.length === 0) {\n throw new Error(\"No spendable UTXOs available\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Multi-vault composite validation\n// ---------------------------------------------------------------------------\n\n/**\n * Validate protocol-level multi-vault deposit inputs.\n * Throws an error if any validation fails.\n *\n * Form-flow checks (wallet connections, provider selection) must be\n * performed by the caller before invoking this function.\n */\nexport function validateMultiVaultDepositInputs(\n params: MultiVaultDepositFlowInputs,\n): void {\n const {\n vaultAmounts,\n confirmedUTXOs,\n vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys,\n minDeposit,\n maxDeposit,\n } = params;\n\n const amountsValidation = validateVaultAmounts(\n vaultAmounts,\n minDeposit,\n maxDeposit,\n );\n if (!amountsValidation.valid) {\n throw new Error(amountsValidation.error);\n }\n\n // Vault provider pubkey\n const pubkeyValidation = validateVaultProviderPubkey(vaultProviderBtcPubkey);\n if (!pubkeyValidation.valid) {\n throw new Error(pubkeyValidation.error);\n }\n\n validateVaultKeepers(vaultKeeperBtcPubkeys);\n validateUniversalChallengers(universalChallengerBtcPubkeys);\n validateUTXOState(confirmedUTXOs);\n}\n","/**\n * RFC-006 read-after-mine verification for a freshly registered vault.\n *\n * A new peg-in is built with each participant's *current* operation key, but\n * the vault does not freeze its key epochs until `submitPeginRequest` executes.\n * An operator rotating in that window would leave the registered vault bonded\n * to keys other than the ones baked into the Bitcoin lock we are about to\n * broadcast — BTC locked into a script no counterparty will presign.\n *\n * So after the registration mines and before the BTC broadcast, re-read the\n * vault's frozen epochs, re-resolve every participant against them, and assert\n * the result is byte-identical to what we built with.\n *\n * Deliberately a sibling of `verifyRegisteredVaultVersions` rather than an\n * extension of it: that function reads `getProtocolInfoBatch` through the\n * shared 13-field ABI and must stay there, while this one needs the extended\n * key-epoch ABI.\n *\n * @module services/deposit/verifyRegisteredParticipantKeys\n */\n\nimport type { Hex } from \"viem\";\n\nimport type {\n OperationKeyReader,\n VaultRegistryReader,\n} from \"../../clients/eth/types\";\nimport { resolveParticipantKeysAtEpochs } from \"../participants/resolveParticipantKeys\";\nimport type { ParticipantKeySet } from \"../participants/types\";\n\n/**\n * Participant operation keys drifted between building the Bitcoin artifacts\n * and the vault freezing its epochs.\n *\n * A *sibling* of `RegisteredVaultVersionMismatchError`, never a subclass, and\n * the distinction is load-bearing. On a version mismatch the orchestrator drops\n * the local pending-pegin record, because the on-chain `prePeginTxHash` is\n * still the authoritative copy of the transaction and a later resume can safely\n * broadcast it from the indexer.\n *\n * Key drift breaks exactly that assumption. The registered hash commits to a\n * transaction whose scripts embed the *pre-rotation* keys, while the vault\n * froze the *post-rotation* epoch — so every counterparty resolves a different\n * funding output and the deposit can never activate. Dropping the record would\n * discard `buildParticipantOperationKeys`, the only thing that lets the resume\n * path re-detect the drift; the next attempt would fall back to the indexer's\n * copy, pass the hash check, and broadcast the very transaction this refused,\n * locking BTC until the refund timelock.\n *\n * So: callers must keep the pending record when they catch this.\n */\nexport class ParticipantKeyDriftError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ParticipantKeyDriftError\";\n }\n}\n\n// `instanceof` alone fails across module boundaries (duplicate SDK copies,\n// test mocks). Fall back to the name field, as the version guard does.\nexport function isParticipantKeyDriftError(\n err: unknown,\n): err is ParticipantKeyDriftError {\n return (\n err instanceof ParticipantKeyDriftError ||\n (err instanceof Error && err.name === \"ParticipantKeyDriftError\")\n );\n}\n\nexport interface VerifyRegisteredParticipantKeysParams {\n vaultRegistryReader: VaultRegistryReader;\n operationKeyReader: OperationKeyReader;\n vaultIds: readonly Hex[];\n /**\n * The exact key set the BTC artifacts were built with. Its `query` supplies\n * the rosters to re-resolve against — deliberately reused rather than\n * accepted as a separate argument, so the two can never disagree and a\n * roster that moved since the build cannot be misreported as a key drift.\n */\n expected: ParticipantKeySet;\n}\n\nfunction diffKeys(\n label: string,\n expected: readonly string[],\n actual: readonly string[],\n): string | null {\n if (\n expected.length === actual.length &&\n expected.every((k, i) => k === actual[i])\n ) {\n return null;\n }\n return `${label} expected [${expected.join(\", \")}], got [${actual.join(\", \")}]`;\n}\n\nexport async function verifyRegisteredParticipantKeys(\n params: VerifyRegisteredParticipantKeysParams,\n): Promise<void> {\n const { vaultRegistryReader, operationKeyReader, vaultIds, expected } =\n params;\n const query = expected.query;\n\n if (vaultIds.length === 0) return;\n\n // Batch registration gives every sibling vault the same epochs, so these\n // reads are redundant across siblings. Kept per-vault anyway: it is one\n // multicall, and asserting each vault individually is what makes the error\n // name the vault that drifted.\n const epochsPerVault =\n await vaultRegistryReader.getVaultKeyEpochsBatch(vaultIds);\n\n const mismatches: string[] = [];\n\n for (const [i, epochs] of epochsPerVault.entries()) {\n const vaultId = vaultIds[i];\n\n let resolved: ParticipantKeySet;\n try {\n resolved = await resolveParticipantKeysAtEpochs({\n operationKeyReader,\n query,\n epochs,\n });\n } catch (error) {\n // A resolution failure here is itself a mismatch signal: the frozen\n // epochs point at a key set we cannot reconstruct, so broadcasting\n // would be worse than aborting.\n mismatches.push(\n `vault ${vaultId}: could not resolve participants at frozen epochs ` +\n `(vp=${epochs.vpKeyEpoch}, keeper=${epochs.appKeeperKeyEpoch}, ` +\n `uc=${epochs.ucKeyEpoch}): ${(error as Error).message}`,\n );\n continue;\n }\n\n if (\n resolved.vaultProvider.operationBtcPubkey !==\n expected.vaultProvider.operationBtcPubkey\n ) {\n mismatches.push(\n `vault ${vaultId}: vault provider key expected ` +\n `${expected.vaultProvider.operationBtcPubkey}, got ` +\n `${resolved.vaultProvider.operationBtcPubkey}`,\n );\n }\n\n const keeperDiff = diffKeys(\n `vault ${vaultId}: vault keeper keys`,\n expected.vaultKeeperOperationKeysSorted,\n resolved.vaultKeeperOperationKeysSorted,\n );\n if (keeperDiff) mismatches.push(keeperDiff);\n\n const challengerDiff = diffKeys(\n `vault ${vaultId}: universal challenger keys`,\n expected.universalChallengerOperationKeysSorted,\n resolved.universalChallengerOperationKeysSorted,\n );\n if (challengerDiff) mismatches.push(challengerDiff);\n }\n\n if (mismatches.length > 0) {\n throw new ParticipantKeyDriftError(\n `Aborting BTC broadcast: participant operation keys changed during registration ` +\n `(${mismatches.join(\"; \")}). The Pre-PegIn was not broadcast; the registered ` +\n `ETH vault will time out per protocol rules.`,\n );\n }\n}\n","import type { Hex } from \"viem\";\n\nimport type { VaultRegistryReader } from \"../../clients/eth/types\";\n\nexport interface VerifyRegisteredVaultVersionsParams {\n vaultRegistryReader: VaultRegistryReader;\n vaultIds: readonly Hex[];\n expectedOffchainParamsVersion: number;\n expectedAppVaultKeepersVersion: number;\n expectedUniversalChallengersVersion: number;\n /**\n * Vault core (tx-graph) version the BTC artifacts were BUILT with. The\n * contract stamps `activeVaultCoreVersion` at registration-tx execution\n * time, so a governance flip between build and registration stamps a\n * different graph than the one the depositor signed — broadcasting would\n * lock BTC into a graph no resume path can rebuild.\n */\n expectedVaultCoreVersion: number;\n}\n\n// Distinct from a transient RPC failure: the orchestrator removes pending\n// pegin entries only when a real mismatch is confirmed on-chain.\nexport class RegisteredVaultVersionMismatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RegisteredVaultVersionMismatchError\";\n }\n}\n\n// `instanceof` alone fails across module boundaries (duplicate SDK copies,\n// test mocks). Fall back to the name field so the cleanup path stays reliable.\nexport function isRegisteredVaultVersionMismatchError(\n err: unknown,\n): err is RegisteredVaultVersionMismatchError {\n return (\n err instanceof RegisteredVaultVersionMismatchError ||\n (err instanceof Error && err.name === \"RegisteredVaultVersionMismatchError\")\n );\n}\n\nexport async function verifyRegisteredVaultVersions(\n params: VerifyRegisteredVaultVersionsParams,\n): Promise<void> {\n const {\n vaultRegistryReader,\n vaultIds,\n expectedOffchainParamsVersion,\n expectedAppVaultKeepersVersion,\n expectedUniversalChallengersVersion,\n expectedVaultCoreVersion,\n } = params;\n\n const infos = await vaultRegistryReader.getProtocolInfoBatch(vaultIds);\n\n const mismatches: string[] = [];\n infos.forEach((v, i) => {\n const id = vaultIds[i];\n if (v.offchainParamsVersion !== expectedOffchainParamsVersion) {\n mismatches.push(\n `vault ${id}: offchainParams expected v${expectedOffchainParamsVersion}, got v${v.offchainParamsVersion}`,\n );\n }\n if (v.appVaultKeepersVersion !== expectedAppVaultKeepersVersion) {\n mismatches.push(\n `vault ${id}: appVaultKeepers expected v${expectedAppVaultKeepersVersion}, got v${v.appVaultKeepersVersion}`,\n );\n }\n if (v.universalChallengersVersion !== expectedUniversalChallengersVersion) {\n mismatches.push(\n `vault ${id}: universalChallengers expected v${expectedUniversalChallengersVersion}, got v${v.universalChallengersVersion}`,\n );\n }\n if (v.vaultCoreVersion !== expectedVaultCoreVersion) {\n mismatches.push(\n `vault ${id}: vaultCoreVersion expected v${expectedVaultCoreVersion} (build-time active), got v${v.vaultCoreVersion}`,\n );\n }\n });\n\n if (mismatches.length > 0) {\n throw new RegisteredVaultVersionMismatchError(\n `Aborting BTC broadcast: signer-set or offchain-params versions changed during registration (${mismatches.join(\"; \")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`,\n );\n }\n}\n","/**\n * Domain errors thrown by the refund service.\n *\n * @module services/refund/errors\n */\n\nimport type { Hex } from \"viem\";\n\n/**\n * Thrown when the broadcast transport rejects the refund tx because the CSV\n * timelock has not yet matured (BIP68 non-final). Callers can surface a\n * friendly \"wait until block N\" message; the original transport error is\n * available via {@link cause}.\n */\nexport class BIP68NotMatureError extends Error {\n public readonly vaultId: Hex;\n public override readonly cause: Error;\n\n constructor(vaultId: Hex, cause: Error) {\n super(`Refund not yet mature (BIP68 not final): ${cause.message}`);\n this.name = \"BIP68NotMatureError\";\n this.vaultId = vaultId;\n this.cause = cause;\n }\n}\n","/**\n * Vault refund orchestration — reclaim BTC from an expired Pre-PegIn HTLC via\n * the CSV-timelocked refund script (leaf 1). SDK owns the sequence of:\n * fetch → fee calc → PSBT build → sign → finalize → broadcast. Pre-fetched\n * data (fee rate) is passed by value; the data-flow-dependent reads\n * (`readVault`, `readPrePeginContext(vault)`) and the interactive transports\n * (`signPsbt`, `broadcastTx`) stay as injected callbacks so the caller keeps\n * its transport choice (viem, wagmi, mempool client, etc.) and error decoding.\n *\n * @module services/refund\n */\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Transaction } from \"bitcoinjs-lib\";\nimport type { Address, Hex } from \"viem\";\n\nimport type { SignPsbtOptions } from \"../../../../shared/wallets/interfaces/BitcoinWallet\";\nimport { findAuthAnchorOpReturn } from \"../../managers/pegin\";\nimport { assertPsbtUnsignedTxMatches } from \"../../primitives/psbt/assertPsbtUnsignedTxMatches\";\nimport { finalizeScriptPathWithSignatures } from \"../../primitives/psbt/finalizeScriptPathWithSignatures\";\nimport { extractPayoutSignature } from \"../../primitives/psbt/payout\";\nimport { buildRefundPsbt } from \"../../primitives/psbt/refund\";\nimport { assertScriptPathSchnorrSignature } from \"../../primitives/psbt/verifyScriptPathSchnorrSignature\";\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\nimport {\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../../primitives/utils/bitcoin\";\nimport { createTaprootScriptPathSignOptions } from \"../../utils/signing\";\n\nimport { BIP68NotMatureError } from \"./errors\";\n\nconst BYTES32_HEX_RE = /^0x[0-9a-fA-F]{64}$/;\n// BTC raw-hex convention: 0x prefix optional, even number of hex chars, must\n// be non-empty. Named distinctly from the ETH-hex regex in activateVault.ts\n// (which requires a 0x prefix and allows empty \"0x\") to make the convention\n// explicit at the call site.\nconst BTC_HEX_BYTES_RE = /^(?:0x)?(?:[0-9a-fA-F]{2})+$/;\n// Pubkeys are either 32 bytes (x-only, 64 hex chars) or 33 bytes (compressed,\n// 66 hex chars). 65 hex chars is not a valid byte length — reject it here\n// rather than letting the malformed value surface as an opaque PSBT/signing\n// failure later.\nconst PUBKEY_HEX_RE = /^(?:0x)?(?:[0-9a-fA-F]{64}|[0-9a-fA-F]{66})$/;\n// Conservative upper bound for the fixed-shape refund tx (1 P2TR script-path\n// input spending the HTLC refund leaf → 1 P2TR/P2WPKH output). Taproot\n// script-path witness: 64-byte Schnorr sig + refund script + control block.\n// This is protocol-owned knowledge; callers don't parameterise it.\nexport const REFUND_VSIZE = 160;\n\n// Hard upper bound on the per-vbyte fee rate the SDK will sign a refund at.\n// Defense-in-depth: a compromised mempool endpoint can legally return up to\n// 10_000 sat/vB (see mempoolApi.ts `MAX_FEE_RATE`), which on a 160-vbyte\n// refund would burn up to 1.6M sats in miner fees.\n//\n// Sizing: during the April 2024 halving / Runes launch `fastestFee` peaked\n// around 1,800 sat/vB, and `halfHourFee` tracked close to it during the\n// worst of the congestion (~1,000–1,500 sat/vB range — the half-hour\n// bucket converges with the fastest bucket when the queue is deep enough).\n// 2000 leaves ~1.3× margin over that historical extreme so the cap doesn't\n// gate legitimate refunds during a comparable event, while still blocking\n// the obvious malicious case (10_000) by 5×. Small-vault burn is bounded\n// separately by REFUND_MAX_FEE_FRACTION_* below, so the rate cap is free\n// to be set generously here.\nexport const REFUND_MAX_FEE_RATE_SATS_VB = 2000;\n\n// Hard upper bound on the absolute refund fee as a fraction of the vault\n// amount. Protects small vaults where even a moderate fee rate burns a\n// disproportionate share (e.g. on a 100k-sat vault, 500 sat/vB would burn\n// 80%). The fraction cap binds before the rate cap whenever the vault is\n// small. Expressed as numerator/denominator to keep arithmetic in bigint\n// and avoid float-precision drift in the comparison.\nexport const REFUND_MAX_FEE_FRACTION_NUMERATOR = 10n;\nexport const REFUND_MAX_FEE_FRACTION_DENOMINATOR = 100n;\n\n/**\n * Network fee (sats) the SDK will charge for a refund tx at the given\n * sat/vB rate. Mirrors the internal computation in\n * {@link buildAndBroadcastRefund} so callers (e.g. UI fee previews) don't\n * have to duplicate the constant.\n */\nexport function estimateRefundFeeSats(feeRateSatsVb: number): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `feeRateSatsVb must be a positive finite number, got ${feeRateSatsVb}`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * REFUND_VSIZE));\n}\n// Refund tx has exactly one input — the HTLC output at htlcVout from the\n// Pre-PegIn tx. Used to tell the signer how many sign entries to generate.\n// (Not the taproot leaf index; the leaf is encoded into the PSBT by the\n// WASM PSBT builder based on the refund script path.)\nconst REFUND_INPUT_COUNT = 1;\nconst BIP68_ERROR_RE = /non-BIP68-final/i;\n\nfunction assertBytes32(value: string, label: string): void {\n if (value.length !== 66) {\n throw new Error(\n `${label} must be 32 bytes (66 hex chars with 0x prefix), got length ${value.length}`,\n );\n }\n if (!BYTES32_HEX_RE.test(value)) {\n throw new Error(\n `${label} must contain only hex characters after the 0x prefix`,\n );\n }\n}\n\n/**\n * One vault's per-HTLC binding in a Pre-PegIn batch. Carries the fields\n * needed to reconstruct the WASM `WasmPrePeginTx` template byte-for-byte\n * against the funded transaction.\n */\nexport interface VaultBatchEntry {\n /** SHA-256 hashlock commitment for this vault (bytes32, 0x-prefixed). */\n hashlock: Hex;\n /**\n * Vault deposit (peg-in) amount in satoshis — the on-chain contract's\n * `amount` field. This is the peg-in amount WASM expects in `pegInAmounts`,\n * NOT the funded HTLC output value (which is `amount + depositorClaimValue +\n * minPeginFee`). WASM re-adds that reserve internally when it sizes the HTLC\n * output, so this value is passed straight through.\n */\n amount: bigint;\n /** Index of this vault's HTLC output in the funded Pre-PegIn tx. */\n htlcVout: number;\n}\n\n/**\n * Authoritative vault fields needed to build a refund. Versioning fields,\n * the hashlock, and htlcVout must come from the on-chain contract (never the\n * indexer). The amount + `unsignedPrePeginTxHex` + `depositorBtcPubkey` can\n * come from the indexer since they are not security-critical for signing\n * (the PSBT builder re-derives the HTLC script from on-chain params).\n *\n * `batch` is the full, vout-ordered HTLC vector for the Pre-PegIn (one\n * entry per sibling vault that shares this funded transaction). For a\n * single-vault deposit this is a length-1 array. For batched deposits\n * (e.g. the Aave split) the orchestrator passes every sibling through\n * so the WASM template matches the funded tx's shape.\n */\nexport interface VaultRefundData {\n /**\n * Vault core (tx-graph) version stamped on-chain at registration\n * (`BTCVaultProtocolInfo.vaultCoreVersion`). The refund template must be\n * reconstructed under the same graph version the Pre-PegIn was built with.\n */\n vaultCoreVersion: number;\n hashlock: Hex;\n htlcVout: number;\n offchainParamsVersion: number;\n appVaultKeepersVersion: number;\n universalChallengersVersion: number;\n vaultProvider: Address;\n applicationEntryPoint: Address;\n /** Vault deposit (peg-in) amount in satoshis — the on-chain `amount` field. */\n amount: bigint;\n /**\n * Funded, pre-witness Pre-PegIn transaction hex. 0x prefix optional.\n * The name mirrors the contract/indexer schema; the bytes are the\n * funded form (refund construction needs real outpoints).\n */\n unsignedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only or compressed hex; 0x prefix optional). */\n depositorBtcPubkey: string;\n /**\n * Full vout-ordered HTLC vector for the funded Pre-PegIn (one entry\n * per sibling vault, including the target vault). Must satisfy\n * `batch[i].htlcVout === i` for all i, and the target's `htlcVout` /\n * `hashlock` / `amount` must equal `batch[vault.htlcVout]`.\n */\n batch: ReadonlyArray<VaultBatchEntry>;\n}\n\n/**\n * Version-resolved protocol context that parameterises the HTLC's taproot\n * scripts. The *signer-set* fields (`vaultKeeperPubkeys`,\n * `universalChallengerPubkeys`) and the version-locked numeric protocol\n * params **must** be sourced from the on-chain contract at the version\n * pinned in {@link VaultRefundData} — this is the trust boundary.\n * `vaultProviderPubkey` today is sourced from the GraphQL indexer via\n * `fetchVaultProviderById`; the caller is responsible for any additional\n * cross-check it requires. Keeper and challenger pubkey arrays must be\n * pre-sorted the same way the Rust protocol sorts them (canonical for\n * script derivation).\n */\nexport interface RefundPrePeginContext {\n vaultProviderPubkey: string;\n vaultKeeperPubkeys: readonly string[];\n universalChallengerPubkeys: readonly string[];\n timelockRefund: number;\n feeRate: bigint;\n minPeginFeeRate: bigint;\n numLocalChallengers: number;\n councilQuorum: number;\n councilSize: number;\n network: Network;\n}\n\n/** Minimum shape required from a broadcast result. */\nexport interface BtcBroadcastResult {\n txId: string;\n}\n\nexport type BtcBroadcaster<R extends BtcBroadcastResult = BtcBroadcastResult> =\n (signedTxHex: string) => Promise<R>;\n\nexport type RefundPsbtSigner = (\n psbtHex: string,\n opts: SignPsbtOptions,\n) => Promise<string>;\n\nexport interface RefundInput<\n R extends BtcBroadcastResult = BtcBroadcastResult,\n> {\n vaultId: Hex;\n /**\n * Fetch authoritative on-chain + indexer vault data. The SDK passes no\n * arguments — the caller closes over `vaultId` (or any other context it\n * needs).\n */\n readVault: () => Promise<VaultRefundData>;\n /**\n * Fetch the version-pinned refund context (sorted pubkeys, timelock, etc.)\n * derived from the vault's locked versions.\n */\n readPrePeginContext: (\n vault: VaultRefundData,\n ) => Promise<RefundPrePeginContext>;\n /**\n * Mempool-derived sat/vB fee rate to use for the refund tx (positive\n * number). Caller fetches this before invoking — it does not depend on\n * any value the SDK computes, and folding it into the call keeps the\n * orchestration honest.\n */\n feeRate: number;\n /** BTC wallet signer; receives a PSBT hex + taproot script-path options. */\n signPsbt: RefundPsbtSigner;\n /** Broadcast callback — returns whatever shape the caller needs. */\n broadcastTx: BtcBroadcaster<R>;\n /** Checked at every async boundary. */\n signal?: AbortSignal;\n}\n\nfunction assertNonNegativeInteger(value: number, label: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(`${label} must be a non-negative integer, got ${value}`);\n }\n}\n\nfunction validateVaultRefundData(v: VaultRefundData): void {\n assertBytes32(v.hashlock, \"hashlock\");\n if (!Number.isInteger(v.htlcVout) || v.htlcVout < 0) {\n throw new Error(\n `htlcVout must be a non-negative integer, got ${v.htlcVout}`,\n );\n }\n // Batch shape — one entry per sibling HTLC, vout-ordered and\n // contiguous from 0. The reconstructed WASM template uses these\n // arrays directly: any gap, duplicate, or mis-ordering against the\n // funded tx would produce an unspendable refund. The target's\n // (hashlock, amount, htlcVout) must equal the corresponding batch\n // entry so the orchestrator and the caller can't disagree about\n // which output is being refunded.\n if (!Array.isArray(v.batch) || v.batch.length === 0) {\n throw new Error(\"batch must be a non-empty array of HTLC entries\");\n }\n if (v.htlcVout >= v.batch.length) {\n throw new Error(\n `htlcVout ${v.htlcVout} is out of range for batch of size ${v.batch.length}`,\n );\n }\n for (let i = 0; i < v.batch.length; i++) {\n const entry = v.batch[i];\n assertBytes32(entry.hashlock, `batch[${i}].hashlock`);\n if (!Number.isInteger(entry.htlcVout) || entry.htlcVout !== i) {\n throw new Error(\n `batch[${i}].htlcVout must equal ${i} (contiguous vout-ordered vector), got ${entry.htlcVout}`,\n );\n }\n if (typeof entry.amount !== \"bigint\" || entry.amount <= 0n) {\n throw new Error(\n `batch[${i}].amount must be a positive bigint, got ${entry.amount}`,\n );\n }\n }\n const targetEntry = v.batch[v.htlcVout];\n if (targetEntry.hashlock.toLowerCase() !== v.hashlock.toLowerCase()) {\n throw new Error(\n `batch[${v.htlcVout}].hashlock (${targetEntry.hashlock}) does not match target hashlock (${v.hashlock})`,\n );\n }\n if (targetEntry.amount !== v.amount) {\n throw new Error(\n `batch[${v.htlcVout}].amount (${targetEntry.amount}) does not match target amount (${v.amount})`,\n );\n }\n // Version fields flow directly into on-chain script derivation via\n // `readPrePeginContext` — NaN, negative, or non-integer values would\n // silently produce wrong scripts. Guard here as defence in depth even\n // though the caller sources these from bigint on-chain reads.\n assertNonNegativeInteger(v.offchainParamsVersion, \"offchainParamsVersion\");\n assertNonNegativeInteger(v.appVaultKeepersVersion, \"appVaultKeepersVersion\");\n assertNonNegativeInteger(\n v.universalChallengersVersion,\n \"universalChallengersVersion\",\n );\n assertValidVaultCoreVersion(\n v.vaultCoreVersion,\n \"VaultRefundData.vaultCoreVersion\",\n );\n if (\n typeof v.unsignedPrePeginTxHex !== \"string\" ||\n v.unsignedPrePeginTxHex.length === 0\n ) {\n throw new Error(\"unsignedPrePeginTxHex must be a non-empty hex string\");\n }\n if (!BTC_HEX_BYTES_RE.test(v.unsignedPrePeginTxHex)) {\n throw new Error(\n \"unsignedPrePeginTxHex must be a hex byte string (optional 0x prefix, even length)\",\n );\n }\n if (!v.depositorBtcPubkey || !PUBKEY_HEX_RE.test(v.depositorBtcPubkey)) {\n throw new Error(\n \"depositorBtcPubkey must be 32 or 33 bytes of hex (optional 0x prefix)\",\n );\n }\n if (typeof v.amount !== \"bigint\" || v.amount <= 0n) {\n throw new Error(`amount must be a positive bigint, got ${v.amount}`);\n }\n}\n\nfunction validateRefundPrePeginContext(c: RefundPrePeginContext): void {\n if (!c.vaultProviderPubkey || !PUBKEY_HEX_RE.test(c.vaultProviderPubkey)) {\n throw new Error(\"vaultProviderPubkey must be 32 or 33 bytes of hex\");\n }\n if (c.vaultKeeperPubkeys.length === 0) {\n throw new Error(\"vaultKeeperPubkeys must be non-empty\");\n }\n if (c.universalChallengerPubkeys.length === 0) {\n throw new Error(\"universalChallengerPubkeys must be non-empty\");\n }\n if (!Number.isInteger(c.timelockRefund) || c.timelockRefund <= 0) {\n throw new Error(\n `timelockRefund must be a positive integer, got ${c.timelockRefund}`,\n );\n }\n if (typeof c.feeRate !== \"bigint\" || c.feeRate <= 0n) {\n throw new Error(\n `protocol feeRate must be a positive bigint, got ${c.feeRate}`,\n );\n }\n if (typeof c.minPeginFeeRate !== \"bigint\" || c.minPeginFeeRate <= 0n) {\n throw new Error(\n `minPeginFeeRate must be a positive bigint, got ${c.minPeginFeeRate}`,\n );\n }\n if (!Number.isInteger(c.numLocalChallengers) || c.numLocalChallengers < 0) {\n throw new Error(\"numLocalChallengers must be a non-negative integer\");\n }\n if (\n !Number.isInteger(c.councilQuorum) ||\n !Number.isInteger(c.councilSize) ||\n c.councilQuorum <= 0 ||\n c.councilSize <= 0 ||\n c.councilQuorum > c.councilSize\n ) {\n throw new Error(\n `councilQuorum (${c.councilQuorum}) must be in [1, councilSize=${c.councilSize}]`,\n );\n }\n}\n\n/**\n * Build, sign, and broadcast a refund transaction for an expired vault.\n *\n * Trust boundary: `readVault` must source the hashlock, htlcVout, and\n * versioning fields from the on-chain contract — an indexer-only path\n * leaves the refund flow open to signer-set substitution. The SDK does\n * not enforce this; it is the caller's responsibility.\n *\n * The broadcast transport is expected to surface Bitcoin's `non-BIP68-final`\n * policy rejection as an `Error` whose message contains that string; when\n * it does, the SDK wraps it in {@link BIP68NotMatureError}. All other\n * transport errors propagate unchanged.\n *\n * @returns whatever the injected `broadcastTx` returns (generic pass-through)\n * @throws `Error` if any validation fails\n * @throws {@link BIP68NotMatureError} if the broadcast is rejected because\n * the refund CSV timelock has not yet matured\n * @throws anything `readVault`, `readPrePeginContext`,\n * `signPsbt`, or `broadcastTx` throws\n */\nexport async function buildAndBroadcastRefund<\n R extends BtcBroadcastResult = BtcBroadcastResult,\n>(input: RefundInput<R>): Promise<R> {\n const {\n vaultId,\n readVault,\n readPrePeginContext,\n feeRate,\n signPsbt,\n broadcastTx,\n signal,\n } = input;\n\n signal?.throwIfAborted();\n assertBytes32(vaultId, \"vaultId\");\n\n const vault = await readVault();\n validateVaultRefundData(vault);\n signal?.throwIfAborted();\n\n const ctx = await readPrePeginContext(vault);\n validateRefundPrePeginContext(ctx);\n signal?.throwIfAborted();\n\n if (!Number.isFinite(feeRate) || feeRate <= 0) {\n throw new Error(`feeRate must be a positive number, got ${feeRate}`);\n }\n // Rate cap: fail closed before PSBT construction if the seeded value\n // exceeds the safety ceiling. A compromised mempool API (or upstream\n // proxy / BGP hijack) can otherwise drive `halfHourFee` to the API's\n // 10_000 sat/vB ceiling and burn the refund as miner fee.\n if (feeRate > REFUND_MAX_FEE_RATE_SATS_VB) {\n throw new Error(\n `feeRate ${feeRate} sat/vB exceeds refund safety cap ` +\n `${REFUND_MAX_FEE_RATE_SATS_VB} sat/vB; refusing to sign refund.`,\n );\n }\n const refundFee = BigInt(Math.ceil(feeRate * REFUND_VSIZE));\n // Fraction cap: even within the rate ceiling, refuse to sign if the\n // absolute fee would consume more than the configured percentage of the\n // vault amount. Protects small vaults from disproportionate burn.\n const maxFeeByFraction =\n (vault.amount * REFUND_MAX_FEE_FRACTION_NUMERATOR) /\n REFUND_MAX_FEE_FRACTION_DENOMINATOR;\n if (refundFee > maxFeeByFraction) {\n throw new Error(\n `Refund fee ${refundFee} sats exceeds the per-vault safety cap ` +\n `of ${maxFeeByFraction} sats ` +\n `(${REFUND_MAX_FEE_FRACTION_NUMERATOR}/${REFUND_MAX_FEE_FRACTION_DENOMINATOR} ` +\n `of vault.amount=${vault.amount}); refusing to sign refund.`,\n );\n }\n signal?.throwIfAborted();\n\n // `vault.depositorBtcPubkey` may arrive as wallet-native compressed sec1\n // (33 bytes) because the caller fetches it live from the wallet for\n // signing. WASM script derivation wants x-only (32 bytes), so normalize\n // here; the raw form is kept for the wallet sign call below.\n const xOnlyDepositorPubkey = processPublicKeyToXOnly(\n vault.depositorBtcPubkey,\n );\n\n const cleanFundedPrePeginTxHex = stripHexPrefix(vault.unsignedPrePeginTxHex);\n\n // Production peg-ins (PeginManager) commit an OP_RETURN <PUSH32\n // SHA256(authAnchor)> output at `vout = hashlocks.length`. The\n // reconstructed unfunded template carries `batch.length` HTLC outputs,\n // so the OP_RETURN — when present — must sit at exactly that vout.\n // Legacy non-auth-anchored Pre-PegIns return `undefined` from the\n // finder; the template then has no OP_RETURN either, which is a\n // matching configuration.\n const found = findAuthAnchorOpReturn(cleanFundedPrePeginTxHex);\n if (found !== undefined && found.vout !== vault.batch.length) {\n throw new Error(\n `Auth-anchor OP_RETURN at vout ${found.vout} does not match batch size ` +\n `(${vault.batch.length} HTLC outputs expect the anchor at vout ${vault.batch.length}). ` +\n `Refund refused — sibling HTLC vector is incomplete.`,\n );\n }\n const authAnchorHash = found?.hash;\n\n // Independent structural check on the funded tx: it must carry at\n // least N HTLC outputs (one per batch entry). If the anchor is\n // present we've already pinned its position above, which transitively\n // proves the tx has ≥ N+1 outputs; if the anchor is absent (legacy)\n // we still need ≥ N to spend `htlcVout = N-1`.\n let parsedFundedTx: Transaction;\n try {\n parsedFundedTx = Transaction.fromHex(cleanFundedPrePeginTxHex);\n } catch (e) {\n throw new Error(\n `Failed to parse funded Pre-PegIn transaction hex: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n if (parsedFundedTx.outs.length < vault.batch.length) {\n throw new Error(\n `Funded Pre-PegIn tx has ${parsedFundedTx.outs.length} outputs but batch ` +\n `requires at least ${vault.batch.length} HTLC outputs. ` +\n `Refund refused — funded tx shape disagrees with sibling vector.`,\n );\n }\n\n const { psbtHex } = await buildRefundPsbt({\n prePeginParams: {\n vaultCoreVersion: vault.vaultCoreVersion,\n depositorPubkey: xOnlyDepositorPubkey,\n vaultProviderPubkey: stripHexPrefix(ctx.vaultProviderPubkey),\n vaultKeeperPubkeys: ctx.vaultKeeperPubkeys.map(stripHexPrefix),\n universalChallengerPubkeys:\n ctx.universalChallengerPubkeys.map(stripHexPrefix),\n hashlocks: vault.batch.map((b) => stripHexPrefix(b.hashlock)),\n timelockRefund: ctx.timelockRefund,\n // `batch[i].amount` is the on-chain vault deposit (peg-in) amount, which\n // is exactly what WASM's `pegInAmounts` expects — it re-adds the protocol\n // reserve (`depositorClaimValue + minPeginFee`) internally when sizing the\n // HTLC output. `buildRefundPsbt`'s value cross-check then binds the result\n // to the funded tx bytes, refusing the refund if the template's HTLC value\n // disagrees with the on-chain commitment.\n pegInAmounts: vault.batch.map((b) => b.amount),\n feeRate: ctx.feeRate,\n minPeginFeeRate: ctx.minPeginFeeRate,\n numLocalChallengers: ctx.numLocalChallengers,\n councilQuorum: ctx.councilQuorum,\n councilSize: ctx.councilSize,\n network: ctx.network,\n authAnchorHash,\n },\n fundedPrePeginTxHex: cleanFundedPrePeginTxHex,\n htlcVout: vault.htlcVout,\n refundFee,\n // buildRefundPsbt's top-level `hashlock` param is documented as \"no 0x\n // prefix\" and flows into the WASM HTLC connector derivation; a prefixed\n // value would derive the wrong refund script leaf and yield an\n // unspendable PSBT. Match the `hashlocks` array handling above.\n hashlock: stripHexPrefix(vault.hashlock),\n });\n signal?.throwIfAborted();\n\n const signOptions = createTaprootScriptPathSignOptions(\n vault.depositorBtcPubkey,\n REFUND_INPUT_COUNT,\n );\n const signedPsbtHex = await signPsbt(psbtHex, signOptions);\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // Critical Path #7: verify the depositor's script-path signature against a\n // sighash recomputed from the PSBT we built before finalizing and broadcasting.\n // The refund spends a single input (the HTLC output) on input 0.\n const REFUND_SIGNED_INPUT_INDEX = 0;\n const refundSignature = extractPayoutSignature(\n signedPsbtHex,\n xOnlyDepositorPubkey,\n REFUND_SIGNED_INPUT_INDEX,\n );\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtHex,\n signatureHex: refundSignature,\n signerXOnlyPubkeyHex: xOnlyDepositorPubkey,\n inputIndex: REFUND_SIGNED_INPUT_INDEX,\n });\n\n // Finalize the PSBT we built, not the one the wallet returned: only the\n // verified signature above crosses over. See the primitive's header for what\n // finalizing the wallet's copy would let through.\n const signedTxHex = finalizeScriptPathWithSignatures({\n requestedPsbtHex: psbtHex,\n signaturesHex: [refundSignature],\n signerXOnlyPubkeyHex: xOnlyDepositorPubkey,\n });\n signal?.throwIfAborted();\n\n try {\n return await broadcastTx(signedTxHex);\n } catch (error) {\n if (error instanceof Error && BIP68_ERROR_RE.test(error.message)) {\n throw new BIP68NotMatureError(vaultId, error);\n }\n throw error;\n }\n}\n","/**\n * Domain errors thrown by the reclaim service.\n *\n * @module services/reclaim/errors\n */\n\n/**\n * Thrown when the fee would consume too much of the swept reserve — either the\n * per-vbyte rate exceeds the safety ceiling, or the absolute fee exceeds the\n * fraction cap.\n *\n * Distinct from a generic error because the caller's response differs: nothing\n * is at risk and nothing expires. The reserve simply stays where it is until\n * fee rates fall, and the UI should say so rather than presenting a failure.\n */\nexport class ReclaimUneconomicalError extends Error {\n /** Fee the reclaim would have paid, in satoshis. */\n public readonly feeSats: bigint;\n /** Sum of the reserves the reclaim would have swept, in satoshis. */\n public readonly sweptTotalSats: bigint;\n\n constructor(message: string, feeSats: bigint, sweptTotalSats: bigint) {\n super(message);\n this.name = \"ReclaimUneconomicalError\";\n this.feeSats = feeSats;\n this.sweptTotalSats = sweptTotalSats;\n }\n}\n","/**\n * Reclaim orchestration — sweep the depositor-claim reserve (PegIn vout 1)\n * back to the depositor after their vault has terminally settled.\n *\n * The SDK owns the sequence: read → vault-id bind → fee caps → PSBT build →\n * sign → verify → finalize → broadcast. Interactive transports (`signPsbt`,\n * `broadcastTx`) and the data read stay as injected callbacks, so the caller\n * keeps its transport choice and error decoding. Mirrors\n * `services/refund/buildAndBroadcastRefund`.\n *\n * > **Eligibility is the caller's job, and it is a safety control.** The claim\n * > leaf carries no timelock, so this service will sweep a reserve whose vault\n * > is still live. Doing that permanently voids the depositor's pre-signed\n * > recourse graph: their `claim_tx` hard-codes `OutPoint(peginTxid, 1)` as its\n * > only input, and every downstream Assert / Payout / NoPayout signature\n * > commits to that tx's txid. There is no re-funding path. The caller must\n * > confirm the vault's Payout has landed — PegIn vout 0 spent and deeply\n * > confirmed — before calling this.\n *\n * @module services/reclaim\n */\n\nimport type { Address, Hex } from \"viem\";\n\nimport type { SignPsbtOptions } from \"../../../../shared/wallets/interfaces/BitcoinWallet\";\nimport { assertPsbtUnsignedTxMatches } from \"../../primitives/psbt/assertPsbtUnsignedTxMatches\";\nimport { finalizeScriptPathWithSignatures } from \"../../primitives/psbt/finalizeScriptPathWithSignatures\";\nimport { extractPayoutSignature } from \"../../primitives/psbt/payout\";\nimport {\n buildReclaimPsbt,\n estimateReclaimFeeSats,\n type ReclaimReserve,\n} from \"../../primitives/psbt/reclaim\";\nimport { assertScriptPathSchnorrSignature } from \"../../primitives/psbt/verifyScriptPathSchnorrSignature\";\nimport {\n ensureHexPrefix,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../../primitives/utils/bitcoin\";\nimport { createTaprootScriptPathSignOptions } from \"../../utils/signing\";\nimport { deriveVaultId } from \"../../wasm\";\nimport { calculateBtcTxHash } from \"../../utils/transaction/btcTxHash\";\n// The BTC broadcast transport types are shared with the refund service rather\n// than redeclared — `services/index.ts` re-exports both modules flat, so a\n// second declaration would collide on the barrel.\nimport type {\n BtcBroadcastResult,\n BtcBroadcaster,\n} from \"../refund/buildAndBroadcastRefund\";\n\nimport { ReclaimUneconomicalError } from \"./errors\";\n\n/**\n * Hard upper bound on the per-vbyte fee rate the SDK will sign a reclaim at.\n * Same reasoning and value as the refund's cap: a compromised mempool endpoint\n * can legally return up to 10,000 sat/vB, and 2000 leaves margin over the\n * worst historical `halfHourFee` while still blocking that by 5×.\n */\nexport const RECLAIM_MAX_FEE_RATE_SATS_VB = 2000;\n\n/**\n * Hard upper bound on the absolute fee as a fraction of the **swept total**.\n *\n * > ⚠️ The basis here is deliberately different from the refund's. There the\n * > basis is `vault.amount` and the swept amount is far larger, so a 10% cap is\n * > generous. Here the basis *is* the swept amount — roughly 33k sats — and a\n * > 10% cap would block every reclaim above about 25 sat/vB. Do not \"fix\" this\n * > into symmetry with `REFUND_MAX_FEE_FRACTION_*`; it would silently change\n * > behaviour. The matching comment lives at the UI cap site.\n */\nexport const RECLAIM_MAX_FEE_FRACTION_NUMERATOR = 25n;\nexport const RECLAIM_MAX_FEE_FRACTION_DENOMINATOR = 100n;\n\n/**\n * Fraction of the swept total above which the UI warns but still allows the\n * reclaim. Exported so the review screen derives its threshold from the same\n * constant the SDK enforces against, rather than restating it.\n */\nexport const RECLAIM_WARN_FEE_FRACTION_NUMERATOR = 10n;\n\nexport type ReclaimPsbtSigner = (\n psbtHex: string,\n opts: SignPsbtOptions,\n) => Promise<string>;\n\n/** One reserve to sweep, as the caller resolves it. */\nexport interface ReclaimVaultData {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Must come from the chain —\n * never the indexer. Its `outs[1]` is one leg of the three-way bind.\n */\n depositorSignedPeginTxHex: string;\n /**\n * Independent chain observation of `peginTxid:1`, including the outpoint the\n * lookup was issued against — see `ReclaimReserve.observed` for why the\n * script and value alone cannot identify a reserve.\n */\n observed: {\n txid: string;\n vout: number;\n scriptPubKey: string;\n value: bigint;\n };\n /** This vault's reserve value, recomputed via `computeMinClaimValue`. */\n expectedClaimValue: bigint;\n}\n\nexport interface ReclaimInput<\n R extends BtcBroadcastResult = BtcBroadcastResult,\n> {\n vaultIds: Hex[];\n /**\n * The depositor's Ethereum address — the second preimage of every vault id.\n * Used to re-derive each requested id from the PegIn bytes `readVaults`\n * returned, so a reserve can be tied to the vault it was asked for.\n */\n depositorEthAddress: Address;\n /**\n * The **connected wallet's live** BTC pubkey — compressed sec1 or x-only.\n * Never the indexer's `depositorBtcPubkey`: re-deriving the claim script\n * from the live key is what proves the wallet about to sign is the wallet\n * that can spend.\n */\n depositorBtcPubkey: string;\n /**\n * Resolve the reserves to sweep, in the same order as `vaultIds`. The SDK\n * passes no arguments — the caller closes over whatever context it needs.\n */\n readVaults: () => Promise<ReclaimVaultData[]>;\n /** Mempool-derived sat/vB fee rate. Caller fetches it before invoking. */\n feeRate: number;\n /** BTC wallet signer; receives a PSBT hex + taproot script-path options. */\n signPsbt: ReclaimPsbtSigner;\n /** Broadcast callback — returns whatever shape the caller needs. */\n broadcastTx: BtcBroadcaster<R>;\n /** Checked at every async boundary. */\n signal?: AbortSignal;\n}\n\n/**\n * Assert every reserve belongs to the vault it was requested for.\n *\n * The PSBT builder's binds all compare a script or a value, and both repeat\n * across every vault a depositor owns under the same protocol parameters — so\n * none of them can tell one of their vaults from another. Re-deriving the\n * vault id from the PegIn bytes closes that: it is the same\n * `keccak256(abi.encode(peginTxHash, depositor))` the registry keys on.\n *\n * This binds the reserve to the id that was asked for. It cannot detect an id\n * that was wrong to begin with — if the caller resolved the wrong vault id\n * upstream, every read follows that vault consistently and this agrees.\n */\nasync function assertReservesMatchVaultIds(\n vaults: readonly ReclaimVaultData[],\n vaultIds: readonly Hex[],\n depositorEthAddress: Address,\n): Promise<void> {\n for (let i = 0; i < vaults.length; i++) {\n const peginTxHash = calculateBtcTxHash(vaults[i].depositorSignedPeginTxHex);\n const derivedVaultId = ensureHexPrefix(\n await deriveVaultId(\n stripHexPrefix(peginTxHash),\n stripHexPrefix(depositorEthAddress),\n ),\n ).toLowerCase();\n\n if (derivedVaultId !== vaultIds[i].toLowerCase()) {\n throw new Error(\n `Reserve ${i} belongs to vault ${derivedVaultId}, not the requested ` +\n `${vaultIds[i].toLowerCase()}. Refusing to sweep a reserve whose ` +\n `vault is not the one the caller asked for — the reserve funds that ` +\n `vault's claim transaction and cannot be replaced.`,\n );\n }\n }\n}\n\n/**\n * Build, sign, and broadcast a reclaim transaction sweeping one or more\n * depositor-claim reserves back to the depositor's BIP-86 address.\n *\n * @returns whatever the injected `broadcastTx` returns (generic pass-through)\n * @throws {@link ReclaimUneconomicalError} if the fee breaches either cap\n * @throws `Error` if any validation or script/value bind fails\n * @throws anything `readVaults`, `signPsbt`, or `broadcastTx` throws\n */\nexport async function buildAndBroadcastReclaim<\n R extends BtcBroadcastResult = BtcBroadcastResult,\n>(input: ReclaimInput<R>): Promise<R> {\n const {\n vaultIds,\n depositorEthAddress,\n depositorBtcPubkey,\n readVaults,\n feeRate,\n signPsbt,\n broadcastTx,\n signal,\n } = input;\n\n signal?.throwIfAborted();\n\n if (vaultIds.length === 0) {\n throw new Error(\"Reclaim requires at least one vault id; got none.\");\n }\n if (!Number.isFinite(feeRate) || feeRate <= 0) {\n throw new Error(`feeRate must be a positive number, got ${feeRate}`);\n }\n // Rate cap first: fail closed before any PSBT construction or wallet prompt.\n if (feeRate > RECLAIM_MAX_FEE_RATE_SATS_VB) {\n throw new ReclaimUneconomicalError(\n `Fee rate ${feeRate} sat/vB exceeds the reclaim safety cap of ` +\n `${RECLAIM_MAX_FEE_RATE_SATS_VB} sat/vB; refusing to sign.`,\n 0n,\n 0n,\n );\n }\n\n const vaults = await readVaults();\n signal?.throwIfAborted();\n\n if (vaults.length !== vaultIds.length) {\n throw new Error(\n `readVaults returned ${vaults.length} reserves for ${vaultIds.length} ` +\n `vault id(s); refusing to sweep a set that does not match the request.`,\n );\n }\n\n // Cardinality alone proves nothing about *which* vaults came back, and\n // `readVaults` is documented as ordered but never checked. Derive each id\n // back from the PegIn bytes so an out-of-order, substituted or otherwise\n // mismatched set is rejected before any of it reaches a PSBT.\n await assertReservesMatchVaultIds(vaults, vaultIds, depositorEthAddress);\n signal?.throwIfAborted();\n\n // x-only for script derivation and signature verification; the raw form is\n // kept for the wallet's own sign call below.\n const xOnlyDepositorPubkey = processPublicKeyToXOnly(depositorBtcPubkey);\n\n const reserves: ReclaimReserve[] = vaults.map((vault) => ({\n depositorSignedPeginTxHex: vault.depositorSignedPeginTxHex,\n observed: vault.observed,\n expectedValue: vault.expectedClaimValue,\n }));\n\n const feeSats = estimateReclaimFeeSats(feeRate, reserves.length);\n\n // Fraction cap: bound the burn against the swept total. See the constant's\n // note on why this basis differs from the refund's.\n const sweptTotal = reserves.reduce((sum, r) => sum + r.expectedValue, 0n);\n const maxFeeByFraction =\n (sweptTotal * RECLAIM_MAX_FEE_FRACTION_NUMERATOR) /\n RECLAIM_MAX_FEE_FRACTION_DENOMINATOR;\n if (feeSats > maxFeeByFraction) {\n throw new ReclaimUneconomicalError(\n `Reclaim fee ${feeSats} sats exceeds ` +\n `${RECLAIM_MAX_FEE_FRACTION_NUMERATOR}/${RECLAIM_MAX_FEE_FRACTION_DENOMINATOR} ` +\n `of the swept total (${sweptTotal} sats, cap ${maxFeeByFraction} sats). ` +\n `The reserve is not at risk — it stays where it is until fee rates fall.`,\n feeSats,\n sweptTotal,\n );\n }\n signal?.throwIfAborted();\n\n // Builds the three-way bind: contract PegIn bytes × chain observation × JS\n // re-derivation from the live wallet key. Throws on any disagreement.\n const { psbtHex } = buildReclaimPsbt({\n depositorPubkey: xOnlyDepositorPubkey,\n inputs: reserves,\n feeSats,\n });\n signal?.throwIfAborted();\n\n const signOptions = createTaprootScriptPathSignOptions(\n depositorBtcPubkey,\n reserves.length,\n );\n const signedPsbtHex = await signPsbt(psbtHex, signOptions);\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // CLAUDE.md critical path #8: `useTweakedSigner: false` / `autoFinalized:\n // false` means wallet success is not evidence of a valid signature. Verify\n // every input against a sighash recomputed from the PSBT we built, before\n // finalizing — not just input 0, or a batch could broadcast with one good\n // signature and the rest garbage.\n const signatures = reserves.map((_reserve, inputIndex) => {\n const signature = extractPayoutSignature(\n signedPsbtHex,\n xOnlyDepositorPubkey,\n inputIndex,\n );\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtHex,\n signatureHex: signature,\n signerXOnlyPubkeyHex: xOnlyDepositorPubkey,\n inputIndex,\n });\n return signature;\n });\n\n // Finalize the PSBT we built, not the one the wallet returned: only the\n // verified signatures above cross over. See the primitive's header for what\n // finalizing the wallet's copy would let through.\n const signedTxHex = finalizeScriptPathWithSignatures({\n requestedPsbtHex: psbtHex,\n signaturesHex: signatures,\n signerXOnlyPubkeyHex: xOnlyDepositorPubkey,\n });\n signal?.throwIfAborted();\n\n return broadcastTx(signedTxHex);\n}\n"],"names":["BYTES32_HEX_RE","ADDRESS_HEX_RE","ETH_HEX_BYTES_RE","assertBytes32","value","label","assertAddress","assertHexBytes","validateActivationInputs","input","normalizedSecret","ensureHexPrefix","validateSecretAgainstHashlock","activateVault","btcVaultRegistryAddress","vaultId","hashlock","activationMetadata","writeContract","signal","BTCVaultRegistryABI","activateVaultAndRedeem","ChallengerSetMismatchError","missing","unexpected","assertChallengerSetMatchesVault","params","local","deriveLocalChallengers","universal","normalizeKey","overlap","key","supplied","suppliedSet","expected","expectedSet","pubkey","stripHexPrefix","PAYOUT_DESTINATION_OUTPUT","PayoutDestinationError","expectedScriptHex","actualScriptHex","assertPayoutPaysRegisteredScript","psbt","Psbt","cause","version","locktime","outs","readPayoutTx","PAYOUT_TX_VERSION","PAYOUT_TX_LOCKTIME","NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT","actual","Buffer","anchor","PAYOUT_ANCHOR_DUST_SATS","out","CLAIM_PEGIN_INPUT","VaultIdBindingError","expectedVaultId","derivedVaultId","peginTxid","peginTxidFromClaimPsbt","claimPsbtBase64","displayTxid","peginTxidFromClaimTx","claimTx","assertClaimSpendsVault","derived","normalizeVaultId","derivePeginVaultId","internalHash","CLAIM_DEPOSITOR_INPUT","ASSERT_CLAIMER_INPUT","PAYOUT_CLAIMER_INPUT","PAYOUT_DEPOSITOR_INPUT","WRONGLY_CHALLENGED_INPUT","assembleWatchtowerArtifacts","txGraphVersion","graphJson","claimPsbt","assertPsbt","payoutClaimerPsbt","wronglyChallengedPsbts","buildClaimPsbt","buildAssertClaimerPsbt","buildPayoutClaimerPsbt","buildWronglyChallengedPsbts","payoutDepositorPsbt","buildPayoutDepositorPsbt","psbtBase64","requests","challengerPubkeys","challengerPubkey","signatures","signAndExtract","cursor","claimSig","assertClaimerSigHex","payoutClaimerSigHex","depositorPayoutSigHex","wronglyChallengedSigs","count","signedClaimTxHex","finalizeClaimTx","buildWatchtowerArtifacts","xOnlyHex","publicKeyHex","hex","assertWalletMatchesDepositor","btcWallet","depositorPublicKey","btcNetwork","walletPublicKey","signerAddress","isAddressFromPublicKey","signedPsbtHexes","signPsbtsWithFallback","request","psbtBase64ToHex","createTaprootScriptPathSignOptionsForInput","signedPsbtHex","i","extractTapScriptSig","psbtHexToBase64","psbtHex","deriveClaimerWotsKeypair","root","deriveVaultRoot","wotsSeed","expandWotsSeed","derivation","wotsKeypairFromSeed","assertMatchesOnChainHash","validateWotsKeypairAgainstGraph","onChain","normalizeHash","hash","DELEGATED_CLAIM_TX_GRAPH_VERSION","ArtifactsVaultMismatchError","actualVaultId","summarizeWatchtowerArtifacts","artifactsJson","parsed","requireString","parseClaimTx","proverCircuitVersion","requireSafeInteger","claimableEventBlockNumber","requireRecord","assertArtifactsUsableForVault","summary","resolved","verifyWatchtowerArtifacts","txHex","Transaction","field","PEGIN_ETH_CONFIRMATIONS","REGISTRATION_DEPTH_POLL_INTERVAL_MS","REGISTRATION_DEPTH_TIMEOUT_MS","REGISTRATION_ABSENT_GRACE_POLLS","PeginRegistrationMissingError","message","PeginRegistrationNotFinalError","isPeginRegistrationMissingError","err","isPeginRegistrationNotFinalError","computeRegistrationConfirmations","currentBlock","createdAtBlock","depth","waitForPeginRegistrationDepth","vaultRegistryReader","getBlockNumber","vaultIds","required","pollIntervalMs","timeoutMs","onProgress","startTime","hasObservedRegistration","absentPolls","lastError","infos","missingIndex","info","zeroAddress","shallowest","shallowestDepth","error","resolve","reject","onAbort","timeoutId","SERDE_HEX_RE","BYTES32_SERDE_HEX_RE","OUTPOINT_RE","INT32_MIN","INT32_MAX","UINT32_MAX","DEPOSITOR_CLAIM_TX_VERSION","DEPOSITOR_CLAIM_OUTPUT_COUNT","CLAIM_ASSERT_VOUT","GraphFingerprintError","node","name","path","asArray","asRecord","asInt","min","max","asSerdeHex","asSerdeBytes32","serializeGraphTx","txNode","tx","at","inputNode","outpoint","match","vout","item","j","output","outputNode","decodePresignTx","readInputOutpoint","inputIndex","assertClaimHasAssertOutput","assertClaimSpendsPegin","spent","PEGIN_DEPOSITOR_CLAIM_VOUT","assertAssertSpendsClaim","assertTx","claimTxid","decodePresignClaimAssertTransactions","args","peginTx","assertPresignAssertSpendsClaim","assertPresignClaimAssertLinkage","assertDepositorClaimShape","claim","extra","spentTxid","canonicalTxSetFingerprint","set","sorted","a","b","parts","challenger","hexToBytes","bytesToHex","sha256","concatBytes","fingerprintPresignTxSet","bytes","c","canonicalizeBtcPubkey","fingerprintReturnedGraph","graph","subgraphs","sub","h","declaredChallengers","pubkeys","declared","role","assertReturnedGraphMatchesFingerprint","expectedFingerprint","fingerprinted","DEPOSITOR_PATH_UNUSED_COMMISSION_BPS","assertChallengerSetMatchesExpected","challengerPresignData","localChallengers","universalChallengerBtcPubkeys","k","suppliedList","readInputTxid","uint8ArrayToHex","assertInputReferencesParent","noPayoutTx","parentTx","parentLabel","parentTxid","inputTxid","collectDepositorGraphPsbts","depositorGraph","ctx","psbtHexes","signOptions","challengerEntries","builtPayout","buildPayoutPsbt","createTaprootScriptPathSignOptions","DEPOSITOR_SIGNED_INPUT_COUNT","claimerPubkey","assertTxParsed","noPayoutIdx","noPayoutHex","buildLocalNoPayoutPsbt","assertNoPayoutOutputMatchesChallenger","challengeAssertXTx","challengeAssertYTx","prevouts","buildNoPayoutPsbt","extractDepositorGraphSignatures","psbtPairs","depositorPubkey","assertPsbtUnsignedTxMatches","payoutSignature","extractPayoutSignature","assertScriptPathSchnorrSignature","perChallenger","entry","nopayoutSignature","signDepositorGraph","signingContext","validateWalletPubkey","requestedPsbtHex","DEFAULT_POLL_INTERVAL_MS","VAULT_ID_LOG_PREFIX_LEN","waitForPeginStatus","statusReader","targetStatuses","response","vaultIdKey","status","DaemonStatus","VP_TERMINAL_FAILURE_STATUSES","JsonRpcError","RpcErrorCode","MAX_POLLING_TIMEOUT_MS","POST_PAYOUT_STATUSES","TARGET_STATUS","prepareTransactionsForSigning","claimerTransactions","processPublicKeyToXOnly","normalizeClaimerPubkey","assertDepositTermsMatchSigningContext","terms","context","refuse","scalars","fromTerms","fromContext","canonical","keys","sameSet","x","y","contextVp","approvedVps","v","assertNonDepositorClaimerSetMatches","suppliedTxs","expectedVpPubkey","expectedVkPubkeys","depositorPubkeyXOnly","depositor","expectedList","suppliedAll","suppliedNonDepositor","buildPayoutSigningInput","signPayoutTransactions","transactions","payoutManager","PayoutManager","totalClaimers","payoutSignatures","r","result","runDepositorPresignFlow","presignClient","depositorPk","depositTerms","recordGraphFingerprint","depositApprovalWallet","supportsDepositApproval","approvedDepositTerms","index","graphFingerprint","depositorPkNormalized","nonDepositorTxs","preparedTransactions","claimerSignatures","depositorClaimerPresignatures","allSignatures","STATUS_POLL_TIMEOUT_MS","TARGET_STATUSES","POST_WOTS_STATUSES","submitWotsPublicKey","wotsSubmitter","wotsPublicKeys","isHintAccepted","matchKeyHint","hint","registrationKey","operationKey","canonicalHint","matchKeySetHint","hints","registrationKeys","operationKeys","canonicalHints","sortedCanonical","setsEqual","assertVaultProviderHintAccepted","vaultProviderEthAddress","hintBtcPubkey","registrationBtcPubkey","readCurrentOperationBtcPubkey","canonicalOperation","resolveOne","rosterEntry","rawOperationKey","genesisBtcPubkey","assertOnChainBtcPubkey","operationBtcPubkey","assertDistinctOperationKeys","participants","seen","participant","previousOwner","finalize","query","raw","resolvedAt","vaultProvider","vaultKeepers","keeper","universalChallengers","p","resolveCurrentParticipantKeys","resolveParticipantKeysAtEpochs","ApplicationEntryPointMismatchError","isApplicationEntryPointMismatchError","sortedSet","validateOnChainParticipantKeys","vaultKeeperReader","universalChallengerReader","applicationEntryPoint","expectedVaultProviderBtcPubkey","expectedVaultKeeperBtcPubkeys","expectedUniversalChallengerBtcPubkeys","operationKeyReader","onIndexerServingOperationKeys","onIndexerHintsInconsistent","blockNumber","registryApplicationEntryPoint","onChainVpKey","expectedUniversalChallengersVersion","ucKeyEpoch","isAddress","isAddressEqual","expectedAppVaultKeepersVersion","appKeeperKeyEpoch","onChainKeepers","onChainChallengers","participantKeys","vpMatch","keeperMatch","challengerMatch","roles","pinsRegistration","m","pinsOperation","isValidXOnlyHex","isDepositAmountValid","amountSats","minDeposit","maxDeposit","btcBalance","estimatedFeeSats","depositorClaimValue","validateDepositAmount","amount","formatSatoshisToBtc","validateRemainingCapacity","effectiveRemaining","validateProviderSelection","selectedProviders","availableProviders","availableProvidersLower","validateVaultAmounts","amounts","validateVaultProviderPubkey","stripped","validateVaultKeepers","vaultKeeperBtcPubkeys","validateUniversalChallengers","validateUTXOState","confirmedUTXOs","validateMultiVaultDepositInputs","vaultAmounts","vaultProviderBtcPubkey","amountsValidation","pubkeyValidation","ParticipantKeyDriftError","isParticipantKeyDriftError","diffKeys","verifyRegisteredParticipantKeys","epochsPerVault","mismatches","epochs","keeperDiff","challengerDiff","RegisteredVaultVersionMismatchError","isRegisteredVaultVersionMismatchError","verifyRegisteredVaultVersions","expectedOffchainParamsVersion","expectedVaultCoreVersion","id","BIP68NotMatureError","__publicField","BTC_HEX_BYTES_RE","PUBKEY_HEX_RE","REFUND_VSIZE","REFUND_MAX_FEE_RATE_SATS_VB","REFUND_MAX_FEE_FRACTION_NUMERATOR","REFUND_MAX_FEE_FRACTION_DENOMINATOR","estimateRefundFeeSats","feeRateSatsVb","REFUND_INPUT_COUNT","BIP68_ERROR_RE","assertNonNegativeInteger","validateVaultRefundData","targetEntry","assertValidVaultCoreVersion","validateRefundPrePeginContext","buildAndBroadcastRefund","readVault","readPrePeginContext","feeRate","signPsbt","broadcastTx","vault","refundFee","maxFeeByFraction","xOnlyDepositorPubkey","cleanFundedPrePeginTxHex","found","findAuthAnchorOpReturn","authAnchorHash","parsedFundedTx","e","buildRefundPsbt","REFUND_SIGNED_INPUT_INDEX","refundSignature","signedTxHex","finalizeScriptPathWithSignatures","ReclaimUneconomicalError","feeSats","sweptTotalSats","RECLAIM_MAX_FEE_RATE_SATS_VB","RECLAIM_MAX_FEE_FRACTION_NUMERATOR","RECLAIM_MAX_FEE_FRACTION_DENOMINATOR","RECLAIM_WARN_FEE_FRACTION_NUMERATOR","assertReservesMatchVaultIds","vaults","depositorEthAddress","peginTxHash","calculateBtcTxHash","deriveVaultId","buildAndBroadcastReclaim","depositorBtcPubkey","readVaults","reserves","estimateReclaimFeeSats","sweptTotal","sum","buildReclaimPsbt","_reserve","signature"],"mappings":"qxBAgBMA,GAAiB,sBACjBC,GAAiB,sBAKjBC,GAAmB,wBAEzB,SAASC,EAAcC,EAAeC,EAAqB,CACzD,GAAID,EAAM,SAAW,GACnB,MAAM,IAAI,MACR,GAAGC,CAAK,+DAA+DD,EAAM,MAAM,EAAA,EAGvF,GAAI,CAACJ,GAAe,KAAKI,CAAK,EAC5B,MAAM,IAAI,MACR,GAAGC,CAAK,uDAAA,CAGd,CAEA,SAASC,GAAcF,EAAeC,EAAqB,CACzD,GAAI,CAACJ,GAAe,KAAKG,CAAK,EAC5B,MAAM,IAAI,MACR,GAAGC,CAAK,uDAAA,CAGd,CAEA,SAASE,GAAeH,EAAeC,EAAqB,CAC1D,GAAI,CAACH,GAAiB,KAAKE,CAAK,EAC9B,MAAM,IAAI,MACR,GAAGC,CAAK,oEAAA,CAGd,CAyEA,SAASG,GAAyBC,EAK1B,CACNH,GAAcG,EAAM,wBAAyB,yBAAyB,EACtEN,EAAcM,EAAM,QAAS,SAAS,EAEtC,MAAMC,EAAmBC,EAAAA,gBAAgBF,EAAM,MAAM,EAGrD,GAFAN,EAAcO,EAAkB,QAAQ,EAEpCD,EAAM,WAAa,SACrBN,EAAcM,EAAM,SAAU,UAAU,EACpC,CAACG,EAAAA,8BAA8BF,EAAkBD,EAAM,QAAQ,GACjE,MAAM,IAAI,MACR,qEAAA,EAKN,OAAOC,CACT,CAoBA,eAAsBG,GAEpBJ,EAA0C,CAC1C,KAAM,CACJ,wBAAAK,EACA,QAAAC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