@babylonlabs-io/ts-sdk 0.57.2 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/{PeginManager-DbMFLh-1.js → PeginManager-C8ixWlUM.js} +319 -298
  2. package/dist/PeginManager-C8ixWlUM.js.map +1 -0
  3. package/dist/PeginManager-CogqZaa2.cjs +2 -0
  4. package/dist/PeginManager-CogqZaa2.cjs.map +1 -0
  5. package/dist/{batchPoll-X7D7OIcu.js → batchPoll-B0VxT62K.js} +4 -4
  6. package/dist/{batchPoll-X7D7OIcu.js.map → batchPoll-B0VxT62K.js.map} +1 -1
  7. package/dist/{batchPoll-D2OuUee1.cjs → batchPoll-D5IDDOa8.cjs} +2 -2
  8. package/dist/{batchPoll-D2OuUee1.cjs.map → batchPoll-D5IDDOa8.cjs.map} +1 -1
  9. package/dist/{bitcoin-CHzNE-rS.js → bitcoin-d9eaaZB_.js} +13 -14
  10. package/dist/bitcoin-d9eaaZB_.js.map +1 -0
  11. package/dist/{bitcoin-Dpcfff7b.cjs → bitcoin-m84N5a8o.cjs} +2 -2
  12. package/dist/bitcoin-m84N5a8o.cjs.map +1 -0
  13. package/dist/buildAndBroadcastRefund-BL8u-Ti4.cjs +2 -0
  14. package/dist/buildAndBroadcastRefund-BL8u-Ti4.cjs.map +1 -0
  15. package/dist/{buildAndBroadcastRefund-D_l93Gln.js → buildAndBroadcastRefund-DBA-Mp4I.js} +406 -376
  16. package/dist/buildAndBroadcastRefund-DBA-Mp4I.js.map +1 -0
  17. package/dist/{challengeAssert-CIHykYs3.cjs → challengeAssert-BFRE2DM-.cjs} +2 -2
  18. package/dist/{challengeAssert-CIHykYs3.cjs.map → challengeAssert-BFRE2DM-.cjs.map} +1 -1
  19. package/dist/{challengeAssert-XeAql2fF.js → challengeAssert-C7PzyJ7g.js} +2 -2
  20. package/dist/{challengeAssert-XeAql2fF.js.map → challengeAssert-C7PzyJ7g.js.map} +1 -1
  21. package/dist/constants-DU5CGcqO.cjs +2 -0
  22. package/dist/{constants-BqU1Uz15.cjs.map → constants-DU5CGcqO.cjs.map} +1 -1
  23. package/dist/constants-GjWXdaqV.js +23 -0
  24. package/dist/{constants-CDQE812z.js.map → constants-GjWXdaqV.js.map} +1 -1
  25. package/dist/{deriveVaultRoot-B5G8y6HJ.js → deriveVaultRoot-D0RY5GJc.js} +2 -2
  26. package/dist/{deriveVaultRoot-B5G8y6HJ.js.map → deriveVaultRoot-D0RY5GJc.js.map} +1 -1
  27. package/dist/{deriveVaultRoot-DH0kEyaS.cjs → deriveVaultRoot-p4uGsM7w.cjs} +2 -2
  28. package/dist/{deriveVaultRoot-DH0kEyaS.cjs.map → deriveVaultRoot-p4uGsM7w.cjs.map} +1 -1
  29. package/dist/errors-2aF9oRwM.cjs +2 -0
  30. package/dist/errors-2aF9oRwM.cjs.map +1 -0
  31. package/dist/errors-kXGQXKxZ.js +28 -0
  32. package/dist/errors-kXGQXKxZ.js.map +1 -0
  33. package/dist/index.cjs +1 -1
  34. package/dist/index.js +108 -105
  35. package/dist/{mempoolApi-4T6J5oxg.js → mempoolApi-CMHEz4ez.js} +3 -3
  36. package/dist/{mempoolApi-4T6J5oxg.js.map → mempoolApi-CMHEz4ez.js.map} +1 -1
  37. package/dist/{mempoolApi-BtIABIAQ.cjs → mempoolApi-DfD3_Y6v.cjs} +2 -2
  38. package/dist/{mempoolApi-BtIABIAQ.cjs.map → mempoolApi-DfD3_Y6v.cjs.map} +1 -1
  39. package/dist/{noPayout-DCf1xoJn.js → noPayout-DuE-UyhQ.js} +3 -3
  40. package/dist/{noPayout-DCf1xoJn.js.map → noPayout-DuE-UyhQ.js.map} +1 -1
  41. package/dist/{noPayout-BkXzkhU1.cjs → noPayout-qUEtRKc_.cjs} +2 -2
  42. package/dist/{noPayout-BkXzkhU1.cjs.map → noPayout-qUEtRKc_.cjs.map} +1 -1
  43. package/dist/{onChainBtcPubkey-DqYufM7j.cjs → onChainBtcPubkey-C_a2L3kL.cjs} +2 -2
  44. package/dist/{onChainBtcPubkey-DqYufM7j.cjs.map → onChainBtcPubkey-C_a2L3kL.cjs.map} +1 -1
  45. package/dist/{onChainBtcPubkey-mP95j21Z.js → onChainBtcPubkey-DeF4cKoO.js} +2 -2
  46. package/dist/{onChainBtcPubkey-mP95j21Z.js.map → onChainBtcPubkey-DeF4cKoO.js.map} +1 -1
  47. package/dist/peginInput-Ci921gTl.cjs +2 -0
  48. package/dist/peginInput-Ci921gTl.cjs.map +1 -0
  49. package/dist/peginInput-HQPWZfly.js +123 -0
  50. package/dist/peginInput-HQPWZfly.js.map +1 -0
  51. package/dist/{reservation-4F9XCk0v.js → reservation-CbAXa7VG.js} +2 -2
  52. package/dist/{reservation-4F9XCk0v.js.map → reservation-CbAXa7VG.js.map} +1 -1
  53. package/dist/{reservation-B_7tzSwY.cjs → reservation-RGKvg2x6.cjs} +2 -2
  54. package/dist/{reservation-B_7tzSwY.cjs.map → reservation-RGKvg2x6.cjs.map} +1 -1
  55. package/dist/signPsbtsWithFallback-Xs4jZw5z.cjs +2 -0
  56. package/dist/signPsbtsWithFallback-Xs4jZw5z.cjs.map +1 -0
  57. package/dist/{signPsbtsWithFallback-DxG_APbS.js → signPsbtsWithFallback-eY1YgV13.js} +69 -67
  58. package/dist/signPsbtsWithFallback-eY1YgV13.js.map +1 -0
  59. package/dist/tbv/core/clients/index.cjs +1 -1
  60. package/dist/tbv/core/clients/index.js +3 -3
  61. package/dist/tbv/core/deposit-terms/__tests__/depositTermsErrors.test.d.ts +2 -0
  62. package/dist/tbv/core/deposit-terms/__tests__/depositTermsErrors.test.d.ts.map +1 -0
  63. package/dist/tbv/core/deposit-terms/buildDepositTerms.d.ts.map +1 -1
  64. package/dist/tbv/core/deposit-terms/depositTerms.d.ts +72 -25
  65. package/dist/tbv/core/deposit-terms/depositTerms.d.ts.map +1 -1
  66. package/dist/tbv/core/deposit-terms/depositTermsErrors.d.ts +24 -0
  67. package/dist/tbv/core/deposit-terms/depositTermsErrors.d.ts.map +1 -0
  68. package/dist/tbv/core/deposit-terms/index.d.ts +2 -1
  69. package/dist/tbv/core/deposit-terms/index.d.ts.map +1 -1
  70. package/dist/tbv/core/index.cjs +1 -1
  71. package/dist/tbv/core/index.js +108 -105
  72. package/dist/tbv/core/managers/PayoutManager.d.ts +2 -0
  73. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  74. package/dist/tbv/core/managers/PeginManager.d.ts +16 -3
  75. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  76. package/dist/tbv/core/managers/index.cjs +1 -1
  77. package/dist/tbv/core/managers/index.js +2 -2
  78. package/dist/tbv/core/primitives/index.cjs +1 -1
  79. package/dist/tbv/core/primitives/index.js +6 -6
  80. package/dist/tbv/core/primitives/psbt/assertPayoutFeeBand.d.ts +14 -32
  81. package/dist/tbv/core/primitives/psbt/assertPayoutFeeBand.d.ts.map +1 -1
  82. package/dist/tbv/core/primitives/psbt/constants.d.ts +10 -1
  83. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  84. package/dist/tbv/core/primitives/psbt/payout.d.ts +8 -2
  85. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  86. package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
  87. package/dist/tbv/core/primitives/utils/bitcoin.d.ts +11 -1
  88. package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
  89. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +1 -1
  90. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  91. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +1 -1
  92. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  93. package/dist/tbv/core/services/index.cjs +1 -1
  94. package/dist/tbv/core/services/index.js +2 -2
  95. package/dist/tbv/core/utils/index.cjs +1 -1
  96. package/dist/tbv/core/utils/index.js +2 -2
  97. package/dist/tbv/core/vault-secrets/index.cjs +1 -1
  98. package/dist/tbv/core/vault-secrets/index.js +1 -1
  99. package/dist/tbv/index.cjs +1 -1
  100. package/dist/tbv/index.js +108 -105
  101. package/dist/testing/index.cjs +1 -1
  102. package/dist/testing/index.js +1 -1
  103. package/dist/{verifyScriptPathSchnorrSignature-wwa1JhiB.js → verifyScriptPathSchnorrSignature-Bav08_7R.js} +268 -240
  104. package/dist/verifyScriptPathSchnorrSignature-Bav08_7R.js.map +1 -0
  105. package/dist/verifyScriptPathSchnorrSignature-CYjK4IP_.cjs +2 -0
  106. package/dist/verifyScriptPathSchnorrSignature-CYjK4IP_.cjs.map +1 -0
  107. package/package.json +1 -1
  108. package/dist/PeginManager-DOmyNYT-.cjs +0 -2
  109. package/dist/PeginManager-DOmyNYT-.cjs.map +0 -1
  110. package/dist/PeginManager-DbMFLh-1.js.map +0 -1
  111. package/dist/bitcoin-CHzNE-rS.js.map +0 -1
  112. package/dist/bitcoin-Dpcfff7b.cjs.map +0 -1
  113. package/dist/buildAndBroadcastRefund-COinY4dk.cjs +0 -2
  114. package/dist/buildAndBroadcastRefund-COinY4dk.cjs.map +0 -1
  115. package/dist/buildAndBroadcastRefund-D_l93Gln.js.map +0 -1
  116. package/dist/constants-BqU1Uz15.cjs +0 -2
  117. package/dist/constants-CDQE812z.js +0 -21
  118. package/dist/errors-B-H0seUG.js +0 -8
  119. package/dist/errors-B-H0seUG.js.map +0 -1
  120. package/dist/errors-Bfjxg_iJ.cjs +0 -2
  121. package/dist/errors-Bfjxg_iJ.cjs.map +0 -1
  122. package/dist/peginInput-CAYuE_5F.cjs +0 -2
  123. package/dist/peginInput-CAYuE_5F.cjs.map +0 -1
  124. package/dist/peginInput-DRUm164W.js +0 -105
  125. package/dist/peginInput-DRUm164W.js.map +0 -1
  126. package/dist/signPsbtsWithFallback-DxG_APbS.js.map +0 -1
  127. package/dist/signPsbtsWithFallback-r3bC-CfM.cjs +0 -2
  128. package/dist/signPsbtsWithFallback-r3bC-CfM.cjs.map +0 -1
  129. package/dist/verifyScriptPathSchnorrSignature-fhjfNoHK.cjs +0 -2
  130. package/dist/verifyScriptPathSchnorrSignature-fhjfNoHK.cjs.map +0 -1
  131. package/dist/verifyScriptPathSchnorrSignature-wwa1JhiB.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { Buffer as i } from "buffer";
2
- import { payments as s, networks as a } from "bitcoinjs-lib";
1
+ import { payments as i, networks as a } from "bitcoinjs-lib";
2
+ import { Buffer as s } from "buffer";
3
3
  const m = 192, d = 64, c = 66, h = 130, v = 128;
4
4
  function o(t) {
5
5
  return t.startsWith("0x") || t.startsWith("0X") ? t.slice(2) : t;
@@ -70,7 +70,7 @@ function g(t) {
70
70
  }
71
71
  function y() {
72
72
  try {
73
- s.p2tr({ internalPubkey: i.alloc(32, 1) });
73
+ i.p2tr({ internalPubkey: s.alloc(32, 1) });
74
74
  } catch (t) {
75
75
  if (t instanceof Error && t.message.includes("No ECC Library provided"))
76
76
  throw new Error(
@@ -93,8 +93,8 @@ function E(t) {
93
93
  }
94
94
  function x(t, e) {
95
95
  y();
96
- const n = u(f(t)), { address: r } = s.p2tr({
97
- internalPubkey: i.from(n),
96
+ const n = u(f(t)), { address: r } = i.p2tr({
97
+ internalPubkey: s.from(n),
98
98
  network: E(e)
99
99
  });
100
100
  if (!r)
@@ -111,8 +111,8 @@ function T(t) {
111
111
  throw new Error(
112
112
  "Invalid x-only pubkey: must be 64 hex characters (32 bytes, no 0x prefix)"
113
113
  );
114
- const { output: n } = s.p2tr({
115
- internalPubkey: i.from(e, "hex")
114
+ const { output: n } = i.p2tr({
115
+ internalPubkey: s.from(e, "hex")
116
116
  });
117
117
  if (!n)
118
118
  throw new Error("Failed to derive BIP-86 P2TR scriptPubKey");
@@ -124,14 +124,12 @@ function P(t, e) {
124
124
  throw new Error(
125
125
  `Native SegWit requires a compressed public key (66 hex chars), got ${n.length}`
126
126
  );
127
- const { address: r } = s.p2wpkh({
128
- pubkey: i.from(u(n)),
127
+ const { address: r } = i.p2wpkh({
128
+ pubkey: s.from(u(n)),
129
129
  network: E(e)
130
130
  });
131
131
  if (!r)
132
- throw new Error(
133
- "Failed to derive native segwit address from public key"
134
- );
132
+ throw new Error("Failed to derive native segwit address from public key");
135
133
  return r;
136
134
  }
137
135
  function X(t, e, n) {
@@ -165,11 +163,12 @@ export {
165
163
  X as i,
166
164
  A as j,
167
165
  E as k,
168
- H as l,
166
+ y as l,
167
+ H as m,
169
168
  f as p,
170
169
  o as s,
171
170
  b as t,
172
171
  w as u,
173
172
  C as v
174
173
  };
175
- //# sourceMappingURL=bitcoin-CHzNE-rS.js.map
174
+ //# sourceMappingURL=bitcoin-d9eaaZB_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bitcoin-d9eaaZB_.js","sources":["../src/tbv/core/primitives/utils/bitcoin.ts"],"sourcesContent":["/**\n * Bitcoin Utilities\n *\n * Common pure utility functions for Bitcoin operations including:\n * - Public key conversions (x-only format)\n * - Hex string manipulation\n * - Uint8Array conversions and validation\n * - Address derivation and validation\n *\n * All functions are pure (no side effects) and work in Node.js, browsers,\n * and serverless environments.\n *\n * @module primitives/utils/bitcoin\n */\n\nimport { networks, payments } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport type { Hex } from \"viem\";\n\n/**\n * BIP-341 Tapscript leaf version for script-path spends.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki\n * @see Rust: bitcoin::taproot::LeafVersion::TapScript\n */\nexport const TAPSCRIPT_LEAF_VERSION = 0xc0;\n\n/**\n * Hex-string length of a 32-byte BIP-340 x-only public key (taproot,\n * Schnorr). Doubles the byte count: `2 * 32 = 64`.\n */\nexport const X_ONLY_PUBKEY_HEX_LEN = 64;\n\n/**\n * Hex-string length of a 33-byte SEC1-compressed secp256k1 public key\n * (`0x02` or `0x03` prefix + 32-byte x-coordinate). `2 * 33 = 66`.\n */\nexport const COMPRESSED_PUBKEY_HEX_LEN = 66;\n\n/**\n * Hex-string length of a 65-byte SEC1-uncompressed secp256k1 public\n * key (`0x04` prefix + 32-byte x + 32-byte y). `2 * 65 = 130`.\n */\nconst UNCOMPRESSED_PUBKEY_HEX_LEN = 130;\n\n/**\n * Hex-string length of a 64-byte BIP-340 Schnorr signature. `2 * 64 = 128`.\n */\nexport const SCHNORR_SIG_HEX_LEN = 128;\n\n/**\n * Strip \"0x\" prefix from hex string if present.\n *\n * Bitcoin expects plain hex (no \"0x\" prefix), but frontend often uses\n * Ethereum-style \"0x\"-prefixed hex.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns Hex string without \"0x\" prefix\n */\nexport function stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n}\n\n/**\n * Ensure \"0x\" prefix on a hex string, returning viem's Hex type.\n *\n * Ethereum/viem APIs expect `0x`-prefixed hex, but Bitcoin tooling\n * typically omits the prefix. This normalises either form.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns `0x`-prefixed hex string typed as viem Hex\n */\nexport function ensureHexPrefix(hex: string): Hex {\n if (hex.startsWith(\"0x\")) return hex as Hex;\n if (hex.startsWith(\"0X\")) return `0x${hex.slice(2)}` as Hex;\n return `0x${hex}` as Hex;\n}\n\n/**\n * Convert hex string to Uint8Array.\n *\n * @param hex - Hex string (with or without 0x prefix)\n * @returns Uint8Array\n * @throws If hex is invalid\n */\nexport function hexToUint8Array(hex: string): Uint8Array {\n const cleanHex = stripHexPrefix(hex);\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex string: ${hex}`);\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Convert Uint8Array to hex string (without 0x prefix).\n *\n * @param bytes - Uint8Array to convert\n * @returns Hex string without 0x prefix\n */\nexport function uint8ArrayToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Read the prevout txid (big-endian hex) from a bitcoinjs-lib transaction input.\n *\n * bitcoinjs-lib stores `hash` in little-endian internal byte order; txids are\n * displayed in big-endian, so the bytes must be reversed before hex-encoding.\n *\n * @param input - Transaction input with a `hash` field (Buffer or Uint8Array)\n * @returns Prevout txid as a hex string (big-endian, no 0x prefix)\n */\nexport function inputTxidHex(input: { hash: Buffer | Uint8Array }): string {\n return uint8ArrayToHex(new Uint8Array(input.hash).slice().reverse());\n}\n\n/**\n * Convert a 33-byte public key to 32-byte x-only format (removes first byte).\n *\n * Used for Taproot/Schnorr signatures which only need the x-coordinate.\n * If the input is already 32 bytes, returns it unchanged.\n *\n * @param pubKey - 33-byte or 32-byte public key\n * @returns 32-byte x-only public key\n */\nexport function toXOnly(pubKey: Uint8Array): Uint8Array {\n return pubKey.length === 32 ? pubKey : pubKey.slice(1, 33);\n}\n\n/**\n * Internal helper: Validate hex string format without stripping prefix\n *\n * @internal\n * @param hex - Hex string (must already have prefix stripped)\n * @returns true if valid hex string\n */\nfunction isValidHexRaw(hex: string): boolean {\n return /^[0-9a-fA-F]*$/.test(hex) && hex.length % 2 === 0;\n}\n\n/**\n * Process and convert a public key to x-only format (32 bytes hex).\n *\n * Handles:\n * - 0x prefix removal\n * - Hex character validation\n * - Length validation\n * - Conversion to x-only format\n *\n * Accepts:\n * - 64 hex chars (32 bytes) - already x-only\n * - 66 hex chars (33 bytes) - compressed pubkey\n * - 130 hex chars (65 bytes) - uncompressed pubkey\n *\n * @param publicKeyHex - Public key in hex format (with or without 0x prefix)\n * @returns X-only public key as 32 bytes hex string (without 0x prefix)\n * @throws If public key format is invalid or contains invalid hex characters\n */\nexport function processPublicKeyToXOnly(publicKeyHex: string): string {\n // Remove '0x' prefix if present\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // Validate hex characters early to prevent silent failures\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex characters in public key: ${publicKeyHex}`);\n }\n\n // If already 64 chars (32 bytes), it's already x-only format\n if (cleanHex.length === X_ONLY_PUBKEY_HEX_LEN) {\n return cleanHex;\n }\n\n // Validate public key length (compressed SEC1 or uncompressed SEC1)\n if (\n cleanHex.length !== COMPRESSED_PUBKEY_HEX_LEN &&\n cleanHex.length !== UNCOMPRESSED_PUBKEY_HEX_LEN\n ) {\n throw new Error(\n `Invalid public key length: ${cleanHex.length} (expected ${X_ONLY_PUBKEY_HEX_LEN}, ${COMPRESSED_PUBKEY_HEX_LEN}, or ${UNCOMPRESSED_PUBKEY_HEX_LEN} hex chars)`,\n );\n }\n\n const pubkeyBytes = hexToUint8Array(cleanHex);\n return uint8ArrayToHex(toXOnly(pubkeyBytes));\n}\n\n/**\n * Normalize a public key to the one form two keys can be compared in:\n * lowercase x-only hex, no `0x`.\n *\n * `processPublicKeyToXOnly` returns already-x-only input untouched, so it\n * preserves case on that path — comparing its output directly is a latent\n * false mismatch for any source that serves uppercase hex. Every comparison\n * site therefore has to pair it with `.toLowerCase()`, and that pairing is\n * what this function exists to stop people re-deriving by hand.\n *\n * @param publicKeyHex - x-only, compressed, or uncompressed key, `0x` optional\n * @throws If the key is not valid hex or has an unexpected length\n */\nexport function canonicalizeBtcPubkey(publicKeyHex: string): string {\n return processPublicKeyToXOnly(publicKeyHex).toLowerCase();\n}\n\n/**\n * Validate hex string format.\n *\n * Checks that the string contains only valid hexadecimal characters (0-9, a-f, A-F)\n * and has an even length (since each byte is represented by 2 hex characters).\n *\n * @param hex - String to validate (with or without 0x prefix)\n * @returns true if valid hex string\n */\nexport function isValidHex(hex: string): boolean {\n const cleanHex = stripHexPrefix(hex);\n return isValidHexRaw(cleanHex);\n}\n\n/**\n * Result of validating a wallet public key against an expected depositor public key.\n */\nexport interface WalletPubkeyValidationResult {\n /** Wallet's raw public key (as returned by wallet, may be compressed) */\n walletPubkeyRaw: string;\n /** Wallet's public key in x-only format (32 bytes, 64 hex chars) */\n walletPubkeyXOnly: string;\n /** The validated depositor public key (x-only format) */\n depositorPubkey: string;\n}\n\n/**\n * Validate that a wallet's public key matches the expected depositor public key.\n *\n * This function:\n * 1. Converts the wallet pubkey to x-only format\n * 2. Validates the wallet x-only pubkey matches the expected depositor pubkey\n * (case-insensitive)\n *\n * @param walletPubkeyRaw - Raw public key from wallet (may be compressed 66 chars or x-only 64 chars)\n * @param expectedDepositorPubkey - Expected depositor public key (x-only).\n * Required: omitting it would degrade this check to a self-comparison.\n * @returns Validation result with both pubkey formats\n * @throws If `expectedDepositorPubkey` is missing/empty\n * @throws If wallet pubkey doesn't match expected depositor pubkey\n */\nexport function validateWalletPubkey(\n walletPubkeyRaw: string,\n expectedDepositorPubkey: string,\n): WalletPubkeyValidationResult {\n if (!expectedDepositorPubkey) {\n throw new Error(\n \"validateWalletPubkey requires expectedDepositorPubkey. Pass the on-chain registered depositor pubkey to avoid a self-comparison.\",\n );\n }\n\n const walletPubkeyXOnly = processPublicKeyToXOnly(walletPubkeyRaw);\n const depositorPubkey = expectedDepositorPubkey;\n\n if (walletPubkeyXOnly.toLowerCase() !== depositorPubkey.toLowerCase()) {\n throw new Error(\n `Wallet public key does not match vault depositor. ` +\n `Expected: ${depositorPubkey}, Got: ${walletPubkeyXOnly}. ` +\n `Please connect the wallet that was used to create this vault.`,\n );\n }\n\n return { walletPubkeyRaw, walletPubkeyXOnly, depositorPubkey };\n}\n\n// ============================================================================\n// BTC formatting\n// ============================================================================\n\nconst SATOSHIS_PER_BTC = 100_000_000n;\n\n/**\n * Format satoshis as a human-readable BTC string with trailing zeros removed.\n */\nexport function formatSatoshisToBtc(satoshis: bigint): string {\n if (satoshis < 0n) {\n return `-${formatSatoshisToBtc(-satoshis)}`;\n }\n const whole = satoshis / SATOSHIS_PER_BTC;\n const fraction = satoshis % SATOSHIS_PER_BTC;\n let fractionStr = fraction.toString().padStart(8, \"0\");\n fractionStr = fractionStr.replace(/0+$/, \"\");\n return fractionStr.length > 0 ? `${whole}.${fractionStr}` : whole.toString();\n}\n\n// ============================================================================\n// Address derivation and validation\n// ============================================================================\n\n/**\n * Assert that the ECC library has been initialized via `initEccLib(ecc)`.\n *\n * The consuming application must call `initEccLib(ecc)` from `bitcoinjs-lib`\n * once at startup before using any SDK function that involves Taproot / P2TR\n * operations. This guard provides a clear error message when that step was\n * missed, instead of letting bitcoinjs-lib throw its generic\n * \"No ECC Library provided\" error deep in a call stack.\n */\nexport function assertEccInitialized(): void {\n try {\n payments.p2tr({ internalPubkey: Buffer.alloc(32, 1) });\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"No ECC Library provided\")) {\n throw new Error(\n \"ECC library not initialized. \" +\n 'You must call initEccLib(ecc) from \"bitcoinjs-lib\" before using the SDK. ' +\n \"See the ts-sdk README for setup instructions.\",\n );\n }\n // Any other error means ECC is loaded (e.g. invalid key is fine — ECC worked).\n }\n}\n\n/**\n * Map SDK network type to bitcoinjs-lib Network object.\n *\n * @param network - Network type (\"bitcoin\", \"testnet\", \"signet\", \"regtest\")\n * @returns bitcoinjs-lib Network object\n */\nexport function getNetwork(network: Network): networks.Network {\n switch (network) {\n case \"bitcoin\":\n return networks.bitcoin;\n case \"testnet\":\n case \"signet\":\n return networks.testnet;\n case \"regtest\":\n return networks.regtest;\n default:\n throw new Error(`Unknown network: ${network}`);\n }\n}\n\n/**\n * Derive a Taproot (P2TR) address from a public key.\n *\n * @param publicKeyHex - Compressed (66 hex) or x-only (64 hex) public key\n * @param network - Bitcoin network\n * @returns Taproot address (bc1p... / tb1p... / bcrt1p...)\n */\nexport function deriveTaprootAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n assertEccInitialized();\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(publicKeyHex));\n const { address } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive taproot address from public key\");\n }\n return address;\n}\n\n/**\n * Strip `0x` prefixes and lex-sort an array of x-only public keys.\n *\n * Used to produce the canonical (Rust-parity) keeper / challenger ordering\n * the protocol expects in payout and refund signing contexts.\n *\n * @param pubkeys - Array of x-only public keys (with or without `0x` prefix)\n * @returns Lex-sorted array of pubkeys with `0x` prefix stripped\n */\nexport function getSortedXOnlyPubkeys(pubkeys: string[]): string[] {\n return pubkeys.map(stripHexPrefix).sort();\n}\n\n/**\n * Derive the BIP-86 P2TR scriptPubKey (`0x`-prefixed hex) from an x-only\n * public key.\n *\n * Matches Rust `Bip86KeyConnector::generate_taproot_script_pubkey`: a\n * keypath-only P2TR output with no script tree. Used to compute the expected\n * payout address for vault keeper claimers, whose payout goes to their own\n * BIP-86 address rather than the depositor's registered payout address.\n *\n * Network-agnostic: P2TR scriptPubKey bytes are `OP_1 <32-byte tweaked-key>`\n * regardless of network.\n *\n * @param xOnlyPubkeyHex - X-only public key (64 hex chars, with or without `0x` prefix)\n * @returns `0x`-prefixed P2TR scriptPubKey hex\n * @throws If `xOnlyPubkeyHex` is not exactly 64 hex chars after prefix stripping\n */\nexport function deriveBip86ScriptPubKeyHex(xOnlyPubkeyHex: string): string {\n assertEccInitialized();\n const cleanHex = stripHexPrefix(xOnlyPubkeyHex);\n if (!/^[0-9a-fA-F]{64}$/.test(cleanHex)) {\n throw new Error(\n \"Invalid x-only pubkey: must be 64 hex characters (32 bytes, no 0x prefix)\",\n );\n }\n const { output } = payments.p2tr({\n internalPubkey: Buffer.from(cleanHex, \"hex\"),\n });\n if (!output) {\n throw new Error(\"Failed to derive BIP-86 P2TR scriptPubKey\");\n }\n return `0x${output.toString(\"hex\")}`;\n}\n\n/**\n * Derive a Native SegWit (P2WPKH) address from a compressed public key.\n *\n * @param publicKeyHex - Compressed public key (66 hex chars, with or without 0x prefix)\n * @param network - Bitcoin network\n * @returns Native SegWit address (bc1q... / tb1q... / bcrt1q...)\n * @throws If publicKeyHex is not a compressed public key (66 hex chars)\n */\nexport function deriveNativeSegwitAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n const cleanHex = stripHexPrefix(publicKeyHex);\n if (cleanHex.length !== 66) {\n throw new Error(\n `Native SegWit requires a compressed public key (66 hex chars), got ${cleanHex.length}`,\n );\n }\n const { address } = payments.p2wpkh({\n pubkey: Buffer.from(hexToUint8Array(cleanHex)),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive native segwit address from public key\");\n }\n return address;\n}\n\n/**\n * Validate that a BTC address was derived from the given public key.\n *\n * Derives Taproot (P2TR) and Native SegWit (P2WPKH) addresses from the\n * public key and checks if the provided address matches any of them.\n *\n * P2WPKH derivation requires the full compressed key with explicit y-parity.\n * When only an x-only key is supplied, the y-parity is unknown and trying\n * both `02|x` and `03|x` would let an opposite-parity P2WPKH address — a\n * script the caller does NOT control — pass validation. We fail closed for\n * P2WPKH in that case; P2TR (which depends only on the x-coordinate) is\n * still validated and remains the supported path for Taproot wallets.\n *\n * @param address - BTC address to validate\n * @param publicKeyHex - Public key from the wallet (x-only 64 or compressed 66 hex chars)\n * @param network - Bitcoin network\n * @returns true if the address matches the public key\n */\nexport function isAddressFromPublicKey(\n address: string,\n publicKeyHex: string,\n network: Network,\n): boolean {\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // P2TR — works with both x-only and compressed keys\n try {\n if (address === deriveTaprootAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n\n // P2WPKH — only attempt when the caller supplied a parity-bearing\n // compressed key. An x-only input is fail-closed here on purpose.\n if (cleanHex.length === COMPRESSED_PUBKEY_HEX_LEN) {\n try {\n if (address === deriveNativeSegwitAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n }\n\n return false;\n}\n"],"names":["TAPSCRIPT_LEAF_VERSION","X_ONLY_PUBKEY_HEX_LEN","COMPRESSED_PUBKEY_HEX_LEN","UNCOMPRESSED_PUBKEY_HEX_LEN","SCHNORR_SIG_HEX_LEN","stripHexPrefix","hex","ensureHexPrefix","hexToUint8Array","cleanHex","isValidHexRaw","bytes","i","uint8ArrayToHex","b","inputTxidHex","input","toXOnly","pubKey","processPublicKeyToXOnly","publicKeyHex","pubkeyBytes","canonicalizeBtcPubkey","isValidHex","validateWalletPubkey","walletPubkeyRaw","expectedDepositorPubkey","walletPubkeyXOnly","depositorPubkey","SATOSHIS_PER_BTC","formatSatoshisToBtc","satoshis","whole","fractionStr","assertEccInitialized","payments","Buffer","e","getNetwork","network","networks","deriveTaprootAddress","xOnly","address","getSortedXOnlyPubkeys","pubkeys","deriveBip86ScriptPubKeyHex","xOnlyPubkeyHex","output","deriveNativeSegwitAddress","isAddressFromPublicKey"],"mappings":";;AA0BO,MAAMA,IAAyB,KAMzBC,IAAwB,IAMxBC,IAA4B,IAMnCC,IAA8B,KAKvBC,IAAsB;AAW5B,SAASC,EAAeC,GAAqB;AAClD,SAAOA,EAAI,WAAW,IAAI,KAAKA,EAAI,WAAW,IAAI,IAAIA,EAAI,MAAM,CAAC,IAAIA;AACvE;AAWO,SAASC,EAAgBD,GAAkB;AAChD,SAAIA,EAAI,WAAW,IAAI,IAAUA,IAC7BA,EAAI,WAAW,IAAI,IAAU,KAAKA,EAAI,MAAM,CAAC,CAAC,KAC3C,KAAKA,CAAG;AACjB;AASO,SAASE,EAAgBF,GAAyB;AACvD,QAAMG,IAAWJ,EAAeC,CAAG;AACnC,MAAI,CAACI,EAAcD,CAAQ;AACzB,UAAM,IAAI,MAAM,uBAAuBH,CAAG,EAAE;AAE9C,QAAMK,IAAQ,IAAI,WAAWF,EAAS,SAAS,CAAC;AAChD,WAASG,IAAI,GAAGA,IAAIH,EAAS,QAAQG,KAAK;AACxC,IAAAD,EAAMC,IAAI,CAAC,IAAI,SAASH,EAAS,MAAMG,GAAGA,IAAI,CAAC,GAAG,EAAE;AAEtD,SAAOD;AACT;AAQO,SAASE,EAAgBF,GAA2B;AACzD,SAAO,MAAM,KAAKA,CAAK,EACpB,IAAI,CAACG,M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||e.startsWith("0X")?e.slice(2):e}function k(e){return e.startsWith("0x")?e:e.startsWith("0X")?`0x${e.slice(2)}`:`0x${e}`}function a(e){const t=i(e);if(!d(t))throw new Error(`Invalid hex string: ${e}`);const n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}function f(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function _(e){return f(new Uint8Array(e.hash).slice().reverse())}function p(e){return e.length===32?e:e.slice(1,33)}function d(e){return/^[0-9a-fA-F]*$/.test(e)&&e.length%2===0}function u(e){const t=i(e);if(!d(t))throw new Error(`Invalid hex characters in public key: ${e}`);if(t.length===l)return t;if(t.length!==s&&t.length!==E)throw new Error(`Invalid public key length: ${t.length} (expected ${l}, ${s}, or ${E} hex chars)`);const n=a(t);return f(p(n))}function H(e){return u(e).toLowerCase()}function v(e){const t=i(e);return d(t)}function m(e,t){if(!t)throw new Error("validateWalletPubkey requires expectedDepositorPubkey. Pass the on-chain registered depositor pubkey to avoid a self-comparison.");const n=u(e),r=t;if(n.toLowerCase()!==r.toLowerCase())throw new Error(`Wallet public key does not match vault depositor. Expected: ${r}, Got: ${n}. Please connect the wallet that was used to create this vault.`);return{walletPubkeyRaw:e,walletPubkeyXOnly:n,depositorPubkey:r}}const h=100000000n;function w(e){if(e<0n)return`-${w(-e)}`;const t=e/h;let r=(e%h).toString().padStart(8,"0");return r=r.replace(/0+$/,""),r.length>0?`${t}.${r}`:t.toString()}function P(){try{o.payments.p2tr({internalPubkey:c.Buffer.alloc(32,1)})}catch(e){if(e instanceof Error&&e.message.includes("No ECC Library provided"))throw new Error('ECC library not initialized. You must call initEccLib(ecc) from "bitcoinjs-lib" before using the SDK. See the ts-sdk README for setup instructions.')}}function y(e){switch(e){case"bitcoin":return o.networks.bitcoin;case"testnet":case"signet":return o.networks.testnet;case"regtest":return o.networks.regtest;default:throw new Error(`Unknown network: ${e}`)}}function b(e,t){P();const n=a(u(e)),{address:r}=o.payments.p2tr({internalPubkey:c.Buffer.from(n),network:y(t)});if(!r)throw new Error("Failed to derive taproot address from public key");return r}function A(e){return e.map(i).sort()}function N(e){P();const t=i(e);if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error("Invalid x-only pubkey: must be 64 hex characters (32 bytes, no 0x prefix)");const{output:n}=o.payments.p2tr({internalPubkey:c.Buffer.from(t,"hex")});if(!n)throw new Error("Failed to derive BIP-86 P2TR scriptPubKey");return`0x${n.toString("hex")}`}function x(e,t){const n=i(e);if(n.length!==66)throw new Error(`Native SegWit requires a compressed public key (66 hex chars), got ${n.length}`);const{address:r}=o.payments.p2wpkh({pubkey:c.Buffer.from(a(n)),network:y(t)});if(!r)throw new Error("Failed to derive native segwit address from public key");return r}function T(e,t,n){const r=i(t);try{if(e===b(r,n))return!0}catch{}if(r.length===s)try{if(e===x(r,n))return!0}catch{}return!1}exports.COMPRESSED_PUBKEY_HEX_LEN=s;exports.SCHNORR_SIG_HEX_LEN=g;exports.TAPSCRIPT_LEAF_VERSION=S;exports.X_ONLY_PUBKEY_HEX_LEN=l;exports.canonicalizeBtcPubkey=H;exports.deriveBip86ScriptPubKeyHex=N;exports.deriveNativeSegwitAddress=x;exports.deriveTaprootAddress=b;exports.ensureHexPrefix=k;exports.formatSatoshisToBtc=w;exports.getNetwork=y;exports.getSortedXOnlyPubkeys=A;exports.hexToUint8Array=a;exports.inputTxidHex=_;exports.isAddressFromPublicKey=T;exports.isValidHex=v;exports.processPublicKeyToXOnly=u;exports.stripHexPrefix=i;exports.toXOnly=p;exports.uint8ArrayToHex=f;exports.validateWalletPubkey=m;
2
- //# sourceMappingURL=bitcoin-Dpcfff7b.cjs.map
1
+ "use strict";const o=require("bitcoinjs-lib"),c=require("buffer"),S=192,l=64,s=66,h=130,g=128;function i(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}function k(e){return e.startsWith("0x")?e:e.startsWith("0X")?`0x${e.slice(2)}`:`0x${e}`}function a(e){const t=i(e);if(!d(t))throw new Error(`Invalid hex string: ${e}`);const n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}function f(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function _(e){return f(new Uint8Array(e.hash).slice().reverse())}function w(e){return e.length===32?e:e.slice(1,33)}function d(e){return/^[0-9a-fA-F]*$/.test(e)&&e.length%2===0}function u(e){const t=i(e);if(!d(t))throw new Error(`Invalid hex characters in public key: ${e}`);if(t.length===l)return t;if(t.length!==s&&t.length!==h)throw new Error(`Invalid public key length: ${t.length} (expected ${l}, ${s}, or ${h} hex chars)`);const n=a(t);return f(w(n))}function H(e){return u(e).toLowerCase()}function v(e){const t=i(e);return d(t)}function m(e,t){if(!t)throw new Error("validateWalletPubkey requires expectedDepositorPubkey. Pass the on-chain registered depositor pubkey to avoid a self-comparison.");const n=u(e),r=t;if(n.toLowerCase()!==r.toLowerCase())throw new Error(`Wallet public key does not match vault depositor. Expected: ${r}, Got: ${n}. Please connect the wallet that was used to create this vault.`);return{walletPubkeyRaw:e,walletPubkeyXOnly:n,depositorPubkey:r}}const p=100000000n;function P(e){if(e<0n)return`-${P(-e)}`;const t=e/p;let r=(e%p).toString().padStart(8,"0");return r=r.replace(/0+$/,""),r.length>0?`${t}.${r}`:t.toString()}function y(){try{o.payments.p2tr({internalPubkey:c.Buffer.alloc(32,1)})}catch(e){if(e instanceof Error&&e.message.includes("No ECC Library provided"))throw new Error('ECC library not initialized. You must call initEccLib(ecc) from "bitcoinjs-lib" before using the SDK. See the ts-sdk README for setup instructions.')}}function E(e){switch(e){case"bitcoin":return o.networks.bitcoin;case"testnet":case"signet":return o.networks.testnet;case"regtest":return o.networks.regtest;default:throw new Error(`Unknown network: ${e}`)}}function b(e,t){y();const n=a(u(e)),{address:r}=o.payments.p2tr({internalPubkey:c.Buffer.from(n),network:E(t)});if(!r)throw new Error("Failed to derive taproot address from public key");return r}function A(e){return e.map(i).sort()}function N(e){y();const t=i(e);if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error("Invalid x-only pubkey: must be 64 hex characters (32 bytes, no 0x prefix)");const{output:n}=o.payments.p2tr({internalPubkey:c.Buffer.from(t,"hex")});if(!n)throw new Error("Failed to derive BIP-86 P2TR scriptPubKey");return`0x${n.toString("hex")}`}function x(e,t){const n=i(e);if(n.length!==66)throw new Error(`Native SegWit requires a compressed public key (66 hex chars), got ${n.length}`);const{address:r}=o.payments.p2wpkh({pubkey:c.Buffer.from(a(n)),network:E(t)});if(!r)throw new Error("Failed to derive native segwit address from public key");return r}function T(e,t,n){const r=i(t);try{if(e===b(r,n))return!0}catch{}if(r.length===s)try{if(e===x(r,n))return!0}catch{}return!1}exports.COMPRESSED_PUBKEY_HEX_LEN=s;exports.SCHNORR_SIG_HEX_LEN=g;exports.TAPSCRIPT_LEAF_VERSION=S;exports.X_ONLY_PUBKEY_HEX_LEN=l;exports.assertEccInitialized=y;exports.canonicalizeBtcPubkey=H;exports.deriveBip86ScriptPubKeyHex=N;exports.deriveNativeSegwitAddress=x;exports.deriveTaprootAddress=b;exports.ensureHexPrefix=k;exports.formatSatoshisToBtc=P;exports.getNetwork=E;exports.getSortedXOnlyPubkeys=A;exports.hexToUint8Array=a;exports.inputTxidHex=_;exports.isAddressFromPublicKey=T;exports.isValidHex=v;exports.processPublicKeyToXOnly=u;exports.stripHexPrefix=i;exports.toXOnly=w;exports.uint8ArrayToHex=f;exports.validateWalletPubkey=m;
2
+ //# sourceMappingURL=bitcoin-m84N5a8o.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bitcoin-m84N5a8o.cjs","sources":["../src/tbv/core/primitives/utils/bitcoin.ts"],"sourcesContent":["/**\n * Bitcoin Utilities\n *\n * Common pure utility functions for Bitcoin operations including:\n * - Public key conversions (x-only format)\n * - Hex string manipulation\n * - Uint8Array conversions and validation\n * - Address derivation and validation\n *\n * All functions are pure (no side effects) and work in Node.js, browsers,\n * and serverless environments.\n *\n * @module primitives/utils/bitcoin\n */\n\nimport { networks, payments } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport type { Hex } from \"viem\";\n\n/**\n * BIP-341 Tapscript leaf version for script-path spends.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki\n * @see Rust: bitcoin::taproot::LeafVersion::TapScript\n */\nexport const TAPSCRIPT_LEAF_VERSION = 0xc0;\n\n/**\n * Hex-string length of a 32-byte BIP-340 x-only public key (taproot,\n * Schnorr). Doubles the byte count: `2 * 32 = 64`.\n */\nexport const X_ONLY_PUBKEY_HEX_LEN = 64;\n\n/**\n * Hex-string length of a 33-byte SEC1-compressed secp256k1 public key\n * (`0x02` or `0x03` prefix + 32-byte x-coordinate). `2 * 33 = 66`.\n */\nexport const COMPRESSED_PUBKEY_HEX_LEN = 66;\n\n/**\n * Hex-string length of a 65-byte SEC1-uncompressed secp256k1 public\n * key (`0x04` prefix + 32-byte x + 32-byte y). `2 * 65 = 130`.\n */\nconst UNCOMPRESSED_PUBKEY_HEX_LEN = 130;\n\n/**\n * Hex-string length of a 64-byte BIP-340 Schnorr signature. `2 * 64 = 128`.\n */\nexport const SCHNORR_SIG_HEX_LEN = 128;\n\n/**\n * Strip \"0x\" prefix from hex string if present.\n *\n * Bitcoin expects plain hex (no \"0x\" prefix), but frontend often uses\n * Ethereum-style \"0x\"-prefixed hex.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns Hex string without \"0x\" prefix\n */\nexport function stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n}\n\n/**\n * Ensure \"0x\" prefix on a hex string, returning viem's Hex type.\n *\n * Ethereum/viem APIs expect `0x`-prefixed hex, but Bitcoin tooling\n * typically omits the prefix. This normalises either form.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns `0x`-prefixed hex string typed as viem Hex\n */\nexport function ensureHexPrefix(hex: string): Hex {\n if (hex.startsWith(\"0x\")) return hex as Hex;\n if (hex.startsWith(\"0X\")) return `0x${hex.slice(2)}` as Hex;\n return `0x${hex}` as Hex;\n}\n\n/**\n * Convert hex string to Uint8Array.\n *\n * @param hex - Hex string (with or without 0x prefix)\n * @returns Uint8Array\n * @throws If hex is invalid\n */\nexport function hexToUint8Array(hex: string): Uint8Array {\n const cleanHex = stripHexPrefix(hex);\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex string: ${hex}`);\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Convert Uint8Array to hex string (without 0x prefix).\n *\n * @param bytes - Uint8Array to convert\n * @returns Hex string without 0x prefix\n */\nexport function uint8ArrayToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Read the prevout txid (big-endian hex) from a bitcoinjs-lib transaction input.\n *\n * bitcoinjs-lib stores `hash` in little-endian internal byte order; txids are\n * displayed in big-endian, so the bytes must be reversed before hex-encoding.\n *\n * @param input - Transaction input with a `hash` field (Buffer or Uint8Array)\n * @returns Prevout txid as a hex string (big-endian, no 0x prefix)\n */\nexport function inputTxidHex(input: { hash: Buffer | Uint8Array }): string {\n return uint8ArrayToHex(new Uint8Array(input.hash).slice().reverse());\n}\n\n/**\n * Convert a 33-byte public key to 32-byte x-only format (removes first byte).\n *\n * Used for Taproot/Schnorr signatures which only need the x-coordinate.\n * If the input is already 32 bytes, returns it unchanged.\n *\n * @param pubKey - 33-byte or 32-byte public key\n * @returns 32-byte x-only public key\n */\nexport function toXOnly(pubKey: Uint8Array): Uint8Array {\n return pubKey.length === 32 ? pubKey : pubKey.slice(1, 33);\n}\n\n/**\n * Internal helper: Validate hex string format without stripping prefix\n *\n * @internal\n * @param hex - Hex string (must already have prefix stripped)\n * @returns true if valid hex string\n */\nfunction isValidHexRaw(hex: string): boolean {\n return /^[0-9a-fA-F]*$/.test(hex) && hex.length % 2 === 0;\n}\n\n/**\n * Process and convert a public key to x-only format (32 bytes hex).\n *\n * Handles:\n * - 0x prefix removal\n * - Hex character validation\n * - Length validation\n * - Conversion to x-only format\n *\n * Accepts:\n * - 64 hex chars (32 bytes) - already x-only\n * - 66 hex chars (33 bytes) - compressed pubkey\n * - 130 hex chars (65 bytes) - uncompressed pubkey\n *\n * @param publicKeyHex - Public key in hex format (with or without 0x prefix)\n * @returns X-only public key as 32 bytes hex string (without 0x prefix)\n * @throws If public key format is invalid or contains invalid hex characters\n */\nexport function processPublicKeyToXOnly(publicKeyHex: string): string {\n // Remove '0x' prefix if present\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // Validate hex characters early to prevent silent failures\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex characters in public key: ${publicKeyHex}`);\n }\n\n // If already 64 chars (32 bytes), it's already x-only format\n if (cleanHex.length === X_ONLY_PUBKEY_HEX_LEN) {\n return cleanHex;\n }\n\n // Validate public key length (compressed SEC1 or uncompressed SEC1)\n if (\n cleanHex.length !== COMPRESSED_PUBKEY_HEX_LEN &&\n cleanHex.length !== UNCOMPRESSED_PUBKEY_HEX_LEN\n ) {\n throw new Error(\n `Invalid public key length: ${cleanHex.length} (expected ${X_ONLY_PUBKEY_HEX_LEN}, ${COMPRESSED_PUBKEY_HEX_LEN}, or ${UNCOMPRESSED_PUBKEY_HEX_LEN} hex chars)`,\n );\n }\n\n const pubkeyBytes = hexToUint8Array(cleanHex);\n return uint8ArrayToHex(toXOnly(pubkeyBytes));\n}\n\n/**\n * Normalize a public key to the one form two keys can be compared in:\n * lowercase x-only hex, no `0x`.\n *\n * `processPublicKeyToXOnly` returns already-x-only input untouched, so it\n * preserves case on that path — comparing its output directly is a latent\n * false mismatch for any source that serves uppercase hex. Every comparison\n * site therefore has to pair it with `.toLowerCase()`, and that pairing is\n * what this function exists to stop people re-deriving by hand.\n *\n * @param publicKeyHex - x-only, compressed, or uncompressed key, `0x` optional\n * @throws If the key is not valid hex or has an unexpected length\n */\nexport function canonicalizeBtcPubkey(publicKeyHex: string): string {\n return processPublicKeyToXOnly(publicKeyHex).toLowerCase();\n}\n\n/**\n * Validate hex string format.\n *\n * Checks that the string contains only valid hexadecimal characters (0-9, a-f, A-F)\n * and has an even length (since each byte is represented by 2 hex characters).\n *\n * @param hex - String to validate (with or without 0x prefix)\n * @returns true if valid hex string\n */\nexport function isValidHex(hex: string): boolean {\n const cleanHex = stripHexPrefix(hex);\n return isValidHexRaw(cleanHex);\n}\n\n/**\n * Result of validating a wallet public key against an expected depositor public key.\n */\nexport interface WalletPubkeyValidationResult {\n /** Wallet's raw public key (as returned by wallet, may be compressed) */\n walletPubkeyRaw: string;\n /** Wallet's public key in x-only format (32 bytes, 64 hex chars) */\n walletPubkeyXOnly: string;\n /** The validated depositor public key (x-only format) */\n depositorPubkey: string;\n}\n\n/**\n * Validate that a wallet's public key matches the expected depositor public key.\n *\n * This function:\n * 1. Converts the wallet pubkey to x-only format\n * 2. Validates the wallet x-only pubkey matches the expected depositor pubkey\n * (case-insensitive)\n *\n * @param walletPubkeyRaw - Raw public key from wallet (may be compressed 66 chars or x-only 64 chars)\n * @param expectedDepositorPubkey - Expected depositor public key (x-only).\n * Required: omitting it would degrade this check to a self-comparison.\n * @returns Validation result with both pubkey formats\n * @throws If `expectedDepositorPubkey` is missing/empty\n * @throws If wallet pubkey doesn't match expected depositor pubkey\n */\nexport function validateWalletPubkey(\n walletPubkeyRaw: string,\n expectedDepositorPubkey: string,\n): WalletPubkeyValidationResult {\n if (!expectedDepositorPubkey) {\n throw new Error(\n \"validateWalletPubkey requires expectedDepositorPubkey. Pass the on-chain registered depositor pubkey to avoid a self-comparison.\",\n );\n }\n\n const walletPubkeyXOnly = processPublicKeyToXOnly(walletPubkeyRaw);\n const depositorPubkey = expectedDepositorPubkey;\n\n if (walletPubkeyXOnly.toLowerCase() !== depositorPubkey.toLowerCase()) {\n throw new Error(\n `Wallet public key does not match vault depositor. ` +\n `Expected: ${depositorPubkey}, Got: ${walletPubkeyXOnly}. ` +\n `Please connect the wallet that was used to create this vault.`,\n );\n }\n\n return { walletPubkeyRaw, walletPubkeyXOnly, depositorPubkey };\n}\n\n// ============================================================================\n// BTC formatting\n// ============================================================================\n\nconst SATOSHIS_PER_BTC = 100_000_000n;\n\n/**\n * Format satoshis as a human-readable BTC string with trailing zeros removed.\n */\nexport function formatSatoshisToBtc(satoshis: bigint): string {\n if (satoshis < 0n) {\n return `-${formatSatoshisToBtc(-satoshis)}`;\n }\n const whole = satoshis / SATOSHIS_PER_BTC;\n const fraction = satoshis % SATOSHIS_PER_BTC;\n let fractionStr = fraction.toString().padStart(8, \"0\");\n fractionStr = fractionStr.replace(/0+$/, \"\");\n return fractionStr.length > 0 ? `${whole}.${fractionStr}` : whole.toString();\n}\n\n// ============================================================================\n// Address derivation and validation\n// ============================================================================\n\n/**\n * Assert that the ECC library has been initialized via `initEccLib(ecc)`.\n *\n * The consuming application must call `initEccLib(ecc)` from `bitcoinjs-lib`\n * once at startup before using any SDK function that involves Taproot / P2TR\n * operations. This guard provides a clear error message when that step was\n * missed, instead of letting bitcoinjs-lib throw its generic\n * \"No ECC Library provided\" error deep in a call stack.\n */\nexport function assertEccInitialized(): void {\n try {\n payments.p2tr({ internalPubkey: Buffer.alloc(32, 1) });\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"No ECC Library provided\")) {\n throw new Error(\n \"ECC library not initialized. \" +\n 'You must call initEccLib(ecc) from \"bitcoinjs-lib\" before using the SDK. ' +\n \"See the ts-sdk README for setup instructions.\",\n );\n }\n // Any other error means ECC is loaded (e.g. invalid key is fine — ECC worked).\n }\n}\n\n/**\n * Map SDK network type to bitcoinjs-lib Network object.\n *\n * @param network - Network type (\"bitcoin\", \"testnet\", \"signet\", \"regtest\")\n * @returns bitcoinjs-lib Network object\n */\nexport function getNetwork(network: Network): networks.Network {\n switch (network) {\n case \"bitcoin\":\n return networks.bitcoin;\n case \"testnet\":\n case \"signet\":\n return networks.testnet;\n case \"regtest\":\n return networks.regtest;\n default:\n throw new Error(`Unknown network: ${network}`);\n }\n}\n\n/**\n * Derive a Taproot (P2TR) address from a public key.\n *\n * @param publicKeyHex - Compressed (66 hex) or x-only (64 hex) public key\n * @param network - Bitcoin network\n * @returns Taproot address (bc1p... / tb1p... / bcrt1p...)\n */\nexport function deriveTaprootAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n assertEccInitialized();\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(publicKeyHex));\n const { address } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive taproot address from public key\");\n }\n return address;\n}\n\n/**\n * Strip `0x` prefixes and lex-sort an array of x-only public keys.\n *\n * Used to produce the canonical (Rust-parity) keeper / challenger ordering\n * the protocol expects in payout and refund signing contexts.\n *\n * @param pubkeys - Array of x-only public keys (with or without `0x` prefix)\n * @returns Lex-sorted array of pubkeys with `0x` prefix stripped\n */\nexport function getSortedXOnlyPubkeys(pubkeys: string[]): string[] {\n return pubkeys.map(stripHexPrefix).sort();\n}\n\n/**\n * Derive the BIP-86 P2TR scriptPubKey (`0x`-prefixed hex) from an x-only\n * public key.\n *\n * Matches Rust `Bip86KeyConnector::generate_taproot_script_pubkey`: a\n * keypath-only P2TR output with no script tree. Used to compute the expected\n * payout address for vault keeper claimers, whose payout goes to their own\n * BIP-86 address rather than the depositor's registered payout address.\n *\n * Network-agnostic: P2TR scriptPubKey bytes are `OP_1 <32-byte tweaked-key>`\n * regardless of network.\n *\n * @param xOnlyPubkeyHex - X-only public key (64 hex chars, with or without `0x` prefix)\n * @returns `0x`-prefixed P2TR scriptPubKey hex\n * @throws If `xOnlyPubkeyHex` is not exactly 64 hex chars after prefix stripping\n */\nexport function deriveBip86ScriptPubKeyHex(xOnlyPubkeyHex: string): string {\n assertEccInitialized();\n const cleanHex = stripHexPrefix(xOnlyPubkeyHex);\n if (!/^[0-9a-fA-F]{64}$/.test(cleanHex)) {\n throw new Error(\n \"Invalid x-only pubkey: must be 64 hex characters (32 bytes, no 0x prefix)\",\n );\n }\n const { output } = payments.p2tr({\n internalPubkey: Buffer.from(cleanHex, \"hex\"),\n });\n if (!output) {\n throw new Error(\"Failed to derive BIP-86 P2TR scriptPubKey\");\n }\n return `0x${output.toString(\"hex\")}`;\n}\n\n/**\n * Derive a Native SegWit (P2WPKH) address from a compressed public key.\n *\n * @param publicKeyHex - Compressed public key (66 hex chars, with or without 0x prefix)\n * @param network - Bitcoin network\n * @returns Native SegWit address (bc1q... / tb1q... / bcrt1q...)\n * @throws If publicKeyHex is not a compressed public key (66 hex chars)\n */\nexport function deriveNativeSegwitAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n const cleanHex = stripHexPrefix(publicKeyHex);\n if (cleanHex.length !== 66) {\n throw new Error(\n `Native SegWit requires a compressed public key (66 hex chars), got ${cleanHex.length}`,\n );\n }\n const { address } = payments.p2wpkh({\n pubkey: Buffer.from(hexToUint8Array(cleanHex)),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive native segwit address from public key\");\n }\n return address;\n}\n\n/**\n * Validate that a BTC address was derived from the given public key.\n *\n * Derives Taproot (P2TR) and Native SegWit (P2WPKH) addresses from the\n * public key and checks if the provided address matches any of them.\n *\n * P2WPKH derivation requires the full compressed key with explicit y-parity.\n * When only an x-only key is supplied, the y-parity is unknown and trying\n * both `02|x` and `03|x` would let an opposite-parity P2WPKH address — a\n * script the caller does NOT control — pass validation. We fail closed for\n * P2WPKH in that case; P2TR (which depends only on the x-coordinate) is\n * still validated and remains the supported path for Taproot wallets.\n *\n * @param address - BTC address to validate\n * @param publicKeyHex - Public key from the wallet (x-only 64 or compressed 66 hex chars)\n * @param network - Bitcoin network\n * @returns true if the address matches the public key\n */\nexport function isAddressFromPublicKey(\n address: string,\n publicKeyHex: string,\n network: Network,\n): boolean {\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // P2TR — works with both x-only and compressed keys\n try {\n if (address === deriveTaprootAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n\n // P2WPKH — only attempt when the caller supplied a parity-bearing\n // compressed key. An x-only input is fail-closed here on purpose.\n if (cleanHex.length === COMPRESSED_PUBKEY_HEX_LEN) {\n try {\n if (address === deriveNativeSegwitAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n }\n\n return false;\n}\n"],"names":["TAPSCRIPT_LEAF_VERSION","X_ONLY_PUBKEY_HEX_LEN","COMPRESSED_PUBKEY_HEX_LEN","UNCOMPRESSED_PUBKEY_HEX_LEN","SCHNORR_SIG_HEX_LEN","stripHexPrefix","hex","ensureHexPrefix","hexToUint8Array","cleanHex","isValidHexRaw","bytes","i","uint8ArrayToHex","b","inputTxidHex","input","toXOnly","pubKey","processPublicKeyToXOnly","publicKeyHex","pubkeyBytes","canonicalizeBtcPubkey","isValidHex","validateWalletPubkey","walletPubkeyRaw","expectedDepositorPubkey","walletPubkeyXOnly","depositorPubkey","SATOSHIS_PER_BTC","formatSatoshisToBtc","satoshis","whole","fractionStr","assertEccInitialized","payments","Buffer","getNetwork","network","networks","deriveTaprootAddress","xOnly","address","getSortedXOnlyPubkeys","pubkeys","deriveBip86ScriptPubKeyHex","xOnlyPubkeyHex","output","deriveNativeSegwitAddress","isAddressFromPublicKey"],"mappings":"kEA0BaA,EAAyB,IAMzBC,EAAwB,GAMxBC,EAA4B,GAMnCC,EAA8B,IAKvBC,EAAsB,IAW5B,SAASC,EAAeC,EAAqB,CAClD,OAAOA,EAAI,WAAW,IAAI,GAAKA,EAAI,WAAW,IAAI,EAAIA,EAAI,MAAM,CAAC,EAAIA,CACvE,CAWO,SAASC,EAAgBD,EAAkB,CAChD,OAAIA,EAAI,WAAW,IAAI,EAAUA,EAC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ACAkB,EACS,CACT,MAAM7B,EAAWJ,EAAee,CAAY,EAG5C,GAAI,CACF,GAAIsB,IAAYF,EAAqB/B,EAAU6B,CAAO,EACpD,MAAO,EAEX,MAAQ,CAER,CAIA,GAAI7B,EAAS,SAAWP,EACtB,GAAI,CACF,GAAIwC,IAAYM,EAA0BvC,EAAU6B,CAAO,EACzD,MAAO,EAEX,MAAQ,CAER,CAGF,MAAO,EACT"}
@@ -0,0 +1,2 @@
1
+ "use strict";var ge=Object.defineProperty;var fe=(e,t,r)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var $=(e,t,r)=>fe(e,typeof t!="symbol"?t+"":t,r);const Pe=require("./BTCVaultRegistry.abi-AUAyCHal.cjs"),p=require("./bitcoin-m84N5a8o.cjs"),_=require("./signPsbtsWithFallback-Xs4jZw5z.cjs"),y=require("./json-rpc-client-BiAmg_ho.cjs"),S=require("bitcoinjs-lib"),w=require("./verifyScriptPathSchnorrSignature-CYjK4IP_.cjs"),D=require("./noPayout-qUEtRKc_.cjs"),N=require("./signing-Bnsro0hE.cjs"),Y=require("./onChainBtcPubkey-C_a2L3kL.cjs"),ye=require("./constants-DU5CGcqO.cjs"),ve=/^0x[0-9a-fA-F]{64}$/,be=/^0x[0-9a-fA-F]{40}$/,me=/^0x([0-9a-fA-F]{2})*$/;function V(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!ve.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function we(e,t){if(!be.test(e))throw new Error(`${t} must be a 20-byte 0x-prefixed hex address (42 chars)`)}function xe(e,t){if(!me.test(e))throw new Error(`${t} must be a 0x-prefixed hex string with an even number of hex chars`)}async function ke(e){const{btcVaultRegistryAddress:t,vaultId:r,hashlock:n,activationMetadata:a,writeContract:l,signal:o}=e;o==null||o.throwIfAborted(),we(t,"btcVaultRegistryAddress"),V(r,"vaultId");const i=p.ensureHexPrefix(e.secret);if(V(i,"secret"),n!==void 0&&(V(n,"hashlock"),!_.validateSecretAgainstHashlock(i,n)))throw new Error("Invalid secret: SHA256(secret) does not match the provided hashlock");return xe(a,"activationMetadata"),l({address:t,abi:Pe.BTCVaultRegistryABI,functionName:"activateVaultWithSecret",args:[r,i,a]})}const Z=1,Ee=1;function Te(e,t){const r=p.stripHexPrefix(t).toLowerCase(),a=e.map(l=>p.stripHexPrefix(l).toLowerCase()).filter(l=>l!==r);if(a.length===0)throw new Error("Cannot derive localChallengers: vault keeper set is empty (or contains only the depositor)");if(new Set(a).size!==a.length)throw new Error("Cannot derive localChallengers: duplicate vaultKeeper key — signing context is misconfigured");return a}function Se(e,t,r){const n=r.map(c=>p.stripHexPrefix(c).toLowerCase()),a=t.filter(c=>n.includes(c));if(a.length>0)throw new Error(`Cannot validate challenger set: vault keepers and universal challengers overlap (${a.join(", ")})`);const l=[...t,...n],o=e.map(c=>p.stripHexPrefix(c.challenger_pubkey).toLowerCase()),i=new Set(o);if(i.size!==o.length)throw new Error("Depositor graph contains duplicate challenger entries in challenger_presign_data");const u=new Set(l),s=l.filter(c=>!i.has(c)),h=o.filter(c=>!u.has(c));if(s.length>0||h.length>0)throw new Error("Depositor graph challenger set does not match expected (local ∪ universal)"+(s.length>0?` (missing: ${s.join(", ")})`:"")+(h.length>0?` (unexpected: ${h.join(", ")})`:""))}function Ce(e,t){const r=e.ins[t];return p.uint8ArrayToHex(new Uint8Array(r.hash).slice().reverse())}function K(e,t,r,n,a){const l=e.ins[t];if(l.index!==0)throw new Error(`NoPayout (challenger ${a}) input ${t} expected to spend ${n} vout 0, got vout ${l.index}`);const o=r.getId(),i=Ce(e,t);if(i!==o)throw new Error(`NoPayout (challenger ${a}) input ${t} does not reference ${n} (expected txid ${o}, got ${i})`)}async function _e(e,t,r){const n=[],a=[],l=[],o=Te(r.vaultKeeperBtcPubkeys,r.depositorBtcPubkey);Se(e.challenger_presign_data,o,r.universalChallengerBtcPubkeys);const i=await w.buildPayoutPsbt({vaultCoreVersion:r.vaultCoreVersion,vkClaimerPayoutScriptPubKeys:r.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:r.vpCommissionScriptPubKey,payoutTxHex:e.payout_tx.tx_hex,peginTxHex:r.peginTxHex,assertTxHex:e.assert_tx.tx_hex,timelockAssert:r.timelockAssert,depositorBtcPubkey:r.depositorBtcPubkey,vaultProviderBtcPubkey:r.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:r.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:r.universalChallengerBtcPubkeys,timelockPegin:r.timelockPegin,network:r.network,claimerBtcPubkey:r.depositorBtcPubkey,registeredPayoutScriptPubKey:r.registeredPayoutScriptPubKey,commissionBps:Ee,protocolFeeRate:r.protocolFeeRate,councilSize:r.councilMembers.length});n.push(i.psbtHex),a.push(N.createTaprootScriptPathSignOptions(t,Z));const u=p.stripHexPrefix(r.depositorBtcPubkey),s=S.Transaction.fromHex(p.stripHexPrefix(e.assert_tx.tx_hex));for(const h of e.challenger_presign_data){const c=p.stripHexPrefix(h.challenger_pubkey),d=n.length,f=await Be({challenger:h,challengerPubkey:c,claimerPubkey:u,localChallengers:o,assertTxParsed:s,ctx:r});n.push(f),a.push(N.createTaprootScriptPathSignOptions(t,Z)),l.push({challengerPubkey:c,noPayoutIdx:d})}return{psbtHexes:n,signOptions:a,challengerEntries:l}}async function Be(e){const{challenger:t,challengerPubkey:r,claimerPubkey:n,localChallengers:a,assertTxParsed:l,ctx:o}=e;D.assertNoPayoutOutputMatchesChallenger(t.nopayout_tx.tx_hex,r,o.network);const i=S.Transaction.fromHex(p.stripHexPrefix(t.nopayout_tx.tx_hex)),u=S.Transaction.fromHex(p.stripHexPrefix(t.challenge_assert_x_tx.tx_hex)),s=S.Transaction.fromHex(p.stripHexPrefix(t.challenge_assert_y_tx.tx_hex));if(i.ins.length!==3)throw new Error(`NoPayout (challenger ${r}) must have exactly 3 inputs, got ${i.ins.length}`);K(i,0,l,"Assert",r),K(i,1,u,"ChallengeAssertX",r),K(i,2,s,"ChallengeAssertY",r);const h=[l.outs[0],u.outs[0],s.outs[0]].map(c=>({script_pubkey:p.uint8ArrayToHex(new Uint8Array(c.script)),value:c.value}));return D.buildNoPayoutPsbt({noPayoutTxHex:t.nopayout_tx.tx_hex,challengerPubkey:r,prevouts:h,connectorParams:{txGraphVersion:o.vaultCoreVersion,claimer:n,localChallengers:a,universalChallengers:o.universalChallengerBtcPubkeys,timelockAssert:o.timelockAssert,councilMembers:o.councilMembers,councilQuorum:o.councilQuorum}})}function Ae(e,t,r){w.assertPsbtUnsignedTxMatches(e[0]);const a=w.extractPayoutSignature(e[0].returnedPsbtHex,r);w.assertScriptPathSchnorrSignature({requestedPsbtHex:e[0].requestedPsbtHex,signatureHex:a,signerXOnlyPubkeyHex:r,inputIndex:0});const l={};for(const o of t){w.assertPsbtUnsignedTxMatches(e[o.noPayoutIdx]);const i=w.extractPayoutSignature(e[o.noPayoutIdx].returnedPsbtHex,r);w.assertScriptPathSchnorrSignature({requestedPsbtHex:e[o.noPayoutIdx].requestedPsbtHex,signatureHex:i,signerXOnlyPubkeyHex:r,inputIndex:0}),l[o.challengerPubkey]={nopayout_signature:i}}return{payout_signatures:{payout_signature:a},per_challenger:l}}async function ne(e){const{depositorGraph:t,btcWallet:r,signingContext:n}=e,a=await r.getPublicKeyHex(),{depositorPubkey:l}=p.validateWalletPubkey(a,p.stripHexPrefix(n.depositorBtcPubkey)),{psbtHexes:o,signOptions:i,challengerEntries:u}=await _e(t,a,n),s=await _.signPsbtsWithFallback(r,o,i),h=o.map((c,d)=>({requestedPsbtHex:c,returnedPsbtHex:s[d]}));return Ae(h,u,l)}const Re=1e4;async function X(e){const{statusReader:t,peginTxid:r,targetStatuses:n,timeoutMs:a,pollIntervalMs:l=Re,signal:o}=e,i=Date.now();for(;;){if(o!=null&&o.aborted)throw new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`);if(Date.now()-i>=a)throw new Error(`Polling timeout after ${a}ms for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`);try{const u=await t.getPeginStatus({pegin_txid:r},o);if(u.pegin_txid.toLowerCase()!==r.toLowerCase())throw new Error(`getPeginStatus returned status for pegin ${u.pegin_txid.slice(0,8)}…, requested ${r.slice(0,8)}…`);const s=u.status;if(n.has(s)||s===y.DaemonStatus.ACTIVATED)return s;if(s===y.DaemonStatus.EXPIRED||y.VP_TERMINAL_FAILURE_STATUSES.has(s))throw new Error(`Pegin ${r.slice(0,8)}… reached terminal status "${s}" while waiting for ${[...n].join(", ")}`)}catch(u){if(!(u instanceof y.JsonRpcError&&u.code===y.RpcErrorCode.PEGIN_NOT_FOUND))throw u}await new Promise((u,s)=>{const h=()=>{clearTimeout(c),s(new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`))},c=setTimeout(()=>{o==null||o.removeEventListener("abort",h),u()},l);o==null||o.addEventListener("abort",h,{once:!0})})}}const $e=1200*1e3,oe=new Set([y.DaemonStatus.PENDING_ACKS,y.DaemonStatus.PENDING_ACTIVATION,y.DaemonStatus.ACTIVATED_PENDING_BROADCAST,y.DaemonStatus.ACTIVATED]),Ve=new Set([y.DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,...oe]);function Ke(e){return e.map(t=>({claimerPubkeyXOnly:p.processPublicKeyToXOnly(t.claimer_pubkey),payoutTxHex:t.payout_tx.tx_hex,assertTxHex:t.assert_tx.tx_hex}))}function k(e){return p.processPublicKeyToXOnly(e).toLowerCase()}function Ie(e,t){const r=(i,u,s)=>{throw new Error(`Deposit terms ${i} (${String(u)}) does not match the vault's version-locked signing context (${String(s)}); refusing to sign payouts against terms that describe a different graph.`)};e.protocolFeeRate!==t.protocolFeeRate&&r("protocolFeeRate",e.protocolFeeRate,t.protocolFeeRate);const n=i=>i.map(k).sort(),a=(i,u)=>{const s=n(i),h=n(u);return s.length===h.length&&s.every((c,d)=>c===h[d])};a(e.vaultKeeperBtcPubkeys,t.vaultKeeperBtcPubkeys)||r("vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys.join(","),t.vaultKeeperBtcPubkeys.join(",")),a(e.universalChallengerBtcPubkeys,t.universalChallengerBtcPubkeys)||r("universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys.join(","),t.universalChallengerBtcPubkeys.join(","));const l=k(t.vaultProviderBtcPubkey),o=e.vaults.map(i=>k(i.vaultProviderBtcPubkey));o.includes(l)||r("vaults[].vaultProviderBtcPubkey",o.join(",")||"<no vaults>",t.vaultProviderBtcPubkey)}function He(e,t,r,n){const a=k(n),l=[k(t),...r.map(k)],o=new Set(l);if(o.size!==l.length)throw new Error("Cannot validate claimer set: signing context contains duplicate vault provider or vault keeper key");if(o.has(a))throw new Error("Cannot validate claimer set: depositor key overlaps with vault provider or vault keeper set");const i=e.map(d=>k(d.claimer_pubkey));if(new Set(i).size!==i.length)throw new Error("Presign response contains duplicate claimer entries");const u=i.filter(d=>d!==a),s=new Set(u),h=l.filter(d=>!s.has(d)),c=u.filter(d=>!o.has(d));if(h.length>0||c.length>0)throw new Error("Presign response claimer set does not match expected (vault provider ∪ vault keepers)"+(h.length>0?` (missing: ${h.join(", ")})`:"")+(c.length>0?` (unexpected: ${c.join(", ")})`:""))}function J(e,t){return{vaultCoreVersion:t.vaultCoreVersion,payoutTxHex:e.payoutTxHex,peginTxHex:t.peginTxHex,assertTxHex:e.assertTxHex,vaultProviderBtcPubkey:t.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys,depositorBtcPubkey:t.depositorBtcPubkey,timelockPegin:t.timelockPegin,timelockAssert:t.timelockAssert,registeredPayoutScriptPubKey:t.registeredPayoutScriptPubKey,claimerBtcPubkey:e.claimerPubkeyXOnly,commissionBps:t.commissionBps,protocolFeeRate:t.protocolFeeRate,councilSize:t.councilMembers.length,vkClaimerPayoutScriptPubKeys:t.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:t.vpCommissionScriptPubKey}}async function Oe(e,t,r,n){const a=new _.PayoutManager({network:t.network,btcWallet:e}),l=r.length;n==null||n(0,l);let o;if(a.supportsBatchSigning())o=(await a.signPayoutTransactionsBatch(r.map(s=>J(s,t)))).map(s=>s.payoutSignature);else{o=[];for(let u=0;u<r.length;u++){n==null||n(u,l);const s=await a.signPayoutTransaction(J(r[u],t));o.push(s.signature)}}const i={};for(let u=0;u<r.length;u++)i[r[u].claimerPubkeyXOnly]={payout_signature:o[u]};return n==null||n(l,l),i}async function De(e){const{statusReader:t,presignClient:r,btcWallet:n,peginTxid:a,depositorPk:l,signingContext:o,depositTerms:i,timeoutMs:u=$e,signal:s,onProgress:h}=e,c=await X({statusReader:t,peginTxid:a,targetStatuses:Ve,timeoutMs:u,signal:s});if(oe.has(c))return;if(s==null||s.throwIfAborted(),i!==void 0&&Ie(i,o),_.supportsDepositApproval(n)){if(!i)throw new Error("runDepositorPresignFlow: this wallet requires approved deposit terms but none were provided. Fresh deposits must pass PreparePeginResult.depositTerms; resume-path rebuild is not wired yet.");await n.approveDepositTerms(i)}const d=await r.requestDepositorPresignTransactions({pegin_txid:a,depositor_pk:l},s);s==null||s.throwIfAborted();const f=k(l);He(d.txs,o.vaultProviderBtcPubkey,o.vaultKeeperBtcPubkeys,l);const P=d.txs.filter(v=>k(v.claimer_pubkey)!==f),T=Ke(P),E=await Oe(n,o,T,h);s==null||s.throwIfAborted();const m=await ne({depositorGraph:d.depositor_graph,btcWallet:n,signingContext:{vaultCoreVersion:o.vaultCoreVersion,peginTxHex:o.peginTxHex,depositorBtcPubkey:l,vaultProviderBtcPubkey:o.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:o.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:o.universalChallengerBtcPubkeys,timelockPegin:o.timelockPegin,timelockAssert:o.timelockAssert,councilMembers:o.councilMembers,councilQuorum:o.councilQuorum,network:o.network,registeredPayoutScriptPubKey:o.registeredPayoutScriptPubKey,protocolFeeRate:o.protocolFeeRate,vkClaimerPayoutScriptPubKeys:o.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:o.vpCommissionScriptPubKey}});s==null||s.throwIfAborted();const x={...E};x[p.stripHexPrefix(l)]=m.payout_signatures,await r.submitDepositorPresignatures({pegin_txid:a,depositor_pk:l,signatures:x,depositor_claimer_presignatures:m},s)}const Ne=300*1e3,Fe=new Set([y.DaemonStatus.PENDING_DEPOSITOR_WOTS_PK,...y.POST_WOTS_STATUSES]);async function Me(e){const{statusReader:t,wotsSubmitter:r,peginTxid:n,depositorPk:a,wotsPublicKeys:l,timeoutMs:o=Ne,signal:i}=e;i==null||i.throwIfAborted();const u=await X({statusReader:t,peginTxid:n,targetStatuses:Fe,timeoutMs:o,signal:i});y.POST_WOTS_STATUSES.has(u)||(i==null||i.throwIfAborted(),await r.submitDepositorWotsKey({pegin_txid:n,depositor_pk:a,wots_public_keys:l},i))}function R(e){return e.registration||e.operation}function ie(e,t,r){const n=p.canonicalizeBtcPubkey(e);return{registration:n===p.canonicalizeBtcPubkey(t),operation:n===p.canonicalizeBtcPubkey(r)}}function F(e,t,r){const n=I(e);return{registration:ee(n,I(t)),operation:ee(n,I(r))}}function I(e){return e.map(p.canonicalizeBtcPubkey).sort()}function ee(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}async function Ue(e){const{vaultProviderEthAddress:t,hintBtcPubkey:r,registrationBtcPubkey:n,readCurrentOperationBtcPubkey:a,context:l}=e;if(!r)return;const o=p.canonicalizeBtcPubkey(r);if(o===p.canonicalizeBtcPubkey(n))return;const i=p.canonicalizeBtcPubkey(await a());if(o!==i)throw new Error(`Vault provider BTC pubkey mismatch for ${t}: indexer hint matches neither the registration key nor the current operation key on-chain.${l?` ${l}`:""}`)}function H(e,t,r){const n=`${e} operation key (admin=${t.ethAddress})`,a=Y.assertOnChainBtcPubkey(t.btcPubKey,`${e} roster key (admin=${t.ethAddress})`),l=Y.assertOnChainBtcPubkey(r,n);return{adminAddress:t.ethAddress,genesisBtcPubkey:a,operationBtcPubkey:l,rotated:l!==a}}function Le(e){const t=new Map;for(const r of e){const n=t.get(r.operationBtcPubkey);if(n)throw new Error(`Participant operation key collision: ${n} and ${r.adminAddress} both resolve to operation key ${r.operationBtcPubkey}`);t.set(r.operationBtcPubkey,r.adminAddress)}}function ae(e,t,r){if(t.vaultKeepers.length!==e.vaultKeepers.length||t.universalChallengers.length!==e.universalChallengers.length)throw new Error(`Operation-key resolution returned ${t.vaultKeepers.length} keeper and ${t.universalChallengers.length} challenger keys for a roster of ${e.vaultKeepers.length} keepers and ${e.universalChallengers.length} challengers`);const n=H("vault provider",{ethAddress:e.vaultProviderEthAddress,btcPubKey:e.vaultProviderGenesisBtcPubkey},t.vaultProvider),a=e.vaultKeepers.map((o,i)=>H("vault keeper",o,t.vaultKeepers[i])),l=e.universalChallengers.map((o,i)=>H("universal challenger",o,t.universalChallengers[i]));return Le([n,...a,...l]),{vaultProvider:n,vaultKeepers:a,universalChallengers:l,vaultKeeperOperationKeysSorted:a.map(o=>o.operationBtcPubkey).sort(),universalChallengerOperationKeysSorted:l.map(o=>o.operationBtcPubkey).sort(),resolvedAt:r,query:e}}async function se(e){const t=await e.operationKeyReader.getCurrentOperationKeys(e.query);return ae(e.query,t,{mode:"current"})}async function ue(e){const t=await e.operationKeyReader.getOperationKeysAtEpochs(e.query,e.epochs);return ae(e.query,t,{mode:"epochs",epochs:e.epochs})}const te=e=>e.map(p.canonicalizeBtcPubkey).sort();async function ze(e){const{vaultRegistryReader:t,vaultKeeperReader:r,universalChallengerReader:n,vaultProviderEthAddress:a,applicationEntryPoint:l,expectedVaultProviderBtcPubkey:o,expectedVaultKeeperBtcPubkeys:i,expectedUniversalChallengerBtcPubkeys:u,operationKeyReader:s,onIndexerServingOperationKeys:h,onIndexerHintsInconsistent:c}=e,[d,f,P]=await Promise.all([t.getVaultProviderBtcPubKey(a),r.getCurrentVaultKeepersVersion(l),n.getLatestUniversalChallengersVersion()]),[T,E]=await Promise.all([r.getVaultKeepersByVersion(l,f),n.getUniversalChallengersByVersion(P)]),m={vaultProvider:p.canonicalizeBtcPubkey(d),vaultKeepers:te(T.map(b=>b.btcPubKey)),universalChallengers:te(E.map(b=>b.btcPubKey))},x=await se({operationKeyReader:s,query:{vaultProviderEthAddress:a,vaultProviderGenesisBtcPubkey:`0x${d}`,applicationEntryPoint:l,vaultKeepers:T,universalChallengers:E}}),v={vaultProvider:x.vaultProvider.operationBtcPubkey,vaultKeepers:[...x.vaultKeeperOperationKeysSorted],universalChallengers:[...x.universalChallengerOperationKeysSorted]},C=ie(o,m.vaultProvider,v.vaultProvider),B=F(i,m.vaultKeepers,v.vaultKeepers),A=F(u,m.universalChallengers,v.universalChallengers);if(!R(C))throw new Error(`Vault provider BTC pubkey indexer hint does not match BTCVaultRegistry for ${a}. Refresh and try again.`);if(!R(B))throw new Error(`Vault keeper BTC pubkeys (v${f}) indexer set does not match ApplicationRegistry on-chain set. Refresh and try again.`);if(!R(A))throw new Error(`Universal challenger BTC pubkeys (v${P}) indexer set does not match ProtocolParams on-chain set. Refresh and try again.`);const g=[C,B,A],de=g.some(b=>b.registration&&!b.operation),Q=g.some(b=>b.operation&&!b.registration);if(de&&Q){const b=`Indexer participant hints are internally inconsistent for vault provider ${a}: some roles match the registration keys while others match the rotated operation keys.`;throw c==null||c(b),new Error(`${b} Refresh and try again.`)}return Q&&(h==null||h(`Indexer is serving rotated operation keys for vault provider ${a}`)),{vaultProviderBtcPubkeyXOnly:v.vaultProvider,vaultKeeperBtcPubkeysSorted:v.vaultKeepers,universalChallengerBtcPubkeysSorted:v.universalChallengers,expectedAppVaultKeepersVersion:f,expectedUniversalChallengersVersion:P,registrationKeys:m,participantKeys:x}}function Xe(e){return/^[0-9a-fA-F]{64}$/.test(e)}function qe(e){const{amountSats:t,minDeposit:r,maxDeposit:n,btcBalance:a,estimatedFeeSats:l,depositorClaimValue:o}=e;return!(t<=0n||t<r||n&&n>0n&&t>n||l==null||o==null||t+l+o>a)}function Ge(e,t,r){return e<=0n?{valid:!1,error:"Deposit amount must be greater than zero"}:e<t?{valid:!1,error:`Minimum deposit is ${p.formatSatoshisToBtc(t)} BTC`}:r&&r>0n&&e>r?{valid:!1,error:`Maximum deposit is ${p.formatSatoshisToBtc(r)} BTC`}:{valid:!0}}function je(e){const{amount:t,effectiveRemaining:r}=e;return r===null?{valid:!0}:r===0n?{valid:!1,error:"Supply cap reached — deposits temporarily paused"}:t>r?{valid:!1,error:`Vault size exceeds remaining capacity (${p.formatSatoshisToBtc(r)} BTC)`}:{valid:!0}}function We(e,t){if(!e||e.length===0)return{valid:!1,error:"At least one vault provider must be selected"};const r=t.map(a=>a.toLowerCase());return e.filter(a=>!r.includes(a.toLowerCase())).length>0?{valid:!1,error:"Invalid vault provider selected"}:{valid:!0}}function le(e,t,r){if(!e||e.length===0)return{valid:!1,error:"At least one vault amount required"};for(let n=0;n<e.length;n++){const a=e[n];if(a<=0n)return{valid:!1,error:`Vault ${n+1} amount must be positive`};if(t&&a<t)return{valid:!1,error:`Vault ${n+1} amount ${p.formatSatoshisToBtc(a)} BTC is below minimum deposit ${p.formatSatoshisToBtc(t)} BTC`};if(r&&a>r)return{valid:!1,error:`Vault ${n+1} amount ${p.formatSatoshisToBtc(a)} BTC exceeds maximum deposit ${p.formatSatoshisToBtc(r)} BTC`}}return{valid:!0}}function ce(e){const t=p.stripHexPrefix(e);return Xe(t)?{valid:!0}:{valid:!1,error:"Invalid pubkey format: must be 64 hex characters (32-byte x-only public key, no 0x prefix)"}}function Qe(e){if(!e||e.length===0)throw new Error("No vault keepers available. The system requires at least one vault keeper to create a deposit.")}function Ye(e){if(!e||e.length===0)throw new Error("No universal challengers available. The system requires at least one universal challenger to create a deposit.")}function Ze(e){if(e.length===0)throw new Error("No spendable UTXOs available")}function Je(e){const{vaultAmounts:t,confirmedUTXOs:r,vaultProviderBtcPubkey:n,vaultKeeperBtcPubkeys:a,universalChallengerBtcPubkeys:l,minDeposit:o,maxDeposit:i}=e,u=le(t,o,i);if(!u.valid)throw new Error(u.error);const s=ce(n);if(!s.valid)throw new Error(s.error);Qe(a),Ye(l),Ze(r)}class q extends Error{constructor(t){super(t),this.name="ParticipantKeyDriftError"}}function et(e){return e instanceof q||e instanceof Error&&e.name==="ParticipantKeyDriftError"}function re(e,t,r){return t.length===r.length&&t.every((n,a)=>n===r[a])?null:`${e} expected [${t.join(", ")}], got [${r.join(", ")}]`}async function tt(e){const{vaultRegistryReader:t,operationKeyReader:r,vaultIds:n,expected:a}=e,l=a.query;if(n.length===0)return;const o=await t.getVaultKeyEpochsBatch(n),i=[];for(const[u,s]of o.entries()){const h=n[u];let c;try{c=await ue({operationKeyReader:r,query:l,epochs:s})}catch(P){i.push(`vault ${h}: could not resolve participants at frozen epochs (vp=${s.vpKeyEpoch}, keeper=${s.appKeeperKeyEpoch}, uc=${s.ucKeyEpoch}): ${P.message}`);continue}c.vaultProvider.operationBtcPubkey!==a.vaultProvider.operationBtcPubkey&&i.push(`vault ${h}: vault provider key expected ${a.vaultProvider.operationBtcPubkey}, got ${c.vaultProvider.operationBtcPubkey}`);const d=re(`vault ${h}: vault keeper keys`,a.vaultKeeperOperationKeysSorted,c.vaultKeeperOperationKeysSorted);d&&i.push(d);const f=re(`vault ${h}: universal challenger keys`,a.universalChallengerOperationKeysSorted,c.universalChallengerOperationKeysSorted);f&&i.push(f)}if(i.length>0)throw new q(`Aborting BTC broadcast: participant operation keys changed during registration (${i.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`)}class G extends Error{constructor(t){super(t),this.name="RegisteredVaultVersionMismatchError"}}function rt(e){return e instanceof G||e instanceof Error&&e.name==="RegisteredVaultVersionMismatchError"}async function nt(e){const{vaultRegistryReader:t,vaultIds:r,expectedOffchainParamsVersion:n,expectedAppVaultKeepersVersion:a,expectedUniversalChallengersVersion:l,expectedVaultCoreVersion:o}=e,i=await t.getProtocolInfoBatch(r),u=[];if(i.forEach((s,h)=>{const c=r[h];s.offchainParamsVersion!==n&&u.push(`vault ${c}: offchainParams expected v${n}, got v${s.offchainParamsVersion}`),s.appVaultKeepersVersion!==a&&u.push(`vault ${c}: appVaultKeepers expected v${a}, got v${s.appVaultKeepersVersion}`),s.universalChallengersVersion!==l&&u.push(`vault ${c}: universalChallengers expected v${l}, got v${s.universalChallengersVersion}`),s.vaultCoreVersion!==o&&u.push(`vault ${c}: vaultCoreVersion expected v${o} (build-time active), got v${s.vaultCoreVersion}`)}),u.length>0)throw new G(`Aborting BTC broadcast: signer-set or offchain-params versions changed during registration (${u.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`)}var j=(e=>(e.CLAIM_EVENT_RECEIVED="ClaimEventReceived",e.CLAIM_BROADCAST="ClaimBroadcast",e.ASSERT_BROADCAST="AssertBroadcast",e.PAYOUT_BROADCAST="PayoutBroadcast",e.PAYOUT_BLOCKED="PayoutBlocked",e))(j||{});const ot=new Set(["PayoutBroadcast","PayoutBlocked"]);function it(e){return Object.values(j).includes(e)}function at(e){return!!e&&ot.has(e)}class pe extends Error{constructor(r,n){super(`Refund not yet mature (BIP68 not final): ${n.message}`);$(this,"vaultId");$(this,"cause");this.name="BIP68NotMatureError",this.vaultId=r,this.cause=n}}const st=/^0x[0-9a-fA-F]{64}$/,ut=/^(?:0x)?(?:[0-9a-fA-F]{2})+$/,he=/^(?:0x)?(?:[0-9a-fA-F]{64}|[0-9a-fA-F]{66})$/,W=160,M=2e3,U=10n,L=100n;function lt(e){if(!Number.isFinite(e)||e<=0)throw new Error(`feeRateSatsVb must be a positive finite number, got ${e}`);return BigInt(Math.ceil(e*W))}const ct=1,pt=/non-BIP68-final/i;function z(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!st.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function O(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer, got ${e}`)}function ht(e){if(z(e.hashlock,"hashlock"),!Number.isInteger(e.htlcVout)||e.htlcVout<0)throw new Error(`htlcVout must be a non-negative integer, got ${e.htlcVout}`);if(!Array.isArray(e.batch)||e.batch.length===0)throw new Error("batch must be a non-empty array of HTLC entries");if(e.htlcVout>=e.batch.length)throw new Error(`htlcVout ${e.htlcVout} is out of range for batch of size ${e.batch.length}`);for(let r=0;r<e.batch.length;r++){const n=e.batch[r];if(z(n.hashlock,`batch[${r}].hashlock`),!Number.isInteger(n.htlcVout)||n.htlcVout!==r)throw new Error(`batch[${r}].htlcVout must equal ${r} (contiguous vout-ordered vector), got ${n.htlcVout}`);if(typeof n.amount!="bigint"||n.amount<=0n)throw new Error(`batch[${r}].amount must be a positive bigint, got ${n.amount}`)}const t=e.batch[e.htlcVout];if(t.hashlock.toLowerCase()!==e.hashlock.toLowerCase())throw new Error(`batch[${e.htlcVout}].hashlock (${t.hashlock}) does not match target hashlock (${e.hashlock})`);if(t.amount!==e.amount)throw new Error(`batch[${e.htlcVout}].amount (${t.amount}) does not match target amount (${e.amount})`);if(O(e.offchainParamsVersion,"offchainParamsVersion"),O(e.appVaultKeepersVersion,"appVaultKeepersVersion"),O(e.universalChallengersVersion,"universalChallengersVersion"),ye.assertValidVaultCoreVersion(e.vaultCoreVersion,"VaultRefundData.vaultCoreVersion"),typeof e.unsignedPrePeginTxHex!="string"||e.unsignedPrePeginTxHex.length===0)throw new Error("unsignedPrePeginTxHex must be a non-empty hex string");if(!ut.test(e.unsignedPrePeginTxHex))throw new Error("unsignedPrePeginTxHex must be a hex byte string (optional 0x prefix, even length)");if(!e.depositorBtcPubkey||!he.test(e.depositorBtcPubkey))throw new Error("depositorBtcPubkey must be 32 or 33 bytes of hex (optional 0x prefix)");if(typeof e.amount!="bigint"||e.amount<=0n)throw new Error(`amount must be a positive bigint, got ${e.amount}`)}function dt(e){if(!e.vaultProviderPubkey||!he.test(e.vaultProviderPubkey))throw new Error("vaultProviderPubkey must be 32 or 33 bytes of hex");if(e.vaultKeeperPubkeys.length===0)throw new Error("vaultKeeperPubkeys must be non-empty");if(e.universalChallengerPubkeys.length===0)throw new Error("universalChallengerPubkeys must be non-empty");if(!Number.isInteger(e.timelockRefund)||e.timelockRefund<=0)throw new Error(`timelockRefund must be a positive integer, got ${e.timelockRefund}`);if(typeof e.feeRate!="bigint"||e.feeRate<=0n)throw new Error(`protocol feeRate must be a positive bigint, got ${e.feeRate}`);if(typeof e.minPeginFeeRate!="bigint"||e.minPeginFeeRate<=0n)throw new Error(`minPeginFeeRate must be a positive bigint, got ${e.minPeginFeeRate}`);if(!Number.isInteger(e.numLocalChallengers)||e.numLocalChallengers<0)throw new Error("numLocalChallengers must be a non-negative integer");if(!Number.isInteger(e.councilQuorum)||!Number.isInteger(e.councilSize)||e.councilQuorum<=0||e.councilSize<=0||e.councilQuorum>e.councilSize)throw new Error(`councilQuorum (${e.councilQuorum}) must be in [1, councilSize=${e.councilSize}]`)}function gt(e){const t=S.Psbt.fromHex(e);try{t.finalizeAllInputs()}catch(r){const n=r instanceof Error?r.message:String(r);if(!n.includes("already finalized"))throw new Error(`Failed to finalize refund PSBT: ${n}`)}return t.extractTransaction().toHex()}async function ft(e){const{vaultId:t,readVault:r,readPrePeginContext:n,feeRate:a,signPsbt:l,broadcastTx:o,signal:i}=e;i==null||i.throwIfAborted(),z(t,"vaultId");const u=await r();ht(u),i==null||i.throwIfAborted();const s=await n(u);if(dt(s),i==null||i.throwIfAborted(),!Number.isFinite(a)||a<=0)throw new Error(`feeRate must be a positive number, got ${a}`);if(a>M)throw new Error(`feeRate ${a} sat/vB exceeds refund safety cap ${M} sat/vB; refusing to sign refund.`);const h=BigInt(Math.ceil(a*W)),c=u.amount*U/L;if(h>c)throw new Error(`Refund fee ${h} sats exceeds the per-vault safety cap of ${c} sats (${U}/${L} of vault.amount=${u.amount}); refusing to sign refund.`);i==null||i.throwIfAborted();const d=p.processPublicKeyToXOnly(u.depositorBtcPubkey),f=p.stripHexPrefix(u.unsignedPrePeginTxHex),P=_.findAuthAnchorOpReturn(f);if(P!==void 0&&P.vout!==u.batch.length)throw new Error(`Auth-anchor OP_RETURN at vout ${P.vout} does not match batch size (${u.batch.length} HTLC outputs expect the anchor at vout ${u.batch.length}). Refund refused — sibling HTLC vector is incomplete.`);const T=P==null?void 0:P.hash;let E;try{E=S.Transaction.fromHex(f)}catch(g){throw new Error(`Failed to parse funded Pre-PegIn transaction hex: ${g instanceof Error?g.message:String(g)}`)}if(E.outs.length<u.batch.length)throw new Error(`Funded Pre-PegIn tx has ${E.outs.length} outputs but batch requires at least ${u.batch.length} HTLC outputs. Refund refused — funded tx shape disagrees with sibling vector.`);const{psbtHex:m}=await D.buildRefundPsbt({prePeginParams:{vaultCoreVersion:u.vaultCoreVersion,depositorPubkey:d,vaultProviderPubkey:p.stripHexPrefix(s.vaultProviderPubkey),vaultKeeperPubkeys:s.vaultKeeperPubkeys.map(p.stripHexPrefix),universalChallengerPubkeys:s.universalChallengerPubkeys.map(p.stripHexPrefix),hashlocks:u.batch.map(g=>p.stripHexPrefix(g.hashlock)),timelockRefund:s.timelockRefund,pegInAmounts:u.batch.map(g=>g.amount),feeRate:s.feeRate,minPeginFeeRate:s.minPeginFeeRate,numLocalChallengers:s.numLocalChallengers,councilQuorum:s.councilQuorum,councilSize:s.councilSize,network:s.network,authAnchorHash:T},fundedPrePeginTxHex:f,htlcVout:u.htlcVout,refundFee:h,hashlock:p.stripHexPrefix(u.hashlock)});i==null||i.throwIfAborted();const x=N.createTaprootScriptPathSignOptions(u.depositorBtcPubkey,ct),v=await l(m,x);w.assertPsbtUnsignedTxMatches({requestedPsbtHex:m,returnedPsbtHex:v});const C=0,B=w.extractPayoutSignature(v,d,C);w.assertScriptPathSchnorrSignature({requestedPsbtHex:m,signatureHex:B,signerXOnlyPubkeyHex:d,inputIndex:C});const A=gt(v);i==null||i.throwIfAborted();try{return await o(A)}catch(g){throw g instanceof Error&&pt.test(g.message)?new pe(t,g):g}}exports.BIP68NotMatureError=pe;exports.ClaimerPegoutStatusValue=j;exports.ParticipantKeyDriftError=q;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=L;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=U;exports.REFUND_MAX_FEE_RATE_SATS_VB=M;exports.REFUND_VSIZE=W;exports.RegisteredVaultVersionMismatchError=G;exports.activateVault=ke;exports.assertVaultProviderHintAccepted=Ue;exports.buildAndBroadcastRefund=ft;exports.estimateRefundFeeSats=lt;exports.isDepositAmountValid=qe;exports.isHintAccepted=R;exports.isParticipantKeyDriftError=et;exports.isPegoutTerminalStatus=at;exports.isRecognizedPegoutStatus=it;exports.isRegisteredVaultVersionMismatchError=rt;exports.matchKeyHint=ie;exports.matchKeySetHint=F;exports.resolveCurrentParticipantKeys=se;exports.resolveParticipantKeysAtEpochs=ue;exports.runDepositorPresignFlow=De;exports.signDepositorGraph=ne;exports.submitWotsPublicKey=Me;exports.validateDepositAmount=Ge;exports.validateMultiVaultDepositInputs=Je;exports.validateOnChainParticipantKeys=ze;exports.validateProviderSelection=We;exports.validateRemainingCapacity=je;exports.validateVaultAmounts=le;exports.validateVaultProviderPubkey=ce;exports.verifyRegisteredParticipantKeys=tt;exports.verifyRegisteredVaultVersions=nt;exports.waitForPeginStatus=X;
2
+ //# sourceMappingURL=buildAndBroadcastRefund-BL8u-Ti4.cjs.map