@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
@@ -0,0 +1,2 @@
1
+ "use strict";var Pe=Object.defineProperty;var fe=(e,t,r)=>t in e?Pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var j=(e,t,r)=>fe(e,typeof t!="symbol"?t+"":t,r);const M=require("./registration-records-DFQgBaYi.cjs"),p=require("./bitcoin-D-O2GjbC.cjs"),N=require("./btcTxHash-CGb5BqFL.cjs"),O=require("bitcoinjs-lib"),ve=require("buffer"),be=require("./tbv/core/clients/mempool/index.cjs"),X=require("./validation-C6XTfZak.cjs"),C=require("viem"),Ee=require("./sha2-Ce6KewYx.cjs"),D=require("./PayoutManager-DOdsgcUR.cjs"),ee=require("./PeginManager-8EUlm10F.cjs"),v=require("./tbv/core/wasm/index.cjs"),xe=require("./deriveVaultRoot-C3uqnJto.cjs"),we=require("./parseFundingOutpoints-C_-PT9BT.cjs"),K=require("./verifyScriptPathSchnorrSignature-D2t1yACC.cjs"),Q=require("./fundPeginTransaction-54-Rwb2k.cjs"),ye=["vaultCoreVersion","offchainParamsVersion","appVaultKeepersVersion","universalChallengersVersion"],Ce=["applicationEntryPoint","vaultProvider"];function te(e,t){const r=t.depositor.toLowerCase(),n=M.registrationPrePeginTxHash(t).toLowerCase();return e.filter(o=>o.vaultId!==t.vaultId&&o.depositor.toLowerCase()===r&&M.registrationPrePeginTxHash(o).toLowerCase()===n)}function re(e,t){for(const r of t){for(const n of ye)if(r.vault.protocol[n]!==e.vault.protocol[n])throw new Error(`Sibling vaults of this Pre-PegIn disagree on ${n} (${r.vault.protocol[n]} vs ${e.vault.protocol[n]}); the batch cannot be described by one set of deposit terms.`);if(r.maxAcceptableCommissionBps!==e.maxAcceptableCommissionBps)throw new Error(`Sibling vaults of this Pre-PegIn disagree on maxAcceptableCommissionBps (${r.maxAcceptableCommissionBps} vs ${e.maxAcceptableCommissionBps}); the batch cannot be described by one set of deposit terms.`);for(const n of Ce)if(r.vault.basic[n].toLowerCase()!==e.vault.basic[n].toLowerCase())throw new Error(`Sibling vaults of this Pre-PegIn disagree on ${n} (${r.vault.basic[n]} vs ${e.vault.basic[n]}); the batch cannot be described by one set of deposit terms.`)}}function ne(e){const t=[...e].sort((r,n)=>r.vault.protocol.htlcVout-n.vault.protocol.htlcVout);return t.forEach((r,n)=>{if(r.vault.protocol.htlcVout!==n)throw new Error(`Sibling discovery produced a non-contiguous HTLC vector (${t.map(o=>o.vault.protocol.htlcVout).join(", ")}).`)}),t.map(r=>({hashlock:r.vault.protocol.hashlock,amount:r.vault.basic.amount}))}const L="DepositTermsRejectedError";class oe extends Error{constructor(r,n="device-envelope"){super(r);j(this,"reason");this.name=L,this.reason=n}}function Re(e){if(e instanceof oe)return!0;if(typeof e!="object"||e===null)return!1;const t=e;return t.name===L&&t.reason==="device-envelope"}async function se(e,t){const r=O.Transaction.fromHex(p.stripHexPrefix(e)),o=(await Promise.all(r.ins.map(i=>be.getUtxoInfo(ve.Buffer.from(i.hash).reverse().toString("hex"),i.index,t)))).reduce((i,a)=>i+BigInt(a.value),0n),u=r.outs.reduce((i,a)=>i+BigInt(a.value),0n),s=o-u;if(s<=0n)throw new Error(`The funded Pre-PegIn transaction's inputs do not cover its outputs plus a fee (computed fee: ${s} sats).`);if(s>X.MAX_REASONABLE_FEE_SATS)throw new Error(`The funded Pre-PegIn transaction's computed fee (${s} sats) exceeds the maximum reasonable fee (${X.MAX_REASONABLE_FEE_SATS} sats); the mempool API may have returned manipulated prevout data.`);return s}async function z(e){const t=e.siblings.length;if(t===0)throw new Error("rebuildDepositTermsCore: at least one sibling is required");for(const[l,E]of e.siblings.entries())if(E.amount<=0n)throw new Error(`rebuildDepositTermsCore: sibling[${l}] has non-positive on-chain pegin amount ${E.amount}; the chain-read vault record is invalid. Resume refused.`);if(e.prepeginMaxFee<=0n)throw new Error(`rebuildDepositTermsCore: prepeginMaxFee must be > 0, got ${e.prepeginMaxFee}`);const r=p.stripHexPrefix(e.prepeginTxid).toLowerCase(),n=p.stripHexPrefix(N.calculateBtcTxHash(e.fundedPrePeginTxHex)).toLowerCase();if(n!==r)throw new Error(`Funded Pre-PegIn tx hashes to ${n}, expected ${r} (on-chain prepeginTxid). Resume refused.`);const o=D.findAuthAnchorOpReturn(p.stripHexPrefix(e.fundedPrePeginTxHex));if(o===void 0)throw new Error("Funded Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN commitment — it either predates auth anchoring or is malformed. The intent resume path requires the anchor to prove sibling completeness. Resume refused.");if(o.vout!==t)throw new Error(`Auth-anchor OP_RETURN at vout ${o.vout} does not match the discovered sibling count ${t}; the discovered sibling set does not cover this transaction's HTLC outputs (a lagging index can cause this — retry later). Resume refused.`);const u=e.vaultKeeperBtcPubkeys.length,s=e.universalChallengerBtcPubkeys.length,i=await v.computeMinClaimValue(e.vaultCoreVersion,u,s,e.councilQuorum,e.councilSize,e.protocolFeeRate),a=await v.computeMinPeginFee(e.vaultCoreVersion,u,s,e.minPeginFeeRate),d=await v.peginP2aAnchorOutput(e.vaultCoreVersion),c=(d==null?void 0:d.value)??0n;if(i<=0n)throw new Error(`WASM returned non-positive depositorClaimValue ${i}; expected > 0. Resume refused.`);if(a<=0n)throw new Error(`WASM returned non-positive peginMaxFee ${a}; expected > 0. Resume refused.`);if(c<0n)throw new Error(`WASM returned negative P2A anchor value ${c}. Resume refused.`);const h=a+c,b=e.minPeginFeeRate*Q.MAX_REASONABLE_PEGIN_VBYTES;if(h<=0n||h>b)throw new Error(`WASM implied PegIn reserve ${h} sat is outside (0, ${b}] (minPeginFeeRate=${e.minPeginFeeRate} × ${Q.MAX_REASONABLE_PEGIN_VBYTES} vbytes). Resume refused.`);const w=e.siblings.map(l=>l.amount+i+a+c),R=await Promise.all(e.siblings.map(async l=>(await v.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorBtcPubkey,vaultProviderPubkey:e.vaultProviderBtcPubkey,vaultKeeperPubkeys:[...e.vaultKeeperBtcPubkeys],universalChallengerPubkeys:[...e.universalChallengerBtcPubkeys],hashlock:p.stripHexPrefix(l.hashlock),timelockRefund:e.timelockRefund,network:e.network})).scriptPubKey)),y=O.Transaction.fromHex(p.stripHexPrefix(e.fundedPrePeginTxHex)).outs.map(l=>({value:l.value,script:l.script}));return K.assertEncodedHtlcOutputsMatch(y,w,R),ee.buildDepositTerms({vaultCoreVersion:e.vaultCoreVersion,protocolFeeRate:e.protocolFeeRate,timelockPegin:e.timelockPegin,timelockAssert:e.timelockAssert,timelockRefund:e.timelockRefund,prepeginTxid:e.prepeginTxid,prepeginMaxFee:e.prepeginMaxFee,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:e.universalChallengerBtcPubkeys,maxAcceptableCommissionBps:e.maxAcceptableCommissionBps,peginAmounts:e.siblings.map(l=>l.amount),depositorClaimValue:i,peginMaxFee:a})}async function ke(e){const{read:t}=e,r=p.canonicalizeBtcPubkey(e.depositorBtcPubkey);if(r!==t.context.depositorBtcPubkey)throw new Error("Connected wallet key is not the vault's depositor key; select the account that made the deposit.");const n=p.stripHexPrefix(t.prePeginTxHash).toLowerCase(),o=p.stripHexPrefix(N.calculateBtcTxHash(e.fundedPrePeginTxHex)).toLowerCase();if(o!==n)throw new Error(`Funded Pre-PegIn tx hashes to ${o}, expected ${n} (on-chain prePeginTxHash).`);const u=await Promise.all(te(t.registrationRecords,t.registrationRecord).map(async d=>{const c=await e.siblingReader.getVaultData(d.vaultId);if(c.protocol.prePeginTxHash.toLowerCase()!==M.registrationPrePeginTxHash(d).toLowerCase())throw new Error(`Sibling ${d.vaultId} is registered against a different Pre-PegIn on chain than its registration log records; refusing an inconsistent node.`);return{vault:c,maxAcceptableCommissionBps:d.maxAcceptableCommissionBps}})),s={vault:t.vault,maxAcceptableCommissionBps:t.registrationRecord.maxAcceptableCommissionBps};re(s,u);const i=ne([s,...u]),a=await se(e.fundedPrePeginTxHex,e.mempoolApiUrl);return z({vaultCoreVersion:t.vault.protocol.vaultCoreVersion,siblings:i,fundedPrePeginTxHex:e.fundedPrePeginTxHex,depositorBtcPubkey:r,vaultProviderBtcPubkey:t.participantKeys.vaultProvider.operationBtcPubkey,vaultKeeperBtcPubkeys:t.participantKeys.vaultKeeperOperationKeysSorted,universalChallengerBtcPubkeys:t.participantKeys.universalChallengerOperationKeysSorted,protocolFeeRate:t.offchainParams.feeRate,minPeginFeeRate:t.offchainParams.minPeginFeeRate,councilQuorum:t.offchainParams.councilQuorum,councilSize:t.offchainParams.securityCouncilKeys.length,timelockPegin:t.context.timelockPegin,timelockAssert:t.context.timelockAssert,timelockRefund:t.offchainParams.tRefund,prepeginTxid:n,prepeginMaxFee:a,maxAcceptableCommissionBps:t.registrationRecord.maxAcceptableCommissionBps,network:e.network})}function Te(e){const t=(e instanceof Error?e.message:typeof e=="string"?e:"").toLowerCase();return t.includes("wots")&&t.includes("hash")&&t.includes("does not match")}const ie="TBV.PeginFingerprint.v1",ae=C.keccak256(C.toHex(ie)),W=65535,J=2n**64n-1n,Ae=2n**256n-1n,Ve=/^0x[0-9a-fA-F]{64}$/,Y=1;class P extends Error{constructor(t){super(t),this.name="PeginFingerprintInputError"}}function Ie(e){return e instanceof P||e instanceof Error&&e.name==="PeginFingerprintInputError"}function _(e,t,r,n){if(typeof t!="bigint")throw new P(`${e} must be a bigint (Solidity ${n}), got ${typeof t}`);if(t<0n||t>r)throw new P(`${e} must fit Solidity ${n} (0..${r}), got ${t}`)}function $(e,t){if(!Number.isInteger(t)||t<0||t>W)throw new P(`${e} must be an integer fitting Solidity uint16 (0..${W}), got ${t}`)}function $e(e,t){if(!Ve.test(t))throw new P(`${e} must be 32 bytes as 0x-prefixed hex (66 characters), got "${t}"`);return t.toLowerCase()}function Be(e){if(!C.isAddress(e,{strict:!1}))throw new P(`registryAddress must be a 20-byte 0x-prefixed address, got "${e}"`);const t=e.toLowerCase();if(t===C.zeroAddress)throw new P("registryAddress must not be the zero address; a zero here means the registry address was never resolved");return t}const Fe=[{name:"domain",type:"bytes32"},{name:"chainId",type:"uint256"},{name:"registry",type:"address"},{name:"vaultProviderBtcKey",type:"bytes32"},{name:"appKeeperKeyEpoch",type:"uint64"},{name:"ucKeyEpoch",type:"uint64"},{name:"appVaultKeepersVersion",type:"uint16"},{name:"universalChallengersVersion",type:"uint16"},{name:"offchainParamsVersion",type:"uint16"},{name:"vaultCoreVersion",type:"uint16"}];function ce(e){if(_("chainId",e.chainId,Ae,"uint256"),e.chainId===0n)throw new P("chainId must not be 0; a zero here means the chain id was never resolved");const t=Be(e.registryAddress),r=$e("vaultProviderBtcKey",e.vaultProviderBtcKey);if(_("appKeeperKeyEpoch",e.appKeeperKeyEpoch,J,"uint64"),_("ucKeyEpoch",e.ucKeyEpoch,J,"uint64"),$("appVaultKeepersVersion",e.appVaultKeepersVersion),$("universalChallengersVersion",e.universalChallengersVersion),$("offchainParamsVersion",e.offchainParamsVersion),$("vaultCoreVersion",e.vaultCoreVersion),e.vaultCoreVersion<Y)throw new P(`vaultCoreVersion must be at least ${Y}; ${e.vaultCoreVersion} means the version was never resolved`);return C.encodeAbiParameters(Fe,[ae,e.chainId,t,r,e.appKeeperKeyEpoch,e.ucKeyEpoch,e.appVaultKeepersVersion,e.universalChallengersVersion,e.offchainParamsVersion,e.vaultCoreVersion])}function Se(e){return C.keccak256(ce(e))}class ue extends Error{constructor(t,r){super(`Re-derived vault root does not match this Pre-PegIn: derived auth-anchor hash ${t}, transaction commits to ${r}. Connect the same wallet, on the same account and the same network, that created the deposit.`),this.derivedAuthAnchorHash=t,this.onChainAuthAnchorHash=r,this.name="VaultRootMismatchError"}}class F extends Error{constructor(t){super(t),this.name="UnanchoredPrePeginError"}}class le extends Error{constructor(t,r,n=[]){super(`No candidate parameter set reproduces this Pre-PegIn's HTLC outputs (${t} candidate(s) tried). `+(n.length>0?`${n.length} version(s) could not be resolved and may hold the answer: ${n.join(" | ")}. `:"")+`Sample rejections: ${r.join(" | ")}`),this.candidatesTried=t,this.sampleRejections=r,this.unresolvedLabels=n,this.name="PeginParamsNotFoundError"}}class he extends Error{constructor(t){super(`${t.length} candidate parameter sets reproduce this Pre-PegIn's HTLC outputs, so the vault's stamped versions cannot be determined: ${t.join(" | ")}. Reconstruction refused.`),this.survivorLabels=t,this.name="PeginParamsAmbiguousError"}}class de extends Error{constructor(t,r){super(`A candidate matched this Pre-PegIn (${t}), but ${r.length} version(s) could not be resolved, so the search space did not provably contain the true parameters: ${r.join(" | ")}. A version sharing the matched timelockRefund and participants is indistinguishable from the true one, so the match cannot be trusted. Reconstruction refused.`),this.matchedLabel=t,this.unresolvedLabels=r,this.name="PeginParamsIncompleteSpaceError"}}class V extends Error{constructor(t){super(`${t}. Reconstruction refused.`),this.name="PeginSizingIntegrityError"}}async function He(e){const{wallet:t,depositorBtcPubkey:r,fundedPrePeginTxHex:n}=e,o=p.stripHexPrefix(n),u=D.findAuthAnchorOpReturn(o);if(u===void 0)throw new F("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN, so the number of HTLC outputs it funds cannot be determined. Legacy pre-anchor deposits are not recoverable by this path.");const s=u.vout;if(s===0)throw new F("Pre-PegIn's auth-anchor OP_RETURN is at vout 0, implying zero HTLC outputs; there is nothing to recover.");const i=we.parseFundingOutpointsFromTx(o),a=await xe.deriveVaultRoot(t,{depositorBtcPubkey:p.hexToUint8Array(p.processPublicKeyToXOnly(r)),fundingOutpoints:i});try{const c=await v.expandAuthAnchor(a);let h;try{h=p.uint8ArrayToHex(Ee.sha256(c))}finally{c.fill(0)}if(h!==u.hash)throw new ue(h,u.hash)}catch(c){throw a.fill(0),c}const{hashlocks:d}=await ee.expandPerVaultSecrets(a,s);return{vaultCount:s,hashlocks:d,authAnchorHash:u.hash}}function _e(e){const{vaultCoreVersion:t,offchainParams:r,participantKeySets:n}=e;if(!Number.isInteger(t)||t<1)throw new Error(`buildPeginParamsCandidates: vaultCoreVersion must be a positive integer, got ${t}`);if(r.length===0)throw new Error("buildPeginParamsCandidates: at least one offchain-params version is required");if(n.length===0)throw new Error("buildPeginParamsCandidates: at least one participant key set is required");const o=[];for(const u of r)for(const s of n)o.push({vaultCoreVersion:t,offchainParams:u,participants:s});return o}function pe(e){return`${e.axis} v${e.version} (${e.reason})`}function B(e){const{participants:t}=e;return`core=${e.vaultCoreVersion} offchain=${e.offchainParams.version} keepers=${t.appVaultKeepersVersion} challengers=${t.universalChallengersVersion} vp=${t.vaultProvider}`}const Z=5;function Me(e,t){return JSON.stringify({terms:e,peginAmounts:t},(r,n)=>typeof n=="bigint"?`${n}`:n)}function Ke(e){const{offchainParams:t,participants:r}=e;return[e.vaultCoreVersion,r.vaultKeeperBtcPubkeys.length,r.universalChallengerBtcPubkeys.length,t.councilQuorum,t.councilSize,t.protocolFeeRate,t.minPeginFeeRate].join("|")}async function Ne(e){const{offchainParams:t,participants:r}=e,n=r.vaultKeeperBtcPubkeys.length,o=r.universalChallengerBtcPubkeys.length,[u,s,i]=await Promise.all([v.computeMinClaimValue(e.vaultCoreVersion,n,o,t.councilQuorum,t.councilSize,t.protocolFeeRate),v.computeMinPeginFee(e.vaultCoreVersion,n,o,t.minPeginFeeRate),v.peginP2aAnchorOutput(e.vaultCoreVersion)]),a=(i==null?void 0:i.value)??0n;if(u<=0n)throw new V(`WASM returned non-positive depositorClaimValue ${u} for graph version ${e.vaultCoreVersion}`);if(s<=0n)throw new V(`WASM returned non-positive peginMaxFee ${s} for graph version ${e.vaultCoreVersion}`);if(a<0n)throw new V(`WASM returned negative P2A anchor value ${a} for graph version ${e.vaultCoreVersion}`);return{depositorClaimValue:u,peginMaxFee:s,p2aAnchorValue:a}}async function Oe(e){const{hashlocks:t,fundedPrePeginTxHex:r,depositorBtcPubkey:n,prepeginMaxFee:o,maxAcceptableCommissionBps:u,network:s,candidates:i,unresolvedVersions:a}=e;if(t.length===0)throw new Error("reconstructPeginParams: at least one hashlock is required");if(i.length===0)throw new Error("reconstructPeginParams: candidate space is empty");const d=p.processPublicKeyToXOnly(n),c=p.stripHexPrefix(r),h=D.findAuthAnchorOpReturn(c);if(h===void 0)throw new F("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN; the sibling set cannot be proven complete. Reconstruction refused.");if(h.vout!==t.length)throw new Error(`reconstructPeginParams: ${t.length} hashlock(s) supplied but the auth-anchor OP_RETURN sits at vout ${h.vout}, so the transaction funds ${h.vout} HTLC output(s). Reconstruction refused.`);const b=O.Transaction.fromHex(c).outs,w=t.map((m,g)=>BigInt(b[g].value)),R=p.stripHexPrefix(N.calculateBtcTxHash(c)).toLowerCase(),y=new Map,l=[],E=[],S=[];let U=0;for(const m of i)try{const g=Ke(m);let f=y.get(g);f===void 0&&(f=await Ne(m),y.set(g,f));const k=f.depositorClaimValue+f.peginMaxFee+f.p2aAnchorValue,T=w.map(A=>A-k),I=T.findIndex(A=>A<=0n);if(I!==-1)throw new K.HtlcOutputMismatchError(`HTLC output[${I}] value ${w[I]} is not above this candidate's reserve ${k}, so it implies a non-positive pegin amount ${T[I]}.`);const{offchainParams:x,participants:H}=m,G=await z({vaultCoreVersion:m.vaultCoreVersion,siblings:t.map((A,ge)=>({hashlock:A,amount:T[ge]})),fundedPrePeginTxHex:c,depositorBtcPubkey:d,vaultProviderBtcPubkey:H.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:H.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:H.universalChallengerBtcPubkeys,protocolFeeRate:x.protocolFeeRate,minPeginFeeRate:x.minPeginFeeRate,councilQuorum:x.councilQuorum,councilSize:x.councilSize,timelockPegin:x.timelockPegin,timelockAssert:x.timelockAssert,timelockRefund:x.timelockRefund,prepeginTxid:R,prepeginMaxFee:o,maxAcceptableCommissionBps:u,network:s});l.push({candidate:m,terms:G,peginAmounts:T,fingerprint:Me(G,T)})}catch(g){if(g instanceof V)throw g;const f=B(m),k=g instanceof Error?g.message:String(g);g instanceof K.HtlcOutputMismatchError?E.length<Z&&E.push(`[${f}] ${k}`):(U++,S.length<Z&&S.push(`${f} (${k})`))}const me=a.length+U,q=[...a.map(pe),...S];if(l.length===0)throw new le(i.length,E,q);if(new Set(l.map(m=>m.fingerprint)).size>1)throw new he(l.map(m=>B(m.candidate)));if(me>0)throw new de(B(l[0].candidate),q);return{candidate:l[0].candidate,terms:l[0].terms,peginAmounts:l[0].peginAmounts,authAnchorHash:h.hash,candidatesTried:i.length,matchedCandidates:l.map(m=>m.candidate)}}function De(e,t){const{htlcVout:r,depositorBtcPubkey:n,applicationEntryPoint:o,fundedPrePeginTxHex:u,hashlocks:s,network:i}=t,{candidate:a,peginAmounts:d}=e,{offchainParams:c,participants:h}=a;if(s.length!==d.length)throw new Error(`toRefundInputs: ${s.length} hashlock(s) but ${d.length} reconstructed amount(s); the reconstruction and the hashlock vector describe different transactions.`);if(!Number.isInteger(r)||r<0||r>=d.length)throw new Error(`toRefundInputs: htlcVout ${r} is outside the reconstructed batch of ${d.length} vault(s).`);const b=d.map((y,l)=>({hashlock:p.ensureHexPrefix(s[l]),amount:y,htlcVout:l})),w={vaultCoreVersion:a.vaultCoreVersion,hashlock:b[r].hashlock,htlcVout:r,offchainParamsVersion:c.version,appVaultKeepersVersion:h.appVaultKeepersVersion,universalChallengersVersion:h.universalChallengersVersion,vaultProvider:h.vaultProvider,applicationEntryPoint:o,amount:d[r],unsignedPrePeginTxHex:u,depositorBtcPubkey:n,batch:b},R={vaultProviderPubkey:h.vaultProviderBtcPubkey,vaultKeeperPubkeys:h.vaultKeeperBtcPubkeys,universalChallengerPubkeys:h.universalChallengerBtcPubkeys,timelockRefund:c.timelockRefund,feeRate:c.protocolFeeRate,minPeginFeeRate:c.minPeginFeeRate,numLocalChallengers:h.vaultKeeperBtcPubkeys.length,councilQuorum:c.councilQuorum,councilSize:c.councilSize,network:i};return{vault:w,context:R}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=L;exports.DepositTermsRejectedError=oe;exports.PEGIN_FINGERPRINT_DOMAIN=ae;exports.PEGIN_FINGERPRINT_DOMAIN_PREIMAGE=ie;exports.PeginFingerprintInputError=P;exports.PeginParamsAmbiguousError=he;exports.PeginParamsIncompleteSpaceError=de;exports.PeginParamsNotFoundError=le;exports.PeginSizingIntegrityError=V;exports.UnanchoredPrePeginError=F;exports.VaultRootMismatchError=ue;exports.assertClaimBatchHomogeneous=re;exports.buildPeginParamsCandidates=_e;exports.computeFundedPrePeginFee=se;exports.computePeginFingerprint=Se;exports.deriveHashlocksFromPrePegin=He;exports.describePeginParamsCandidate=B;exports.describeUnresolvedVersion=pe;exports.encodePeginFingerprintPreimage=ce;exports.isDepositTermsRejectedError=Re;exports.isPeginFingerprintInputError=Ie;exports.isWotsMismatchError=Te;exports.orderClaimBatchByHtlcVout=ne;exports.rebuildDepositTermsCore=z;exports.rebuildDepositTermsForClaim=ke;exports.reconstructPeginParams=Oe;exports.selectSiblingRegistrations=te;exports.toRefundInputs=De;
2
+ //# sourceMappingURL=toRefundInputs-BZXvuOMY.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toRefundInputs-BZXvuOMY.cjs","sources":["../src/tbv/core/deposit-terms/claimSiblings.ts","../src/tbv/core/deposit-terms/depositTermsErrors.ts","../src/tbv/core/deposit-terms/fundedPrePeginFee.ts","../src/tbv/core/deposit-terms/rebuildDepositTermsCore.ts","../src/tbv/core/deposit-terms/rebuildDepositTermsForClaim.ts","../src/tbv/core/wots/errors.ts","../src/tbv/core/pegin-fingerprint/peginFingerprint.ts","../src/tbv/core/recovery/recoveryErrors.ts","../src/tbv/core/recovery/deriveHashlocksFromPrePegin.ts","../src/tbv/core/recovery/peginParamsCandidates.ts","../src/tbv/core/recovery/reconstructPeginParams.ts","../src/tbv/core/recovery/toRefundInputs.ts"],"sourcesContent":["/**\n * Sibling discovery for the claim-time terms rebuild — pure, fail-closed.\n *\n * A batch deposit registers every sibling in one transaction, so the target's\n * registration block holds them all: the siblings are the block's other\n * registrations by the same depositor whose `unsignedPrePeginTx` is the same\n * transaction. Completeness is backstopped by the core's auth-anchor check.\n *\n * @module deposit-terms/claimSiblings\n */\n\nimport { registrationPrePeginTxHash } from \"../clients/eth/registration-records\";\nimport type { PeginRegistrationRecord, VaultData } from \"../clients/eth/types\";\nimport type { RebuildSibling } from \"./rebuildDepositTermsCore\";\n\n/**\n * One batch member: the chain record plus its registration-log ceiling.\n *\n * @experimental\n */\nexport interface ClaimBatchMember {\n vault: VaultData;\n maxAcceptableCommissionBps: number;\n}\n\n/**\n * Fields that must be uniform across the batch: each sibling is stamped by its\n * own `submitPeginRequest`, so governance changes between registrations can\n * stamp them differently — and Gate 1 cannot see fields not encoded in the\n * HTLC outputs (timelocks, commission).\n */\nconst STAMPED_PROTOCOL_FIELDS = [\n \"vaultCoreVersion\",\n \"offchainParamsVersion\",\n \"appVaultKeepersVersion\",\n \"universalChallengersVersion\",\n] as const;\nconst STAMPED_ADDRESS_FIELDS = [\n \"applicationEntryPoint\",\n \"vaultProvider\",\n] as const;\n\n/** @experimental */\nexport function selectSiblingRegistrations(\n records: readonly PeginRegistrationRecord[],\n target: PeginRegistrationRecord,\n): PeginRegistrationRecord[] {\n const depositor = target.depositor.toLowerCase();\n const prePeginTxHash = registrationPrePeginTxHash(target).toLowerCase();\n // Depositor first, so only the depositor's own registrations are ever parsed.\n return records.filter(\n (r) =>\n r.vaultId !== target.vaultId &&\n r.depositor.toLowerCase() === depositor &&\n registrationPrePeginTxHash(r).toLowerCase() === prePeginTxHash,\n );\n}\n\n/** @experimental */\nexport function assertClaimBatchHomogeneous(\n target: ClaimBatchMember,\n siblings: readonly ClaimBatchMember[],\n): void {\n for (const sibling of siblings) {\n for (const field of STAMPED_PROTOCOL_FIELDS) {\n if (sibling.vault.protocol[field] !== target.vault.protocol[field]) {\n throw new Error(\n `Sibling vaults of this Pre-PegIn disagree on ${field} ` +\n `(${sibling.vault.protocol[field]} vs ${target.vault.protocol[field]}); ` +\n `the batch cannot be described by one set of deposit terms.`,\n );\n }\n }\n if (\n sibling.maxAcceptableCommissionBps !== target.maxAcceptableCommissionBps\n ) {\n throw new Error(\n `Sibling vaults of this Pre-PegIn disagree on maxAcceptableCommissionBps ` +\n `(${sibling.maxAcceptableCommissionBps} vs ${target.maxAcceptableCommissionBps}); ` +\n `the batch cannot be described by one set of deposit terms.`,\n );\n }\n for (const field of STAMPED_ADDRESS_FIELDS) {\n if (\n sibling.vault.basic[field].toLowerCase() !==\n target.vault.basic[field].toLowerCase()\n ) {\n throw new Error(\n `Sibling vaults of this Pre-PegIn disagree on ${field} ` +\n `(${sibling.vault.basic[field]} vs ${target.vault.basic[field]}); ` +\n `the batch cannot be described by one set of deposit terms.`,\n );\n }\n }\n }\n}\n\n/**\n * Sort by `htlcVout` and project into the core's sibling shape. htlcVout is\n * derived from array position downstream, so the vector must cover [0, N-1].\n *\n * @experimental\n */\nexport function orderClaimBatchByHtlcVout(\n members: readonly ClaimBatchMember[],\n): RebuildSibling[] {\n const ordered = [...members].sort(\n (a, b) => a.vault.protocol.htlcVout - b.vault.protocol.htlcVout,\n );\n ordered.forEach((member, i) => {\n if (member.vault.protocol.htlcVout !== i) {\n throw new Error(\n `Sibling discovery produced a non-contiguous HTLC vector ` +\n `(${ordered.map((m) => m.vault.protocol.htlcVout).join(\", \")}).`,\n );\n }\n });\n return ordered.map((m) => ({\n hashlock: m.vault.protocol.hashlock,\n amount: m.vault.basic.amount,\n }));\n}\n","/**\n * Typed rejection contract for deposit-terms approval. Providers cannot import\n * this class (no dependency edge between the packages), so the cross-package\n * contract is the error SHAPE on {@link DepositTermsApprover}. Consumers land\n * with the first provider (#2109) and its app error mapping (#2110).\n *\n * @module deposit-terms/depositTermsErrors\n */\n\n/** The `name` value providers must set on envelope rejections (the wire contract). */\nexport const DEPOSIT_TERMS_REJECTED_ERROR_NAME = \"DepositTermsRejectedError\";\n\n/** Why the terms were rejected before approval. */\nexport type DepositTermsRejectionReason = \"device-envelope\";\n\n/** SDK-owned typed rejection thrown when deposit terms fail pre-approval validation. */\nexport class DepositTermsRejectedError extends Error {\n readonly reason: DepositTermsRejectionReason;\n\n constructor(\n message: string,\n reason: DepositTermsRejectionReason = \"device-envelope\",\n ) {\n super(message);\n this.name = DEPOSIT_TERMS_REJECTED_ERROR_NAME;\n this.reason = reason;\n }\n}\n\n/**\n * Guard for app-side error mapping. Matches `instanceof` OR the documented\n * `name` — providers and foreign realms throw structurally-conforming plain\n * errors that `instanceof` cannot see.\n */\nexport function isDepositTermsRejectedError(\n err: unknown,\n): err is DepositTermsRejectedError {\n if (err instanceof DepositTermsRejectedError) return true;\n if (typeof err !== \"object\" || err === null) return false;\n const shaped = err as { name?: unknown; reason?: unknown };\n // The documented provider shape REQUIRES the reason; a name-only match is\n // a contract violation and propagates unnormalized.\n return (\n shaped.name === DEPOSIT_TERMS_REJECTED_ERROR_NAME &&\n shaped.reason === \"device-envelope\"\n );\n}\n","/**\n * Fee of a funded Pre-PegIn: Σ prevouts − Σ outputs, prevouts resolved from\n * the mempool API by display-order txid. Becomes the device's\n * `prepegin_max_fee` bound. Mirrors the vault app's\n * `resolveFundedTxFeeAndUtxos`, without the UTXO record the broadcast reuses.\n *\n * @module deposit-terms/fundedPrePeginFee\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { getUtxoInfo } from \"../clients/mempool\";\nimport { stripHexPrefix } from \"../primitives/utils/bitcoin\";\nimport { MAX_REASONABLE_FEE_SATS } from \"../utils/validation\";\n\n/**\n * @throws When the inputs do not cover the outputs, or the fee exceeds\n * `MAX_REASONABLE_FEE_SATS` (a manipulated prevout answer).\n * @experimental\n */\nexport async function computeFundedPrePeginFee(\n fundedPrePeginTxHex: string,\n mempoolApiUrl: string,\n): Promise<bigint> {\n const tx = Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n const prevouts = await Promise.all(\n tx.ins.map((input) =>\n // Bitcoin stores the prev-txid in reverse (internal) byte order.\n getUtxoInfo(\n Buffer.from(input.hash).reverse().toString(\"hex\"),\n input.index,\n mempoolApiUrl,\n ),\n ),\n );\n const totalIn = prevouts.reduce((sum, u) => sum + BigInt(u.value), 0n);\n const totalOut = tx.outs.reduce((sum, o) => sum + BigInt(o.value), 0n);\n const fee = totalIn - totalOut;\n if (fee <= 0n) {\n throw new Error(\n `The funded Pre-PegIn transaction's inputs do not cover its outputs plus a fee ` +\n `(computed fee: ${fee} sats).`,\n );\n }\n if (fee > MAX_REASONABLE_FEE_SATS) {\n throw new Error(\n `The funded Pre-PegIn transaction's computed fee (${fee} sats) exceeds the maximum ` +\n `reasonable fee (${MAX_REASONABLE_FEE_SATS} sats); the mempool API may have ` +\n `returned manipulated prevout data.`,\n );\n }\n return fee;\n}\n","/**\n * Pure core of the resume-broadcast DepositTerms rebuild (#2220 Part 2).\n *\n * Takes plain chain-derived data (the app orchestrator does the chain reads +\n * sibling discovery) and: (1) asserts sibling completeness against the funded\n * tx's auth-anchor OP_RETURN, (2) recomputes the amount-independent sizing\n * (depositorClaimValue, peginMaxFee, anchor) via WASM, (3) byte-matches each\n * HTLC output's value + scriptPubKey against the funded tx (Gate 1), then (4)\n * projects into DepositTerms. No chain access, no browser state — unit-testable.\n *\n * btc-vault is the protocol source of truth (`compute_min_htlc_value`,\n * `derive_challengers_for`).\n */\n\nimport {\n computeMinClaimValue,\n computeMinPeginFee,\n getPrePeginHtlcConnectorInfo,\n peginP2aAnchorOutput,\n} from \"../wasm\";\nimport { Transaction } from \"bitcoinjs-lib\";\n\nimport { findAuthAnchorOpReturn } from \"../managers/pegin/assertAuthAnchorOpReturn\";\nimport { assertEncodedHtlcOutputsMatch } from \"../primitives/psbt/assertWasmPeginSizing\";\nimport { stripHexPrefix } from \"../primitives/utils/bitcoin\";\nimport { MAX_REASONABLE_PEGIN_VBYTES } from \"../utils/fee/constants\";\nimport { calculateBtcTxHash } from \"../utils/transaction/btcTxHash\";\n\nimport { buildDepositTerms } from \"./buildDepositTerms\";\nimport type { DepositTerms } from \"./depositTerms\";\n\n/** One HTLC in the shared Pre-PegIn tx, ordered by (and contiguous in) htlcVout. */\nexport interface RebuildSibling {\n /** 32-byte hex hashlock (0x prefix optional), per-vault (feeds the HTLC scriptPubKey). */\n hashlock: string;\n /** btc-vault `pegin_amount` for this sibling (satoshis). */\n amount: bigint;\n}\n\nexport interface RebuildDepositTermsCoreInput {\n /** Stamped tx-graph version (NOT chain-active). */\n vaultCoreVersion: number;\n /** Sibling HTLCs ordered by htlcVout; index === htlcVout (asserted by the app). */\n siblings: readonly RebuildSibling[];\n /** Funded Pre-PegIn tx hex. Gate 0 (hash vs prepeginTxid) is SELF-verified below — callers need not pre-verify. */\n fundedPrePeginTxHex: string;\n\n // Stamped-version participant data (already resolved + sorted by the app).\n depositorBtcPubkey: string;\n vaultProviderBtcPubkey: string;\n vaultKeeperBtcPubkeys: readonly string[];\n universalChallengerBtcPubkeys: readonly string[];\n\n // Version-locked scalars.\n protocolFeeRate: bigint;\n minPeginFeeRate: bigint;\n councilQuorum: number;\n councilSize: number;\n timelockPegin: number;\n timelockAssert: number;\n timelockRefund: number;\n\n // Pass-through into DepositTerms.\n prepeginTxid: string;\n /** Funded-tx fee (Σin − Σout), computed by the app; the device's `prepegin_max_fee` bound. */\n prepeginMaxFee: bigint;\n maxAcceptableCommissionBps: number;\n\n /** WASM network descriptor for scriptPubKey derivation. */\n network: Parameters<typeof getPrePeginHtlcConnectorInfo>[0][\"network\"];\n}\n\nexport async function rebuildDepositTermsCore(\n input: RebuildDepositTermsCoreInput,\n): Promise<DepositTerms> {\n const siblingCount = input.siblings.length;\n if (siblingCount === 0) {\n throw new Error(\n \"rebuildDepositTermsCore: at least one sibling is required\",\n );\n }\n for (const [i, sibling] of input.siblings.entries()) {\n if (sibling.amount <= 0n) {\n throw new Error(\n `rebuildDepositTermsCore: sibling[${i}] has non-positive on-chain pegin ` +\n `amount ${sibling.amount}; the chain-read vault record is invalid. Resume refused.`,\n );\n }\n }\n if (input.prepeginMaxFee <= 0n) {\n throw new Error(\n `rebuildDepositTermsCore: prepeginMaxFee must be > 0, got ${input.prepeginMaxFee}`,\n );\n }\n\n // Gate 0, self-verified: everything below trusts these bytes, and a\n // substituted tx replicating the HTLC outputs would pass Gate 1 with a\n // different fee/txid.\n const expectedTxid = stripHexPrefix(input.prepeginTxid).toLowerCase();\n const actualTxid = stripHexPrefix(\n calculateBtcTxHash(input.fundedPrePeginTxHex),\n ).toLowerCase();\n if (actualTxid !== expectedTxid) {\n throw new Error(\n `Funded Pre-PegIn tx hashes to ${actualTxid}, expected ${expectedTxid} ` +\n `(on-chain prepeginTxid). Resume refused.`,\n );\n }\n\n // Completeness anchor: the single auth-anchor OP_RETURN sits at vout === HTLC\n // count — the only guard against an indexer-lagged partial sibling set.\n const found = findAuthAnchorOpReturn(\n stripHexPrefix(input.fundedPrePeginTxHex),\n );\n if (found === undefined) {\n throw new Error(\n `Funded Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN ` +\n `commitment — it either predates auth anchoring or is malformed. The ` +\n `intent resume path requires the anchor to prove sibling completeness. ` +\n `Resume refused.`,\n );\n }\n if (found.vout !== siblingCount) {\n throw new Error(\n `Auth-anchor OP_RETURN at vout ${found.vout} does not match the ` +\n `discovered sibling count ${siblingCount}; the discovered sibling set ` +\n `does not cover this transaction's HTLC outputs (a lagging index can ` +\n `cause this — retry later). Resume refused.`,\n );\n }\n\n // Amount-independent sizing. Depositor-as-claimer: numLocalChallengers ===\n // numVks (VP excluded) — btc-vault graph.rs derive_challengers_for.\n const numVks = input.vaultKeeperBtcPubkeys.length;\n const numUcs = input.universalChallengerBtcPubkeys.length;\n const depositorClaimValue = await computeMinClaimValue(\n input.vaultCoreVersion,\n numVks,\n numUcs,\n input.councilQuorum,\n input.councilSize,\n input.protocolFeeRate,\n );\n const peginMaxFee = await computeMinPeginFee(\n input.vaultCoreVersion,\n numVks,\n numUcs,\n input.minPeginFeeRate,\n );\n const anchor = await peginP2aAnchorOutput(input.vaultCoreVersion);\n const anchorValue = anchor?.value ?? 0n;\n\n // Independent bounds on the WASM outputs (mirrors assertWasmPeginSizing):\n // Gate 1 only proves the DCV+fee+anchor SUM — these constrain the\n // decomposition the device is shown.\n if (depositorClaimValue <= 0n) {\n throw new Error(\n `WASM returned non-positive depositorClaimValue ${depositorClaimValue}; ` +\n `expected > 0. Resume refused.`,\n );\n }\n if (peginMaxFee <= 0n) {\n throw new Error(\n `WASM returned non-positive peginMaxFee ${peginMaxFee}; expected > 0. ` +\n `Resume refused.`,\n );\n }\n // Explicit anchor check: the sum bound alone would let a negative anchor\n // offset an inflated peginMaxFee (kept local, not inherited from the facade).\n if (anchorValue < 0n) {\n throw new Error(\n `WASM returned negative P2A anchor value ${anchorValue}. Resume refused.`,\n );\n }\n const impliedReserve = peginMaxFee + anchorValue;\n const maxImpliedReserve = input.minPeginFeeRate * MAX_REASONABLE_PEGIN_VBYTES;\n if (impliedReserve <= 0n || impliedReserve > maxImpliedReserve) {\n throw new Error(\n `WASM implied PegIn reserve ${impliedReserve} sat is outside ` +\n `(0, ${maxImpliedReserve}] (minPeginFeeRate=${input.minPeginFeeRate} × ` +\n `${MAX_REASONABLE_PEGIN_VBYTES} vbytes). Resume refused.`,\n );\n }\n\n // Gate 1: per sibling, value = amount + DCV + peginMaxFee + anchor (btc-vault\n // compute_min_htlc_value) + scriptPubKey from the on-chain hashlock,\n // byte-matched against outputs 0..N-1.\n const expectedHtlcValues = input.siblings.map(\n (s) => s.amount + depositorClaimValue + peginMaxFee + anchorValue,\n );\n const expectedHtlcScriptPubKeys = await Promise.all(\n input.siblings.map(async (s) => {\n const connector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: input.vaultCoreVersion,\n depositorPubkey: input.depositorBtcPubkey,\n vaultProviderPubkey: input.vaultProviderBtcPubkey,\n vaultKeeperPubkeys: [...input.vaultKeeperBtcPubkeys],\n universalChallengerPubkeys: [...input.universalChallengerBtcPubkeys],\n hashlock: stripHexPrefix(s.hashlock),\n timelockRefund: input.timelockRefund,\n network: input.network,\n });\n return connector.scriptPubKey;\n }),\n );\n const fundedOutputs = Transaction.fromHex(\n stripHexPrefix(input.fundedPrePeginTxHex),\n ).outs.map((o) => ({ value: o.value, script: o.script }));\n assertEncodedHtlcOutputsMatch(\n fundedOutputs,\n expectedHtlcValues,\n expectedHtlcScriptPubKeys,\n );\n\n return buildDepositTerms({\n vaultCoreVersion: input.vaultCoreVersion,\n protocolFeeRate: input.protocolFeeRate,\n timelockPegin: input.timelockPegin,\n timelockAssert: input.timelockAssert,\n timelockRefund: input.timelockRefund,\n prepeginTxid: input.prepeginTxid,\n prepeginMaxFee: input.prepeginMaxFee,\n vaultProviderBtcPubkey: input.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: input.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: input.universalChallengerBtcPubkeys,\n maxAcceptableCommissionBps: input.maxAcceptableCommissionBps,\n peginAmounts: input.siblings.map((s) => s.amount),\n depositorClaimValue,\n peginMaxFee,\n });\n}\n","/**\n * Rebuild a {@link DepositTerms} at claim time, from chain and mempool only.\n *\n * The delegated claim can run months after the deposit, with no in-memory\n * terms and possibly no vault provider. An approval wallet still has to load\n * this vault's intent to sign the Assert and the depositor Payout, and the\n * device recomputes the PegIn txid from the intent, so every value here must\n * be the one the deposit was built with: the stamped versions and rosters,\n * the ceiling from the registration log, the siblings from the same log, the\n * funded fee from the transaction the chain saw.\n *\n * Takes the `readDelegatedClaimVaultContext` read rather than a vault id: that\n * read already fetched the vault record, the registration block, the\n * participant keys and the stamped params, and on a public RPC every repeat is\n * another chance of a spurious empty answer. Only the siblings still need a\n * reader.\n *\n * No lifecycle gate: the vault app's resume rebuild refuses non-PENDING\n * vaults and closed ack windows because it is about to finish a deposit; a\n * claimable vault is REDEEMED and long past both. The homogeneity and\n * contiguity checks are kept.\n *\n * @module deposit-terms/rebuildDepositTermsForClaim\n */\n\nimport { registrationPrePeginTxHash } from \"../clients/eth/registration-records\";\nimport type { VaultRegistryReader } from \"../clients/eth/types\";\nimport {\n canonicalizeBtcPubkey,\n stripHexPrefix,\n} from \"../primitives/utils/bitcoin\";\nimport type { DelegatedClaimVaultRead } from \"../services/delegated-claim/readDelegatedClaimVaultContext\";\nimport { calculateBtcTxHash } from \"../utils/transaction/btcTxHash\";\nimport {\n assertClaimBatchHomogeneous,\n orderClaimBatchByHtlcVout,\n selectSiblingRegistrations,\n type ClaimBatchMember,\n} from \"./claimSiblings\";\nimport type { DepositTerms } from \"./depositTerms\";\nimport { computeFundedPrePeginFee } from \"./fundedPrePeginFee\";\nimport {\n rebuildDepositTermsCore,\n type RebuildDepositTermsCoreInput,\n} from \"./rebuildDepositTermsCore\";\n\n/** @experimental */\nexport interface RebuildDepositTermsForClaimParams {\n /** The vault read this rebuild reuses instead of re-reading the chain. */\n read: DelegatedClaimVaultRead;\n /**\n * The connected wallet's own key (compressed or x-only): refused unless it\n * is the vault's depositor. Passing the on-chain key here makes that check\n * vacuous.\n */\n depositorBtcPubkey: string;\n /**\n * Funded Pre-PegIn hex, e.g. `getTxHex(prepeginTxid, mempoolApiUrl)`.\n * Hash-checked against the vault's `prePeginTxHash` here before any mempool\n * lookup, and again by the core (Gate 0).\n */\n fundedPrePeginTxHex: string;\n /** Reads the sibling vaults of the batch; the target is already in `read`. */\n siblingReader: Pick<VaultRegistryReader, \"getVaultData\">;\n /** Mempool API base URL, for the prevouts the fee is computed from. */\n mempoolApiUrl: string;\n network: RebuildDepositTermsCoreInput[\"network\"];\n}\n\n/**\n * @throws When the wallet key is not the depositor's, the hex is not the\n * vault's Pre-PegIn, a sibling is registered against a different\n * Pre-PegIn than its log records, the siblings disagree on a stamped\n * field or are non-contiguous, the fee is out of bounds, or the core\n * refuses (see `rebuildDepositTermsCore`).\n * A sibling registered in another block is missing from this read and\n * surfaces as the core's auth-anchor refusal, whose message suggests a\n * lagging index and a retry: on this path there is no index, and a\n * retry cannot help — that sibling must be registered in the same block.\n * @experimental\n */\nexport async function rebuildDepositTermsForClaim(\n params: RebuildDepositTermsForClaimParams,\n): Promise<DepositTerms> {\n const { read } = params;\n const connectedDepositor = canonicalizeBtcPubkey(params.depositorBtcPubkey);\n if (connectedDepositor !== read.context.depositorBtcPubkey) {\n throw new Error(\n `Connected wallet key is not the vault's depositor key; select the account ` +\n `that made the deposit.`,\n );\n }\n\n const prepeginTxid = stripHexPrefix(read.prePeginTxHash).toLowerCase();\n const actualTxid = stripHexPrefix(\n calculateBtcTxHash(params.fundedPrePeginTxHex),\n ).toLowerCase();\n if (actualTxid !== prepeginTxid) {\n throw new Error(\n `Funded Pre-PegIn tx hashes to ${actualTxid}, expected ${prepeginTxid} (on-chain prePeginTxHash).`,\n );\n }\n\n const siblingMembers: ClaimBatchMember[] = await Promise.all(\n selectSiblingRegistrations(\n read.registrationRecords,\n read.registrationRecord,\n ).map(async (record) => {\n const vault = await params.siblingReader.getVaultData(record.vaultId);\n if (\n vault.protocol.prePeginTxHash.toLowerCase() !==\n registrationPrePeginTxHash(record).toLowerCase()\n ) {\n throw new Error(\n `Sibling ${record.vaultId} is registered against a different Pre-PegIn on chain ` +\n `than its registration log records; refusing an inconsistent node.`,\n );\n }\n return {\n vault,\n maxAcceptableCommissionBps: record.maxAcceptableCommissionBps,\n };\n }),\n );\n const targetMember: ClaimBatchMember = {\n vault: read.vault,\n maxAcceptableCommissionBps:\n read.registrationRecord.maxAcceptableCommissionBps,\n };\n assertClaimBatchHomogeneous(targetMember, siblingMembers);\n const siblings = orderClaimBatchByHtlcVout([targetMember, ...siblingMembers]);\n\n const prepeginMaxFee = await computeFundedPrePeginFee(\n params.fundedPrePeginTxHex,\n params.mempoolApiUrl,\n );\n\n return rebuildDepositTermsCore({\n vaultCoreVersion: read.vault.protocol.vaultCoreVersion,\n siblings,\n fundedPrePeginTxHex: params.fundedPrePeginTxHex,\n depositorBtcPubkey: connectedDepositor,\n vaultProviderBtcPubkey:\n read.participantKeys.vaultProvider.operationBtcPubkey,\n vaultKeeperBtcPubkeys: read.participantKeys.vaultKeeperOperationKeysSorted,\n universalChallengerBtcPubkeys:\n read.participantKeys.universalChallengerOperationKeysSorted,\n protocolFeeRate: read.offchainParams.feeRate,\n minPeginFeeRate: read.offchainParams.minPeginFeeRate,\n councilQuorum: read.offchainParams.councilQuorum,\n councilSize: read.offchainParams.securityCouncilKeys.length,\n timelockPegin: read.context.timelockPegin,\n timelockAssert: read.context.timelockAssert,\n timelockRefund: read.offchainParams.tRefund,\n prepeginTxid,\n prepeginMaxFee,\n // The submitted ceiling, verbatim: the device must see the terms the\n // depositor originally approved.\n maxAcceptableCommissionBps:\n read.registrationRecord.maxAcceptableCommissionBps,\n network: params.network,\n });\n}\n","/**\n * Check whether an error from the vault provider indicates that the\n * submitted WOTS public key hash does not match the on-chain\n * commitment. This signals that the wrong wallet is connected (its\n * `deriveContextHash` produces a different vault root and therefore\n * different WOTS keys).\n */\nexport function isWotsMismatchError(error: unknown): boolean {\n const msg = (\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\"\n ).toLowerCase();\n\n return (\n msg.includes(\"wots\") &&\n msg.includes(\"hash\") &&\n msg.includes(\"does not match\")\n );\n}\n","/**\n * Canonical peg-in configuration fingerprint: the commitment a depositor sends\n * with a peg-in registration so the registry can prove, at inclusion, that the\n * protocol state it is about to bond the vault to is the state the Bitcoin lock\n * was actually built from.\n *\n * ## Why it exists\n *\n * Seven values are resolved live when a peg-in request is included, and every\n * one of them changes the bytes a depositor must have built: the vault\n * provider's operation-BTC key, the vault-keeper and universal-challenger key\n * epochs, the two roster versions (which members are in the HTLC all-party leaf\n * at all), the off-chain params version (`tRefund` in the refund leaf,\n * `minPeginFeeRate` in the output value) and the vault core version (the PegIn\n * output count, so the P2A anchor term in the value). A rotation, roster change\n * or version bump landing between the depositor's build and inclusion would\n * bond the vault to bytes the funded HTLC does not commit to. The registry\n * recomputes this fingerprint and reverts with `PeginFingerprintChanged` rather\n * than accepting such a request.\n *\n * ## Reproducing the contract exactly\n *\n * The encoding is `abi.encode`, never `abi.encodePacked` — the two produce\n * completely different bytes. Under `abi.encode` every field here is static and\n * occupies one left-padded 32-byte word, so the declared integer *width* never\n * reaches the output: encoding the tuple with all-`uint256` slots yields a\n * byte-identical hash. Only the field ORDER, the field COUNT, and whether a\n * type is static or dynamic can change the result. The widths in\n * {@link PeginFingerprintInput} therefore document the contract's own\n * declarations and bound the accepted inputs; they are not what makes the bytes\n * come out right.\n *\n * Mirrors `_peginFingerprint` in `src/protocol/lib/PeginLogic.sol` of\n * `babylonlabs-io/vault-contracts-aave-v4`. Pinned byte-for-byte against that\n * repository's committed vectors — see\n * `__tests__/peginFingerprint.golden.test.ts`.\n *\n * @module pegin-fingerprint/peginFingerprint\n */\n\nimport {\n encodeAbiParameters,\n isAddress,\n keccak256,\n toHex,\n zeroAddress,\n type Address,\n type Hex,\n} from \"viem\";\n\n/**\n * Domain-separation string hashed into every fingerprint, so the commitment\n * cannot be replayed as a different one. Matches the contract's\n * `PEGIN_FINGERPRINT_DOMAIN` preimage.\n */\nexport const PEGIN_FINGERPRINT_DOMAIN_PREIMAGE = \"TBV.PeginFingerprint.v1\";\n\n/**\n * `keccak256(\"TBV.PeginFingerprint.v1\")`, the first word of the encoded\n * preimage.\n *\n * Derived from {@link PEGIN_FINGERPRINT_DOMAIN_PREIMAGE} rather than pasted as\n * a hex literal, so the string that defines it stays visible. The golden test\n * pins the derived value against the constant the contract's vector file\n * publishes, so a change to either side is still caught.\n */\nexport const PEGIN_FINGERPRINT_DOMAIN: Hex = keccak256(\n toHex(PEGIN_FINGERPRINT_DOMAIN_PREIMAGE),\n);\n\n/** Inclusive upper bound of Solidity `uint16`, the width of all four versions. */\nconst UINT16_MAX = 65_535;\n/** Inclusive upper bound of Solidity `uint64`, the width of both key epochs. */\nconst UINT64_MAX = 2n ** 64n - 1n;\n/** Inclusive upper bound of Solidity `uint256`, the width of `block.chainid`. */\nconst UINT256_MAX = 2n ** 256n - 1n;\n/** A `bytes32` value as viem accepts it: `0x` followed by 64 hex digits. */\nconst BYTES32_PATTERN = /^0x[0-9a-fA-F]{64}$/;\n/**\n * Lowest `vaultCoreVersion` any live contract reports: the setter on\n * `ProtocolParams` rejects 0, so a 0 can only be a mis-decoded read.\n *\n * Mirrors the bound `assertValidVaultCoreVersion` applies in\n * `primitives/vaultCoreVersion.ts`; the two must move together. That function\n * is not called here because it throws a bare `Error`, which would put a second\n * error type into a module whose whole validation surface is\n * {@link PeginFingerprintInputError}.\n */\nconst VAULT_CORE_VERSION_MIN = 1;\n\n/**\n * Protocol state a Pre-PegIn transaction commits to, one field per encoded\n * word.\n *\n * Declared in encoding order so the interface reads as the specification does.\n * Reordering these fields does not change the output — the encoder names each\n * one explicitly — but keeping them aligned makes a divergence from the\n * contract visible on sight.\n */\nexport interface PeginFingerprintInput {\n /** `block.chainid` of the chain the registry is deployed on. */\n chainId: bigint;\n /**\n * The `BTCVaultRegistry` address, which the contract encodes as\n * `address(this)`. EIP-55 checksum casing is irrelevant to the encoded word\n * and is not required here; see {@link encodePeginFingerprintPreimage}.\n */\n registryAddress: Address;\n /**\n * The vault provider's RESOLVED operation-BTC key, 32 bytes, `0x`-prefixed.\n *\n * The resolved key, not an epoch counter: the VP epoch is one registry-wide\n * counter that ANY provider's key or payout append bumps, so committing to it\n * would let any registered provider invalidate every in-flight Pre-PegIn\n * protocol-wide. Only the chosen provider's key reaches the HTLC leaf, so\n * that is what is committed.\n *\n * Note the SDK resolves this key as an x-only pubkey WITHOUT a `0x` prefix\n * (`OnChainBtcPubkey`); callers add the prefix.\n */\n vaultProviderBtcKey: Hex;\n /** Vault-keeper operation-key epoch for this application (`uint64`). */\n appKeeperKeyEpoch: bigint;\n /** Universal-challenger operation-key epoch (`uint64`). */\n ucKeyEpoch: bigint;\n /** Roster version selecting which vault keepers are in the leaf (`uint16`). */\n appVaultKeepersVersion: number;\n /** Roster version selecting which universal challengers are in the leaf (`uint16`). */\n universalChallengersVersion: number;\n /** Off-chain params version: `tRefund` and `minPeginFeeRate` (`uint16`). */\n offchainParamsVersion: number;\n /** Vault core (tx-graph) version: the PegIn output count (`uint16`). */\n vaultCoreVersion: number;\n}\n\n/** An input field is missing, malformed, or outside the width the contract declares for it. */\nexport class PeginFingerprintInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PeginFingerprintInputError\";\n }\n}\n\n/**\n * Recognise the error above, including across a module boundary.\n *\n * Every message it carries names an internal field and the width it broke, so a\n * consumer needs to be able to catch it and substitute its own copy rather than\n * show the depositor what went wrong internally. `instanceof` alone fails\n * across duplicate module copies and test mocks, so the name is the fallback —\n * the same pattern the deposit-path drift guards use.\n */\nexport function isPeginFingerprintInputError(\n err: unknown,\n): err is PeginFingerprintInputError {\n return (\n err instanceof PeginFingerprintInputError ||\n (err instanceof Error && err.name === \"PeginFingerprintInputError\")\n );\n}\n\n/**\n * The type is checked before the range, and deliberately so.\n *\n * A purely relational guard (`value < 0n || value > max`) is not a guard at\n * all for a non-bigint: every comparison against `undefined`, `null` and `NaN`\n * evaluates `false`, so all three slip through, and `\"7\"` and `true` slip\n * through AND then encode — as 7 and as 1 — producing a well-formed\n * fingerprint from a value nobody supplied. TypeScript does not close this;\n * a JS consumer, a snapshot object missing a key, or an unawaited read all\n * reach here.\n */\nfunction assertUnsignedRange(\n field: string,\n value: bigint,\n max: bigint,\n solidityType: string,\n): void {\n if (typeof value !== \"bigint\") {\n throw new PeginFingerprintInputError(\n `${field} must be a bigint (Solidity ${solidityType}), got ${typeof value}`,\n );\n }\n if (value < 0n || value > max) {\n throw new PeginFingerprintInputError(\n `${field} must fit Solidity ${solidityType} (0..${max}), got ${value}`,\n );\n }\n}\n\nfunction assertUint16(field: string, value: number): void {\n if (!Number.isInteger(value) || value < 0 || value > UINT16_MAX) {\n throw new PeginFingerprintInputError(\n `${field} must be an integer fitting Solidity uint16 (0..${UINT16_MAX}), got ${value}`,\n );\n }\n}\n\n/**\n * Validate a `bytes32` field and return it lowercased.\n *\n * viem echoes the caller's hex casing straight into the encoded output, so an\n * upper-case key would yield a correct fingerprint (keccak hashes bytes, not\n * text) beside a preimage that no longer compares equal to the contract's.\n * That would defeat the one job {@link encodePeginFingerprintPreimage} has.\n */\nfunction normalizeBytes32(field: string, value: Hex): Hex {\n if (!BYTES32_PATTERN.test(value)) {\n throw new PeginFingerprintInputError(\n `${field} must be 32 bytes as 0x-prefixed hex (66 characters), got \"${value}\"`,\n );\n }\n return value.toLowerCase() as Hex;\n}\n\n/**\n * Validate the registry address and return it in the form the ABI word encodes.\n *\n * EIP-55 mixed-case is a display checksum over the same 20 bytes, and Solidity\n * never sees it. viem does: `encodeAbiParameters` rejects a mixed-case address\n * whose checksum does not verify, which would make legitimate inputs — the\n * contract's own `maximum_field_values` vector among them — fail to encode. So\n * the checksum is not enforced and the value is lowercased before encoding.\n *\n * This is normalisation, not a fallback: an address that is not 20 bytes of hex\n * is still rejected, loudly, before anything is encoded, as is the zero address\n * (the shape an unresolved contract-address read takes).\n */\nfunction normalizeRegistryAddress(registryAddress: Address): Address {\n if (!isAddress(registryAddress, { strict: false })) {\n throw new PeginFingerprintInputError(\n `registryAddress must be a 20-byte 0x-prefixed address, got \"${registryAddress}\"`,\n );\n }\n const normalized = registryAddress.toLowerCase() as Address;\n if (normalized === zeroAddress) {\n throw new PeginFingerprintInputError(\n \"registryAddress must not be the zero address; a zero here means the registry address was never resolved\",\n );\n }\n return normalized;\n}\n\n/**\n * The encoded tuple, as one list so the ordering lives in exactly one place.\n *\n * Not re-exported from the module barrel — this is internal, and exists in\n * this shape so the golden test can render it back into the type string the\n * contract's vector file publishes and compare the two. That comparison is a\n * second, independent check on the field order, one that does not depend on\n * the sample values in the vectors.\n */\nexport const PEGIN_FINGERPRINT_ABI_PARAMETERS = [\n { name: \"domain\", type: \"bytes32\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"registry\", type: \"address\" },\n { name: \"vaultProviderBtcKey\", type: \"bytes32\" },\n { name: \"appKeeperKeyEpoch\", type: \"uint64\" },\n { name: \"ucKeyEpoch\", type: \"uint64\" },\n { name: \"appVaultKeepersVersion\", type: \"uint16\" },\n { name: \"universalChallengersVersion\", type: \"uint16\" },\n { name: \"offchainParamsVersion\", type: \"uint16\" },\n { name: \"vaultCoreVersion\", type: \"uint16\" },\n] as const;\n\n/**\n * The `abi.encode` preimage the contract hashes — ten 32-byte words, 320 bytes.\n *\n * Exposed alongside {@link computePeginFingerprint} because a fingerprint\n * mismatch is otherwise two opaque hashes: comparing preimages word by word\n * localises the disagreement to a field. The contract's vector file ships the\n * same preimage next to each hash for exactly that reason.\n *\n * Three fields are held to a tighter bound than the contract's own width — a\n * zero `chainId`, a zero `registryAddress`, and a `vaultCoreVersion` below 1 —\n * because for each of them a zero is unreachable on-chain and so can only mean\n * a read that failed or was mis-decoded. No chain has id 0, no registry lives\n * at the zero address, and\n * `activeVaultCoreVersion()` is documented `uint16 >= 1` with a setter that\n * rejects 0. Encoding any of them would produce a well-formed fingerprint that\n * cannot ever match, turning a local mistake into an opaque on-chain revert.\n *\n * The three roster and params versions are NOT tightened: 0 is a legitimate\n * value on those axes.\n *\n * @throws {PeginFingerprintInputError} If any field is missing, malformed, or\n * outside the accepted range, naming the field and what was expected.\n */\nexport function encodePeginFingerprintPreimage(\n input: PeginFingerprintInput,\n): Hex {\n assertUnsignedRange(\"chainId\", input.chainId, UINT256_MAX, \"uint256\");\n if (input.chainId === 0n) {\n throw new PeginFingerprintInputError(\n \"chainId must not be 0; a zero here means the chain id was never resolved\",\n );\n }\n const registry = normalizeRegistryAddress(input.registryAddress);\n const vaultProviderBtcKey = normalizeBytes32(\n \"vaultProviderBtcKey\",\n input.vaultProviderBtcKey,\n );\n assertUnsignedRange(\n \"appKeeperKeyEpoch\",\n input.appKeeperKeyEpoch,\n UINT64_MAX,\n \"uint64\",\n );\n assertUnsignedRange(\"ucKeyEpoch\", input.ucKeyEpoch, UINT64_MAX, \"uint64\");\n assertUint16(\"appVaultKeepersVersion\", input.appVaultKeepersVersion);\n assertUint16(\n \"universalChallengersVersion\",\n input.universalChallengersVersion,\n );\n assertUint16(\"offchainParamsVersion\", input.offchainParamsVersion);\n assertUint16(\"vaultCoreVersion\", input.vaultCoreVersion);\n if (input.vaultCoreVersion < VAULT_CORE_VERSION_MIN) {\n throw new PeginFingerprintInputError(\n `vaultCoreVersion must be at least ${VAULT_CORE_VERSION_MIN}; ` +\n `${input.vaultCoreVersion} means the version was never resolved`,\n );\n }\n\n // Field order is the whole specification. The parameter list, this value\n // list, and the contract's `abi.encode(...)` call move together.\n return encodeAbiParameters(PEGIN_FINGERPRINT_ABI_PARAMETERS, [\n PEGIN_FINGERPRINT_DOMAIN,\n input.chainId,\n registry,\n vaultProviderBtcKey,\n input.appKeeperKeyEpoch,\n input.ucKeyEpoch,\n input.appVaultKeepersVersion,\n input.universalChallengersVersion,\n input.offchainParamsVersion,\n input.vaultCoreVersion,\n ]);\n}\n\n/**\n * The fingerprint to send as `expectedFingerprint` on a peg-in registration.\n *\n * Must equal what the registry recomputes at inclusion, byte for byte — the\n * comparison is exact equality, never \"no older than\", because resolving at a\n * superseded epoch would bond a new vault to a retired key.\n *\n * @throws {PeginFingerprintInputError} If any field is outside the width the\n * contract declares for it.\n */\nexport function computePeginFingerprint(input: PeginFingerprintInput): Hex {\n return keccak256(encodePeginFingerprintPreimage(input));\n}\n","/**\n * Typed failures for Pre-PegIn parameter recovery (#2203).\n *\n * Split by who can act on them. A root mismatch is user-fixable — wrong\n * wallet, wrong account or wrong network — and must be distinguishable from\n * a search that found nothing, which is ours. Without the split both look\n * identical to the caller.\n *\n * @module recovery/recoveryErrors\n */\n\n/**\n * The re-derived vault root does not match the funded Pre-PegIn's auth-anchor\n * OP_RETURN commitment.\n *\n * The root is bound to the wallet seed, the derivation account AND the\n * network (the wallet's `deriveContextHash` folds the connected pubkey and the\n * canonical network name into the HKDF `info`), so all three must match the\n * ones that created the deposit.\n */\nexport class VaultRootMismatchError extends Error {\n constructor(\n readonly derivedAuthAnchorHash: string,\n readonly onChainAuthAnchorHash: string,\n ) {\n super(\n `Re-derived vault root does not match this Pre-PegIn: derived ` +\n `auth-anchor hash ${derivedAuthAnchorHash}, transaction commits to ` +\n `${onChainAuthAnchorHash}. Connect the same wallet, on the same ` +\n `account and the same network, that created the deposit.`,\n );\n this.name = \"VaultRootMismatchError\";\n }\n}\n\n/**\n * The Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN.\n *\n * The anchor sits at `vout === htlcCount`, and it is the only structural\n * signal for how many HTLC outputs the transaction funds. Without it the\n * vault count would have to be guessed, so recovery refuses rather than\n * deriving the wrong number of hashlocks.\n */\nexport class UnanchoredPrePeginError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UnanchoredPrePeginError\";\n }\n}\n\n/**\n * No candidate parameter set reproduces the funded Pre-PegIn's HTLC outputs.\n *\n * Either the true parameters are outside the enumerated space — an operator\n * roster that rotated more than once has no chain-reachable historical read —\n * or the transaction is not one of ours.\n */\nexport class PeginParamsNotFoundError extends Error {\n constructor(\n readonly candidatesTried: number,\n /** A bounded sample of per-candidate rejection reasons, for diagnosis. */\n readonly sampleRejections: readonly string[],\n /** Versions that could not be read, the likeliest reason for no match. */\n readonly unresolvedLabels: readonly string[] = [],\n ) {\n super(\n `No candidate parameter set reproduces this Pre-PegIn's HTLC outputs ` +\n `(${candidatesTried} candidate(s) tried). ` +\n (unresolvedLabels.length > 0\n ? `${unresolvedLabels.length} version(s) could not be resolved and ` +\n `may hold the answer: ${unresolvedLabels.join(\" | \")}. `\n : \"\") +\n `Sample rejections: ${sampleRejections.join(\" | \")}`,\n );\n this.name = \"PeginParamsNotFoundError\";\n }\n}\n\n/**\n * More than one candidate reproduces the funded Pre-PegIn. Fail closed.\n *\n * Every survivor byte-matched the SAME funded outputs, so they agree on each\n * HTLC scriptPubKey and on the total value of each output, and would produce\n * the same refund transaction. What they disagree on is the SPLIT of that\n * value into `peginAmount` and reserve, and the version stamps that determine\n * it — neither of which the transaction carries any evidence of.\n */\nexport class PeginParamsAmbiguousError extends Error {\n constructor(readonly survivorLabels: readonly string[]) {\n super(\n `${survivorLabels.length} candidate parameter sets reproduce this ` +\n `Pre-PegIn's HTLC outputs, so the vault's stamped versions cannot be ` +\n `determined: ${survivorLabels.join(\" | \")}. Reconstruction refused.`,\n );\n this.name = \"PeginParamsAmbiguousError\";\n }\n}\n\n/**\n * Exactly one candidate matched, but the candidate space was known to be\n * incomplete. Fail closed.\n *\n * Uniqueness only detects a wrong answer when the right answer is ALSO in the\n * space. If the true version could not be read, a different version sharing\n * the same `timelockRefund` and participants matches the transaction just as\n * well — the search subtracts that candidate's reserve and the verifier adds\n * the same reserve back, so it survives — and the sole survivor would be\n * returned with the wrong version stamps and the wrong `peginAmount` split.\n *\n * Resolve the versions below and search again rather than trusting the match.\n */\nexport class PeginParamsIncompleteSpaceError extends Error {\n constructor(\n readonly matchedLabel: string,\n readonly unresolvedLabels: readonly string[],\n ) {\n super(\n `A candidate matched this Pre-PegIn (${matchedLabel}), but ` +\n `${unresolvedLabels.length} version(s) could not be resolved, so the ` +\n `search space did not provably contain the true parameters: ` +\n `${unresolvedLabels.join(\" | \")}. A version sharing the matched ` +\n `timelockRefund and participants is indistinguishable from the true ` +\n `one, so the match cannot be trusted. Reconstruction refused.`,\n );\n this.name = \"PeginParamsIncompleteSpaceError\";\n }\n}\n\n/**\n * A WASM sizing call returned a value no valid parameter set can produce.\n *\n * Raised before the value is consumed, and deliberately NOT treated as a\n * candidate rejection: it indicts the binary rather than the candidate, so it\n * escapes the search instead of being counted as one more parameter set that\n * did not match.\n */\nexport class PeginSizingIntegrityError extends Error {\n constructor(message: string) {\n super(`${message}. Reconstruction refused.`);\n this.name = \"PeginSizingIntegrityError\";\n }\n}\n","/**\n * Re-derive a stranded deposit's per-vault hashlocks from the wallet and the\n * funded Pre-PegIn transaction alone (#2203).\n *\n * An Ethereum reorg that drops the registration takes the vault row with it,\n * so the depositor pubkey, the HTLC vout and the hashlocks are gone. All three\n * are recoverable without a single `vaultId`-keyed read: the depositor pubkey\n * comes from the connected wallet, the vault count from the transaction's\n * auth-anchor OP_RETURN vout, and the hashlocks from the same HKDF pipeline the\n * deposit used.\n *\n * The parameter search that turns these hashlocks back into a refundable\n * template lives in `reconstructPeginParams` and needs no wallet.\n *\n * @module recovery/deriveHashlocksFromPrePegin\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nimport { findAuthAnchorOpReturn } from \"../managers/pegin/assertAuthAnchorOpReturn\";\nimport { expandPerVaultSecrets } from \"../managers/pegin/expandPerVaultSecrets\";\nimport {\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../primitives/utils/bitcoin\";\nimport {\n deriveVaultRoot,\n expandAuthAnchor,\n parseFundingOutpointsFromTx,\n type DeriveContextHashCapableWallet,\n} from \"../vault-secrets\";\n\nimport {\n UnanchoredPrePeginError,\n VaultRootMismatchError,\n} from \"./recoveryErrors\";\n\nexport interface DeriveHashlocksFromPrePeginInput {\n /** Any wallet implementing `deriveContextHash` — the depositor's own. */\n wallet: DeriveContextHashCapableWallet;\n /**\n * Depositor BTC public key, read from the CONNECTED WALLET. The reorg\n * destroyed the row that would normally supply it, and taking it from any\n * chain read would defeat the recovery.\n *\n * Accepted in whatever form the wallet hands back — x-only, 33-byte\n * compressed or 65-byte uncompressed, `0x` optional — and narrowed to x-only\n * here. Wallets return the compressed form from `getPublicKey`, so requiring\n * x-only would make the common case an error.\n */\n depositorBtcPubkey: string;\n /** Funded (broadcast) Pre-PegIn transaction hex, `0x` optional. */\n fundedPrePeginTxHex: string;\n}\n\nexport interface DeriveHashlocksFromPrePeginResult {\n /** Number of HTLC outputs the transaction funds, from the anchor's vout. */\n vaultCount: number;\n /** 32-byte hex hashlocks (no `0x`), indexed by `htlcVout`. */\n hashlocks: readonly string[];\n /** The transaction's auth-anchor commitment, `SHA256(authAnchor)` as hex. */\n authAnchorHash: string;\n}\n\n/**\n * Derive the per-vault hashlocks committed by a funded Pre-PegIn.\n *\n * Validates the re-derived root against the transaction's auth-anchor\n * OP_RETURN before expanding anything else. That check costs one HKDF call,\n * needs zero protocol parameters, and is what separates \"wrong wallet,\n * account or network\" from \"right wallet, no candidate matched\" — otherwise\n * both surface as a fruitless parameter search.\n *\n * @throws {UnanchoredPrePeginError} If the transaction carries no single,\n * unambiguous auth-anchor OP_RETURN.\n * @throws {VaultRootMismatchError} If the derived root does not commit to the\n * transaction's anchor.\n */\nexport async function deriveHashlocksFromPrePegin(\n input: DeriveHashlocksFromPrePeginInput,\n): Promise<DeriveHashlocksFromPrePeginResult> {\n const { wallet, depositorBtcPubkey, fundedPrePeginTxHex } = input;\n\n const cleanTxHex = stripHexPrefix(fundedPrePeginTxHex);\n const anchor = findAuthAnchorOpReturn(cleanTxHex);\n if (anchor === undefined) {\n throw new UnanchoredPrePeginError(\n `Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN, so the ` +\n `number of HTLC outputs it funds cannot be determined. Legacy ` +\n `pre-anchor deposits are not recoverable by this path.`,\n );\n }\n // The anchor sits immediately after the HTLC outputs, so its vout IS the\n // vault count. At vout 0 it would claim a Pre-PegIn that funds nothing.\n const vaultCount = anchor.vout;\n if (vaultCount === 0) {\n throw new UnanchoredPrePeginError(\n `Pre-PegIn's auth-anchor OP_RETURN is at vout 0, implying zero HTLC ` +\n `outputs; there is nothing to recover.`,\n );\n }\n\n const fundingOutpoints = parseFundingOutpointsFromTx(cleanTxHex);\n\n const root = await deriveVaultRoot(wallet, {\n // The vault context takes the 32-byte x-only key; a wallet's compressed\n // key would otherwise fail a byte-length check deep in the encoder with\n // nothing pointing back at the caller.\n depositorBtcPubkey: hexToUint8Array(\n processPublicKeyToXOnly(depositorBtcPubkey),\n ),\n fundingOutpoints,\n });\n\n // Ordering is load-bearing: `expandPerVaultSecrets` takes ownership of\n // `root` and zeroes it, so the anchor expansion must run first. On any\n // throw in this window nothing else will wipe the root, so wipe it here.\n try {\n const authAnchorBytes = await expandAuthAnchor(root);\n let derivedAuthAnchorHash: string;\n try {\n derivedAuthAnchorHash = uint8ArrayToHex(sha256(authAnchorBytes));\n } finally {\n authAnchorBytes.fill(0);\n }\n if (derivedAuthAnchorHash !== anchor.hash) {\n throw new VaultRootMismatchError(derivedAuthAnchorHash, anchor.hash);\n }\n } catch (err) {\n root.fill(0);\n throw err;\n }\n\n // Shares the deposit-time expansion rather than a hashlock-only variant, so\n // the two can never drift. Its WOTS output is unused here and dropped with\n // the result object; refunding spends the timelock leaf, not the preimage.\n const { hashlocks } = await expandPerVaultSecrets(root, vaultCount);\n\n return { vaultCount, hashlocks, authAnchorHash: anchor.hash };\n}\n","/**\n * The candidate parameter space `reconstructPeginParams` searches (#2203).\n *\n * A reorg destroys the vault row's version stamps but not the versioned data\n * they point at: `getOffchainParamsByVersion`, `getVaultKeepersByVersion` and\n * `getUniversalChallengersByVersion` are keyed by version, not by `vaultId`,\n * and survive. So the stamps are recoverable by enumeration.\n *\n * Two parameters are deliberately NOT axes here.\n *\n * `vaultCoreVersion` is supplied, not searched. The Pre-PegIn carries no\n * evidence of it: `getPrePeginHtlcConnectorInfo` produces a byte-identical\n * scriptPubKey for v1 and v2, and the version's only other effect on the\n * transaction is the size of the reserve folded into the HTLC value — which\n * the search inverts back out of that same value, so it matches by\n * construction. Enumerating it would guarantee an ambiguous result rather than\n * narrow one. See `__tests__/reconstructPeginParams.test.ts`, which pins the\n * identical-scriptPubKey fact so a future graph version that DOES change the\n * connector fails loudly here.\n *\n * The RFC-006 operation-key epochs are not enumerable at all. Every\n * epoch-keyed read needs `getVaultKeyEpochs(vaultId)` — the destroyed row —\n * and no ABI in this repo exposes an epoch history, a counter, or an event.\n * Only the genesis keys and the operators' current keys are reachable, which\n * is why {@link KeyEpochPolicy} has exactly two values and why they apply to\n * the whole participant set at once: a vault whose participants rotated more\n * than once since creation cannot be reconstructed.\n *\n * @module recovery/peginParamsCandidates\n */\n\nimport type { Address } from \"viem\";\n\n/** One versioned offchain-params snapshot, flattened to what a trial needs. */\nexport interface OffchainParamsCandidate {\n /** `offchainParamsVersion` stamp this snapshot would restore. */\n version: number;\n /** `VersionedOffchainParams.feeRate`. */\n protocolFeeRate: bigint;\n minPeginFeeRate: bigint;\n councilQuorum: number;\n /** `VersionedOffchainParams.securityCouncilKeys.length`. */\n councilSize: number;\n /** `getTimelockPeginByVersion(version)` — not a field on the params struct. */\n timelockPegin: number;\n timelockAssert: number;\n /** `VersionedOffchainParams.tRefund` — the only scalar here that reaches the HTLC scriptPubKey. */\n timelockRefund: number;\n}\n\n/**\n * One participant key set: a vault provider plus the two rosters at the\n * versions the vault was stamped with.\n *\n * Every key here must be an RFC-006 **operation** key resolved at that\n * participant's own key epoch, and the two roster arrays must be sorted —\n * exactly what `resolveParticipantKeysAtEpochs` produces as\n * `vaultKeeperOperationKeysSorted` / `universalChallengerOperationKeysSorted`.\n * Registration keys are NOT interchangeable: they only coincide with operation\n * keys while nobody has rotated, so passing them yields a wrong script on every\n * candidate and a not-found that wrongly implies the true set was tried.\n *\n * The three epochs are stamped independently by three registries, so a mixed\n * state — the vault provider rotated before this deposit, a challenger after —\n * is ordinary rather than impossible. That is why epochs are resolved per\n * participant from the `PegInSubmitted` log rather than chosen as one\n * all-genesis or all-current policy.\n */\nexport interface ParticipantKeySetCandidate {\n vaultProvider: Address;\n /** x-only operation-key hex (no `0x`) at the vault's `vpKeyEpoch`. */\n vaultProviderBtcPubkey: string;\n appVaultKeepersVersion: number;\n /** Sorted operation keys at the vault's `appKeeperKeyEpoch`. */\n vaultKeeperBtcPubkeys: readonly string[];\n universalChallengersVersion: number;\n /** Sorted operation keys at the vault's `ucKeyEpoch`. */\n universalChallengerBtcPubkeys: readonly string[];\n}\n\n/** A fully-determined parameter set to trial against the funded Pre-PegIn. */\nexport interface PeginParamsCandidate {\n /**\n * Stamped tx-graph version (NOT the chain-active one). Carried so the result\n * describes itself, but constant across a candidate space — see the module\n * note on why it cannot be searched.\n */\n vaultCoreVersion: number;\n offchainParams: OffchainParamsCandidate;\n participants: ParticipantKeySetCandidate;\n}\n\nexport interface BuildPeginParamsCandidatesInput {\n /**\n * The tx-graph version the stranded deposit was built with. A scalar, not a\n * list: the transaction cannot discriminate it, so this is taken on trust.\n * Read it from the orphaned `PegInSubmitted` log — `activeVaultCoreVersion()`\n * is the current version and is wrong for any deposit that predates a bump.\n */\n vaultCoreVersion: number;\n offchainParams: readonly OffchainParamsCandidate[];\n participantKeySets: readonly ParticipantKeySetCandidate[];\n}\n\n/**\n * Expand the two searchable axes into the flat candidate list\n * `reconstructPeginParams` trials.\n *\n * With the parameters read from the `PegInSubmitted` log this is called with\n * one entry per axis and produces a single candidate to verify. The\n * multi-element form is the fallback search.\n */\nexport function buildPeginParamsCandidates(\n input: BuildPeginParamsCandidatesInput,\n): PeginParamsCandidate[] {\n const { vaultCoreVersion, offchainParams, participantKeySets } = input;\n if (!Number.isInteger(vaultCoreVersion) || vaultCoreVersion < 1) {\n throw new Error(\n `buildPeginParamsCandidates: vaultCoreVersion must be a positive integer, got ${vaultCoreVersion}`,\n );\n }\n if (offchainParams.length === 0) {\n throw new Error(\n \"buildPeginParamsCandidates: at least one offchain-params version is required\",\n );\n }\n if (participantKeySets.length === 0) {\n throw new Error(\n \"buildPeginParamsCandidates: at least one participant key set is required\",\n );\n }\n\n const candidates: PeginParamsCandidate[] = [];\n for (const params of offchainParams) {\n for (const participants of participantKeySets) {\n candidates.push({\n vaultCoreVersion,\n offchainParams: params,\n participants,\n });\n }\n }\n return candidates;\n}\n\n/** Which enumeration a version belongs to. */\nexport type CandidateAxis =\n | \"offchainParams\"\n | \"vaultKeepers\"\n | \"universalChallengers\";\n\n/**\n * A version the caller enumerated over but could not resolve into candidate\n * data — dropped by `fetchAllOffchainParams`'s validation, or reported to a\n * roster loop's `onSkippedVersion` observer.\n *\n * Recorded rather than ignored because an unresolved version is UNRESOLVABLE,\n * not absent: it may be the very version that stamped the stranded vault, and\n * a search space missing its answer can still return a confident look-alike.\n */\nexport interface UnresolvedVersion {\n axis: CandidateAxis;\n version: number;\n reason: string;\n}\n\n/** Compact identity of an unresolved version, for error messages. */\nexport function describeUnresolvedVersion(\n unresolved: UnresolvedVersion,\n): string {\n return `${unresolved.axis} v${unresolved.version} (${unresolved.reason})`;\n}\n\n/** Compact identity of a candidate, for error messages and result labels. */\nexport function describePeginParamsCandidate(\n candidate: PeginParamsCandidate,\n): string {\n const { participants } = candidate;\n return (\n `core=${candidate.vaultCoreVersion} ` +\n `offchain=${candidate.offchainParams.version} ` +\n `keepers=${participants.appVaultKeepersVersion} ` +\n `challengers=${participants.universalChallengersVersion} ` +\n `vp=${participants.vaultProvider}`\n );\n}\n","/**\n * Recover a stranded deposit's destroyed protocol parameters by trialling an\n * enumerated candidate space against the funded Pre-PegIn transaction (#2203).\n *\n * This is a candidate enumerator plus a loop over an EXISTING verifier.\n * `rebuildDepositTermsCore` already answers \"do these parameters and this\n * funded transaction agree?\" — it rebuilds every HTLC scriptPubKey through the\n * WASM oracle and byte-matches script and value against the transaction, from\n * plain inputs with no chain access. Recovery reuses it verbatim so there is\n * exactly one implementation of that judgement in the codebase.\n *\n * No wallet, no `vaultId`, no browser: every input is either supplied by the\n * caller or read off the transaction. Hashlocks come from\n * `deriveHashlocksFromPrePegin`.\n *\n * @module recovery/reconstructPeginParams\n */\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Transaction } from \"bitcoinjs-lib\";\n\nimport type { DepositTerms } from \"../deposit-terms/depositTerms\";\nimport { rebuildDepositTermsCore } from \"../deposit-terms/rebuildDepositTermsCore\";\nimport { findAuthAnchorOpReturn } from \"../managers/pegin/assertAuthAnchorOpReturn\";\nimport { HtlcOutputMismatchError } from \"../primitives/psbt/assertWasmPeginSizing\";\nimport {\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../primitives/utils/bitcoin\";\nimport { calculateBtcTxHash } from \"../utils/transaction/btcTxHash\";\nimport {\n computeMinClaimValue,\n computeMinPeginFee,\n peginP2aAnchorOutput,\n} from \"../wasm\";\n\nimport {\n describePeginParamsCandidate,\n describeUnresolvedVersion,\n type PeginParamsCandidate,\n type UnresolvedVersion,\n} from \"./peginParamsCandidates\";\nimport {\n PeginParamsAmbiguousError,\n PeginParamsIncompleteSpaceError,\n PeginParamsNotFoundError,\n PeginSizingIntegrityError,\n UnanchoredPrePeginError,\n} from \"./recoveryErrors\";\n\n/**\n * How many per-candidate reasons an error message carries, for rejections and\n * for unevaluated candidates alike. The full list is one line per candidate and\n * runs to hundreds; a handful is enough to tell \"wrong transaction\" from\n * \"roster not enumerated\". Only the message is capped — the counts that drive\n * the fail-closed decisions stay exact.\n */\nconst MAX_REPORTED_REJECTIONS = 5;\n\nexport interface ReconstructPeginParamsInput {\n /** Hashlocks indexed by `htlcVout`, from `deriveHashlocksFromPrePegin`. */\n hashlocks: readonly string[];\n /** Funded (broadcast) Pre-PegIn transaction hex, `0x` optional. */\n fundedPrePeginTxHex: string;\n /** Depositor x-only BTC pubkey hex, from the connected wallet. */\n depositorBtcPubkey: string;\n /**\n * Funded-transaction fee, `Σin − Σout`. Not derivable from the transaction\n * alone — the input values live in the funding UTXOs — but those are\n * Bitcoin-keyed reads, which a reorg on Ethereum leaves intact.\n */\n prepeginMaxFee: bigint;\n /**\n * Commission ceiling projected into the returned {@link DepositTerms}. Not a\n * search axis: it never reaches the HTLC scriptPubKey or value, so the\n * transaction carries no evidence of it and the caller must supply the bound\n * it is willing to accept.\n */\n maxAcceptableCommissionBps: number;\n network: Network;\n /** The space to search, from `buildPeginParamsCandidates`. */\n candidates: readonly PeginParamsCandidate[];\n /**\n * Versions the caller enumerated over but could not resolve. Required, and\n * `[]` is the explicit claim that the enumeration was complete — so a caller\n * cannot arrive at a trusted answer by forgetting to mention its gaps.\n *\n * A non-empty list turns a sole match into a\n * {@link PeginParamsIncompleteSpaceError}: uniqueness only rules out a wrong\n * answer when the right answer was in the space to begin with.\n */\n unresolvedVersions: readonly UnresolvedVersion[];\n}\n\nexport interface ReconstructPeginParamsResult {\n /** The single candidate whose rebuild matched the funded transaction. */\n candidate: PeginParamsCandidate;\n /**\n * Terms projected from the matched candidate.\n *\n * The transaction pins the participant keys, `timelockRefund`, and each\n * HTLC's scriptPubKey and total value. It does NOT pin how that value splits\n * into `peginAmount`, `depositorClaimValue` and `peginMaxFee` — that split\n * follows from the matched candidate's fee-side parameters, which the\n * transaction carries no evidence of.\n */\n terms: DepositTerms;\n /**\n * Per-vault `peginAmount`, inverted from the observed HTLC output values.\n * Only as sound as the matched candidate's reserve — see {@link terms}.\n */\n peginAmounts: readonly bigint[];\n /** The transaction's `SHA256(authAnchor)` commitment, for the refund rebuild. */\n authAnchorHash: string;\n /** Size of the space actually trialled, for the recovery record. */\n candidatesTried: number;\n /**\n * Every candidate that matched and projected identical terms.\n *\n * More than one is normal rather than suspicious: candidates differing only\n * in fields the transaction cannot express — version labels whose\n * script- and value-relevant content is the same — are indistinguishable by\n * construction and describe the same deposit. They are reported rather than\n * refused; refusal is reserved for survivors whose terms actually differ.\n */\n matchedCandidates: readonly PeginParamsCandidate[];\n}\n\n/**\n * Canonical form of a match's observable content, for equality only.\n *\n * Two survivors agreeing here produce the same refund and the same reported\n * amounts, so the difference between them is a label with no consequence.\n */\nfunction matchFingerprint(\n terms: DepositTerms,\n peginAmounts: readonly bigint[],\n): string {\n return JSON.stringify({ terms, peginAmounts }, (_key, value) =>\n typeof value === \"bigint\" ? `${value}` : value,\n );\n}\n\n/** Amount-independent per-HTLC reserve, recomputed exactly as the verifier does. */\ninterface PeginSizing {\n depositorClaimValue: bigint;\n peginMaxFee: bigint;\n p2aAnchorValue: bigint;\n}\n\n/** Identity of the inputs that determine a candidate's reserve, for memoising it. */\nfunction sizingCacheKey(candidate: PeginParamsCandidate): string {\n const { offchainParams: params, participants } = candidate;\n return [\n candidate.vaultCoreVersion,\n participants.vaultKeeperBtcPubkeys.length,\n participants.universalChallengerBtcPubkeys.length,\n params.councilQuorum,\n params.councilSize,\n params.protocolFeeRate,\n params.minPeginFeeRate,\n ].join(\"|\");\n}\n\n/**\n * Compute the amount-independent reserve for one candidate, asserting the WASM\n * outputs before they are consumed (CLAUDE.md critical path 1).\n *\n * Only binary-integrity invariants are asserted here — a claim value or fee of\n * zero, or a negative anchor, is impossible for ANY valid parameter set, so it\n * indicts the binary rather than the candidate and must escape the search loop\n * instead of being counted as a rejection. The plausibility band on the implied\n * reserve is deliberately NOT duplicated: it depends on the candidate's own\n * `minPeginFeeRate`, so a candidate can legitimately fail it, and the verifier\n * applies it where it belongs — as a candidate filter.\n *\n * An absent anchor reads as `0n` because the facade returns `null` for graph\n * versions whose PegIn carries no anchor and never a zero-valued placeholder,\n * which is the same reading `rebuildDepositTermsCore` takes.\n */\nasync function computePeginSizing(\n candidate: PeginParamsCandidate,\n): Promise<PeginSizing> {\n const { offchainParams: params, participants } = candidate;\n // Depositor-as-claimer: the local-challenger count is the keeper count\n // (the vault provider is excluded) — btc-vault graph.rs derive_challengers_for.\n const numVks = participants.vaultKeeperBtcPubkeys.length;\n const numUcs = participants.universalChallengerBtcPubkeys.length;\n const [depositorClaimValue, peginMaxFee, anchorOutput] = await Promise.all([\n computeMinClaimValue(\n candidate.vaultCoreVersion,\n numVks,\n numUcs,\n params.councilQuorum,\n params.councilSize,\n params.protocolFeeRate,\n ),\n computeMinPeginFee(\n candidate.vaultCoreVersion,\n numVks,\n numUcs,\n params.minPeginFeeRate,\n ),\n peginP2aAnchorOutput(candidate.vaultCoreVersion),\n ]);\n const p2aAnchorValue = anchorOutput?.value ?? 0n;\n\n if (depositorClaimValue <= 0n) {\n throw new PeginSizingIntegrityError(\n `WASM returned non-positive depositorClaimValue ${depositorClaimValue} for graph version ${candidate.vaultCoreVersion}`,\n );\n }\n if (peginMaxFee <= 0n) {\n throw new PeginSizingIntegrityError(\n `WASM returned non-positive peginMaxFee ${peginMaxFee} for graph version ${candidate.vaultCoreVersion}`,\n );\n }\n if (p2aAnchorValue < 0n) {\n throw new PeginSizingIntegrityError(\n `WASM returned negative P2A anchor value ${p2aAnchorValue} for graph version ${candidate.vaultCoreVersion}`,\n );\n }\n\n return { depositorClaimValue, peginMaxFee, p2aAnchorValue };\n}\n\n/**\n * Search the candidate space for the parameter set that reproduces the funded\n * Pre-PegIn, and project it back into {@link DepositTerms}.\n *\n * Per candidate: invert each vault's `peginAmount` from the observed HTLC\n * output value via the protocol identity `htlcValue = peginAmount +\n * depositorClaimValue + peginMaxFee + p2aAnchorValue`, then hand the result to\n * `rebuildDepositTermsCore`, which independently recomputes that same sizing\n * and byte-matches both the value and the scriptPubKey of every HTLC output.\n *\n * Because the amount is inverted from the value it is compared against, the\n * VALUE check cannot discriminate between candidates: it holds for any\n * candidate whose reserve leaves a positive amount. The scriptPubKey does all\n * the discriminating, and `getPrePeginHtlcConnectorInfo` accepts exactly one\n * offchain-params scalar — `timelockRefund`. So two offchain versions sharing\n * a `timelockRefund` are indistinguishable however much their fee rates or\n * council parameters differ, and that is precisely the ambiguity this function\n * refuses to guess through. The value check is still run, by the verifier, as\n * the bound that stops a candidate whose reserve exceeds the funded output.\n *\n * Every candidate is trialled; the loop does not stop at the first match,\n * because detecting ambiguity is the point. Matches are then COMPARED rather\n * than counted — several candidates matching is the ordinary case whenever\n * their differences cannot reach the transaction, and refusing on a count\n * alone would reject a deposit whose refund is fully determined.\n *\n * A candidate is only rejected on a Gate-1 byte mismatch, which is the\n * transaction positively disagreeing with it. Any other failure means the\n * candidate was never really evaluated, so it is recorded as unresolved and\n * feeds the same fail-closed path as a version that could not be read —\n * otherwise an incidental error on the TRUE candidate would remove it silently\n * and hand back a look-alike as a trusted unique answer.\n *\n * @throws {UnanchoredPrePeginError} If the transaction carries no single,\n * unambiguous auth-anchor OP_RETURN.\n * @throws {PeginParamsNotFoundError} If no candidate matched.\n * @throws {PeginParamsAmbiguousError} If matches disagree on the projected terms.\n * @throws {PeginParamsIncompleteSpaceError} If a match is found but the space\n * was known to be incomplete, or a candidate failed to evaluate.\n */\nexport async function reconstructPeginParams(\n input: ReconstructPeginParamsInput,\n): Promise<ReconstructPeginParamsResult> {\n const {\n hashlocks,\n fundedPrePeginTxHex,\n depositorBtcPubkey,\n prepeginMaxFee,\n maxAcceptableCommissionBps,\n network,\n candidates,\n unresolvedVersions,\n } = input;\n\n if (hashlocks.length === 0) {\n throw new Error(\n \"reconstructPeginParams: at least one hashlock is required\",\n );\n }\n if (candidates.length === 0) {\n throw new Error(\"reconstructPeginParams: candidate space is empty\");\n }\n\n // The verifier compares this against WASM-built scripts and does not\n // normalise, while the derivation half accepts a `0x` prefix. Passing one\n // wallet string to both must not make step 1 pass and step 2 fail every\n // candidate, which would present as \"no parameters found\".\n const normalizedDepositorBtcPubkey =\n processPublicKeyToXOnly(depositorBtcPubkey);\n\n const cleanTxHex = stripHexPrefix(fundedPrePeginTxHex);\n const anchor = findAuthAnchorOpReturn(cleanTxHex);\n if (anchor === undefined) {\n throw new UnanchoredPrePeginError(\n `Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN; the ` +\n `sibling set cannot be proven complete. Reconstruction refused.`,\n );\n }\n // The verifier re-checks this, but catching it here attributes the failure\n // to the hashlock set rather than to every candidate in turn.\n if (anchor.vout !== hashlocks.length) {\n throw new Error(\n `reconstructPeginParams: ${hashlocks.length} hashlock(s) supplied but ` +\n `the auth-anchor OP_RETURN sits at vout ${anchor.vout}, so the ` +\n `transaction funds ${anchor.vout} HTLC output(s). Reconstruction refused.`,\n );\n }\n\n const outputs = Transaction.fromHex(cleanTxHex).outs;\n const observedHtlcValues = hashlocks.map((_, i) => BigInt(outputs[i].value));\n const prepeginTxid = stripHexPrefix(\n calculateBtcTxHash(cleanTxHex),\n ).toLowerCase();\n\n const sizingCache = new Map<string, PeginSizing>();\n const survivors: {\n candidate: PeginParamsCandidate;\n terms: DepositTerms;\n peginAmounts: bigint[];\n fingerprint: string;\n }[] = [];\n const rejections: string[] = [];\n // Count drives the fail-closed decision and must stay exact; only the labels\n // that reach the error message are capped, since in the fallback search every\n // candidate can land here and each entry embeds a full error message.\n const unevaluatedLabels: string[] = [];\n let unevaluatedCount = 0;\n\n for (const candidate of candidates) {\n try {\n const cacheKey = sizingCacheKey(candidate);\n let sizing = sizingCache.get(cacheKey);\n if (sizing === undefined) {\n sizing = await computePeginSizing(candidate);\n sizingCache.set(cacheKey, sizing);\n }\n const reserve =\n sizing.depositorClaimValue + sizing.peginMaxFee + sizing.p2aAnchorValue;\n const peginAmounts = observedHtlcValues.map((value) => value - reserve);\n // A reserve larger than the funded output is the transaction positively\n // disagreeing with this candidate — the value bound doing the one piece\n // of discriminating it can. The verifier would reject it too, but with a\n // generic error that would be misread as \"never evaluated\" and would\n // pollute the space with phantom gaps.\n const shortIndex = peginAmounts.findIndex((amount) => amount <= 0n);\n if (shortIndex !== -1) {\n throw new HtlcOutputMismatchError(\n `HTLC output[${shortIndex}] value ${observedHtlcValues[shortIndex]} ` +\n `is not above this candidate's reserve ${reserve}, so it implies a ` +\n `non-positive pegin amount ${peginAmounts[shortIndex]}.`,\n );\n }\n\n const { offchainParams: params, participants } = candidate;\n const terms = await rebuildDepositTermsCore({\n vaultCoreVersion: candidate.vaultCoreVersion,\n siblings: hashlocks.map((hashlock, i) => ({\n hashlock,\n amount: peginAmounts[i],\n })),\n fundedPrePeginTxHex: cleanTxHex,\n depositorBtcPubkey: normalizedDepositorBtcPubkey,\n vaultProviderBtcPubkey: participants.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: participants.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys:\n participants.universalChallengerBtcPubkeys,\n protocolFeeRate: params.protocolFeeRate,\n minPeginFeeRate: params.minPeginFeeRate,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n timelockPegin: params.timelockPegin,\n timelockAssert: params.timelockAssert,\n timelockRefund: params.timelockRefund,\n prepeginTxid,\n prepeginMaxFee,\n maxAcceptableCommissionBps,\n network,\n });\n\n survivors.push({\n candidate,\n terms,\n peginAmounts,\n fingerprint: matchFingerprint(terms, peginAmounts),\n });\n } catch (err) {\n // A malformed WASM sizing output is not a property of the candidate, so\n // counting it as a rejection would bury a broken binary under \"no\n // candidate matched\". Let it out.\n if (err instanceof PeginSizingIntegrityError) {\n throw err;\n }\n const label = describePeginParamsCandidate(candidate);\n const reason = err instanceof Error ? err.message : String(err);\n if (err instanceof HtlcOutputMismatchError) {\n // The transaction positively disagrees with this candidate — the\n // expected outcome for all but one, so it cannot propagate. Recorded,\n // and a sample reaches the not-found error to keep it diagnosable.\n if (rejections.length < MAX_REPORTED_REJECTIONS) {\n rejections.push(`[${label}] ${reason}`);\n }\n } else {\n // Anything else says nothing about the transaction: this candidate was\n // never actually evaluated. Treating it as a rejection would let an\n // incidental failure on the true candidate hand back a look-alike.\n unevaluatedCount++;\n if (unevaluatedLabels.length < MAX_REPORTED_REJECTIONS) {\n unevaluatedLabels.push(`${label} (${reason})`);\n }\n }\n }\n }\n\n // A candidate that could not be evaluated is a hole in the space in exactly\n // the same way an unreadable version is, so the two are reported together.\n const gapCount = unresolvedVersions.length + unevaluatedCount;\n const gaps = [\n ...unresolvedVersions.map(describeUnresolvedVersion),\n ...unevaluatedLabels,\n ];\n\n if (survivors.length === 0) {\n throw new PeginParamsNotFoundError(candidates.length, rejections, gaps);\n }\n\n // Compare, do not count. Survivors all byte-matched the same funded outputs,\n // so they already agree on every HTLC scriptPubKey and total value; if they\n // also project identical terms there is nothing to choose between them and\n // nothing is at stake in choosing.\n const distinct = new Set(survivors.map((s) => s.fingerprint));\n if (distinct.size > 1) {\n throw new PeginParamsAmbiguousError(\n survivors.map((s) => describePeginParamsCandidate(s.candidate)),\n );\n }\n\n // Reported after ambiguity: disagreeing survivors are the more specific\n // diagnosis, and that error already names them.\n if (gapCount > 0) {\n throw new PeginParamsIncompleteSpaceError(\n describePeginParamsCandidate(survivors[0].candidate),\n gaps,\n );\n }\n\n return {\n candidate: survivors[0].candidate,\n terms: survivors[0].terms,\n peginAmounts: survivors[0].peginAmounts,\n authAnchorHash: anchor.hash,\n candidatesTried: candidates.length,\n matchedCandidates: survivors.map((s) => s.candidate),\n };\n}\n","/**\n * Close the loop from a verified reconstruction to the ordinary refund path\n * (#2203).\n *\n * `buildAndBroadcastRefund` takes its two reads — the vault row and the\n * version-pinned Pre-PegIn context — as injected callbacks rather than\n * performing them itself. That is the whole seam recovery needs: a stranded\n * deposit has no row to read, but it does have a reconstruction that was\n * byte-verified against the funded transaction, and those are exactly the\n * fields the callbacks are expected to return.\n *\n * So recovery does not need a parallel refund implementation, and must not\n * have one. It supplies the same shapes from a different source and reuses the\n * orchestrator verbatim, which keeps the refund-fee cap, the abort checks, the\n * `htlcVout` contiguity invariant and the bitcoind error classification in one\n * place for both paths.\n *\n * @module recovery/toRefundInputs\n */\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport type { Address, Hex } from \"viem\";\n\nimport { ensureHexPrefix } from \"../primitives/utils/bitcoin\";\nimport type {\n RefundPrePeginContext,\n VaultRefundData,\n} from \"../services/refund/buildAndBroadcastRefund\";\n\nimport type { ReconstructPeginParamsResult } from \"./reconstructPeginParams\";\n\nexport interface ToRefundInputsOptions {\n /**\n * Which sibling of the Pre-PegIn to refund, as an index into the\n * reconstruction's hashlocks and amounts. Equal to the vault's `htlcVout`\n * by construction — `PeginManager` asserts `perVault[i].htlcVout === i`.\n */\n htlcVout: number;\n /**\n * Depositor BTC pubkey, the same value the reconstruction was run with.\n * Passed through rather than re-derived so the refund is built against the\n * key that was actually verified.\n *\n * Deliberately NOT narrowed to x-only here. `VaultRefundData.depositorBtcPubkey`\n * accepts \"32 or 33 bytes of hex\", and `buildAndBroadcastRefund` narrows it\n * with `processPublicKeyToXOnly` before it reaches the PSBT builder — so a\n * wallet's compressed key flows through unchanged, which is what wallets\n * actually return. Narrowing early would discard the parity byte the\n * orchestrator's own validation accepts.\n */\n depositorBtcPubkey: string;\n /**\n * The vault provider's application entry point. Not recoverable from the\n * Bitcoin transaction and not part of the verified parameter set — it is a\n * field of the vault-provider registry row, which is address-keyed and\n * survives the reorg untouched.\n */\n applicationEntryPoint: Address;\n /** Funded Pre-PegIn transaction hex, `0x` optional. */\n fundedPrePeginTxHex: string;\n /** Hashlocks indexed by `htlcVout`, as passed to the reconstruction. */\n hashlocks: readonly string[];\n /**\n * The Bitcoin network the reconstruction was verified against. An input to\n * the search rather than an output of it, so it is restated here; passing a\n * different one would build the refund against a different script tree than\n * the one that was proven to match.\n */\n network: Network;\n}\n\nexport interface RefundInputsFromRecovery {\n vault: VaultRefundData;\n context: RefundPrePeginContext;\n}\n\n/**\n * Project a verified reconstruction into the two shapes\n * `buildAndBroadcastRefund` injects.\n *\n * Every value here comes from a parameter set that has already been\n * byte-matched against the funded transaction's HTLC outputs, so this is a\n * projection and not a second validation pass. The orchestrator re-checks the\n * parts it owns regardless.\n *\n * @throws If `htlcVout` does not index the reconstructed batch, or the\n * hashlock vector disagrees with the reconstructed amounts.\n */\nexport function toRefundInputs(\n result: ReconstructPeginParamsResult,\n options: ToRefundInputsOptions,\n): RefundInputsFromRecovery {\n const {\n htlcVout,\n depositorBtcPubkey,\n applicationEntryPoint,\n fundedPrePeginTxHex,\n hashlocks,\n network,\n } = options;\n\n const { candidate, peginAmounts } = result;\n const { offchainParams, participants } = candidate;\n\n if (hashlocks.length !== peginAmounts.length) {\n throw new Error(\n `toRefundInputs: ${hashlocks.length} hashlock(s) but ` +\n `${peginAmounts.length} reconstructed amount(s); the reconstruction ` +\n `and the hashlock vector describe different transactions.`,\n );\n }\n if (\n !Number.isInteger(htlcVout) ||\n htlcVout < 0 ||\n htlcVout >= peginAmounts.length\n ) {\n throw new Error(\n `toRefundInputs: htlcVout ${htlcVout} is outside the reconstructed ` +\n `batch of ${peginAmounts.length} vault(s).`,\n );\n }\n\n // The orchestrator requires the complete vout-ordered batch, not just the\n // target: its anchor check is fail-closed, so refunding one sibling of a\n // multi-vault Pre-PegIn without the others is rejected outright.\n const batch = peginAmounts.map((amount, index) => ({\n hashlock: ensureHexPrefix(hashlocks[index]),\n amount,\n htlcVout: index,\n }));\n\n const vault: VaultRefundData = {\n vaultCoreVersion: candidate.vaultCoreVersion,\n hashlock: batch[htlcVout].hashlock as Hex,\n htlcVout,\n offchainParamsVersion: offchainParams.version,\n appVaultKeepersVersion: participants.appVaultKeepersVersion,\n universalChallengersVersion: participants.universalChallengersVersion,\n vaultProvider: participants.vaultProvider,\n applicationEntryPoint,\n amount: peginAmounts[htlcVout],\n unsignedPrePeginTxHex: fundedPrePeginTxHex,\n depositorBtcPubkey,\n batch,\n };\n\n const context: RefundPrePeginContext = {\n vaultProviderPubkey: participants.vaultProviderBtcPubkey,\n vaultKeeperPubkeys: participants.vaultKeeperBtcPubkeys,\n universalChallengerPubkeys: participants.universalChallengerBtcPubkeys,\n timelockRefund: offchainParams.timelockRefund,\n feeRate: offchainParams.protocolFeeRate,\n minPeginFeeRate: offchainParams.minPeginFeeRate,\n // Depositor-as-claimer: the local-challenger count is the keeper count,\n // the vault provider excluded — btc-vault graph.rs derive_challengers.\n numLocalChallengers: participants.vaultKeeperBtcPubkeys.length,\n councilQuorum: offchainParams.councilQuorum,\n councilSize: offchainParams.councilSize,\n network,\n };\n\n return { vault, context };\n}\n"],"names":["STAMPED_PROTOCOL_FIELDS","STAMPED_ADDRESS_FIELDS","selectSiblingRegistrations","records","target","depositor","prePeginTxHash","registrationPrePeginTxHash","r","assertClaimBatchHomogeneous","siblings","sibling","field","orderClaimBatchByHtlcVout","members","ordered","a","b","member","i","m","DEPOSIT_TERMS_REJECTED_ERROR_NAME","DepositTermsRejectedError","message","reason","__publicField","isDepositTermsRejectedError","err","shaped","computeFundedPrePeginFee","fundedPrePeginTxHex","mempoolApiUrl","tx","Transaction","stripHexPrefix","totalIn","input","getUtxoInfo","Buffer","sum","u","totalOut","o","fee","MAX_REASONABLE_FEE_SATS","rebuildDepositTermsCore","siblingCount","expectedTxid","actualTxid","calculateBtcTxHash","found","findAuthAnchorOpReturn","numVks","numUcs","depositorClaimValue","computeMinClaimValue","peginMaxFee","computeMinPeginFee","anchor","peginP2aAnchorOutput","anchorValue","impliedReserve","maxImpliedReserve","MAX_REASONABLE_PEGIN_VBYTES","expectedHtlcValues","s","expectedHtlcScriptPubKeys","getPrePeginHtlcConnectorInfo","fundedOutputs","assertEncodedHtlcOutputsMatch","buildDepositTerms","rebuildDepositTermsForClaim","params","read","connectedDepositor","canonicalizeBtcPubkey","prepeginTxid","siblingMembers","record","vault","targetMember","prepeginMaxFee","isWotsMismatchError","error","msg","PEGIN_FINGERPRINT_DOMAIN_PREIMAGE","PEGIN_FINGERPRINT_DOMAIN","keccak256","toHex","UINT16_MAX","UINT64_MAX","UINT256_MAX","BYTES32_PATTERN","VAULT_CORE_VERSION_MIN","PeginFingerprintInputError","isPeginFingerprintInputError","assertUnsignedRange","value","max","solidityType","assertUint16","normalizeBytes32","normalizeRegistryAddress","registryAddress","isAddress","normalized","zeroAddress","PEGIN_FINGERPRINT_ABI_PARAMETERS","encodePeginFingerprintPreimage","registry","vaultProviderBtcKey","encodeAbiParameters","computePeginFingerprint","VaultRootMismatchError","derivedAuthAnchorHash","onChainAuthAnchorHash","UnanchoredPrePeginError","PeginParamsNotFoundError","candidatesTried","sampleRejections","unresolvedLabels","PeginParamsAmbiguousError","survivorLabels","PeginParamsIncompleteSpaceError","matchedLabel","PeginSizingIntegrityError","deriveHashlocksFromPrePegin","wallet","depositorBtcPubkey","cleanTxHex","vaultCount","fundingOutpoints","parseFundingOutpointsFromTx","root","deriveVaultRoot","hexToUint8Array","processPublicKeyToXOnly","authAnchorBytes","expandAuthAnchor","uint8ArrayToHex","sha256","hashlocks","expandPerVaultSecrets","buildPeginParamsCandidates","vaultCoreVersion","offchainParams","participantKeySets","candidates","participants","describeUnresolvedVersion","unresolved","describePeginParamsCandidate","candidate","MAX_REPORTED_REJECTIONS","matchFingerprint","terms","peginAmounts","_key","sizingCacheKey","computePeginSizing","anchorOutput","p2aAnchorValue","reconstructPeginParams","maxAcceptableCommissionBps","network","unresolvedVersions","normalizedDepositorBtcPubkey","outputs","observedHtlcValues","_","sizingCache","survivors","rejections","unevaluatedLabels","unevaluatedCount","cacheKey","sizing","reserve","shortIndex","amount","HtlcOutputMismatchError","hashlock","label","gapCount","gaps","toRefundInputs","result","options","htlcVout","applicationEntryPoint","batch","index","ensureHexPrefix","context"],"mappings":"6zBA+BMA,GAA0B,CAC9B,mBACA,wBACA,yBACA,6BACF,EACMC,GAAyB,CAC7B,wBACA,eACF,EAGO,SAASC,GACdC,EACAC,EAC2B,CAC3B,MAAMC,EAAYD,EAAO,UAAU,YAAA,EAC7BE,EAAiBC,EAAAA,2BAA2BH,CAAM,EAAE,YAAA,EAE1D,OAAOD,EAAQ,OACZK,GACCA,EAAE,UAAYJ,EAAO,SACrBI,EAAE,UAAU,YAAA,IAAkBH,GAC9BE,EAAAA,2BAA2BC,CAAC,EAAE,gBAAkBF,CAAA,CAEtD,CAGO,SAASG,GACdL,EACAM,EACM,CACN,UAAWC,KAAWD,EAAU,CAC9B,UAAWE,KAASZ,GAClB,GAAIW,EAAQ,MAAM,SAASC,CAAK,IAAMR,EAAO,MAAM,SAASQ,CAAK,EAC/D,MAAM,IAAI,MACR,gDAAgDA,CAAK,KAC/CD,EAAQ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