@babylonlabs-io/ts-sdk 3.1.2 → 3.2.1

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 (168) hide show
  1. package/dist/BTCVaultRegistry.abi-BH2-LHxN.cjs +2 -0
  2. package/dist/BTCVaultRegistry.abi-BH2-LHxN.cjs.map +1 -0
  3. package/dist/{BTCVaultRegistry.abi-BmHpMUWD.js → BTCVaultRegistry.abi-BzNTa_EU.js} +19 -1
  4. package/dist/BTCVaultRegistry.abi-BzNTa_EU.js.map +1 -0
  5. package/dist/{PayoutManager-DOdsgcUR.cjs → PayoutManager-B1Ev0r7o.cjs} +2 -2
  6. package/dist/{PayoutManager-DOdsgcUR.cjs.map → PayoutManager-B1Ev0r7o.cjs.map} +1 -1
  7. package/dist/{PayoutManager-BZ212yml.js → PayoutManager-xEGvTbhL.js} +3 -3
  8. package/dist/{PayoutManager-BZ212yml.js.map → PayoutManager-xEGvTbhL.js.map} +1 -1
  9. package/dist/{PeginManager-PyKbfy5q.cjs → PeginManager-BCRtUqyX.cjs} +2 -2
  10. package/dist/{PeginManager-PyKbfy5q.cjs.map → PeginManager-BCRtUqyX.cjs.map} +1 -1
  11. package/dist/{PeginManager-Dfr5Qe1g.js → PeginManager-sizm3dlw.js} +7 -7
  12. package/dist/{PeginManager-Dfr5Qe1g.js.map → PeginManager-sizm3dlw.js.map} +1 -1
  13. package/dist/buildAndBroadcastReclaim-CE77jzTp.cjs +2 -0
  14. package/dist/buildAndBroadcastReclaim-CE77jzTp.cjs.map +1 -0
  15. package/dist/{buildAndBroadcastReclaim-R0HNpLMD.js → buildAndBroadcastReclaim-rQyAiAUS.js} +901 -867
  16. package/dist/buildAndBroadcastReclaim-rQyAiAUS.js.map +1 -0
  17. package/dist/challengeAssert-B2otuf7y.js +509 -0
  18. package/dist/challengeAssert-B2otuf7y.js.map +1 -0
  19. package/dist/challengeAssert-C3eMcM5Y.cjs +2 -0
  20. package/dist/challengeAssert-C3eMcM5Y.cjs.map +1 -0
  21. package/dist/constants-CAm10Qwp.cjs +2 -0
  22. package/dist/constants-CAm10Qwp.cjs.map +1 -0
  23. package/dist/constants-CvQZuxKv.js +48 -0
  24. package/dist/constants-CvQZuxKv.js.map +1 -0
  25. package/dist/{index-CVBtBjQ5.js → index-BRsWXDlv.js} +6 -6
  26. package/dist/{index-CVBtBjQ5.js.map → index-BRsWXDlv.js.map} +1 -1
  27. package/dist/{index-DpjYs5yr.cjs → index-C6avwx1s.cjs} +2 -2
  28. package/dist/{index-DpjYs5yr.cjs.map → index-C6avwx1s.cjs.map} +1 -1
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.js +297 -298
  31. package/dist/index.js.map +1 -1
  32. package/dist/{pegin-registration-client-kdz4fT5_.js → pegin-registration-client-8tzSRDaq.js} +46 -45
  33. package/dist/pegin-registration-client-8tzSRDaq.js.map +1 -0
  34. package/dist/pegin-registration-client-Bmkh1OZ9.cjs +2 -0
  35. package/dist/pegin-registration-client-Bmkh1OZ9.cjs.map +1 -0
  36. package/dist/peginState-CIibG9S_.js +75 -0
  37. package/dist/peginState-CIibG9S_.js.map +1 -0
  38. package/dist/peginState-IyE22wWh.cjs +2 -0
  39. package/dist/peginState-IyE22wWh.cjs.map +1 -0
  40. package/dist/{primeVpAuth-BPj2TPdD.cjs → primeVpAuth-CXNXYKrh.cjs} +2 -2
  41. package/dist/{primeVpAuth-BPj2TPdD.cjs.map → primeVpAuth-CXNXYKrh.cjs.map} +1 -1
  42. package/dist/{primeVpAuth-CiCdRNGf.js → primeVpAuth-D4UWXQ76.js} +2 -2
  43. package/dist/{primeVpAuth-CiCdRNGf.js.map → primeVpAuth-D4UWXQ76.js.map} +1 -1
  44. package/dist/{registration-records-CKLAv3gw.js → registration-records-BBOz21Dm.js} +15 -15
  45. package/dist/{registration-records-CKLAv3gw.js.map → registration-records-BBOz21Dm.js.map} +1 -1
  46. package/dist/{registration-records-DFQgBaYi.cjs → registration-records-DaBufozs.cjs} +2 -2
  47. package/dist/{registration-records-DFQgBaYi.cjs.map → registration-records-DaBufozs.cjs.map} +1 -1
  48. package/dist/{reservation-DOAHVT3B.js → reservation-BZQABu4g.js} +2 -2
  49. package/dist/{reservation-DOAHVT3B.js.map → reservation-BZQABu4g.js.map} +1 -1
  50. package/dist/{reservation-ECxjZi5t.cjs → reservation-CA5knoQ0.cjs} +2 -2
  51. package/dist/{reservation-ECxjZi5t.cjs.map → reservation-CA5knoQ0.cjs.map} +1 -1
  52. package/dist/{signer-set-reader-DFAu6I-v.cjs → signer-set-reader-D-CyIYR5.cjs} +2 -2
  53. package/dist/{signer-set-reader-DFAu6I-v.cjs.map → signer-set-reader-D-CyIYR5.cjs.map} +1 -1
  54. package/dist/{signer-set-reader-BCtmSKUM.js → signer-set-reader-DFF9MgQN.js} +2 -2
  55. package/dist/{signer-set-reader-BCtmSKUM.js.map → signer-set-reader-DFF9MgQN.js.map} +1 -1
  56. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  57. package/dist/tbv/core/clients/eth/index.js +4 -4
  58. package/dist/tbv/core/clients/eth/types.d.ts +8 -0
  59. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  60. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  61. package/dist/tbv/core/clients/index.cjs +1 -1
  62. package/dist/tbv/core/clients/index.js +6 -6
  63. package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
  64. package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
  65. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +14 -0
  66. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  67. package/dist/tbv/core/contracts/index.cjs +1 -1
  68. package/dist/tbv/core/contracts/index.js +1 -1
  69. package/dist/tbv/core/index.cjs +1 -1
  70. package/dist/tbv/core/index.js +293 -294
  71. package/dist/tbv/core/index.js.map +1 -1
  72. package/dist/tbv/core/managers/index.cjs +1 -1
  73. package/dist/tbv/core/managers/index.js +2 -2
  74. package/dist/tbv/core/primitives/index.cjs +1 -1
  75. package/dist/tbv/core/primitives/index.js +29 -30
  76. package/dist/tbv/core/primitives/index.js.map +1 -1
  77. package/dist/tbv/core/primitives/psbt/__tests__/challengeAssert.test.d.ts +2 -0
  78. package/dist/tbv/core/primitives/psbt/__tests__/challengeAssert.test.d.ts.map +1 -0
  79. package/dist/tbv/core/primitives/psbt/__tests__/noPayout.test.d.ts +2 -0
  80. package/dist/tbv/core/primitives/psbt/__tests__/noPayout.test.d.ts.map +1 -0
  81. package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +43 -0
  82. package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -1
  83. package/dist/tbv/core/primitives/psbt/constants.d.ts +50 -2
  84. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  85. package/dist/tbv/core/primitives/psbt/noPayout.d.ts +42 -0
  86. package/dist/tbv/core/primitives/psbt/noPayout.d.ts.map +1 -1
  87. package/dist/tbv/core/services/activation/activateVault.d.ts +50 -0
  88. package/dist/tbv/core/services/activation/activateVault.d.ts.map +1 -1
  89. package/dist/tbv/core/services/activation/index.d.ts +1 -1
  90. package/dist/tbv/core/services/activation/index.d.ts.map +1 -1
  91. package/dist/tbv/core/services/delegated-claim/__tests__/realWasmWatchtowerArtifacts.test.d.ts +9 -0
  92. package/dist/tbv/core/services/delegated-claim/__tests__/realWasmWatchtowerArtifacts.test.d.ts.map +1 -0
  93. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts +5 -7
  94. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts.map +1 -1
  95. package/dist/tbv/core/services/delegated-claim/index.d.ts +3 -4
  96. package/dist/tbv/core/services/delegated-claim/index.d.ts.map +1 -1
  97. package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts.map +1 -1
  98. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts +14 -8
  99. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts.map +1 -1
  100. package/dist/tbv/core/services/delegated-claim/types.d.ts +32 -19
  101. package/dist/tbv/core/services/delegated-claim/types.d.ts.map +1 -1
  102. package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.realGraph.test.d.ts +12 -0
  103. package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.realGraph.test.d.ts.map +1 -0
  104. package/dist/tbv/core/services/deposit/peginState.d.ts +20 -1
  105. package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -1
  106. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +7 -0
  107. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  108. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +46 -1
  109. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  110. package/dist/tbv/core/services/index.cjs +1 -1
  111. package/dist/tbv/core/services/index.js +59 -59
  112. package/dist/tbv/core/utils/index.cjs +1 -1
  113. package/dist/tbv/core/utils/index.js +1 -1
  114. package/dist/tbv/core/wasm/__tests__/challengeAssertOutputConnector.test.d.ts +2 -0
  115. package/dist/tbv/core/wasm/__tests__/challengeAssertOutputConnector.test.d.ts.map +1 -0
  116. package/dist/tbv/core/wasm/index.cjs +1 -1
  117. package/dist/tbv/core/wasm/index.cjs.map +1 -1
  118. package/dist/tbv/core/wasm/index.d.ts +14 -2
  119. package/dist/tbv/core/wasm/index.d.ts.map +1 -1
  120. package/dist/tbv/core/wasm/index.js +81 -77
  121. package/dist/tbv/core/wasm/index.js.map +1 -1
  122. package/dist/tbv/index.cjs +1 -1
  123. package/dist/tbv/index.js +293 -294
  124. package/dist/tbv/index.js.map +1 -1
  125. package/dist/{toRefundInputs-BbAOOUg6.cjs → toRefundInputs-DOCLxqC1.cjs} +2 -2
  126. package/dist/{toRefundInputs-BbAOOUg6.cjs.map → toRefundInputs-DOCLxqC1.cjs.map} +1 -1
  127. package/dist/{toRefundInputs-DW14g6wH.js → toRefundInputs-Dso_QEr-.js} +5 -5
  128. package/dist/{toRefundInputs-DW14g6wH.js.map → toRefundInputs-Dso_QEr-.js.map} +1 -1
  129. package/dist/{types-Bda75Od0.cjs → types-DGr5HWwD.cjs} +2 -2
  130. package/dist/types-DGr5HWwD.cjs.map +1 -0
  131. package/dist/{types-C5jj3Cc-.js → types-Dbs--c2M.js} +2 -2
  132. package/dist/types-Dbs--c2M.js.map +1 -0
  133. package/dist/{verifyKeyPathSchnorrSignature-CQUut2-O.cjs → verifyKeyPathSchnorrSignature-BRTpEH9X.cjs} +2 -2
  134. package/dist/{verifyKeyPathSchnorrSignature-CQUut2-O.cjs.map → verifyKeyPathSchnorrSignature-BRTpEH9X.cjs.map} +1 -1
  135. package/dist/{verifyKeyPathSchnorrSignature-DxPbeSdQ.js → verifyKeyPathSchnorrSignature-IIj3Z2se.js} +2 -2
  136. package/dist/{verifyKeyPathSchnorrSignature-DxPbeSdQ.js.map → verifyKeyPathSchnorrSignature-IIj3Z2se.js.map} +1 -1
  137. package/dist/{verifyScriptPathSchnorrSignature-D2t1yACC.cjs → verifyScriptPathSchnorrSignature-CahYx5Td.cjs} +2 -2
  138. package/dist/{verifyScriptPathSchnorrSignature-D2t1yACC.cjs.map → verifyScriptPathSchnorrSignature-CahYx5Td.cjs.map} +1 -1
  139. package/dist/{verifyScriptPathSchnorrSignature-B3-VkvnK.js → verifyScriptPathSchnorrSignature-owu3BfyT.js} +2 -2
  140. package/dist/{verifyScriptPathSchnorrSignature-B3-VkvnK.js.map → verifyScriptPathSchnorrSignature-owu3BfyT.js.map} +1 -1
  141. package/package.json +3 -3
  142. package/dist/BTCVaultRegistry.abi-BmHpMUWD.js.map +0 -1
  143. package/dist/BTCVaultRegistry.abi-DffWFdpA.cjs +0 -2
  144. package/dist/BTCVaultRegistry.abi-DffWFdpA.cjs.map +0 -1
  145. package/dist/buildAndBroadcastReclaim-Da8rD5Z7.cjs +0 -2
  146. package/dist/buildAndBroadcastReclaim-Da8rD5Z7.cjs.map +0 -1
  147. package/dist/buildAndBroadcastReclaim-R0HNpLMD.js.map +0 -1
  148. package/dist/challengeAssert-Cp_GeRg8.js +0 -64
  149. package/dist/challengeAssert-Cp_GeRg8.js.map +0 -1
  150. package/dist/challengeAssert-Z7_YULBb.cjs +0 -2
  151. package/dist/challengeAssert-Z7_YULBb.cjs.map +0 -1
  152. package/dist/constants-BeYquVd-.js +0 -36
  153. package/dist/constants-BeYquVd-.js.map +0 -1
  154. package/dist/constants-BwCg5K6R.cjs +0 -2
  155. package/dist/constants-BwCg5K6R.cjs.map +0 -1
  156. package/dist/noPayout-B-vGXJ-V.js +0 -361
  157. package/dist/noPayout-B-vGXJ-V.js.map +0 -1
  158. package/dist/noPayout-DOHak0ui.cjs +0 -2
  159. package/dist/noPayout-DOHak0ui.cjs.map +0 -1
  160. package/dist/pegin-registration-client-C-abxMWq.cjs +0 -2
  161. package/dist/pegin-registration-client-C-abxMWq.cjs.map +0 -1
  162. package/dist/pegin-registration-client-kdz4fT5_.js.map +0 -1
  163. package/dist/peginState-BU2ONFXF.js +0 -68
  164. package/dist/peginState-BU2ONFXF.js.map +0 -1
  165. package/dist/peginState-DUv10EJR.cjs +0 -2
  166. package/dist/peginState-DUv10EJR.cjs.map +0 -1
  167. package/dist/types-Bda75Od0.cjs.map +0 -1
  168. package/dist/types-C5jj3Cc-.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"noPayout-B-vGXJ-V.js","sources":["../src/tbv/core/wasm/value-guards.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport { loadTbvWasm, tapInternalPubkey } from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\nimport { REFUND_TX_LOCKTIME, REFUND_TX_VERSION } from \"./constants\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n const { WasmPrePeginTx } = await loadTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against an independent\n // TypeScript derivation and the funded transaction bytes.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const wasmHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n const expectedHtlc = deriveExpectedPrePeginHtlc(prePeginParams, hashlock);\n const expectedHtlcScriptPubKey = expectedHtlc.scriptPubKey.toString(\"hex\");\n if (wasmHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `WASM HTLC scriptPubKey ${wasmHtlcScriptPubKey} does not match the ` +\n `independently derived scriptPubKey ${expectedHtlcScriptPubKey}.`,\n );\n }\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + p2aAnchorValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.version !== REFUND_TX_VERSION) {\n throw new Error(\n `Refund transaction version ${refundTx.version} does not match ` +\n `protocol version ${REFUND_TX_VERSION}.`,\n );\n }\n if (refundTx.locktime !== REFUND_TX_LOCKTIME) {\n throw new Error(\n `Refund transaction locktime ${refundTx.locktime} does not match ` +\n `protocol locktime ${REFUND_TX_LOCKTIME}.`,\n );\n }\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n if (refundInput.sequence !== prePeginParams.timelockRefund) {\n throw new Error(\n `Refund input sequence ${refundInput.sequence} does not match ` +\n `timelockRefund ${prePeginParams.timelockRefund}.`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.refundScript,\n controlBlock: expectedHtlc.refundControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `tapLeafScript, got ${tapLeafScripts?.length ?? 0}.`,\n );\n }\n const leaf = tapLeafScripts[0];\n if (leaf.leafVersion !== TAPSCRIPT_LEAF_VERSION) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}], used verbatim — derive them from the parent txs */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","fundedTx","wasmHtlcScriptPubKey","expectedHtlc","deriveExpectedPrePeginHtlc","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","hexToUint8Array","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyTo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S=require("./tbv/core/wasm/index.cjs"),t=require("./bitcoin-D-O2GjbC.cjs"),h=require("./verifyScriptPathSchnorrSignature-D2t1yACC.cjs"),v=require("./constants-BwCg5K6R.cjs"),N=require("./fundPeginTransaction-54-Rwb2k.cjs"),k=require("./validation-C6XTfZak.cjs"),V=(1n<<64n)-1n;function B(r,u){if(!Array.isArray(r))throw new Error(`${u} must be an array of positive bigints (got ${typeof r}).`);if(r.length===0)throw new Error(`${u} must not be empty.`);return r.forEach((e,n)=>{if(typeof e!="bigint")throw new Error(`${u}[${n}] must be a bigint (got ${typeof e}); refusing to feed it into satoshi math.`);if(e<=0n)throw new Error(`${u}[${n}] must be > 0 (got ${e}).`);if(e>V)throw new Error(`${u}[${n}] must fit in a u64 (got ${e}); refusing to feed it into satoshi math.`)}),r}async function K(r){const{WasmPrePeginTx:u}=await S.loadTbvWasm(),{prePeginParams:e,fundedPrePeginTxHex:n,htlcVout:s,refundFee:f,hashlock:c}=r,l=h.normalizeAuthAnchorHash(e.authAnchorHash),o=new u(e.vaultCoreVersion,e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(B(e.pegInAmounts,"pegInAmounts")),e.timelockRefund,e.feeRate,e.minPeginFeeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,l);let a=null;try{const d=o.getHtlcScriptPubKey(s).toLowerCase(),i=h.deriveExpectedPrePeginHtlc(e,c),P=i.scriptPubKey.toString("hex");if(d!==P)throw new Error(`WASM HTLC scriptPubKey ${d} does not match the independently derived scriptPubKey ${P}.`);const T=o.getHtlcValue(s);a=o.fromFundedTransaction(n);const w=a.buildRefundTx(f,s),b=n.startsWith("0x")?n.slice(2):n,$=m.Transaction.fromHex(b),E=$.outs[s];if(!E)throw new Error(`HTLC output at vout ${s} not found in funded Pre-PegIn tx (tx has ${$.outs.length} outputs)`);const I=t.uint8ArrayToHex(new Uint8Array(E.script)).toLowerCase();if(I!==P)throw new Error(`HTLC scriptPubKey mismatch at vout ${s}: reconstructed template expects ${P}, funded tx carries ${I}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`);const g=BigInt(E.value);if(g!==T)throw new Error(`HTLC value mismatch at vout ${s}: reconstructed template expects ${T} sat, funded tx carries ${g} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`);const p=m.Transaction.fromHex(w);if(p.version!==v.REFUND_TX_VERSION)throw new Error(`Refund transaction version ${p.version} does not match protocol version ${v.REFUND_TX_VERSION}.`);if(p.locktime!==v.REFUND_TX_LOCKTIME)throw new Error(`Refund transaction locktime ${p.locktime} does not match protocol locktime ${v.REFUND_TX_LOCKTIME}.`);if(p.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${p.ins.length}`);const y=p.ins[0],H=$.getId(),O=t.uint8ArrayToHex(new Uint8Array(y.hash).slice().reverse());if(O!==H)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${H}, got ${O}`);if(y.index!==s)throw new Error(`Refund input index ${y.index} does not match expected htlcVout ${s}`);if(y.sequence!==e.timelockRefund)throw new Error(`Refund input sequence ${y.sequence} does not match timelockRefund ${e.timelockRefund}.`);const R=new m.Psbt;if(R.setVersion(p.version),R.setLocktime(p.locktime),R.addInput({hash:y.hash,index:y.index,sequence:y.sequence,witnessUtxo:{script:E.script,value:E.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:i.refundScript,controlBlock:i.refundControlBlock}],tapInternalKey:x.Buffer.from(S.tapInternalPubkey),tapMerkleRoot:i.tapMerkleRoot}),p.outs.length!==1)throw new Error(`Refund transaction must have exactly 1 output, got ${p.outs.length}`);const _=p.outs[0],A=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(e.depositorPubkey)).toLowerCase(),L=t.uint8ArrayToHex(new Uint8Array(_.script)).toLowerCase();if(L!==A)throw new Error(`Refund output scriptPubKey ${L} does not match the depositor's BIP-86 address ${A}. Refund refused — the reclaimed funds would not return to the depositor.`);const C=g-f;if(BigInt(_.value)!==C)throw new Error(`Refund output value ${BigInt(_.value)} sat does not equal the HTLC value ${g} sat minus the requested fee ${f} sat (expected ${C} sat). Refund refused — the reclaimed amount would be burned as excess fee.`);return R.addOutput({script:_.script,value:_.value}),{psbtHex:R.toHex()}}finally{a==null||a.free(),o.free()}}const M=2,D=4294967293,q=214,X=299,F=4;function U(r){if(!Number.isInteger(r)||r<1)throw new Error(`Reclaim input count must be a positive integer, got ${r}.`);return Math.ceil((q+X*r)/F)}function G(r,u){if(!Number.isFinite(r)||r<=0)throw new Error(`Reclaim fee rate must be a positive number, got ${r}.`);return BigInt(Math.ceil(r*U(u)))}function z(r){const{depositorPubkey:u,inputs:e,feeSats:n}=r;if(e.length===0)throw new Error("Reclaim requires at least one input; got none.");if(n<=0n)throw new Error(`Reclaim fee must be positive, got ${n} sat. Refusing to build a transaction that would not relay.`);const s=h.deriveDepositorClaimDescriptor(u),f=t.uint8ArrayToHex(new Uint8Array(s.scriptPubKey)).toLowerCase(),c=new m.Psbt;c.setVersion(M),c.setLocktime(0);let l=0n;const o=new Set;if(e.forEach((i,P)=>{const T=m.Transaction.fromHex(t.stripHexPrefix(i.depositorSignedPeginTxHex)),w=T.getId(),b=T.outs[h.PEGIN_DEPOSITOR_CLAIM_VOUT];if(!b)throw new Error(`PegIn ${w} has no output at vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${T.outs.length}); there is no depositor-claim reserve to reclaim.`);const $=t.stripHexPrefix(i.observed.txid).toLowerCase();if($!==w)throw new Error(`Input ${P}: the observation is of ${$}, but this input spends PegIn ${w}. Reclaim refused — the reserve that was looked up is not the one being swept.`);if(i.observed.vout!==h.PEGIN_DEPOSITOR_CLAIM_VOUT)throw new Error(`Input ${P}: the observation is of vout ${i.observed.vout}, but the depositor-claim reserve is at vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`);const E=t.uint8ArrayToHex(new Uint8Array(b.script)).toLowerCase();if(E!==f)throw new Error(`Input ${P}: PegIn ${w} vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${E}, but the connected wallet's depositor-claim script is ${f}. Reclaim refused — this reserve belongs to a different wallet.`);const I=t.stripHexPrefix(i.observed.scriptPubKey).toLowerCase();if(I!==f)throw new Error(`Input ${P}: the observed UTXO ${w}:${h.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${I}, expected ${f}. Reclaim refused — chain state disagrees with the contract's PegIn.`);const g=BigInt(b.value);if(g!==i.observed.value)throw new Error(`Input ${P}: PegIn ${w} vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${g} sat, but the observed UTXO carries ${i.observed.value} sat. Reclaim refused.`);if(g!==i.expectedValue)throw new Error(`Input ${P}: PegIn ${w} vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${g} sat, but this vault's parameters compute a depositor-claim value of ${i.expectedValue} sat. Reclaim refused.`);const p=`${w}:${h.PEGIN_DEPOSITOR_CLAIM_VOUT}`;if(o.has(p))throw new Error(`Input ${P} repeats outpoint ${p}, which is already being swept by an earlier input. Reclaim refused.`);o.add(p),l+=g,c.addInput({hash:w,index:h.PEGIN_DEPOSITOR_CLAIM_VOUT,sequence:D,witnessUtxo:{script:b.script,value:b.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:s.leafScript,controlBlock:s.controlBlock}],tapInternalKey:s.internalKey})}),n>=l)throw new Error(`Reclaim fee ${n} sat is not less than the swept total ${l} sat. Refusing to build a transaction with no output.`);const a=l-n;if(a<=N.DUST_THRESHOLD)throw new Error(`Reclaim output ${a} sat is at or below the dust threshold ${N.DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it is until fee rates fall.`);const d=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(u));return c.addOutput({script:x.Buffer.from(t.hexToUint8Array(d)),value:Number(a)}),{psbtHex:c.toHex(),outputValue:a,totalInputValue:l}}function W(r){const{requestedPsbtHex:u,signaturesHex:e,signerXOnlyPubkeyHex:n}=r,s=t.stripHexPrefix(n);if(s.length!==k.X_ONLY_PUBKEY_HEX_LEN)throw new Error(`Signer x-only pubkey must be ${k.X_ONLY_PUBKEY_HEX_LEN} hex chars (32 bytes), got ${s.length}.`);const f=x.Buffer.from(t.hexToUint8Array(s)),c=m.Psbt.fromHex(u);if(e.length!==c.data.inputs.length)throw new Error(`Cannot finalize: got ${e.length} signature(s) for ${c.data.inputs.length} input(s). Every input must be signed — refusing to broadcast a partially signed transaction.`);return c.data.inputs.forEach((l,o)=>{if(l.tapKeySig)throw new Error(`Cannot finalize: input ${o} of the locally built PSBT carries a key-path signature. These outputs are script-path only.`);const a=l.tapLeafScript;if(!a||a.length!==1)throw new Error(`Cannot finalize: input ${o} must have exactly one tapLeafScript, got ${(a==null?void 0:a.length)??0}.`);const d=a[0];if(d.leafVersion!==t.TAPSCRIPT_LEAF_VERSION)throw new Error(`Cannot finalize: input ${o} tapLeafScript has leaf version 0x${d.leafVersion.toString(16)}, expected 0x${t.TAPSCRIPT_LEAF_VERSION.toString(16)}.`);const i=t.stripHexPrefix(e[o]);if(i.length!==t.SCHNORR_SIG_HEX_LEN)throw new Error(`Signature for input ${o} must be ${t.SCHNORR_SIG_HEX_LEN} hex chars (64 bytes), got ${i.length}.`);c.updateInput(o,{tapScriptSig:[{pubkey:f,leafHash:h.computeTapLeafHash(d.leafVersion,d.script),signature:x.Buffer.from(t.hexToUint8Array(i))}]})}),c.finalizeAllInputs(),c.extractTransaction().toHex()}async function Y(r){const u=t.stripHexPrefix(r.noPayoutTxHex),e=m.Transaction.fromHex(u),{noPayoutScript:n,noPayoutControlBlock:s}=await S.getAssertNoPayoutScriptInfo(r.connectorParams,r.challengerPubkey),f=t.hexToUint8Array(n),c=t.hexToUint8Array(s),l=new m.Psbt;l.setVersion(e.version),l.setLocktime(e.locktime);for(let o=0;o<e.ins.length;o++){const a=e.ins[o],d=r.prevouts[o];if(!d)throw new Error(`Missing prevout data for input ${o}`);const i={hash:a.hash,index:a.index,sequence:a.sequence,witnessUtxo:{script:x.Buffer.from(t.hexToUint8Array(t.stripHexPrefix(d.script_pubkey))),value:d.value}};o===0&&(i.tapLeafScript=[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:x.Buffer.from(f),controlBlock:x.Buffer.from(c)}],i.tapInternalKey=x.Buffer.from(S.tapInternalPubkey)),l.addInput(i)}for(const o of e.outs)l.addOutput({script:o.script,value:o.value});return l.toHex()}function Q(r,u,e){const n=m.Transaction.fromHex(t.stripHexPrefix(r));if(n.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${n.outs.length}`);const s=t.hexToUint8Array(t.processPublicKeyToXOnly(u)),{output:f}=m.payments.p2tr({internalPubkey:x.Buffer.from(s),network:t.getNetwork(e)});if(!f)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!n.outs[0].script.equals(f))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=Q;exports.buildNoPayoutPsbt=Y;exports.buildReclaimPsbt=z;exports.buildRefundPsbt=K;exports.estimateReclaimFeeSats=G;exports.finalizeScriptPathWithSignatures=W;exports.reclaimVsize=U;
2
- //# sourceMappingURL=noPayout-DOHak0ui.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"noPayout-DOHak0ui.cjs","sources":["../src/tbv/core/wasm/value-guards.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport { loadTbvWasm, tapInternalPubkey } from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\nimport { REFUND_TX_LOCKTIME, REFUND_TX_VERSION } from \"./constants\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n const { WasmPrePeginTx } = await loadTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against an independent\n // TypeScript derivation and the funded transaction bytes.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const wasmHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n const expectedHtlc = deriveExpectedPrePeginHtlc(prePeginParams, hashlock);\n const expectedHtlcScriptPubKey = expectedHtlc.scriptPubKey.toString(\"hex\");\n if (wasmHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `WASM HTLC scriptPubKey ${wasmHtlcScriptPubKey} does not match the ` +\n `independently derived scriptPubKey ${expectedHtlcScriptPubKey}.`,\n );\n }\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + p2aAnchorValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.version !== REFUND_TX_VERSION) {\n throw new Error(\n `Refund transaction version ${refundTx.version} does not match ` +\n `protocol version ${REFUND_TX_VERSION}.`,\n );\n }\n if (refundTx.locktime !== REFUND_TX_LOCKTIME) {\n throw new Error(\n `Refund transaction locktime ${refundTx.locktime} does not match ` +\n `protocol locktime ${REFUND_TX_LOCKTIME}.`,\n );\n }\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n if (refundInput.sequence !== prePeginParams.timelockRefund) {\n throw new Error(\n `Refund input sequence ${refundInput.sequence} does not match ` +\n `timelockRefund ${prePeginParams.timelockRefund}.`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.refundScript,\n controlBlock: expectedHtlc.refundControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `tapLeafScript, got ${tapLeafScripts?.length ?? 0}.`,\n );\n }\n const leaf = tapLeafScripts[0];\n if (leaf.leafVersion !== TAPSCRIPT_LEAF_VERSION) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}], used verbatim — derive them from the parent txs */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","fundedTx","wasmHtlcScriptPubKey","expectedHtlc","deriveExpectedPrePeginHtlc","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","hexToUint8Array","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"wUAoBMA,GAAW,IAAM,KAAO,GAYvB,SAASC,E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,EACrB,MAAM,IAAI,MACR,wDAAwDA,EAAG,KAAK,MAAM,EAAA,EAI1E,MAAMC,EAAQ7B,EAAAA,gBAAgB8B,EAAAA,wBAAwBJ,CAAgB,CAAC,EACjE,CAAE,OAAQK,GAAmBC,EAAAA,SAAS,KAAK,CAC/C,eAAgBxE,EAAAA,OAAO,KAAKqE,CAAK,EACjC,QAASI,EAAAA,WAAWN,CAAO,CAAA,CAC5B,EACD,GAAI,CAACI,EACH,MAAM,IAAI,MACR,qFAAA,EAIJ,GAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc,EAC1C,MAAM,IAAI,MACR,kFAAA,CAGN"}
@@ -1,2 +0,0 @@
1
- "use strict";const f=require("viem"),a=require("./BTCVaultRegistry.abi-DffWFdpA.cjs"),C=require("./BTCVaultRegistryKeyEpochs.abi-CReWFJdu.cjs"),v=require("./constants-BwCg5K6R.cjs"),k=require("./tbv/core/utils/eth/index.cjs"),h=require("./registration-records-DFQgBaYi.cjs"),B=25,S=9999;function w(r){if(!Number.isInteger(r)||r<0||r>=v.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`Quoted commissionBps must be an integer in [0, ${v.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${r}`);return Math.min(r+B,S)}const T=9999;function A(r){return{depositor:r.depositor,depositorBtcPubKey:r.depositorBtcPubKey,amount:r.amount,vaultProvider:r.vaultProvider,status:r.status,applicationEntryPoint:r.applicationEntryPoint,createdAt:r.createdAt}}function y(r){const t=Number(r.offchainParamsVersion);return h.assertValidOffchainParamsVersion(t),{depositorSignedPeginTx:r.depositorSignedPeginTx,universalChallengersVersion:r.universalChallengersVersion,appVaultKeepersVersion:r.appVaultKeepersVersion,offchainParamsVersion:t,verifiedAt:r.verifiedAt,depositorWotsPkHash:r.depositorWotsPkHash,hashlock:r.hashlock,htlcVout:r.htlcVout,depositorPopSignature:r.depositorPopSignature,prePeginTxHash:r.prePeginTxHash,vaultProviderCommissionBps:r.vaultProviderCommissionBps,vaultCoreVersion:r.vaultCoreVersion}}const _=1n<<64n,$=0n,K=[f.getAbiItem({abi:a.BTCVaultRegistryABI,name:"PegInSubmitted"}),f.getAbiItem({abi:a.BTCVaultRegistryABI,name:"PegInSubmittedV2"})],N=f.getAbiItem({abi:a.BTCVaultRegistryABI,name:"VaultClaimableBy"}),O=7200n;function M(r,t){return r>t?r:t}function H(r,t){return{vaultId:r.vaultId.toLowerCase(),depositor:r.depositor,vaultProvider:r.vaultProvider,amount:r.amount,vaultCoreVersion:r.vaultCoreVersion,universalChallengersVersion:r.universalChallengersVersion,appVaultKeepersVersion:r.appVaultKeepersVersion,proverCircuitVersion:r.proverCircuitVersion,offchainParamsVersion:r.offchainParamsVersion,peginTxHash:r.peginTxHash.toLowerCase(),depositorPayoutScriptPubKey:r.depositorPayoutBtcAddress.toLowerCase(),unsignedPrePeginTx:r.unsignedPrePeginTx,maxAcceptableCommissionBps:r.maxAcceptableCommissionBps,blockNumber:t}}function V(r,t,e){if(r<0n||r>=_)throw new Error(`getBtcVaultProtocolInfo returned ${t}=${r} for vault ${e}, outside the uint64 range — the registry may predate RFC-006`);return r}function I(r,t){return{vpKeyEpoch:V(r.vpKeyEpoch,"vpKeyEpoch",t),appKeeperKeyEpoch:V(r.appKeeperKeyEpoch,"appKeeperKeyEpoch",t),ucKeyEpoch:V(r.ucKeyEpoch,"ucKeyEpoch",t)}}class R{constructor(t,e){this.publicClient=t,this.contractAddress=e}async getVaultProviderGenesisBtcPubKey(t,e){return this.getVaultProviderOperationBtcKeyAtEpoch(t,$,e)}async getVaultProviderOperationBtcKeyAtEpoch(t,e,o){const s=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[t,e],blockNumber:o});return h.assertOnChainBtcPubkey(s,`getOperationBtcKeyAtEpoch (vp=${t}, epoch=${e})`)}async getVaultProviderApplication(t,e){return await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getVaultProviderApplication",args:[t],blockNumber:e})}async getCurrentVaultProviderOperationBtcKey(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[t]});return h.assertOnChainBtcPubkey(e,`getCurrentOperationBtcKey (vp=${t})`)}async getVaultKeyEpochs(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:C.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[t]});return I(e,t)}async getVaultKeyEpochsBatch(t){return t.length===0?[]:(await this.publicClient.multicall({contracts:t.map(o=>({address:this.contractAddress,abi:C.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,s)=>I(o,t[s]))}async getVaultBasicInfo(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]});return A(e)}async getVaultProtocolInfo(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[t]});return y(e)}async getProtocolInfoBatch(t){return t.length===0?[]:(await this.publicClient.multicall({contracts:t.map(o=>({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,s)=>{const i=o;if(!i.depositorSignedPeginTx||i.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t[s]} not found on-chain or has no pegin transaction`);return y(i)})}async getPegInFee(t){return await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getPegInFee",args:[t]})}async getVaultProviderCommission(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[t]});if(!Number.isInteger(e)||e<0||e>T)throw new Error(`getVaultProviderCommission returned ${e} bps for ${t}, outside the protocol range [0, ${T}]`);return e}async getVaultData(t){const[e,o]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]},{address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[t]}],allowFailure:!1}),s=A(e),i=y(o);if(!i.depositorSignedPeginTx||i.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t} not found on-chain or has no pegin transaction`);return{basic:s,protocol:i}}async getRegistrationRecordsAtBlock(t){const e=await this.publicClient.getLogs({address:this.contractAddress,events:K,fromBlock:t,toBlock:t,strict:!0});if(e.length===0)throw new h.RegistrationLogsUnavailableError(t);const o=new Map;for(const s of e){if(s.eventName!=="PegInSubmittedV2")continue;const i=H(s.args,s.blockNumber);if(o.has(i.vaultId))throw new Error(`Expected one PegInSubmittedV2 log for vault ${i.vaultId} at block ${t}, found more than one`);o.set(i.vaultId,i)}if(o.size===0)throw new h.RegistrationLogsUnavailableError(t,`Block ${t} holds ${e.length} PegInSubmitted registration log(s) but no PegInSubmittedV2 log: either the node served a partial answer for block ${t} (retry, preferably another node) or the registry predates the depositor's commission ceiling (vault-contracts-aave-v4 #548) and the ceiling cannot be recovered on-chain`);return[...o.values()]}async getMaxAcceptableCommissionBpsBatch(t,e){if(t.length===0)return[];const o=await this.getRegistrationRecordsAtBlock(e);return t.map(s=>h.findRegistrationRecord(o,s,e).maxAcceptableCommissionBps)}async getVaultClaimableBy(t,e,o){const i=`0x${h.assertOnChainBtcPubkey(e,`getVaultClaimableBy claimer (vault=${t})`)}`,n=t.toLowerCase(),{number:c}=await this.publicClient.getBlock({blockTag:"finalized"});if(c<o)throw new Error(`Finalized block ${c} is below vault ${t}'s registration block ${o}; the registration is not finalized yet, or the node is behind it`);let u=c;for(;;){const l=M(o,u-O+1n),p=await this.publicClient.getLogs({address:this.contractAddress,event:N,args:{vaultId:n,claimerPK:i},fromBlock:l,toBlock:u,strict:!0});if(p.length>1){const d=new Set(p.map(b=>b.transactionHash));if(d.size>1)throw new Error(`Found ${p.length} VaultClaimableBy logs for vault ${t} and claimer ${i} across ${d.size} transactions in blocks ${l}..${u}; a vault is redeemed once, so the node's answer is inconsistent`)}if(p.length>=1){const d=p[0];return{blockNumber:d.blockNumber,claimerPk:h.assertOnChainBtcPubkey(d.args.claimerPK,`VaultClaimableBy.claimerPK (vault=${t})`),peginTxHash:d.args.peginTxHash,vaultCoreVersion:d.args.vaultCoreVersion,proverCircuitVersion:d.args.proverCircuitVersion,offchainParamsVersion:d.args.offchainParamsVersion,universalChallengersVersion:d.args.universalChallengersVersion,appVaultKeepersVersion:d.args.appVaultKeepersVersion}}if(l===o)throw new h.VaultClaimableByNotFoundError(t,i,o,c);u=l-1n}}}const q=0,F=255,L=12e4;function m(r,t){const e=r.startsWith("0x")?r:r.startsWith("0X")?`0x${r.slice(2)}`:`0x${r}`;if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(e))throw new Error(`${t} must be non-empty, even-length hex`);return e}function E(r,t){if(!/^0x[0-9a-fA-F]{64}$/.test(r))throw new Error(`${t} must be a 32-byte hex value`)}const z="0x0000000000000000000000000000000000000000000000000000000000000000";function x(r){if(E(r,"expectedFingerprint"),r.toLowerCase()===z)throw new Error("expectedFingerprint must not be zero: the registry cannot resolve a zero fingerprint, so this submission would always revert")}function W(r){if(!Number.isInteger(r)||r<0||r>F)throw new Error(`htlcVout must be a uint8, got ${r}`)}class U{constructor(t){this.config=t}async registerPeginOnChain(t){const e={...t,popSignature:{...t.popSignature}};this.assertQuotedCommissionPresentWhenRequired(e.quotedCommissionBps),x(e.expectedFingerprint);const o=this.assertPopMatchesEthAccount(e.popSignature),s=this.normalizeBtcPubkey(e.popSignature),i=m(e.popSignature.btcPopSignature,"btcPopSignature"),n=this.normalizeRequest(e,o,s);await this.assertVaultDoesNotExist(n.vaultId,n.peginTxHash);const c=await this.readPeginFee(e.vaultProvider),u=await this.resolveMaxAcceptableCommissionBps(e.vaultProvider,e.quotedCommissionBps),l=f.encodeFunctionData({abi:a.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[o,s,i,n.unsignedPrePeginTx,n.depositorSignedPeginTx,e.vaultProvider,u,e.hashlock,e.htlcVout,n.payoutScript,e.depositorWotsPkHash,e.expectedFingerprint]});return{ethTxHash:await this.sendAndWait(l,c,!1,o),vaultId:n.vaultId,peginTxHash:n.peginTxHash}}async registerPeginBatchOnChain(t){const e={...t,popSignature:{...t.popSignature},requests:t.requests.map(g=>({...g}))};if(e.requests.length===0)throw new Error("Batch pegin requires at least one request");this.assertQuotedCommissionPresentWhenRequired(e.quotedCommissionBps),x(e.expectedFingerprint);const o=this.assertPopMatchesEthAccount(e.popSignature),s=m(e.unsignedPrePeginTx,"unsignedPrePeginTx"),i=this.normalizeBtcPubkey(e.popSignature),n=m(e.popSignature.btcPopSignature,"btcPopSignature"),c=[],u=[],l=new Set;for(const g of e.requests){const P=this.normalizeRequest({...g,unsignedPrePeginTx:e.unsignedPrePeginTx,vaultProvider:e.vaultProvider,depositorBtcPubkeyRaw:e.depositorBtcPubkeyRaw},o,i);if(l.has(P.vaultId))throw new Error(`Duplicate vault in batch: ${P.vaultId}`);l.add(P.vaultId),c.push({vaultId:P.vaultId,peginTxHash:P.peginTxHash}),u.push({depositorBtcPubKey:i,btcPopSignature:n,unsignedPrePeginTx:s,depositorSignedPeginTx:P.depositorSignedPeginTx,hashlock:g.hashlock,htlcVout:g.htlcVout,referralCode:q,depositorPayoutBtcAddress:P.payoutScript,depositorWotsPkHash:g.depositorWotsPkHash})}for(const g of c)await this.assertVaultDoesNotExist(g.vaultId,g.peginTxHash);const p=await this.readPeginFee(e.vaultProvider),d=await this.resolveMaxAcceptableCommissionBps(e.vaultProvider,e.quotedCommissionBps),b=f.encodeFunctionData({abi:a.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[o,e.vaultProvider,d,e.expectedFingerprint,u]});return{ethTxHash:await this.sendAndWait(b,p*BigInt(e.requests.length),!0,o),vaults:c}}assertQuotedCommissionPresentWhenRequired(t){if(t===void 0&&this.config.requireQuotedCommissionBps)throw new Error("quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote.")}assertPopMatchesEthAccount(t){return this.assertEthAccount(t.depositorEthAddress)}assertEthAccount(t){const e=this.config.ethWallet.account;if(!e)throw new Error("Ethereum wallet account not found");if(!f.isAddressEqual(t,e.address))throw new Error(`Proof of possession was signed for ${t} but the Ethereum wallet is currently connected to ${e.address}. Reconnect the original account or sign a new proof of possession.`);return e.address}normalizeBtcPubkey(t){return`0x${h.assertOnChainBtcPubkey(m(t.depositorBtcPubkey,"Proof of possession BTC pubkey"),"Proof of possession BTC pubkey")}`}normalizeRequest(t,e,o){E(t.hashlock,"hashlock"),E(t.depositorWotsPkHash,"depositorWotsPkHash"),W(t.htlcVout);const s=m(t.unsignedPrePeginTx,"unsignedPrePeginTx"),i=m(t.depositorSignedPeginTx,"depositorSignedPeginTx"),n=h.calculateBtcTxHash(i);return{unsignedPrePeginTx:s,depositorSignedPeginTx:i,payoutScript:h.assertPayoutScriptMatchesPopKey(t.depositorPayoutScriptPubKey,o,t.depositorBtcPubkeyRaw),peginTxHash:n,vaultId:m(h.derivePeginVaultId(n,e),"vaultId")}}async assertVaultDoesNotExist(t,e){if((await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]})).depositor!==f.zeroAddress)throw new Error(`Vault already exists (ID: ${t}, peginTxHash: ${e}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`)}async readPeginFee(t){try{return await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:a.BTCVaultRegistryABI,functionName:"getPegInFee",args:[t]})}catch(e){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and contract address.",{cause:e})}}async resolveMaxAcceptableCommissionBps(t,e){let o;try{o=await new R(this.config.publicClient,this.config.btcVaultRegistry).getVaultProviderCommission(t)}catch(s){throw new Error("Failed to query vault provider commission from the contract. Please check your network connection and contract address.",{cause:s})}if(e!==void 0){if(o>e+B)throw new Error(`Vault provider commission changed since quote: quoted ${e} bps, chain currently reports ${o} bps (allowed drift ${B} bps). Please refresh and try again.`);return w(e)}return w(o)}async sendAndWait(t,e,o,s){let i=this.assertEthAccount(s),n;try{n=await this.config.publicClient.estimateGas({to:this.config.btcVaultRegistry,data:t,value:e,account:i})}catch(l){C.handleContractError(l)}i=this.assertEthAccount(s);let c;try{c=await this.config.ethWallet.sendTransaction({to:this.config.btcVaultRegistry,data:t,value:e,gas:n,account:i,chain:this.config.ethChain})}catch(l){C.handleContractError(l)}const u=await k.waitForTransactionReceiptSmartAware({publicClient:this.config.publicClient,walletAddress:s,hash:c,timeout:this.config.receiptTimeoutMs??L});return u.status==="reverted"&&C.handleContractError(new Error(`${o?"Batch transaction":"Transaction"} reverted. Hash: ${u.transactionHash}. Check a block explorer for details.`)),u.transactionHash}}exports.COMMISSION_BPS_HEADROOM=B;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=S;exports.ViemPeginRegistrationClient=U;exports.ViemVaultRegistryReader=R;exports.capMaxAcceptableCommissionBps=w;
2
- //# sourceMappingURL=pegin-registration-client-C-abxMWq.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pegin-registration-client-C-abxMWq.cjs","sources":["../src/tbv/core/deposit-terms/commissionCeiling.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/eth/pegin-registration-client.ts"],"sourcesContent":["/**\n * The depositor's commission ceiling (`maxAcceptableCommissionBps`) policy:\n * quoted VP commission + drift headroom, capped below the contract's\n * exclusive bound. Shared by `PeginManager` (the approved terms) and the\n * registration calldata so both carry the same ceiling; a resume rebuild reads\n * that submitted value back from the `PegInSubmittedV2` log instead.\n *\n * @module deposit-terms/commissionCeiling\n */\n\n/*\n * Commission-check map (each guards a DIFFERENT boundary — do not consolidate):\n * 1. assertVpCommissionInProtocolRange (vault app, vaultPayoutSignatureService)\n * — chain-read trust boundary; mirrors VPKeyRegistryLogic.sol bounds.\n * 2. capMaxAcceptableCommissionBps (here) — depositor quote → ceiling policy;\n * mirrors PeginLogic.sol's strict > check via the +25bps headroom.\n * 3. buildDepositTerms range check — public-API precondition on the projection\n * that mints the device-enforced commissionFee.\n * 4. payout.ts commission cap — the VP-built tx's output value vs bps at the\n * signing site (CLAUDE.md Critical Path #3).\n * 5. envelope.ts dust/cross-field gates (ledger-vault-signer) — firmware-only\n * constants, pre-device-I/O (Critical Path #7).\n */\n\nimport { MAX_VP_COMMISSION_BPS_EXCLUSIVE } from \"../primitives/psbt/constants\";\n\n/**\n * Headroom (in basis points) added to the current VP commission to compute\n * `maxAcceptableCommissionBps` at submit time. Lets the VP raise its\n * commission by up to this amount between read and submit without forcing\n * a re-quote. Capped by {@link MAX_ACCEPTABLE_COMMISSION_BPS_CAP}.\n *\n * Contract check is strict `>` (PeginLogic.sol `VaultProviderCommissionExceeded`\n * revert), so +25 allows up\n * to +25 bps of drift.\n */\nexport const COMMISSION_BPS_HEADROOM = 25;\n\n/**\n * Hard ceiling for `maxAcceptableCommissionBps`. The contract enforces\n * `commissionBps < 10000`, so any value at/above that is unreachable;\n * `9999` is the maximum useful cap.\n */\nexport const MAX_ACCEPTABLE_COMMISSION_BPS_CAP = 9999;\n\n/**\n * The commission ceiling submitted as registration calldata and mirrored\n * into `DepositTerms.commissionFee`: quoted + drift headroom, capped.\n * Single source for both consumers — feed it the SAME quoted bps at prepare\n * and register time so device-accept stays coextensive with contract-accept.\n */\nexport function capMaxAcceptableCommissionBps(bps: number): number {\n // Validate the raw quote before headroom shifts its domain — a negative\n // quote must throw here, not become a small \"legal\" ceiling.\n // Reject an out-of-range quote outright — clamping it to 9999 would turn a\n // bad read into a 99.99% ceiling, the exact failure the cap exists to stop.\n if (\n !Number.isInteger(bps) ||\n bps < 0 ||\n bps >= MAX_VP_COMMISSION_BPS_EXCLUSIVE\n ) {\n throw new Error(\n `Quoted commissionBps must be an integer in ` +\n `[0, ${MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${bps}`,\n );\n }\n return Math.min(\n bps + COMMISSION_BPS_HEADROOM,\n MAX_ACCEPTABLE_COMMISSION_BPS_CAP,\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\nimport { getAbiItem } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { BTCVaultRegistryKeyEpochsABI } from \"../../contracts/abis/BTCVaultRegistryKeyEpochs.abi\";\nimport { VaultClaimableByNotFoundError } from \"./claimable-event-error\";\nimport { assertOnChainBtcPubkey } from \"./onChainBtcPubkey\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport { RegistrationLogsUnavailableError } from \"./registration-logs-error\";\nimport { findRegistrationRecord } from \"./registration-records\";\nimport type {\n KeyEpochs,\n OnChainBtcPubkey,\n PeginRegistrationRecord,\n VaultBasicInfo,\n VaultClaimableByEvent,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/**\n * Raw `getBtcVaultProtocolInfo` tuple as decoded by viem.\n *\n * Mirrors the ABI's components except `claimExpiredUntil`, which nothing\n * consumes: it is the post-expiry grace deadline for `claimExpired`, scoped to\n * vaults that expired without activating, and it is not a deadline on the\n * depositor's claim right. The ABI still declares it — the decode is\n * positional, so removing it there would shift `vaultCoreVersion`.\n */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Exclusive upper bound for a `uint64` epoch.\n *\n * viem does not range-check a decoded `uint64`, so a misaligned decode can\n * hand back a value far larger than the field can hold. Rejecting those is\n * cheap defence in depth against a mis-decode of the extended ABI.\n *\n * The state this is load-bearing for is narrower than \"a registry that predates\n * RFC-006\". Against a *fully* pre-RFC-006 registry the path fails closed on its\n * own: `resolveParticipantKeysAtEpochs` goes on to call\n * `getOperationBtcKeyAtEpochOrGenesis` on ApplicationRegistry and\n * ProtocolParams, which do not exist there, so the multicall reverts and these\n * epochs are never used. The reachable gap is a registry that *has* the\n * operation-key getters but whose `BTCVaultProtocolInfo` struct is not\n * extended — there the tail-data epochs resolve with no error at all, and this\n * range check is the only thing looking at them.\n *\n * Even for that case it is only a backstop, and a weak one: a misaligned decode\n * can land on a small, plausible-looking integer this range accepts. Correctness\n * rests on only ever pointing at an RFC-006 registry, which is a deployment\n * precondition rather than something this call can establish — see\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2192 for where that\n * check is owned, and `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\nconst UINT64_EXCLUSIVE_UPPER_BOUND = 1n << 64n;\n\n/**\n * The epoch a vault provider's registration key is bonded at.\n *\n * A provider's operation-key history is append-only and every appended version\n * is stamped at epoch 1 or later, so epoch 0 always resolves to the key set at\n * registration. This is what lets `getOperationBtcKeyAtEpoch` stand in for the\n * removed `getVaultProviderBTCKey` getter.\n */\nconst VP_GENESIS_KEY_EPOCH = 0n;\n\n/**\n * Both registration events, queried together so one answer settles whether a\n * vault's V2 log is missing (pre-upgrade registration) or the node served no\n * logs for the block at all.\n */\nconst PEGIN_SUBMITTED_EVENTS = [\n getAbiItem({ abi: BTCVaultRegistryABI, name: \"PegInSubmitted\" }),\n getAbiItem({ abi: BTCVaultRegistryABI, name: \"PegInSubmittedV2\" }),\n] as const;\n\nconst VAULT_CLAIMABLE_BY_EVENT = getAbiItem({\n abi: BTCVaultRegistryABI,\n name: \"VaultClaimableBy\",\n});\n\n/**\n * Block span of one `VaultClaimableBy` query: btc-vault's own scan chunk\n * (`EVENT_QUERY_CHUNK_BLOCKS = 7200`, `crates/eth-client/src/client.rs:793`\n * @ ac4954e7), about a day of Ethereum blocks, so a recent redeem costs one\n * request. Not every provider serves a range this wide — an Alchemy free key\n * caps `eth_getLogs` at 10 blocks\n * (https://www.alchemy.com/docs/reference/eth-getlogs) — and a provider that\n * answered a wide range short instead of erroring would make this scan report\n * not-found, so confirming the RPC honours 7,200-block ranges is a\n * prerequisite of a claim run.\n */\nconst VAULT_CLAIMABLE_BY_QUERY_CHUNK_BLOCKS = 7_200n;\n\nfunction maxBigint(a: bigint, b: bigint): bigint {\n return a > b ? a : b;\n}\n\n/**\n * A `PegInSubmittedV2` log's decoded args, as viem's strict `getLogs` hands\n * them back after the `eventName` narrowing.\n */\ninterface PegInSubmittedV2Args {\n vaultId: Hex;\n peginTxHash: Hex;\n depositor: Address;\n vaultProvider: Address;\n amount: bigint;\n vaultCoreVersion: number;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n proverCircuitVersion: number;\n offchainParamsVersion: number;\n depositorPayoutBtcAddress: Hex;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n unsignedPrePeginTx: Hex;\n maxAcceptableCommissionBps: number;\n}\n\nfunction mapRegistrationRecord(\n args: PegInSubmittedV2Args,\n blockNumber: bigint,\n): PeginRegistrationRecord {\n // A plain decode of every V2 log in the block, strangers' included: nothing\n // here parses a transaction or bound-checks a script, so one malformed\n // registration elsewhere in the block cannot fail the caller's read. The\n // strict per-record checks live in registration-records.ts. A duplicate\n // vault id is not covered: a vault registers once, so two logs for one id\n // are an inconsistent node and fail the read closed (see the caller).\n return {\n vaultId: args.vaultId.toLowerCase() as Hex,\n depositor: args.depositor,\n vaultProvider: args.vaultProvider,\n amount: args.amount,\n vaultCoreVersion: args.vaultCoreVersion,\n universalChallengersVersion: args.universalChallengersVersion,\n appVaultKeepersVersion: args.appVaultKeepersVersion,\n proverCircuitVersion: args.proverCircuitVersion,\n offchainParamsVersion: args.offchainParamsVersion,\n peginTxHash: args.peginTxHash.toLowerCase() as Hex,\n depositorPayoutScriptPubKey:\n args.depositorPayoutBtcAddress.toLowerCase() as Hex,\n unsignedPrePeginTx: args.unsignedPrePeginTx,\n maxAcceptableCommissionBps: args.maxAcceptableCommissionBps,\n blockNumber,\n };\n}\n\nfunction assertEpochInRange(\n value: bigint,\n field: string,\n vaultId: Hex,\n): bigint {\n if (value < 0n || value >= UINT64_EXCLUSIVE_UPPER_BOUND) {\n throw new Error(\n `getBtcVaultProtocolInfo returned ${field}=${value} for vault ${vaultId}, ` +\n `outside the uint64 range — the registry may predate RFC-006`,\n );\n }\n return value;\n}\n\nfunction mapKeyEpochs(result: KeyEpochs, vaultId: Hex): KeyEpochs {\n return {\n vpKeyEpoch: assertEpochInRange(result.vpKeyEpoch, \"vpKeyEpoch\", vaultId),\n appKeeperKeyEpoch: assertEpochInRange(\n result.appKeeperKeyEpoch,\n \"appKeeperKeyEpoch\",\n vaultId,\n ),\n ucKeyEpoch: assertEpochInRange(result.ucKeyEpoch, \"ucKeyEpoch\", vaultId),\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's **genesis** (registration) x-only BTC pubkey — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Resolved as \"the operation key at epoch 0\" rather than through the\n * dedicated `getVaultProviderBTCKey` getter, which\n * https://github.com/babylonlabs-io/vault-contracts-aave-v4/pull/539 removes.\n * Epoch 0 predates any rotation — appended versions are stamped at epoch 1 or\n * later — so it resolves to the registration key, and the contracts team has\n * confirmed that is a property we can rely on rather than an implementation\n * detail. The devnet comparison behind that claim — both getters returning the\n * identical key for a provider that *has* rotated, while\n * `getCurrentOperationBtcKey` differed — is recorded in\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2188.\n *\n * This makes the read RFC-006-only, where the removed getter also existed on a\n * legacy registry. That costs nothing: every caller of this method already\n * resolves participant keys through `OperationKeyReader`, so all of them\n * require an RFC-006 registry regardless.\n *\n * Validates length, hex form, and secp256k1 curve membership before minting\n * the brand. Returns 64-char lowercase hex without the `0x` prefix.\n */\n async getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<OnChainBtcPubkey> {\n return this.getVaultProviderOperationBtcKeyAtEpoch(\n vpAddress,\n VP_GENESIS_KEY_EPOCH,\n blockNumber,\n );\n }\n\n /**\n * Read the VP operation key selected by `epoch`.\n *\n * This is public rather than hidden inside `OperationKeyReader` because\n * subject-specific VP authentication needs exactly one participant: the\n * gRPC bootstrap is signed by the key frozen into the vault, while the\n * JSON-RPC bootstrap is signed by the provider's live key.\n */\n async getVaultProviderOperationBtcKeyAtEpoch(\n vpAddress: Address,\n epoch: bigint,\n blockNumber?: bigint,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getOperationBtcKeyAtEpoch\",\n args: [vpAddress, epoch],\n blockNumber,\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getOperationBtcKeyAtEpoch (vp=${vpAddress}, epoch=${epoch})`,\n );\n }\n\n /**\n * Read the application entry point a vault provider is registered for.\n *\n * This is the registry's own `vaultProviders[vp].applicationEntryPoint`, and\n * it is the value the peg-in submit path resolves internally — it selects\n * which application's vault-keeper roster, roster version and keeper key\n * epoch a deposit is bonded to. The dApp separately carries an entry point\n * from its own configuration; the two agree today, but they are different\n * sources of truth, so the build path reads this one and asserts the\n * configured value matches it rather than trusting either alone.\n */\n async getVaultProviderApplication(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<Address> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderApplication\",\n args: [vpAddress],\n blockNumber,\n })) as Address;\n }\n\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key.\n *\n * Falls back on-chain to the registration key when the provider has never\n * rotated, so this returns the same value as\n * `getVaultProviderGenesisBtcPubKey` until the first rotation.\n *\n * This is the key the VP's server uses for JSON-RPC-subject authentication.\n * The gRPC-subject bootstrap is instead bound to the existing vault's frozen\n * epoch and resolves through `getVaultProviderOperationBtcKeyAtEpoch`.\n */\n async getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getCurrentOperationBtcKey\",\n args: [vpAddress],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getCurrentOperationBtcKey (vp=${vpAddress})`,\n );\n }\n\n /**\n * Read a vault's frozen RFC-006 operation-key epochs.\n *\n * Reads `getBtcVaultProtocolInfo` through the **extended** ABI, which is only\n * valid against an RFC-006 registry: against one whose `BTCVaultProtocolInfo`\n * struct is not extended this call does not fail for a populated vault, it\n * silently returns three words of tail data as epochs. Nothing here can detect\n * that, so the guarantee is a deployment one — every network this ships to has\n * the RFC-006 getters, and mainnet is a fresh RFC-006 deploy.\n *\n * A registry missing the operation-key getters entirely is the *safer* of the\n * two cases: `resolveParticipantKeysAtEpochs` reverts downstream and these\n * epochs never reach key resolution. See {@link UINT64_EXCLUSIVE_UPPER_BOUND}\n * for which state the range check actually guards, and\n * `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\n async getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as unknown as KeyEpochs;\n\n return mapKeyEpochs(result, vaultId);\n }\n\n async getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) =>\n mapKeyEpochs(info as unknown as KeyEpochs, vaultIds[i]),\n );\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as RawVaultProtocolInfo;\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n // An empty record is not proof the vault is absent: a lagging RPC\n // node returns HTTP 200 with a zero struct, so no retry below this\n // layer can see it. Single-shot is only safe because the finality\n // gate (`waitForPeginRegistrationDepth`) runs first on the deposit\n // path — move this ahead of it and the read-after-write race returns.\n // The vault app matches this message to render \"still confirming\".\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n return mapVaultProtocolInfo(result);\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n /** @inheritdoc */\n async getRegistrationRecordsAtBlock(\n createdAt: bigint,\n ): Promise<PeginRegistrationRecord[]> {\n // Deliberately no `vaultId` topic filter: both events must come back in\n // ONE answer for the empty-vs-missing discriminator below to hold, and\n // viem's multi-event form takes no `args` — so the block's registration\n // logs are fetched whole and ids are matched client-side. strict: a log\n // whose data does not decode against the ABI is dropped (viem\n // parseEventLogs) instead of surfacing as `args: {}`.\n const logs = await this.publicClient.getLogs({\n address: this.contractAddress,\n events: PEGIN_SUBMITTED_EVENTS,\n fromBlock: createdAt,\n toBlock: createdAt,\n strict: true,\n });\n if (logs.length === 0) {\n throw new RegistrationLogsUnavailableError(createdAt);\n }\n\n const records = new Map<string, PeginRegistrationRecord>();\n for (const log of logs) {\n if (log.eventName !== \"PegInSubmittedV2\") continue;\n const record = mapRegistrationRecord(log.args, log.blockNumber);\n // Lenient decoding covers a malformed log, not a duplicate: a vault\n // registers once, so two logs for any id mean the node is inconsistent\n // and every record from this block is suspect — fail closed by design.\n if (records.has(record.vaultId)) {\n throw new Error(\n `Expected one PegInSubmittedV2 log for vault ${record.vaultId} at block ${createdAt}, ` +\n `found more than one`,\n );\n }\n records.set(record.vaultId, record);\n }\n // The registry emits V1 and V2 together on every submission\n // (vault-contracts-aave-v4 `PeginLogic.sol:144-147` @ c559f5c2), so this\n // is as readily a node that served only part of the block as a pre-#548\n // registry — retryable either way.\n if (records.size === 0) {\n throw new RegistrationLogsUnavailableError(\n createdAt,\n `Block ${createdAt} holds ${logs.length} PegInSubmitted registration log(s) but no ` +\n `PegInSubmittedV2 log: either the node served a partial answer for block ${createdAt} ` +\n `(retry, preferably another node) or the registry predates the depositor's commission ` +\n `ceiling (vault-contracts-aave-v4 #548) and the ceiling cannot be recovered on-chain`,\n );\n }\n return [...records.values()];\n }\n\n /**\n * Read the depositor's commission ceiling (`maxAcceptableCommissionBps`)\n * for vaults registered in the same block, from their `PegInSubmittedV2`\n * logs. Returned in `vaultIds` order.\n *\n * The contract bound-checks the ceiling and discards it (PeginLogic.sol,\n * `VaultProviderCommissionExceeded`), so the registration log is its only\n * on-chain source. Vault ids are matched case-insensitively.\n *\n * @throws As {@link getRegistrationRecordsAtBlock}, plus the same typed\n * transient error when a vault has no registration log in its own\n * `createdAt` block.\n */\n async getMaxAcceptableCommissionBpsBatch(\n vaultIds: readonly Hex[],\n createdAt: bigint,\n ): Promise<number[]> {\n if (vaultIds.length === 0) return [];\n\n const records = await this.getRegistrationRecordsAtBlock(createdAt);\n return vaultIds.map(\n (vaultId) =>\n findRegistrationRecord(records, vaultId, createdAt)\n .maxAcceptableCommissionBps,\n );\n }\n\n /** @inheritdoc */\n async getVaultClaimableBy(\n vaultId: Hex,\n claimerPk: Hex,\n createdAt: bigint,\n ): Promise<VaultClaimableByEvent> {\n const claimer = assertOnChainBtcPubkey(\n claimerPk,\n `getVaultClaimableBy claimer (vault=${vaultId})`,\n );\n const claimerTopic = `0x${claimer}` as Hex;\n // viem re-filters the decoded logs client-side against `args`, comparing a\n // bytes32 with `===` against lower-case hex (parseEventLogs.ts:140,172-188).\n const vaultIdTopic = vaultId.toLowerCase() as Hex;\n // Finalized, not latest: the block found here is what the prover proves\n // against, and an unfinalized redeem can reorg away (btc-vault binds the\n // same scan to its finality level, eth-client client.rs:5989-6040).\n const { number: finalized } = await this.publicClient.getBlock({\n blockTag: \"finalized\",\n });\n if (finalized < createdAt) {\n throw new Error(\n `Finalized block ${finalized} is below vault ${vaultId}'s registration block ${createdAt}; ` +\n `the registration is not finalized yet, or the node is behind it`,\n );\n }\n\n // Newest first: the redeem usually trails the tip by far less than it\n // trails the registration. The contract emits every VaultClaimableBy of a\n // vault in one transaction, so the first non-empty chunk is the answer.\n let toBlock = finalized;\n for (;;) {\n const fromBlock = maxBigint(\n createdAt,\n toBlock - VAULT_CLAIMABLE_BY_QUERY_CHUNK_BLOCKS + 1n,\n );\n const logs = await this.publicClient.getLogs({\n address: this.contractAddress,\n event: VAULT_CLAIMABLE_BY_EVENT,\n args: { vaultId: vaultIdTopic, claimerPK: claimerTopic },\n fromBlock,\n toBlock,\n strict: true,\n });\n // A redeem emits every VaultClaimableBy of a vault in ONE transaction\n // (RedeemLogic.sol), and `redeemForDepositor` emits the VP's key and\n // then the depositor's — so when those two keys are equal this filter\n // legitimately matches twice. Identical authorizations from one\n // transaction are the same fact; logs spanning transactions are not.\n if (logs.length > 1) {\n const transactions = new Set(logs.map((log) => log.transactionHash));\n if (transactions.size > 1) {\n throw new Error(\n `Found ${logs.length} VaultClaimableBy logs for vault ${vaultId} and claimer ` +\n `${claimerTopic} across ${transactions.size} transactions in blocks ` +\n `${fromBlock}..${toBlock}; a vault is redeemed once, so the node's answer ` +\n `is inconsistent`,\n );\n }\n }\n if (logs.length >= 1) {\n const log = logs[0];\n return {\n blockNumber: log.blockNumber,\n claimerPk: assertOnChainBtcPubkey(\n log.args.claimerPK,\n `VaultClaimableBy.claimerPK (vault=${vaultId})`,\n ),\n peginTxHash: log.args.peginTxHash,\n vaultCoreVersion: log.args.vaultCoreVersion,\n proverCircuitVersion: log.args.proverCircuitVersion,\n offchainParamsVersion: log.args.offchainParamsVersion,\n universalChallengersVersion: log.args.universalChallengersVersion,\n appVaultKeepersVersion: log.args.appVaultKeepersVersion,\n };\n }\n if (fromBlock === createdAt) {\n throw new VaultClaimableByNotFoundError(\n vaultId,\n claimerTopic,\n createdAt,\n finalized,\n );\n }\n toBlock = fromBlock - 1n;\n }\n }\n}\n","import {\n encodeFunctionData,\n isAddressEqual,\n zeroAddress,\n type Address,\n type Chain,\n type Hex,\n type PublicClient,\n type WalletClient,\n} from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { handleContractError } from \"../../contracts/errors\";\nimport {\n capMaxAcceptableCommissionBps,\n COMMISSION_BPS_HEADROOM,\n} from \"../../deposit-terms/commissionCeiling\";\nimport { waitForTransactionReceiptSmartAware } from \"../../utils/eth\";\nimport { assertOnChainBtcPubkey } from \"./onChainBtcPubkey\";\nimport { assertPayoutScriptMatchesPopKey } from \"./payout-script\";\nimport { calculateBtcTxHash, derivePeginVaultId } from \"./pegin-transaction\";\nimport { ViemVaultRegistryReader } from \"./vault-registry-reader\";\n\n/** Referral code sent with peg-in registration. Zero means no referral. */\nexport const NO_REFERRAL_CODE = 0;\nconst UINT8_MAX = 255;\n// Match the prior vault-service timeout. A dropped transaction must not wait forever.\nconst RECEIPT_TIMEOUT_MS = 120_000;\n\nfunction ensureHex(value: string, label: string): Hex {\n const prefixed = value.startsWith(\"0x\")\n ? value\n : value.startsWith(\"0X\")\n ? `0x${value.slice(2)}`\n : `0x${value}`;\n if (!/^0x(?:[0-9a-fA-F]{2})+$/.test(prefixed)) {\n throw new Error(`${label} must be non-empty, even-length hex`);\n }\n return prefixed as Hex;\n}\n\nfunction assertBytes32(value: Hex, label: string): void {\n if (!/^0x[0-9a-fA-F]{64}$/.test(value)) {\n throw new Error(`${label} must be a 32-byte hex value`);\n }\n}\n\n/** All-zero `bytes32` — the shape an unresolved fingerprint takes. */\nconst ZERO_BYTES32 =\n \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n\n/**\n * The single validation point for `expectedFingerprint`, on both the singular\n * and batch paths.\n *\n * Zero is rejected separately from the shape check because it is a *well-formed*\n * `bytes32` that the registry can never accept — the live fingerprint is a\n * keccak256 over a domain-separated preimage — so it can only ever mean the\n * caller had no value and filled the slot. Catching it here turns a defaulted\n * field into a named error instead of an opaque on-chain revert with two\n * hashes and no hint.\n */\nfunction assertFingerprint(value: Hex): void {\n assertBytes32(value, \"expectedFingerprint\");\n if (value.toLowerCase() === ZERO_BYTES32) {\n throw new Error(\n \"expectedFingerprint must not be zero: the registry cannot resolve a \" +\n \"zero fingerprint, so this submission would always revert\",\n );\n }\n}\n\nfunction assertHtlcVout(value: number): void {\n if (!Number.isInteger(value) || value < 0 || value > UINT8_MAX) {\n throw new Error(`htlcVout must be a uint8, got ${value}`);\n }\n}\n\n/** A PoP prepared by a Bitcoin wallet, reusable by the ETH submit client. */\nexport interface PopSignature {\n btcPopSignature: Hex;\n depositorEthAddress: Address;\n /** x-only secp256k1 public key, 64 hex chars without `0x`. */\n depositorBtcPubkey: string;\n}\n\nexport interface ViemPeginRegistrationClientConfig {\n ethWallet: WalletClient;\n ethChain: Chain;\n publicClient: PublicClient;\n btcVaultRegistry: Address;\n receiptTimeoutMs?: number;\n /**\n * Refuse to register without a `quotedCommissionBps`. Set it to `true` when\n * the depositor approved deposit terms on a device: approval froze the\n * commission ceiling from the quote, so the chain-current fallback could\n * admit a commission the device would later refuse to pay out.\n *\n * Required, with no default: an omitted flag would silently pick the unsafe\n * direction for the integrator least able to probe the wallet capability.\n */\n requireQuotedCommissionBps: boolean;\n}\n\nexport interface RegisterPeginOnChainParams {\n unsignedPrePeginTx: string;\n depositorSignedPeginTx: string;\n vaultProvider: Address;\n hashlock: Hex;\n depositorWotsPkHash: Hex;\n popSignature: PopSignature;\n /** Raw x-only, compressed, or uncompressed BTC pubkey from the PoP wallet. */\n depositorBtcPubkeyRaw: string;\n htlcVout: number;\n /**\n * Bitcoin output script bytes, not an address. The client verifies that the\n * script pays the proof-of-possession key before it submits the transaction.\n */\n depositorPayoutScriptPubKey: string;\n quotedCommissionBps?: number;\n /**\n * `keccak256(abi.encode(...))` over the protocol state the Pre-PegIn was\n * built against — see the SDK's `pegin-fingerprint` module.\n *\n * The registry recomputes it live at inclusion and reverts with\n * `PeginFingerprintChanged` on any difference, so it must be computed from\n * the same block-pinned snapshot that shaped the Bitcoin scripts. Required,\n * with no default: a fingerprint the caller did not resolve is not a\n * fingerprint, and the registry has no way to tell the two apart.\n */\n expectedFingerprint: Hex;\n}\n\nexport interface PeginRegistrationResult {\n ethTxHash: Hex;\n vaultId: Hex;\n peginTxHash: Hex;\n}\n\nexport interface BatchPeginRegistrationItem {\n depositorSignedPeginTx: string;\n hashlock: Hex;\n htlcVout: number;\n /**\n * Bitcoin output script bytes, not an address. The client verifies that the\n * script pays the proof-of-possession key before it submits the transaction.\n */\n depositorPayoutScriptPubKey: string;\n depositorWotsPkHash: Hex;\n}\n\nexport interface RegisterPeginBatchOnChainParams {\n vaultProvider: Address;\n unsignedPrePeginTx: string;\n requests: BatchPeginRegistrationItem[];\n popSignature: PopSignature;\n /** Raw x-only, compressed, or uncompressed BTC pubkey from the PoP wallet. */\n depositorBtcPubkeyRaw: string;\n quotedCommissionBps?: number;\n /**\n * See {@link RegisterPeginOnChainParams.expectedFingerprint}. One value for\n * the whole batch: the fingerprint takes no per-request input and a batch\n * fixes one vault provider, so every entry would resolve the same value.\n */\n expectedFingerprint: Hex;\n}\n\nexport interface BatchPeginRegistrationResultItem {\n vaultId: Hex;\n peginTxHash: Hex;\n}\n\nexport interface PeginBatchRegistrationResult {\n ethTxHash: Hex;\n vaults: BatchPeginRegistrationResultItem[];\n}\n\n/**\n * Ethereum-only client for the on-chain half of peg-in registration.\n *\n * It consumes Bitcoin artifacts that were prepared earlier, but owns no BTC\n * wallet and imports neither Bitcoin libraries nor the Rust/WASM package.\n */\nexport class ViemPeginRegistrationClient {\n constructor(private readonly config: ViemPeginRegistrationClientConfig) {}\n\n async registerPeginOnChain(\n params: RegisterPeginOnChainParams,\n ): Promise<PeginRegistrationResult> {\n const request = {\n ...params,\n popSignature: { ...params.popSignature },\n };\n this.assertQuotedCommissionPresentWhenRequired(request.quotedCommissionBps);\n // Second, matching the batch path, so the two public entry points validate\n // in the same order and neither can drift behind a chain call.\n assertFingerprint(request.expectedFingerprint);\n const depositor = this.assertPopMatchesEthAccount(request.popSignature);\n const depositorBtcPubkey = this.normalizeBtcPubkey(request.popSignature);\n const btcPopSignature = ensureHex(\n request.popSignature.btcPopSignature,\n \"btcPopSignature\",\n );\n const normalized = this.normalizeRequest(\n request,\n depositor,\n depositorBtcPubkey,\n );\n\n await this.assertVaultDoesNotExist(\n normalized.vaultId,\n normalized.peginTxHash,\n );\n const peginFee = await this.readPeginFee(request.vaultProvider);\n const maxCommission = await this.resolveMaxAcceptableCommissionBps(\n request.vaultProvider,\n request.quotedCommissionBps,\n );\n const callData = encodeFunctionData({\n abi: BTCVaultRegistryABI,\n functionName: \"submitPeginRequest\",\n args: [\n depositor,\n depositorBtcPubkey,\n btcPopSignature,\n normalized.unsignedPrePeginTx,\n normalized.depositorSignedPeginTx,\n request.vaultProvider,\n maxCommission,\n request.hashlock,\n request.htlcVout,\n normalized.payoutScript,\n request.depositorWotsPkHash,\n // Appended last on the singular overload; the batch takes it at\n // position 4 instead. Order is the selector, so do not \"tidy\" either.\n request.expectedFingerprint,\n ],\n });\n\n const ethTxHash = await this.sendAndWait(\n callData,\n peginFee,\n false,\n depositor,\n );\n return {\n ethTxHash,\n vaultId: normalized.vaultId,\n peginTxHash: normalized.peginTxHash,\n };\n }\n\n async registerPeginBatchOnChain(\n params: RegisterPeginBatchOnChainParams,\n ): Promise<PeginBatchRegistrationResult> {\n const batch = {\n ...params,\n popSignature: { ...params.popSignature },\n requests: params.requests.map((request) => ({ ...request })),\n };\n if (batch.requests.length === 0) {\n throw new Error(\"Batch pegin requires at least one request\");\n }\n this.assertQuotedCommissionPresentWhenRequired(batch.quotedCommissionBps);\n assertFingerprint(batch.expectedFingerprint);\n const depositor = this.assertPopMatchesEthAccount(batch.popSignature);\n const unsignedPrePeginTx = ensureHex(\n batch.unsignedPrePeginTx,\n \"unsignedPrePeginTx\",\n );\n const depositorBtcPubkey = this.normalizeBtcPubkey(batch.popSignature);\n const btcPopSignature = ensureHex(\n batch.popSignature.btcPopSignature,\n \"btcPopSignature\",\n );\n\n const vaults: BatchPeginRegistrationResultItem[] = [];\n const requests = [];\n const seenVaultIds = new Set<string>();\n for (const request of batch.requests) {\n const normalized = this.normalizeRequest(\n {\n ...request,\n unsignedPrePeginTx: batch.unsignedPrePeginTx,\n vaultProvider: batch.vaultProvider,\n depositorBtcPubkeyRaw: batch.depositorBtcPubkeyRaw,\n },\n depositor,\n depositorBtcPubkey,\n );\n if (seenVaultIds.has(normalized.vaultId)) {\n throw new Error(`Duplicate vault in batch: ${normalized.vaultId}`);\n }\n seenVaultIds.add(normalized.vaultId);\n vaults.push({\n vaultId: normalized.vaultId,\n peginTxHash: normalized.peginTxHash,\n });\n requests.push({\n depositorBtcPubKey: depositorBtcPubkey,\n btcPopSignature,\n unsignedPrePeginTx,\n depositorSignedPeginTx: normalized.depositorSignedPeginTx,\n hashlock: request.hashlock,\n htlcVout: request.htlcVout,\n referralCode: NO_REFERRAL_CODE,\n depositorPayoutBtcAddress: normalized.payoutScript,\n depositorWotsPkHash: request.depositorWotsPkHash,\n });\n }\n for (const vault of vaults) {\n await this.assertVaultDoesNotExist(vault.vaultId, vault.peginTxHash);\n }\n\n const peginFee = await this.readPeginFee(batch.vaultProvider);\n const maxCommission = await this.resolveMaxAcceptableCommissionBps(\n batch.vaultProvider,\n batch.quotedCommissionBps,\n );\n const callData = encodeFunctionData({\n abi: BTCVaultRegistryABI,\n functionName: \"submitPeginRequestBatch\",\n // `expectedFingerprint` sits BEFORE `requests`, not appended. Reordering\n // these five changes the selector and the call stops existing.\n args: [\n depositor,\n batch.vaultProvider,\n maxCommission,\n batch.expectedFingerprint,\n requests,\n ],\n });\n const ethTxHash = await this.sendAndWait(\n callData,\n peginFee * BigInt(batch.requests.length),\n true,\n depositor,\n );\n return { ethTxHash, vaults };\n }\n\n private assertQuotedCommissionPresentWhenRequired(\n quotedCommissionBps?: number,\n ): void {\n if (\n quotedCommissionBps === undefined &&\n this.config.requireQuotedCommissionBps\n ) {\n throw new Error(\n \"quotedCommissionBps is required when the wallet approved deposit \" +\n \"terms: the registration ceiling must anchor to the approved quote.\",\n );\n }\n }\n\n private assertPopMatchesEthAccount(pop: PopSignature): Address {\n return this.assertEthAccount(pop.depositorEthAddress);\n }\n\n private assertEthAccount(expectedDepositor: Address): Address {\n const account = this.config.ethWallet.account;\n if (!account) throw new Error(\"Ethereum wallet account not found\");\n if (!isAddressEqual(expectedDepositor, account.address)) {\n throw new Error(\n `Proof of possession was signed for ${expectedDepositor} ` +\n `but the Ethereum wallet is currently connected to ${account.address}. ` +\n `Reconnect the original account or sign a new proof of possession.`,\n );\n }\n return account.address;\n }\n\n private normalizeBtcPubkey(pop: PopSignature): Hex {\n return `0x${assertOnChainBtcPubkey(\n ensureHex(pop.depositorBtcPubkey, \"Proof of possession BTC pubkey\"),\n \"Proof of possession BTC pubkey\",\n )}`;\n }\n\n // `expectedFingerprint` is omitted rather than accepted and ignored: nothing\n // here normalizes it, and requiring it would force the batch loop to thread a\n // value through a per-request helper that has no use for it. It is validated\n // once per call, at the top of each public method.\n private normalizeRequest(\n params: Omit<\n RegisterPeginOnChainParams,\n \"popSignature\" | \"expectedFingerprint\"\n >,\n depositor: Address,\n depositorBtcPubkey: Hex,\n ) {\n assertBytes32(params.hashlock, \"hashlock\");\n assertBytes32(params.depositorWotsPkHash, \"depositorWotsPkHash\");\n assertHtlcVout(params.htlcVout);\n const unsignedPrePeginTx = ensureHex(\n params.unsignedPrePeginTx,\n \"unsignedPrePeginTx\",\n );\n const depositorSignedPeginTx = ensureHex(\n params.depositorSignedPeginTx,\n \"depositorSignedPeginTx\",\n );\n const peginTxHash = calculateBtcTxHash(depositorSignedPeginTx);\n return {\n unsignedPrePeginTx,\n depositorSignedPeginTx,\n payoutScript: assertPayoutScriptMatchesPopKey(\n params.depositorPayoutScriptPubKey,\n depositorBtcPubkey,\n params.depositorBtcPubkeyRaw,\n ),\n peginTxHash,\n vaultId: ensureHex(derivePeginVaultId(peginTxHash, depositor), \"vaultId\"),\n };\n }\n\n private async assertVaultDoesNotExist(\n vaultId: Hex,\n peginTxHash: Hex,\n ): Promise<void> {\n const result = (await this.config.publicClient.readContract({\n address: this.config.btcVaultRegistry,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as { depositor: Address };\n if (result.depositor !== zeroAddress) {\n throw new Error(\n `Vault already exists (ID: ${vaultId}, peginTxHash: ${peginTxHash}). ` +\n `Vault IDs are derived from the pegin transaction hash and depositor address. ` +\n `To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`,\n );\n }\n }\n\n private async readPeginFee(vaultProvider: Address): Promise<bigint> {\n try {\n return (await this.config.publicClient.readContract({\n address: this.config.btcVaultRegistry,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n } catch (error) {\n throw new Error(\n \"Failed to query pegin fee from the contract. \" +\n \"Please check your network connection and contract address.\",\n { cause: error },\n );\n }\n }\n\n private async resolveMaxAcceptableCommissionBps(\n vaultProvider: Address,\n quotedCommissionBps?: number,\n ): Promise<number> {\n let currentBps: number;\n try {\n currentBps = await new ViemVaultRegistryReader(\n this.config.publicClient,\n this.config.btcVaultRegistry,\n ).getVaultProviderCommission(vaultProvider);\n } catch (error) {\n throw new Error(\n \"Failed to query vault provider commission from the contract. \" +\n \"Please check your network connection and contract address.\",\n { cause: error },\n );\n }\n if (quotedCommissionBps !== undefined) {\n if (currentBps > quotedCommissionBps + COMMISSION_BPS_HEADROOM) {\n throw new Error(\n `Vault provider commission changed since quote: quoted ${quotedCommissionBps} bps, ` +\n `chain currently reports ${currentBps} bps (allowed drift ${COMMISSION_BPS_HEADROOM} bps). ` +\n `Please refresh and try again.`,\n );\n }\n return capMaxAcceptableCommissionBps(quotedCommissionBps);\n }\n return capMaxAcceptableCommissionBps(currentBps);\n }\n\n private async sendAndWait(\n data: Hex,\n value: bigint,\n batch: boolean,\n depositor: Address,\n ): Promise<Hex> {\n let account = this.assertEthAccount(depositor);\n let gas: bigint;\n try {\n gas = await this.config.publicClient.estimateGas({\n to: this.config.btcVaultRegistry,\n data,\n value,\n account,\n });\n } catch (error) {\n handleContractError(error);\n }\n\n account = this.assertEthAccount(depositor);\n let submittedHash: Hex;\n try {\n submittedHash = await this.config.ethWallet.sendTransaction({\n to: this.config.btcVaultRegistry,\n data,\n value,\n gas,\n account,\n chain: this.config.ethChain,\n });\n } catch (error) {\n handleContractError(error);\n }\n const receipt = await waitForTransactionReceiptSmartAware({\n publicClient: this.config.publicClient,\n walletAddress: depositor,\n hash: submittedHash,\n timeout: this.config.receiptTimeoutMs ?? RECEIPT_TIMEOUT_MS,\n });\n if (receipt.status === \"reverted\") {\n handleContractError(\n new Error(\n `${batch ? \"Batch transaction\" : \"Transaction\"} reverted. ` +\n `Hash: ${receipt.transactionHash}. Check a block explorer for details.`,\n ),\n );\n }\n return receipt.transactionHash;\n }\n}\n"],"names":["COMMISSION_BPS_HEADROOM","MAX_ACCEPTABLE_COMMISSION_BPS_CAP","capMaxAcceptableCommissionBps","bps","MAX_VP_COMMISSION_BPS_EXCLUSIVE","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","assertValidOffchainParamsVersion","UINT64_EXCLUSIVE_UPPER_BOUND","VP_GENESIS_KEY_EPOCH","PEGIN_SUBMITTED_EVENTS","getAbiItem","BTCVaultRegistryABI","VAULT_CLAIMABLE_BY_EVENT","VAULT_CLAIMABLE_BY_QUERY_CHUNK_BLOCKS","maxBigint","a","b","mapRegistrationRecord","args","blockNumber","assertEpochInRange","value","field","vaultId","mapKeyEpochs","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","epoch","assertOnChainBtcPubkey","BTCVaultRegistryKeyEpochsABI","vaultIds","info","i","vaultProvider","basicRaw","protocolRaw","basic","protocol","createdAt","logs","RegistrationLogsUnavailableError","records","log","record","findRegistrationRecord","claimerPk","claimerTopic","vaultIdTopic","finalized","toBlock","fromBlock","transactions","VaultClaimableByNotFoundError","NO_REFERRAL_CODE","UINT8_MAX","RECEIPT_TIMEOUT_MS","ensureHex","label","prefixed","assertBytes32","ZERO_BYTES32","assertFingerprint","assertHtlcVout","ViemPeginRegistrationClient","config","params","request","depositor","depositorBtcPubkey","btcPopSignature","normalized","peginFee","maxCommission","callData","encodeFunctionData","batch","unsignedPrePeginTx","vaults","requests","seenVaultIds","vault","quotedCommissionBps","pop","expectedDepositor","account","isAddressEqual","depositorSignedPeginTx","peginTxHash","calculateBtcTxHash","assertPayoutScriptMatchesPopKey","derivePeginVaultId","zeroAddress","error","currentBps","data","gas","handleContractError","submittedHash","receipt","waitForTransactionReceiptSmartAware"],"mappings":"mRAoCaA,EAA0B,GAO1BC,EAAoC,KAQ1C,SAASC,E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