@babylonlabs-io/ts-sdk 0.32.0 → 0.33.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.
- package/dist/{PeginManager-DUR1BTKM.js → PeginManager-BMrWtTji.js} +136 -124
- package/dist/PeginManager-BMrWtTji.js.map +1 -0
- package/dist/PeginManager-DUMF84XK.cjs +2 -0
- package/dist/PeginManager-DUMF84XK.cjs.map +1 -0
- package/dist/{buildAndBroadcastRefund-CIHhUmRv.cjs → buildAndBroadcastRefund-6pR681fI.cjs} +2 -2
- package/dist/buildAndBroadcastRefund-6pR681fI.cjs.map +1 -0
- package/dist/{buildAndBroadcastRefund-DwrX_IBf.js → buildAndBroadcastRefund-Ba56IKL7.js} +38 -38
- package/dist/buildAndBroadcastRefund-Ba56IKL7.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +74 -70
- package/dist/tbv/core/clients/eth/index.d.ts +1 -1
- package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/types.d.ts +13 -0
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +8 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +30 -27
- package/dist/tbv/core/clients/vault-provider/api.d.ts +13 -2
- package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/createAuthenticatedVpClient.test.d.ts +11 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/createAuthenticatedVpClient.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenRegistry.test.d.ts +2 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenRegistry.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts +16 -0
- package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/gatedMethods.d.ts +10 -0
- package/dist/tbv/core/clients/vault-provider/auth/gatedMethods.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/index.d.ts +5 -2
- package/dist/tbv/core/clients/vault-provider/auth/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/innerTokenClient.d.ts +4 -0
- package/dist/tbv/core/clients/vault-provider/auth/innerTokenClient.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts +11 -0
- package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts +18 -23
- package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts +48 -0
- package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +8 -12
- package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +14 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +65 -61
- package/dist/tbv/core/managers/index.d.ts +1 -1
- package/dist/tbv/core/services/deposit/__tests__/runDepositorPresignFlow.test.d.ts +2 -0
- package/dist/tbv/core/services/deposit/__tests__/runDepositorPresignFlow.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/index.d.ts +2 -2
- package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/{signAndSubmitPayouts.d.ts → runDepositorPresignFlow.d.ts} +3 -3
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -0
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +11 -11
- package/dist/tbv/core/vault-secrets/__tests__/parseFundingOutpoints.test.d.ts +2 -0
- package/dist/tbv/core/vault-secrets/__tests__/parseFundingOutpoints.test.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/index.d.ts +1 -0
- package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/parseFundingOutpoints.d.ts +3 -0
- package/dist/tbv/core/vault-secrets/parseFundingOutpoints.d.ts.map +1 -0
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +65 -61
- package/dist/{types-jmEyzzhY.cjs → types-C2IUB0Jd.cjs} +2 -2
- package/dist/types-C2IUB0Jd.cjs.map +1 -0
- package/dist/{types-CnG3JsRs.js → types-D1o_3Q__.js} +20 -9
- package/dist/types-D1o_3Q__.js.map +1 -0
- package/dist/{vault-registry-reader-CG6bea1S.js → vault-registry-reader-BeIEh62N.js} +436 -292
- package/dist/vault-registry-reader-BeIEh62N.js.map +1 -0
- package/dist/vault-registry-reader-DdUgC5IF.cjs +2 -0
- package/dist/vault-registry-reader-DdUgC5IF.cjs.map +1 -0
- package/package.json +1 -1
- package/dist/PeginManager-CTRPJo8m.cjs +0 -2
- package/dist/PeginManager-CTRPJo8m.cjs.map +0 -1
- package/dist/PeginManager-DUR1BTKM.js.map +0 -1
- package/dist/buildAndBroadcastRefund-CIHhUmRv.cjs.map +0 -1
- package/dist/buildAndBroadcastRefund-DwrX_IBf.js.map +0 -1
- package/dist/tbv/core/services/deposit/__tests__/signAndSubmitPayouts.test.d.ts +0 -2
- package/dist/tbv/core/services/deposit/__tests__/signAndSubmitPayouts.test.d.ts.map +0 -1
- package/dist/tbv/core/services/deposit/signAndSubmitPayouts.d.ts.map +0 -1
- package/dist/types-CnG3JsRs.js.map +0 -1
- package/dist/types-jmEyzzhY.cjs.map +0 -1
- package/dist/vault-registry-reader-BBS1_AON.cjs +0 -2
- package/dist/vault-registry-reader-BBS1_AON.cjs.map +0 -1
- package/dist/vault-registry-reader-CG6bea1S.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PeginManager-CTRPJo8m.cjs","sources":["../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_u64.js","../src/tbv/core/managers/pegin/assertAuthAnchorOpReturn.ts","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/hmac.js","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/hkdf.js","../src/tbv/core/vault-secrets/info.ts","../src/tbv/core/vault-secrets/expand.ts","../src/tbv/core/vault-secrets/context.ts","../src/tbv/core/vault-secrets/deriveVaultRoot.ts","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/legacy.js","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/sha3.js","../src/tbv/core/wots/blockDerivation.ts","../src/tbv/core/wots/errors.ts","../src/tbv/core/managers/pegin/expandPerVaultSecrets.ts","../src/tbv/core/managers/pegin/normalizeWalletInputs.ts","../src/tbv/core/managers/pegin/signPsbtsWithFallback.ts","../src/tbv/core/contracts/errors.ts","../src/tbv/core/managers/PeginManager.ts"],"sourcesContent":["/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * Structural verifier for the auth-anchor OP_RETURN in a funded\n * Pre-PegIn transaction.\n *\n * @module managers/pegin/assertAuthAnchorOpReturn\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** OP_RETURN opcode. */\nconst OP_RETURN = 0x6a;\n/** Push-32-bytes opcode (raw push, not OP_PUSHDATA1). */\nconst OP_PUSH32 = 0x20;\n/** Encoded length of a standard OP_RETURN script with a 32-byte payload. */\nconst OP_RETURN_PUSH32_SCRIPT_LEN = 1 + 1 + 32;\n\n/**\n * Verify the broadcast Pre-PegIn carries the expected OP_RETURN\n * commitment to the auth anchor.\n *\n * The OP_RETURN sits at `vout = vaultCount` (right after the per-vault\n * HTLC outputs and before the depositor-claim/change outputs) and\n * pushes the 32-byte `SHA256(authAnchor)`. The script encoding is\n * exactly `OP_RETURN || PUSH32 || <32 bytes>` (34 bytes). A\n * non-conformant WASM build that omitted the OP_RETURN, swapped its\n * position, or changed its push payload would let the depositor\n * obtain a valid bearer token for a Pre-PegIn whose on-chain\n * commitment doesn't actually bind the anchor — degrading the auth\n * from on-chain-bound to a shared secret. Fail closed.\n *\n * @throws If the OP_RETURN is missing, mis-located, mis-encoded, or\n * pushes a payload other than `expectedAuthAnchorHashHex`.\n */\nexport function assertAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vaultCount: number,\n expectedAuthAnchorHashHex: string,\n): void {\n const cleanHex = stripHexPrefix(fundedPrePeginTxHex);\n const tx = bitcoin.Transaction.fromHex(cleanHex);\n\n if (tx.outs.length <= vaultCount) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${tx.outs.length} ` +\n `outputs, expected at least ${vaultCount + 1} (vault outputs + OP_RETURN)`,\n );\n }\n\n const opReturnOutput = tx.outs[vaultCount];\n const script = opReturnOutput.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has unexpected ` +\n `script encoding (got ${script.length}-byte script with prefix ` +\n `0x${script.slice(0, Math.min(2, script.length)).toString(\"hex\")}; ` +\n `expected ${OP_RETURN_PUSH32_SCRIPT_LEN}-byte OP_RETURN + PUSH32 layout)`,\n );\n }\n\n const pushedHex = script.slice(2).toString(\"hex\").toLowerCase();\n if (pushedHex !== expectedAuthAnchorHashHex.toLowerCase()) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${vaultCount}: ` +\n `tx pushes ${pushedHex}, expected ${expectedAuthAnchorHashHex}`,\n );\n }\n\n if (opReturnOutput.value !== 0) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has non-zero ` +\n `value ${opReturnOutput.value}; OP_RETURN outputs must be 0-value`,\n );\n }\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean } from \"./utils.js\";\n/** Internal class for HMAC. */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen, 'output');\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new _HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See https://soatok.blog/2021/11/17/understanding-hkdf/.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\nimport { abytes, ahash, anumber, clean } from \"./utils.js\";\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n */\nexport function extract(hash, ikm, salt) {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return hmac(hash, salt, ikm);\n}\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n */\nexport function expand(hash, prk, info, length = 32) {\n ahash(hash);\n anumber(length, 'length');\n const olen = hash.outputLen;\n if (length > 255 * olen)\n throw new Error('Length must be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n else\n abytes(info, undefined, 'info');\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * olen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, olen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n clean(T, HKDF_COUNTER);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n * @example\n * import { hkdf } from '@noble/hashes/hkdf';\n * import { sha256 } from '@noble/hashes/sha2';\n * import { randomBytes } from '@noble/hashes/utils';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = 'application-key';\n * const hk1 = hkdf(sha256, inputKey, salt, info, 32);\n */\nexport const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map","/**\n * Info encoding for HKDF-Expand per `derive-vault-secrets.md` Appendix A.\n *\n * ```\n * info(label, ctx) :=\n * \"babylonvault\" // fixed 12-byte ASCII domain tag\n * || I2OSP(len(label), 1) // 1-byte label length\n * || label // ASCII bytes of the label\n * || I2OSP(len(ctx), 2) // 2-byte big-endian ctx length\n * || ctx // opaque per-label context bytes\n * ```\n *\n * The fixed-width length prefixes make the encoding injective over the\n * set of legal `(label, ctx)` pairs, which is what lets distinct labels\n * produce computationally-independent HKDF-Expand outputs under the\n * HMAC-SHA-256 PRF assumption.\n *\n * @module vault-secrets/info\n */\n\nconst DOMAIN_TAG_BYTES = new TextEncoder().encode(\"babylonvault\");\n\n/** Max label length (1-byte prefix). */\nconst MAX_LABEL_LEN = 0xff;\n\n/** Max ctx length (2-byte prefix). */\nconst MAX_CTX_LEN = 0xffff;\n\n/** Size of the ctx length prefix in bytes. */\nconst CTX_LEN_PREFIX_SIZE = 2;\n\n/**\n * @internal Label for the per-HTLC hashlock preimage (Appendix A §A.2).\n * Exported only so the spec-conformance tests can pin the literal value.\n */\nexport const LABEL_HASHLOCK = \"hashlock\";\n\n/**\n * @internal Label for the per-Pre-PegIn shared auth-anchor (Appendix A §A.2).\n * Exported only so the spec-conformance tests can pin the literal value.\n */\nexport const LABEL_AUTH_ANCHOR = \"auth-anchor\";\n\n/**\n * @internal Label for the per-HTLC WOTS block-derivation seed (Appendix A §A.2).\n * Exported only so the spec-conformance tests can pin the literal value.\n */\nexport const LABEL_WOTS_SEED = \"wots-seed\";\n\n/**\n * Encode a 32-bit unsigned integer as 4 big-endian bytes (RFC 8017 §4.1,\n * `I2OSP(n, 4)`).\n *\n * @internal Helper used by `buildInfo` and the per-HTLC `expand*`\n * functions; consumed directly only by tests.\n *\n * @throws If `value` is not a non-negative integer ≤ `0xffffffff`.\n */\nexport function i2osp4(value: number): Uint8Array {\n if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {\n throw new Error(`i2osp4: value must be a u32, got ${value}`);\n }\n const out = new Uint8Array(4);\n out[0] = (value >>> 24) & 0xff;\n out[1] = (value >>> 16) & 0xff;\n out[2] = (value >>> 8) & 0xff;\n out[3] = value & 0xff;\n return out;\n}\n\n/**\n * Build the `info` byte-string for an HKDF-Expand invocation.\n *\n * @internal Used by the per-HTLC `expand*` functions; exposed for the\n * spec-conformance tests that pin the encoded byte layout.\n *\n * @param label - ASCII label tag. Length MUST be in `[1, 255]`.\n * @param ctx - Optional opaque context bytes. Length MUST be in `[0, 65535]`.\n */\nexport function buildInfo(\n label: string,\n ctx: Uint8Array = new Uint8Array(0),\n): Uint8Array {\n const labelBytes = new TextEncoder().encode(label);\n\n if (labelBytes.length === 0 || labelBytes.length > MAX_LABEL_LEN) {\n throw new Error(\n `info: label length must be in [1, ${MAX_LABEL_LEN}], got ${labelBytes.length}`,\n );\n }\n if (ctx.length > MAX_CTX_LEN) {\n throw new Error(\n `info: ctx length must be in [0, ${MAX_CTX_LEN}], got ${ctx.length}`,\n );\n }\n\n const total =\n DOMAIN_TAG_BYTES.length +\n 1 +\n labelBytes.length +\n CTX_LEN_PREFIX_SIZE +\n ctx.length;\n\n const out = new Uint8Array(total);\n let offset = 0;\n\n out.set(DOMAIN_TAG_BYTES, offset);\n offset += DOMAIN_TAG_BYTES.length;\n\n out[offset] = labelBytes.length;\n offset += 1;\n\n out.set(labelBytes, offset);\n offset += labelBytes.length;\n\n // I2OSP(len, 2) big-endian\n out[offset] = (ctx.length >>> 8) & 0xff;\n out[offset + 1] = ctx.length & 0xff;\n offset += CTX_LEN_PREFIX_SIZE;\n\n out.set(ctx, offset);\n\n return out;\n}\n","/**\n * HKDF-Expand-based vault-secret derivation per\n * `derive-vault-secrets.md` §2.2.\n *\n * Pure, synchronous expanders that derive three domain-separated\n * secrets from a 32-byte `root`. The root is spec-opaque — typically\n * obtained via `deriveVaultRoot(wallet, vaultContextInput)` (which\n * forwards to the wallet's `deriveContextHash`), but any 32-byte\n * pseudorandom source satisfies the contract.\n *\n * All expand calls use HKDF-Expand-SHA-256 with `root` directly as the\n * PRK (RFC 5869 §3.3: the Extract step is omitted when the input is\n * already a uniformly-distributed pseudorandom key of HashLen bytes).\n *\n * @module vault-secrets/expand\n */\n\nimport { expand as hkdfExpand } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nimport {\n LABEL_AUTH_ANCHOR,\n LABEL_HASHLOCK,\n LABEL_WOTS_SEED,\n buildInfo,\n i2osp4,\n} from \"./info\";\n\nconst ROOT_SIZE = 32;\nconst AUTH_ANCHOR_SIZE = 32;\nconst HASHLOCK_SIZE = 32;\nconst WOTS_SEED_SIZE = 64;\n\nfunction assertRoot(root: Uint8Array): void {\n if (root.length !== ROOT_SIZE) {\n throw new Error(\n `vault-secrets: root must be exactly ${ROOT_SIZE} bytes, got ${root.length}`,\n );\n }\n}\n\n/**\n * Derive the 32-byte `authAnchor` shared across a single Pre-PegIn\n * transaction.\n *\n * `SHA256(authAnchor)` is committed as the OP_RETURN preimage hash in\n * the Pre-PegIn; the raw preimage is revealed to the vault provider's\n * `auth_createDepositorToken` RPC in exchange for a CWT bearer token.\n *\n * @stability frozen — on-chain-binding. Changing the HKDF info encoding\n * (label or argument order) rotates the anchor and invalidates the VP\n * bearer-token flow for existing deposits.\n */\nexport function expandAuthAnchor(root: Uint8Array): Uint8Array {\n assertRoot(root);\n return hkdfExpand(\n sha256,\n root,\n buildInfo(LABEL_AUTH_ANCHOR),\n AUTH_ANCHOR_SIZE,\n );\n}\n\n/**\n * Derive the 32-byte `hashlockSecret` for the HTLC at output index\n * `htlcVout`.\n *\n * `SHA256(hashlockSecret)` is committed as the HTLC taproot hashlock\n * at vout = `htlcVout` in the Pre-PegIn. The raw preimage is revealed\n * on Ethereum via `activateVaultWithSecret`.\n *\n * @stability frozen — on-chain-binding. Changing the HKDF info\n * encoding produces a different secret whose SHA-256 will not match\n * the on-chain hashlock; affected vaults can never be activated.\n */\nexport function expandHashlockSecret(\n root: Uint8Array,\n htlcVout: number,\n): Uint8Array {\n assertRoot(root);\n return hkdfExpand(\n sha256,\n root,\n buildInfo(LABEL_HASHLOCK, i2osp4(htlcVout)),\n HASHLOCK_SIZE,\n );\n}\n\n/**\n * Derive the 64-byte `wotsSeed` for the vault at output index\n * `htlcVout`.\n *\n * Fed into the per-vault WOTS block-keypair derivation. Only the\n * `keccak256` hash of the derived public keys appears on-chain\n * (committed as `depositorWotsPkHash`).\n *\n * @stability frozen — on-chain-binding. Changing the HKDF info\n * encoding (label or htlcVout serialization) rotates the seed and\n * therefore the WOTS keys; existing `depositorWotsPkHash` commitments\n * would no longer match. Per-vault domain separation depends on the\n * `i2osp4(htlcVout)` argument: do not change its encoding.\n */\nexport function expandWotsSeed(root: Uint8Array, htlcVout: number): Uint8Array {\n assertRoot(root);\n return hkdfExpand(\n sha256,\n root,\n buildInfo(LABEL_WOTS_SEED, i2osp4(htlcVout)),\n WOTS_SEED_SIZE,\n );\n}\n","/**\n * Canonical `vaultContext` byte encoding per\n * `derive-vault-secrets.md` §2.3.\n *\n * ```\n * vaultContext :=\n * I2OSP(32, 4) || depositorBtcPubkey // 32B x-only\n * || I2OSP(32, 4) || fundingOutpointsCommitment // 32B SHA-256\n * ```\n *\n * `fundingOutpointsCommitment` is SHA-256 over the canonically-sorted\n * funding outpoints of the Pre-PegIn transaction, serialized as\n * `txid (32B display/RPC order) || vout (4B u32 big-endian)` per\n * outpoint. Sorting by 36-byte lex order makes the commitment\n * invariant under tx-level input reordering, so same-inputs RBF and\n * reorg rebroadcasts yield the same context.\n *\n * @module vault-secrets/context\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nconst DEPOSITOR_PUBKEY_SIZE = 32;\nconst TXID_SIZE = 32;\nconst OUTPOINT_SIZE = 36;\nconst COMMITMENT_SIZE = 32;\nconst FIELD_LEN_PREFIX_SIZE = 4;\nconst VAULT_CONTEXT_SIZE =\n FIELD_LEN_PREFIX_SIZE +\n DEPOSITOR_PUBKEY_SIZE +\n FIELD_LEN_PREFIX_SIZE +\n COMMITMENT_SIZE;\n\nexport interface FundingOutpoint {\n /**\n * Bitcoin txid in **display / RPC order** (byte-reversed from the\n * internal little-endian wire form used when hashing a raw tx).\n */\n txid: Uint8Array;\n /** Output index within the referenced transaction (u32). */\n vout: number;\n}\n\nexport interface VaultContextInput {\n /** Depositor's x-only BTC public key (32 bytes). */\n depositorBtcPubkey: Uint8Array;\n /** Funding outpoints of the Pre-PegIn transaction. MUST be non-empty. */\n fundingOutpoints: readonly FundingOutpoint[];\n}\n\nfunction writeUint32BE(out: Uint8Array, offset: number, value: number): void {\n out[offset] = (value >>> 24) & 0xff;\n out[offset + 1] = (value >>> 16) & 0xff;\n out[offset + 2] = (value >>> 8) & 0xff;\n out[offset + 3] = value & 0xff;\n}\n\nfunction serializeOutpoint(outpoint: FundingOutpoint): Uint8Array {\n if (outpoint.txid.length !== TXID_SIZE) {\n throw new Error(\n `outpoint.txid must be exactly ${TXID_SIZE} bytes, got ${outpoint.txid.length}`,\n );\n }\n if (\n !Number.isInteger(outpoint.vout) ||\n outpoint.vout < 0 ||\n outpoint.vout > 0xffffffff\n ) {\n throw new Error(`outpoint.vout must be a u32, got ${outpoint.vout}`);\n }\n const out = new Uint8Array(OUTPOINT_SIZE);\n out.set(outpoint.txid, 0);\n writeUint32BE(out, TXID_SIZE, outpoint.vout);\n return out;\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n const len = Math.min(a.length, b.length);\n for (let i = 0; i < len; i++) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return a.length - b.length;\n}\n\n/**\n * Compute SHA-256 over canonically-sorted funding outpoints.\n *\n * Outpoints are serialized as 36-byte `txid || vout_BE`, sorted\n * ascending lexicographically, concatenated, then hashed.\n *\n * @stability frozen — on-chain-binding. Any change to layout, sort\n * order, or serialization is a hard fork; existing deposits would no\n * longer match their committed `depositorWotsPkHash`.\n *\n * @throws If `outpoints` is empty or contains duplicates.\n */\nexport function buildFundingOutpointsCommitment(\n outpoints: readonly FundingOutpoint[],\n): Uint8Array {\n if (outpoints.length === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: outpoints must be non-empty\",\n );\n }\n const serialized = outpoints.map(serializeOutpoint);\n serialized.sort(compareBytes);\n\n for (let i = 1; i < serialized.length; i++) {\n if (compareBytes(serialized[i - 1], serialized[i]) === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: duplicate outpoint detected\",\n );\n }\n }\n\n const flat = new Uint8Array(serialized.length * OUTPOINT_SIZE);\n for (let i = 0; i < serialized.length; i++) {\n flat.set(serialized[i], i * OUTPOINT_SIZE);\n }\n return sha256(flat);\n}\n\n/**\n * Build the canonical `vaultContext` byte string fed into the wallet's\n * `deriveContextHash` (or a locally-implemented equivalent on the\n * app side).\n *\n * Output length is always 72 bytes.\n *\n * @stability frozen — on-chain-binding. The 72-byte layout is the\n * input to `deriveContextHash`; any change rotates the vault root and\n * therefore every WOTS key, hashlock secret, and auth anchor derived\n * from it. Existing deposits cannot be recovered after a layout change.\n */\nexport function buildVaultContext(input: VaultContextInput): Uint8Array {\n if (input.depositorBtcPubkey.length !== DEPOSITOR_PUBKEY_SIZE) {\n throw new Error(\n `vaultContext: depositorBtcPubkey must be exactly ${DEPOSITOR_PUBKEY_SIZE} bytes, got ${input.depositorBtcPubkey.length}`,\n );\n }\n const commitment = buildFundingOutpointsCommitment(input.fundingOutpoints);\n\n const out = new Uint8Array(VAULT_CONTEXT_SIZE);\n let offset = 0;\n\n writeUint32BE(out, offset, DEPOSITOR_PUBKEY_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(input.depositorBtcPubkey, offset);\n offset += DEPOSITOR_PUBKEY_SIZE;\n\n writeUint32BE(out, offset, COMMITMENT_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(commitment, offset);\n\n return out;\n}\n","/**\n * Vault-root derivation via the wallet's `deriveContextHash` API.\n *\n * Implements the canonical root source from `derive-vault-secrets.md`\n * §2.2:\n *\n * ```\n * rootDerivation = deriveContextHash(\"babylon-vault\", hex(vaultContext))\n * ```\n *\n * The 32-byte output is fed directly into the {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, and {@link expandWotsSeed} functions in\n * this module.\n *\n * @module vault-secrets/deriveVaultRoot\n */\n\nimport { hexToUint8Array, uint8ArrayToHex } from \"../primitives/utils/bitcoin\";\n\nimport { buildVaultContext, type VaultContextInput } from \"./context\";\n\n/**\n * The fixed `appName` passed to the wallet's `deriveContextHash` for\n * Babylon vault derivations. The wallet displays this in its approval\n * dialog. Defined by `derive-vault-secrets.md` §2.2 — must not be\n * changed without coordinating a spec revision and a downstream\n * migration plan, as it provides app-level domain separation across\n * applications using the same wallet.\n */\nexport const VAULT_APP_NAME = \"babylon-vault\";\n\n/** Expected length of the wallet output in bytes per spec §2.1. */\nconst ROOT_OUTPUT_BYTES = 32;\n\n/** Expected length of the wallet output in lowercase hex chars. */\nconst ROOT_OUTPUT_HEX_LEN = ROOT_OUTPUT_BYTES * 2;\n\nconst LOWERCASE_HEX_RE = /^[0-9a-f]+$/;\n\n/**\n * Minimal structural shape for the wallet capability needed by this\n * helper. Typed against the method directly so callers can pass any\n * value that implements `deriveContextHash` — `BitcoinWallet` from\n * this SDK, `IBTCProvider` from `@babylonlabs-io/wallet-connector`,\n * or a test mock — without depending on the rest of either interface.\n */\nexport interface DeriveContextHashCapableWallet {\n deriveContextHash(appName: string, context: string): Promise<string>;\n}\n\n/**\n * Derive the 32-byte vault root from a wallet by encoding the\n * canonical {@link VaultContextInput} and forwarding to\n * `wallet.deriveContextHash`.\n *\n * Validates the wallet's output strictly: must be exactly 64\n * lowercase hex characters per `derive-context-hash.md` §2.1. A\n * conformant wallet always satisfies this, but we re-check at the\n * SDK boundary so a non-conformant wallet (or a wallet returning a\n * malformed value through a buggy adapter) fails loud here rather\n * than producing silently-wrong derived secrets downstream.\n *\n * The helper itself produces only valid spec inputs (`appName` is\n * the hardcoded `VAULT_APP_NAME`; `context` is hex of the 72-byte\n * `vaultContext`, always 144 chars lowercase), so input-side\n * validation is unnecessary.\n *\n * @param wallet - Any value implementing `deriveContextHash`.\n * @param input - The canonical {@link VaultContextInput} that\n * uniquely identifies the vault. Encoded by\n * {@link buildVaultContext} into a 72-byte structure\n * before being hex-encoded for the wallet.\n * @stability frozen — on-chain-binding. The pair (`VAULT_APP_NAME`,\n * `vaultContext` encoding) is the wallet's input space; changing\n * either rotates the root and invalidates every secret derived from\n * it. `VAULT_APP_NAME` is fixed by `derive-vault-secrets.md` §2.2\n * and must never change without a coordinated spec revision.\n *\n * @returns 32-byte root suitable for {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, {@link expandWotsSeed}.\n * @throws If the wallet returns a non-64-char or non-lowercase-hex\n * string. Errors from the wallet (user rejection,\n * method-not-supported, etc.) propagate unchanged.\n */\nexport async function deriveVaultRoot(\n wallet: DeriveContextHashCapableWallet,\n input: VaultContextInput,\n): Promise<Uint8Array> {\n const vaultContext = buildVaultContext(input);\n const contextHex = uint8ArrayToHex(vaultContext);\n\n const rootHex = await wallet.deriveContextHash(VAULT_APP_NAME, contextHex);\n\n if (typeof rootHex !== \"string\") {\n throw new Error(\n `deriveVaultRoot: wallet must return a string, got ${typeof rootHex}`,\n );\n }\n if (rootHex.length !== ROOT_OUTPUT_HEX_LEN) {\n throw new Error(\n `deriveVaultRoot: wallet must return a ${ROOT_OUTPUT_HEX_LEN}-character hex string (${ROOT_OUTPUT_BYTES} bytes), got length ${rootHex.length}`,\n );\n }\n if (!LOWERCASE_HEX_RE.test(rootHex)) {\n throw new Error(\n \"deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters\",\n );\n }\n\n return hexToUint8Array(rootHex);\n}\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD {\n A = SHA1_IV[0] | 0;\n B = SHA1_IV[1] | 0;\n C = SHA1_IV[2] | 0;\n D = SHA1_IV[3] | 0;\n E = SHA1_IV[4] | 0;\n constructor() {\n super(64, 20, 8, false);\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD {\n A = MD5_IV[0] | 0;\n B = MD5_IV[1] | 0;\n C = MD5_IV[2] | 0;\n D = MD5_IV[3] | 0;\n constructor() {\n super(64, 16, 8, true);\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n }\n else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new _MD5());\n// RIPEMD-160\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class _RIPEMD160 extends HashMD {\n h0 = 0x67452301 | 0;\n h1 = 0xefcdab89 | 0;\n h2 = 0x98badcfe | 0;\n h3 = 0x10325476 | 0;\n h4 = 0xc3d2e1f0 | 0;\n constructor() {\n super(64, 20, 8, true);\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n//# sourceMappingURL=legacy.js.map","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createHasher, oidNist, swap32IfBE, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/** Keccak sponge function. */\nexport class Keccak {\n state;\n pos = 0;\n posOut = 0;\n finished = false;\n state32;\n destroyed = false;\n blockLen;\n suffix;\n outputLen;\n enableXOF = false;\n rounds;\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, 'outputLen');\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n/** SHA3-224 hash function. */\nexport const sha3_224 = /* @__PURE__ */ genKeccak(0x06, 144, 28, \n/* @__PURE__ */ oidNist(0x07));\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n/** SHAKE128 XOF with 256-bit output (NIST version). */\nexport const shake128_32 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n/** SHAKE256 XOF with 512-bit output (NIST version). */\nexport const shake256_64 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n//# sourceMappingURL=sha3.js.map","/**\n * WOTS Block Key Derivation\n *\n * Derives deterministic WOTS (Winternitz One-Time Signature) block public\n * keys from a per-vault 64-byte seed, matching the Rust `babe::wots`\n * chain logic.\n *\n * Callers obtain the seed from `expandWotsSeed(root, htlcVout)` in the\n * vault-secrets module, where\n * `root = await deriveVaultRoot(wallet, vaultContextInput)`. Per-vault\n * uniqueness is already encoded in the seed via `htlcVout`, so this\n * module only handles the chain derivation — no further key splitting\n * by `(vaultId, depositorPk, appContract)` is needed.\n *\n * @module wots/blockDerivation\n */\n\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport type { Hex } from \"viem\";\n\nimport type {\n WotsBlockPublicKey,\n WotsConfig,\n} from \"../clients/vault-provider/types\";\n\n// ---------------------------------------------------------------------------\n// Constants — must match btc-vault / babe::wots\n// ---------------------------------------------------------------------------\n\n/** Required size of the per-vault WOTS seed in bytes. */\nconst WOTS_SEED_SIZE = 64;\n\n/** Hash160 output size in bytes (= RIPEMD-160(SHA-256(x))). */\nconst CHAIN_ELEMENT_SIZE = 20;\n\n/** Bits per WOTS digit. Matches `babe::WOTS_DIGIT_BITS`. */\nconst WOTS_DIGIT_BITS = 4;\n\n/** Number of checksum digits in canonical WOTS ordering. */\nconst WOTS_CHECKSUM_DIGITS = 2;\n\n/** Digit index for the checksum minor chain (canonical ordering). */\nconst CHECKSUM_MINOR_DIGIT_INDEX = 0;\n\n/** Digit index for the checksum major chain (canonical ordering). */\nconst CHECKSUM_MAJOR_DIGIT_INDEX = 1;\n\n/**\n * Message digit counts per assert block.\n * Matches `btc_vault::ASSERT_WOTS_BLOCK_DIGIT_COUNTS`.\n */\nconst ASSERT_WOTS_BLOCK_DIGIT_COUNTS: readonly number[] = [64, 64];\n\n// ---------------------------------------------------------------------------\n// Cryptographic primitives\n// ---------------------------------------------------------------------------\n\nconst toHex = (bytes: Uint8Array) =>\n Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\nfunction hash160(data: Uint8Array): Uint8Array {\n return ripemd160(sha256(data));\n}\n\n// ---------------------------------------------------------------------------\n// WOTS chain derivation — mirrors Rust babe::wots\n// ---------------------------------------------------------------------------\n\nfunction maxDigitValue(d: number): number {\n return (1 << d) - 1;\n}\n\nfunction defaultChecksumRadix(wMax: number): number {\n let radix = 1;\n while (radix * radix < wMax + 1) radix++;\n return Math.max(radix, 2);\n}\n\nfunction createWotsConfig(n: number): WotsConfig {\n const d = WOTS_DIGIT_BITS;\n const wMax = n * maxDigitValue(d);\n return { d, n, checksum_radix: defaultChecksumRadix(wMax) };\n}\n\n/**\n * Derive the starting chain value for a given digit index.\n * Matches Rust `chain_start_for_digit(seed, digit_index)`:\n * hash160(seed || varint_le(digit_index))\n */\nfunction chainStartForDigit(seed: Uint8Array, digitIndex: number): Uint8Array {\n const suffixBytes: number[] = [];\n let idx = digitIndex;\n while (idx > 0) {\n suffixBytes.push(idx & 0xff);\n idx >>>= 8;\n }\n const preimage = new Uint8Array(seed.length + suffixBytes.length);\n preimage.set(seed);\n for (let i = 0; i < suffixBytes.length; i++) {\n preimage[seed.length + i] = suffixBytes[i];\n }\n return hash160(preimage);\n}\n\n/**\n * Compute the terminal value of a Hash160 chain of given length.\n * Matches Rust `compute_chain(seed, len)` — returns chain[len].\n */\nfunction computeChainTerminal(start: Uint8Array, steps: number): Uint8Array {\n let current = start;\n for (let i = 0; i < steps; i++) {\n current = hash160(current);\n }\n return current;\n}\n\n// ---------------------------------------------------------------------------\n// Per-block public key derivation\n// ---------------------------------------------------------------------------\n\nfunction deriveBlockPublicKey(\n blockSeed: Uint8Array,\n config: WotsConfig,\n): WotsBlockPublicKey {\n const k = maxDigitValue(config.d);\n const checksumMinorMax = config.checksum_radix - 1;\n const checksumMajorMax = Math.floor((config.n * k) / config.checksum_radix);\n\n const messageTerminals: number[][] = [];\n for (let digit = 0; digit < config.n; digit++) {\n const start = chainStartForDigit(blockSeed, digit + WOTS_CHECKSUM_DIGITS);\n const terminal = computeChainTerminal(start, k);\n messageTerminals.push(Array.from(terminal));\n }\n\n const checksumMinorStart = chainStartForDigit(\n blockSeed,\n CHECKSUM_MINOR_DIGIT_INDEX,\n );\n const checksumMinorTerminal = computeChainTerminal(\n checksumMinorStart,\n checksumMinorMax,\n );\n\n const checksumMajorStart = chainStartForDigit(\n blockSeed,\n CHECKSUM_MAJOR_DIGIT_INDEX,\n );\n const checksumMajorTerminal = computeChainTerminal(\n checksumMajorStart,\n checksumMajorMax,\n );\n\n return {\n config,\n message_terminals: messageTerminals,\n checksum_major_terminal: Array.from(checksumMajorTerminal),\n checksum_minor_terminal: Array.from(checksumMinorTerminal),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Derive deterministic WOTS block public keys from a per-vault 64-byte seed.\n *\n * The seed must come from `expandWotsSeed(root, htlcVout)` (vault-secrets\n * module). Per-vault uniqueness is encoded in `htlcVout`; this function\n * only handles the chain derivation. Per-block 20-byte seeds are derived\n * as `hash160(seed || blockIdx)` and fed into the standard Rust\n * `babe::wots` chain logic.\n *\n * The seed is zeroed in the `finally` block.\n *\n * @stability frozen — on-chain-binding. Per-block seed derivation,\n * chain length, checksum-digit ordering, and terminal byte layout\n * must match Rust `babe::wots` byte-for-byte. Any divergence rotates\n * `depositorWotsPkHash` and breaks resume + on-chain verification\n * for every existing vault.\n *\n * @param seed - 64-byte per-vault seed.\n * @returns Array of 2 WOTS block public keys.\n * @throws If `seed.length !== 64`.\n */\nexport async function deriveWotsBlocksFromSeed(\n seed: Uint8Array,\n): Promise<WotsBlockPublicKey[]> {\n // try/finally wraps the size check so the seed buffer is zeroed on\n // every exit path, including malformed-input rejection.\n try {\n if (seed.length !== WOTS_SEED_SIZE) {\n throw new Error(\n `WOTS seed must be exactly ${WOTS_SEED_SIZE} bytes, got ${seed.length}`,\n );\n }\n\n const blocks: WotsBlockPublicKey[] = [];\n\n for (\n let blockIdx = 0;\n blockIdx < ASSERT_WOTS_BLOCK_DIGIT_COUNTS.length;\n blockIdx++\n ) {\n const n = ASSERT_WOTS_BLOCK_DIGIT_COUNTS[blockIdx];\n const config = createWotsConfig(n);\n\n // Per-block 20-byte seed: hash160(seed || blockIdx)\n const blockSeedInput = new Uint8Array(seed.length + 1);\n blockSeedInput.set(seed);\n blockSeedInput[seed.length] = blockIdx;\n const blockSeed = hash160(blockSeedInput);\n\n try {\n const block = deriveBlockPublicKey(blockSeed, config);\n\n if (block.config.d !== WOTS_DIGIT_BITS) {\n throw new Error(\n `Block ${blockIdx}: expected d=${WOTS_DIGIT_BITS}, got d=${block.config.d}`,\n );\n }\n if (block.config.n !== n) {\n throw new Error(\n `Block ${blockIdx}: expected n=${n}, got n=${block.config.n}`,\n );\n }\n if (block.message_terminals.length !== n) {\n throw new Error(\n `Block ${blockIdx}: expected ${n} message terminals, got ${block.message_terminals.length}`,\n );\n }\n for (let t = 0; t < block.message_terminals.length; t++) {\n if (block.message_terminals[t].length !== CHAIN_ELEMENT_SIZE) {\n throw new Error(\n `Block ${blockIdx} terminal ${t}: expected ${CHAIN_ELEMENT_SIZE} bytes, got ${block.message_terminals[t].length}`,\n );\n }\n }\n if (block.checksum_minor_terminal.length !== CHAIN_ELEMENT_SIZE) {\n throw new Error(\n `Block ${blockIdx} checksum_minor: expected ${CHAIN_ELEMENT_SIZE} bytes`,\n );\n }\n if (block.checksum_major_terminal.length !== CHAIN_ELEMENT_SIZE) {\n throw new Error(\n `Block ${blockIdx} checksum_major: expected ${CHAIN_ELEMENT_SIZE} bytes`,\n );\n }\n\n blocks.push(block);\n } finally {\n blockSeedInput.fill(0);\n blockSeed.fill(0);\n }\n }\n\n if (blocks.length !== ASSERT_WOTS_BLOCK_DIGIT_COUNTS.length) {\n throw new Error(\n `Expected ${ASSERT_WOTS_BLOCK_DIGIT_COUNTS.length} blocks, got ${blocks.length}`,\n );\n }\n\n return blocks;\n } finally {\n seed.fill(0);\n }\n}\n\n/** Validate a single chain terminal: correct length and all bytes in [0, 255]. */\nfunction validateTerminal(\n terminal: number[],\n blockIdx: number,\n label: string,\n): void {\n if (terminal.length !== CHAIN_ELEMENT_SIZE) {\n throw new Error(\n `Block ${blockIdx} ${label}: expected ${CHAIN_ELEMENT_SIZE} bytes, got ${terminal.length}`,\n );\n }\n for (let j = 0; j < terminal.length; j++) {\n const b = terminal[j];\n if (!Number.isInteger(b) || b < 0 || b > 255) {\n throw new Error(\n `Block ${blockIdx} ${label}[${j}]: invalid byte value ${b}`,\n );\n }\n }\n}\n\n/**\n * Compute the keccak256 hash of WOTS block public keys.\n *\n * Matches Rust `btc_vault::wots_public_keys_keccak256`: for each block,\n * chain tips are concatenated in canonical order\n * `[checksum_minor, checksum_major, message_terminals...]`, then all\n * blocks are concatenated and hashed.\n *\n * The result is committed on-chain as `depositorWotsPkHash` so the vault\n * provider can verify submitted WOTS public keys.\n *\n * @stability frozen — on-chain-binding. Concatenation order of chain\n * tips and the keccak256 input layout MUST match Rust\n * `btc_vault::wots_public_keys_keccak256` byte-for-byte. Any change\n * rotates the on-chain commitment and breaks every existing vault.\n */\nexport function computeWotsBlockPublicKeysHash(\n publicKeys: WotsBlockPublicKey[],\n): Hex {\n if (publicKeys.length === 0) {\n throw new Error(\"Public keys array must not be empty\");\n }\n\n for (let i = 0; i < publicKeys.length; i++) {\n const pk = publicKeys[i];\n validateTerminal(pk.checksum_minor_terminal, i, \"checksum_minor_terminal\");\n validateTerminal(pk.checksum_major_terminal, i, \"checksum_major_terminal\");\n for (let t = 0; t < pk.message_terminals.length; t++) {\n validateTerminal(pk.message_terminals[t], i, `message_terminal[${t}]`);\n }\n }\n\n let totalTips = 0;\n for (const pk of publicKeys) {\n totalTips += WOTS_CHECKSUM_DIGITS + pk.message_terminals.length;\n }\n\n const buffer = new Uint8Array(totalTips * CHAIN_ELEMENT_SIZE);\n let offset = 0;\n\n for (const pk of publicKeys) {\n buffer.set(pk.checksum_minor_terminal, offset);\n offset += CHAIN_ELEMENT_SIZE;\n buffer.set(pk.checksum_major_terminal, offset);\n offset += CHAIN_ELEMENT_SIZE;\n for (const terminal of pk.message_terminals) {\n buffer.set(terminal, offset);\n offset += CHAIN_ELEMENT_SIZE;\n }\n }\n\n const digest = keccak_256(buffer);\n return `0x${toHex(digest)}`;\n}\n","/**\n * Check whether an error from the vault provider indicates that the\n * submitted WOTS public key hash does not match the on-chain\n * commitment. This signals that the wrong wallet is connected (its\n * `deriveContextHash` produces a different vault root and therefore\n * different WOTS keys).\n */\nexport function isWotsMismatchError(error: unknown): boolean {\n const msg = (\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\"\n ).toLowerCase();\n\n return (\n msg.includes(\"wots\") &&\n msg.includes(\"hash\") &&\n msg.includes(\"does not match\")\n );\n}\n","/**\n * Per-vault HKDF expansion of WOTS keys + HTLC preimages from the\n * wallet root.\n *\n * @module managers/pegin/expandPerVaultSecrets\n */\n\nimport type { Hex } from \"viem\";\n\nimport type { WotsBlockPublicKey } from \"../../clients/vault-provider/types\";\nimport {\n ensureHexPrefix,\n uint8ArrayToHex,\n} from \"../../primitives/utils/bitcoin\";\nimport { computeHashlock } from \"../../services\";\nimport {\n expandHashlockSecret,\n expandWotsSeed,\n} from \"../../vault-secrets\";\nimport {\n computeWotsBlockPublicKeysHash,\n deriveWotsBlocksFromSeed,\n} from \"../../wots\";\n\n/**\n * Result of {@link expandPerVaultSecrets}.\n */\nexport interface PerVaultExpansionResult {\n perVaultWotsKeys: WotsBlockPublicKey[][];\n /** Keccak256 of WOTS keys, ready as `depositorWotsPkHash` (0x-prefixed). */\n wotsPkHashes: Hex[];\n /** HTLC preimage hex per vault (no 0x prefix). */\n htlcSecretHexes: string[];\n /** SHA-256 of each HTLC preimage as 64-char hex (no 0x prefix). */\n hashlocks: string[];\n}\n\n/**\n * Derive per-vault WOTS keys + HTLC preimages from the wallet root.\n *\n * Takes ownership of `root`: zeros the buffer (and per-vault secret\n * buffers) before returning, regardless of how the caller exits.\n *\n * @param root 32-byte wallet-derived root from `deriveVaultRoot`.\n * @param vaultCount Number of vaults (= length of `amounts`).\n */\nexport async function expandPerVaultSecrets(\n root: Uint8Array,\n vaultCount: number,\n): Promise<PerVaultExpansionResult> {\n const perVaultWotsKeys: WotsBlockPublicKey[][] = [];\n const wotsPkHashes: Hex[] = [];\n const htlcSecretHexes: string[] = [];\n const hashlocks: string[] = [];\n\n try {\n for (let i = 0; i < vaultCount; i++) {\n const wotsSeed = expandWotsSeed(root, i);\n try {\n const wotsPublicKeys = await deriveWotsBlocksFromSeed(wotsSeed);\n perVaultWotsKeys.push(wotsPublicKeys);\n wotsPkHashes.push(computeWotsBlockPublicKeysHash(wotsPublicKeys));\n } finally {\n wotsSeed.fill(0);\n }\n\n const secretBytes = expandHashlockSecret(root, i);\n try {\n const secretHex = uint8ArrayToHex(secretBytes);\n htlcSecretHexes.push(secretHex);\n hashlocks.push(computeHashlock(ensureHexPrefix(secretHex)).slice(2));\n } finally {\n secretBytes.fill(0);\n }\n }\n } finally {\n root.fill(0);\n }\n\n return { perVaultWotsKeys, wotsPkHashes, htlcSecretHexes, hashlocks };\n}\n","/**\n * Normalizers for wallet-returned values consumed by the Pre-PegIn flow.\n *\n * @module managers/pegin/normalizeWalletInputs\n */\n\nimport { Buffer } from \"buffer\";\nimport type { Hex } from \"viem\";\n\nimport { processPublicKeyToXOnly } from \"../../primitives/utils/bitcoin\";\n\nconst HEX_SIGNATURE_REGEX = /^0x[0-9a-f]+$/i;\nconst UNPREFIXED_HEX_SIGNATURE_REGEX = /^[0-9a-f]+$/i;\nconst BASE64_SIGNATURE_REGEX = /^[A-Za-z0-9+/]+={0,2}$/;\n\n/**\n * Normalize a wallet-returned BTC public key to the canonical x-only\n * 64-char lowercase hex form (no 0x prefix).\n *\n * Throws on empty/non-string input. Idempotent on x-only input.\n */\nexport function normalizeXOnlyPubkey(raw: unknown): string {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw new Error(\"BTC wallet returned empty public key\");\n }\n // Lowercase so case-sensitive equality checks downstream don't fail\n // on uppercase wallet output (processPublicKeyToXOnly passes a 64-char\n // input through unchanged).\n return processPublicKeyToXOnly(raw).toLowerCase();\n}\n\n/**\n * Normalize a wallet-returned BIP-322 signature into 0x-prefixed hex.\n *\n * Accepts:\n * - 0x-prefixed lowercase/uppercase hex\n * - unprefixed hex (wins over base64 when input is pure `[0-9a-fA-F]+`)\n * - canonical standard base64 (`[A-Za-z0-9+/]` with `=` padding to a\n * multiple of 4 and no non-canonical encodings)\n *\n * Rejects URL-safe base64 (`-`/`_`) and base64 without padding. Wallets\n * known to return BIP-322 signatures (Keystone, UniSat, OKX, OneKey,\n * Unisat) all use standard base64; URL-safe is an explicit non-goal.\n */\nexport function normalizePopSignature(raw: unknown): Hex {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw new Error(\"BTC wallet returned empty BIP-322 signature\");\n }\n\n if (raw.startsWith(\"0x\") || raw.startsWith(\"0X\")) {\n if (\n !HEX_SIGNATURE_REGEX.test(raw) ||\n raw.length < 4 ||\n raw.length % 2 !== 0\n ) {\n throw new Error(\"BTC wallet returned malformed hex BIP-322 signature\");\n }\n return raw.toLowerCase() as Hex;\n }\n\n // Prefer hex when the input could be either: every hex char is also a\n // valid base64 char, so the base64 branch alone would silently misdecode\n // a wallet returning \"deadbeef\" instead of \"0xdeadbeef\".\n if (UNPREFIXED_HEX_SIGNATURE_REGEX.test(raw)) {\n if (raw.length % 2 !== 0) {\n throw new Error(\"BTC wallet returned malformed hex BIP-322 signature\");\n }\n return `0x${raw.toLowerCase()}` as Hex;\n }\n\n if (!BASE64_SIGNATURE_REGEX.test(raw) || raw.length % 4 !== 0) {\n throw new Error(\"BTC wallet returned malformed base64 BIP-322 signature\");\n }\n const bytes = Buffer.from(raw, \"base64\");\n // Round-trip to reject non-canonical base64 (e.g. \"AB==\" decodes but\n // re-encodes to \"AA==\").\n if (bytes.length === 0 || bytes.toString(\"base64\") !== raw) {\n throw new Error(\"BTC wallet returned malformed base64 BIP-322 signature\");\n }\n return `0x${bytes.toString(\"hex\")}` as Hex;\n}\n","/**\n * Batch-sign helper that prefers native `signPsbts` and falls back to\n * sequential `signPsbt` for wallets that don't implement batch signing.\n *\n * @module managers/pegin/signPsbtsWithFallback\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../../shared/wallets\";\n\n/**\n * Sign multiple PSBTs against a wallet. Wallets exposing native batch\n * signing (e.g. UniSat) sign all PSBTs in a single interaction; others\n * (Ledger, AppKit) loop `signPsbt` internally, so the popup UX depends\n * on the wallet adapter.\n *\n * @throws If `signPsbts` returns a different number of signed PSBTs\n * than were submitted.\n */\nexport async function signPsbtsWithFallback(\n wallet: BitcoinWallet,\n psbtsHexes: string[],\n options: SignPsbtOptions[],\n): Promise<string[]> {\n if (typeof wallet.signPsbts === \"function\") {\n const signedPsbts = await wallet.signPsbts(psbtsHexes, options);\n if (signedPsbts.length !== psbtsHexes.length) {\n throw new Error(\n `Expected ${psbtsHexes.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n return signedPsbts;\n }\n\n const signedPsbts: string[] = [];\n for (let i = 0; i < psbtsHexes.length; i++) {\n const signed = await wallet.signPsbt(psbtsHexes[i], options[i]);\n signedPsbts.push(signed);\n }\n return signedPsbts;\n}\n","/**\n * Contract Error Handling Utilities\n *\n * Provides utilities for extracting and handling contract revert errors.\n * Maps known error selectors to user-friendly messages.\n *\n * @module contracts/errors\n */\n\n/**\n * Known contract error signatures mapped to user-friendly messages.\n *\n * Error selectors are the first 4 bytes of keccak256(error signature).\n * Example: keccak256(\"VaultAlreadyExists()\") = 0x04aabf33...\n */\nexport const CONTRACT_ERRORS: Record<string, string> = {\n // VaultAlreadyExists()\n \"0x04aabf33\":\n \"Vault already exists: This Bitcoin transaction has already been registered. \" +\n \"Please select different UTXOs or use a different amount to create a unique transaction.\",\n // ScriptPubKeyMismatch() - taproot output doesn't match expected script\n \"0x4fec082d\":\n \"Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. \" +\n \"This may be caused by incorrect vault participants or key configuration.\",\n // InvalidBTCProofOfPossession()\n \"0x6cc363a5\":\n \"Invalid BTC proof of possession: The signature could not be verified. \" +\n \"Please ensure you're signing with the correct Bitcoin wallet.\",\n // InvalidBTCPublicKey()\n \"0x6c3f2bf6\":\n \"Invalid BTC public key: The Bitcoin public key format is invalid.\",\n // InvalidAmount()\n \"0x2c5211c6\":\n \"Invalid amount: The deposit amount is invalid or below the minimum required.\",\n // ApplicationNotRegistered()\n \"0x0405f772\":\n \"Application not registered: The application controller is not registered in the system.\",\n // InvalidProviderStatus()\n \"0x24e165cc\":\n \"Invalid provider status: The vault provider is not in a valid state to accept deposits.\",\n // ZeroAddress()\n \"0xd92e233d\":\n \"Zero address: One of the required addresses is the zero address.\",\n // BtcKeyMismatch()\n \"0x65aa7007\":\n \"BTC key mismatch: The Bitcoin public key does not match the expected key.\",\n // Unauthorized()\n \"0x82b42900\":\n \"Unauthorized: You must be the depositor or vault provider to submit this transaction.\",\n // InvalidSignature() - common signature verification error\n \"0x8baa579f\":\n \"Invalid signature: The BTC proof of possession signature could not be verified.\",\n // InvalidBtcTransaction()\n \"0x2f9d01e9\":\n \"Invalid BTC transaction: The Bitcoin transaction format is invalid.\",\n // VaultProviderNotRegistered()\n \"0x5a3c6b3e\":\n \"Vault provider not registered: The selected vault provider is not registered.\",\n // InvalidPeginFee(uint256,uint256)\n \"0x979f4518\":\n \"Invalid pegin fee: The ETH fee sent does not match the required amount. \" +\n \"This may indicate a fee rate change during the transaction.\",\n // PrePeginOutputAlreadyUsed()\n \"0x5fad9694\":\n \"This pre-pegin output has already been used to activate another vault.\",\n // PeginTransactionAlreadyUsed()\n \"0x7ed061c9\":\n \"This pegin transaction has already been used to activate another vault.\",\n};\n\n/**\n * Extract error data from various error formats.\n *\n * Viem and wallet providers wrap errors in multiple levels. This function\n * searches through the error chain to find the revert data.\n *\n * @param error - The error object to extract data from\n * @returns The error data (e.g., \"0x04aabf33\") or undefined\n */\nexport function extractErrorData(error: unknown): string | undefined {\n if (!error || typeof error !== \"object\") return undefined;\n\n const err = error as Record<string, unknown>;\n\n // Check direct properties first\n if (typeof err.data === \"string\" && err.data.startsWith(\"0x\")) {\n return err.data;\n }\n if (typeof err.details === \"string\" && err.details.startsWith(\"0x\")) {\n return err.details;\n }\n\n // Walk the cause chain (viem wraps errors multiple levels deep)\n let current: unknown = err.cause;\n let depth = 0;\n const maxDepth = 5;\n\n while (current && typeof current === \"object\" && depth < maxDepth) {\n const cause = current as Record<string, unknown>;\n if (typeof cause.data === \"string\" && cause.data.startsWith(\"0x\")) {\n return cause.data;\n }\n current = cause.cause;\n depth++;\n }\n\n // Check error message for embedded hex error selector\n const message = typeof err.message === \"string\" ? err.message : \"\";\n const hexMatch = message.match(/\\b(0x[a-fA-F0-9]{8})\\b/);\n if (hexMatch) {\n return hexMatch[1];\n }\n\n return undefined;\n}\n\n/**\n * Get a user-friendly error message for a contract error.\n *\n * @param error - The error object from a contract call\n * @returns A user-friendly error message, or undefined if error is not recognized\n */\nexport function getContractErrorMessage(error: unknown): string | undefined {\n const errorData = extractErrorData(error);\n if (errorData) {\n // Check exact match first, then match by 4-byte selector prefix.\n // Parametric errors (e.g. InvalidPeginFee(uint256,uint256)) return\n // the selector + ABI-encoded args, so the full string won't match.\n const selector = errorData.substring(0, 10); // \"0x\" + 4 bytes\n return CONTRACT_ERRORS[errorData] ?? CONTRACT_ERRORS[selector];\n }\n return undefined;\n}\n\n/**\n * Check if an error is a known contract error.\n *\n * @param error - The error object to check\n * @returns True if the error is a known contract error\n */\nexport function isKnownContractError(error: unknown): boolean {\n const errorData = extractErrorData(error);\n if (errorData === undefined) return false;\n const selector = errorData.substring(0, 10);\n return errorData in CONTRACT_ERRORS || selector in CONTRACT_ERRORS;\n}\n\n/**\n * Handle a contract error by throwing a user-friendly error.\n *\n * This function extracts error data, maps it to a user-friendly message,\n * and throws an appropriate error. Use this in catch blocks after contract calls.\n *\n * @param error - The error from a contract call\n * @throws Always throws an error with a descriptive message\n */\nexport function handleContractError(error: unknown): never {\n // Log full error for debugging\n console.error(\"[Contract Error] Raw error:\", error);\n\n // Extract error data from the error chain\n const errorData = extractErrorData(error);\n console.error(\"[Contract Error] Extracted error data:\", errorData);\n\n // Check for known contract error signatures (exact match or 4-byte selector prefix)\n if (errorData) {\n const selector = errorData.substring(0, 10);\n const knownError = CONTRACT_ERRORS[errorData] ?? CONTRACT_ERRORS[selector];\n if (knownError) {\n console.error(\"[Contract Error] Known error:\", knownError);\n throw new Error(knownError);\n }\n }\n\n // Check for gas estimation errors or internal JSON-RPC errors\n const errorMsg = (error as Error)?.message || \"\";\n if (\n errorMsg.includes(\"gas limit too high\") ||\n errorMsg.includes(\"21000000\") ||\n errorMsg.includes(\"Internal JSON-RPC error\")\n ) {\n // If we found error data but it's not in our known list, include it\n const errorHint = errorData ? ` (error code: ${errorData})` : \"\";\n console.error(\n \"[Contract Error] Transaction rejected. Error code:\",\n errorData,\n \"Message:\",\n errorMsg,\n );\n throw new Error(\n `Transaction failed: The contract rejected this transaction${errorHint}. ` +\n \"Possible causes: (1) Vault already exists for this transaction, \" +\n \"(2) Invalid signature, (3) Unauthorized caller. \" +\n \"Please check your transaction parameters and try again.\",\n );\n }\n\n // Default: re-throw original error with better context\n if (error instanceof Error) {\n console.error(\"[Contract Error] Unhandled error:\", error.message);\n throw error;\n }\n throw new Error(`Contract call failed: ${String(error)}`);\n}\n","/**\n * Peg-in Manager - Wallet Orchestration for Peg-in Operations\n *\n * This module provides the PeginManager class that orchestrates the complete\n * peg-in flow using SDK primitives, utilities, and wallet interfaces.\n *\n * @remarks\n * PeginManager handles the peg-in flow:\n * 1. **preparePegin()** - Build Pre-PegIn HTLC, fund it, sign PegIn input\n * 2. **signProofOfPossession()** - Sign BIP-322 PoP (one per deposit session)\n * 3. **registerPeginOnChain()** - Submit to Ethereum contract with PoP\n * 4. **signAndBroadcast()** - Sign and broadcast Pre-PegIn tx to Bitcoin network\n * 5. *(Use {@link PayoutManager} for payout authorization signing)*\n *\n * @see {@link PayoutManager} - For Step 5: sign payout transactions\n * @see {@link buildPrePeginPsbt} - Lower-level primitive used internally\n *\n * @module managers/PeginManager\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport {\n assertAuthAnchorOpReturn,\n expandPerVaultSecrets,\n normalizePopSignature,\n normalizeXOnlyPubkey,\n signPsbtsWithFallback,\n} from \"./pegin\";\nimport {\n createPublicClient,\n encodeFunctionData,\n http,\n isAddressEqual,\n zeroAddress,\n type Address,\n type Chain,\n type Hex,\n type WalletClient,\n} from \"viem\";\n\nimport type { BitcoinWallet, Hash, SignPsbtOptions } from \"../../../shared/wallets\";\nimport type { WotsBlockPublicKey } from \"../clients/vault-provider/types\";\nimport { type UtxoInfo, getUtxoInfo, pushTx } from \"../clients/mempool\";\nimport { BTCVaultRegistryABI, handleContractError } from \"../contracts\";\nimport {\n buildPrePeginPsbt,\n buildPeginTxFromFundedPrePegin,\n buildPeginInputPsbt,\n extractPeginInputSignature,\n finalizePeginInputPsbt,\n deriveVaultId,\n type PrePeginParams,\n type Network,\n} from \"../primitives\";\nimport {\n ensureHexPrefix,\n hexToUint8Array,\n isAddressFromPublicKey,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../primitives/utils/bitcoin\";\nimport {\n calculateBtcTxHash,\n fundPeginTransaction,\n getNetwork,\n getPsbtInputFields,\n peginOutputCount,\n selectUtxosForPegin,\n type UTXO,\n MAX_REASONABLE_FEE_SATS,\n} from \"../utils\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\nimport {\n deriveVaultRoot,\n expandAuthAnchor,\n type FundingOutpoint,\n} from \"../vault-secrets\";\n\n/** Referral code sent with pegin registration — 0 means no referral. */\nconst NO_REFERRAL_CODE = 0;\n\n/**\n * 32-byte zero hex used as a placeholder during the sizing pass for any\n * value whose content does not affect output sizes — currently the\n * per-vault hashlocks and the auth-anchor commitment. The commit pass\n * substitutes real values; UTXO selection and fee sizing are invariant\n * under the swap because all four (placeholder hashlock, real\n * SHA256(secret), placeholder anchor, real SHA256(authAnchor)) are\n * 32-byte pushes. Substitution invariance is pinned in `pegin.test.ts`.\n */\nconst SIZING_PASS_PLACEHOLDER_BYTES32_HEX = \"00\".repeat(32);\n\n/**\n * Configuration for the PeginManager.\n */\nexport interface PeginManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n btcNetwork: Network;\n\n /**\n * Bitcoin wallet for signing peg-in transactions.\n */\n btcWallet: BitcoinWallet;\n\n /**\n * Ethereum wallet for registering peg-in on-chain.\n * Uses viem's WalletClient directly for proper gas estimation.\n */\n ethWallet: WalletClient;\n\n /**\n * Ethereum chain configuration.\n * Required for proper gas estimation in contract calls.\n */\n ethChain: Chain;\n\n /**\n * Vault contract addresses.\n */\n vaultContracts: {\n /**\n * BTCVaultRegistry contract address on Ethereum.\n */\n btcVaultRegistry: Address;\n };\n\n /**\n * Mempool API URL for fetching UTXO data and broadcasting transactions.\n * Use MEMPOOL_API_URLS constant for standard mempool.space URLs, or provide\n * a custom URL if running your own mempool instance.\n */\n mempoolApiUrl: string;\n}\n\n/**\n * Parameters for the pegin flow (pre-pegin + pegin transactions).\n */\nexport interface PreparePeginParams {\n /**\n * Amounts to peg in per HTLC (in satoshis).\n * Must have the same length as `hashlocks`.\n * For single deposits, pass a single-element array.\n */\n amounts: readonly bigint[];\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n * Can be provided with or without \"0x\" prefix (will be stripped automatically).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n * Can be provided with or without \"0x\" prefix (will be stripped automatically).\n */\n vaultKeeperBtcPubkeys: readonly string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n * Can be provided with or without \"0x\" prefix (will be stripped automatically).\n */\n universalChallengerBtcPubkeys: readonly string[];\n\n /**\n * CSV timelock in blocks for the PegIn vault output.\n */\n timelockPegin: number;\n\n /**\n * CSV timelock in blocks for the Pre-PegIn HTLC refund path.\n */\n timelockRefund: number;\n\n /**\n * Protocol fee rate in sat/vB from the contract offchain params.\n * Used by WASM for computing depositorClaimValue and min pegin fee.\n */\n protocolFeeRate: bigint;\n\n /**\n * Mempool fee rate in sat/vB for funding the Pre-PegIn transaction.\n * Used for UTXO selection and change calculation.\n */\n mempoolFeeRate: number;\n\n /**\n * M in M-of-N council multisig (from contract params).\n */\n councilQuorum: number;\n\n /**\n * N in M-of-N council multisig (from contract params).\n */\n councilSize: number;\n\n /**\n * Available UTXOs from the depositor's wallet for funding the Pre-PegIn transaction.\n */\n availableUTXOs: readonly UTXO[];\n\n /**\n * Bitcoin address for receiving change from the Pre-PegIn transaction.\n */\n changeAddress: string;\n}\n\n/**\n * Result of preparing a pegin.\n */\n/** Per-vault PegIn data derived from a shared Pre-PegIn transaction */\nexport interface PerVaultPeginData {\n /** Index of the HTLC output in the Pre-PegIn transaction (0, 1, 2, ...) */\n htlcVout: number;\n /** HTLC output value in satoshis */\n htlcValue: bigint;\n /** Depositor-signed PegIn transaction hex (for contract registration) */\n peginTxHex: string;\n /** PegIn transaction ID */\n peginTxid: string;\n /** Depositor's Schnorr signature over PegIn input (HTLC leaf 0) */\n peginInputSignature: string;\n /** Vault output scriptPubKey hex */\n vaultScriptPubKey: string;\n}\n\n/**\n * Broadcast-ready transaction output of {@link PeginManager.preparePegin}.\n * Safe to log / persist — contains no sensitive material.\n */\nexport interface PreparePeginTransaction {\n /**\n * Funded, pre-witness Pre-PegIn tx hex. Pass this for register calls'\n * `unsignedPrePeginTx` — despite the contract-side name, the registry\n * stores the funded form so indexers can rebuild refund PSBTs.\n */\n fundedPrePeginTxHex: string;\n /** Funded Pre-PegIn transaction ID */\n prePeginTxid: string;\n /** Per-vault PegIn data — one entry per amount */\n perVault: PerVaultPeginData[];\n /** UTXOs selected to fund the Pre-PegIn transaction */\n selectedUTXOs: UTXO[];\n /** Transaction fee in satoshis */\n fee: bigint;\n /** Change amount in satoshis (if any) */\n changeAmount: bigint;\n}\n\n/**\n * Sensitive material derived from the wallet root. Do not log; do not\n * persist beyond the activation flow. Strings are immutable in JS, so\n * lifetime is GC-only — secrets stay live until the result is dropped.\n */\nexport interface PreparePeginDerivedSecrets {\n /** Per-vault WOTS block public keys (one array per vault). */\n perVaultWotsKeys: WotsBlockPublicKey[][];\n /** Per-vault keccak256 of WOTS keys, ready as `depositorWotsPkHash`. */\n wotsPkHashes: Hex[];\n /**\n * Per-vault HTLC preimage hex (no 0x prefix). Re-derivable any time\n * via `expandHashlockSecret(root, htlcVout)`; not persisted.\n */\n htlcSecretHexes: string[];\n /**\n * Raw 32-byte auth-anchor preimage as 64-char lowercase hex (no `0x`).\n * Sent to the VP via `auth_createDepositorToken` to obtain a bearer\n * token; the VP validates `SHA256(authAnchorHex) === OP_RETURN_PUSH32`\n * in the broadcast Pre-PegIn. Reveal is intentional: once exposed\n * the anchor is public, but its scope is bound to a single\n * `peginTxid`. Domain-separated from `htlcSecretHexes` and\n * `perVaultWotsKeys` via the HKDF `info` label, so revealing it does\n * not weaken the other derived secrets.\n */\n authAnchorHex: string;\n}\n\nexport interface PreparePeginResult {\n /** Broadcast-ready Pre-PegIn + per-vault PegIn txs. Safe to log. */\n transaction: PreparePeginTransaction;\n /**\n * x-only depositor pubkey snapshot used end-to-end across sizing,\n * vault-root derivation, and PSBT signing. Safe to persist; not\n * sensitive. Reusing this snapshot downstream guarantees that\n * derived secrets and signed PSBTs reference the same identity.\n */\n depositorBtcPubkey: string;\n /** Sensitive derived material — see {@link PreparePeginDerivedSecrets}. */\n derivedSecrets: PreparePeginDerivedSecrets;\n}\n\n\n/**\n * Parameters for signing and broadcasting a transaction.\n */\nexport interface SignAndBroadcastParams {\n /**\n * Funded Pre-PegIn transaction hex from preparePegin().\n */\n fundedPrePeginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex).\n * Can be provided with or without \"0x\" prefix.\n * Required for Taproot signing.\n */\n depositorBtcPubkey: string;\n\n /**\n * Optional pre-fetched prevout data for inputs not yet in the mempool.\n * Key format: \"txid:vout\" (e.g. \"abc123...def:0\").\n * When provided, matching inputs skip the mempool API fetch.\n * Useful for split transactions where outputs are unconfirmed.\n */\n localPrevouts?: Record<string, { scriptPubKey: string; value: number }>;\n}\n\n/**\n * BIP-322 BTC Proof-of-Possession binding a depositor's BTC key to their\n * Ethereum account. Produced by {@link PeginManager.signProofOfPossession}\n * and reusable across every register call in the same session — the\n * embedded identities are re-checked at register time.\n */\nexport interface PopSignature {\n /** BIP-322 signature over the PoP message (0x-prefixed hex). */\n btcPopSignature: Hex;\n /** Ethereum address the PoP was signed for. */\n depositorEthAddress: Address;\n /** BTC x-only public key (64-char hex, no 0x prefix). */\n depositorBtcPubkey: string;\n}\n\n/**\n * Parameters for registering a peg-in on Ethereum.\n */\nexport interface RegisterPeginParams {\n /**\n * Funded, pre-witness Pre-PegIn tx hex — pass\n * {@link PreparePeginTransaction.fundedPrePeginTxHex} from\n * {@link PreparePeginResult.transaction}. The contract-side parameter\n * is named `unsignedPrePeginTx` but it stores the funded form.\n */\n unsignedPrePeginTx: string;\n\n /**\n * Depositor-signed PegIn transaction hex (submitted to contract; vault ID derived from this).\n */\n depositorSignedPeginTx: string;\n\n /**\n * Vault provider's Ethereum address.\n */\n vaultProvider: Address;\n\n /**\n * SHA256 hashlock for HTLC activation (bytes32 hex with 0x prefix).\n */\n hashlock: Hex;\n\n /**\n * Depositor's BTC payout address (e.g. bc1p..., bc1q...).\n * Converted to scriptPubKey internally via bitcoinjs-lib.\n *\n * If omitted, defaults to the connected BTC wallet's address\n * via `btcWallet.getAddress()`.\n */\n depositorPayoutBtcAddress?: string;\n\n /** Keccak256 hash of the depositor's WOTS public key (bytes32) */\n depositorWotsPkHash: Hex;\n\n /** Proof of possession from {@link PeginManager.signProofOfPossession}. */\n popSignature: PopSignature;\n\n /**\n * Zero-based index of the HTLC output in the Pre-PegIn transaction that\n * this PegIn spends. In a batch Pre-PegIn with N HTLC outputs, each vault\n * registration references a different htlcVout (0..N-1).\n */\n htlcVout: number;\n}\n\n/**\n * Result of registering a peg-in on Ethereum.\n */\nexport interface RegisterPeginResult {\n /**\n * Ethereum transaction hash for the peg-in registration.\n */\n ethTxHash: Hash;\n\n /**\n * Derived vault ID: keccak256(abi.encode(peginTxHash, depositor)).\n * Used for contract reads/writes and indexer queries.\n */\n vaultId: Hex;\n\n /**\n * Raw Bitcoin pegin transaction hash (double-SHA256 of the signed pegin tx).\n * Used for VP RPC operations which key on the BTC transaction ID.\n */\n peginTxHash: Hex;\n}\n\n/**\n * Single request in a batch pegin registration.\n * All requests in a batch share the same vault provider, depositor BTC\n * pubkey, and Pre-PegIn transaction.\n */\nexport interface BatchPeginRequestItem {\n /** Signed PegIn tx hex for this vault */\n depositorSignedPeginTx: string;\n /** SHA256 hashlock for HTLC activation (bytes32 hex) */\n hashlock: Hex;\n /** Zero-based HTLC output index in the Pre-PegIn tx (unique per request) */\n htlcVout: number;\n /** Depositor's BTC payout address (required — funds are sent here on payout) */\n depositorPayoutBtcAddress: string;\n /** Keccak256 hash of the depositor's WOTS public key (bytes32) */\n depositorWotsPkHash: Hex;\n}\n\n/**\n * Parameters for registerPeginBatchOnChain.\n */\nexport interface RegisterPeginBatchParams {\n /** Vault provider address (shared across all vaults in batch) */\n vaultProvider: Address;\n /**\n * Funded, pre-witness Pre-PegIn tx hex — shared across every request in\n * the batch. See {@link RegisterPeginParams.unsignedPrePeginTx}.\n */\n unsignedPrePeginTx: string;\n /** Individual pegin requests (one per vault) */\n requests: BatchPeginRequestItem[];\n /** Proof of possession from {@link PeginManager.signProofOfPossession}. */\n popSignature: PopSignature;\n}\n\n/**\n * Per-vault result from a batch pegin registration.\n */\nexport interface BatchPeginResultItem {\n /** Derived vault ID: keccak256(abi.encode(peginTxHash, depositor)) */\n vaultId: Hex;\n /** Raw BTC pegin transaction hash */\n peginTxHash: Hex;\n}\n\n/**\n * Result of registering a batch of pegins on Ethereum in a single transaction.\n */\nexport interface RegisterPeginBatchResult {\n /** Ethereum transaction hash */\n ethTxHash: Hex;\n /** Per-vault results (same order as input requests) */\n vaults: BatchPeginResultItem[];\n}\n\n\n/**\n * Resolve prevout data for a transaction input.\n * Checks localPrevouts first; falls back to mempool API.\n */\nfunction resolveUtxoInfo(\n txid: string,\n vout: number,\n localPrevouts: Record<string, { scriptPubKey: string; value: number }> | undefined,\n apiUrl: string,\n): Promise<UtxoInfo> {\n const local = localPrevouts?.[`${txid}:${vout}`];\n if (local) {\n return Promise.resolve({\n txid,\n vout,\n value: local.value,\n scriptPubKey: local.scriptPubKey,\n });\n }\n return getUtxoInfo(txid, vout, apiUrl);\n}\n\n/**\n * Manager for orchestrating peg-in operations.\n *\n * This manager provides a high-level API for creating peg-in transactions\n * by coordinating between SDK primitives, utilities, and wallet interfaces.\n *\n * @remarks\n * The complete peg-in flow consists of 5 steps:\n *\n * | Step | Method | Description |\n * |------|--------|-------------|\n * | 1 | {@link preparePegin} | Build Pre-PegIn HTLC, fund it, sign PegIn input |\n * | 2 | {@link signProofOfPossession} | Sign BIP-322 PoP (one per deposit session) |\n * | 3 | {@link registerPeginOnChain} | Submit to Ethereum contract |\n * | 4 | {@link signAndBroadcast} | Sign and broadcast Pre-PegIn tx to Bitcoin network |\n * | 5 | {@link PayoutManager} | Sign BOTH payout authorizations |\n *\n * **Important:** Step 5 uses {@link PayoutManager}, not this class. After\n * step 4, the vault provider observes the broadcast Pre-PegIn and prepares\n * 3 transactions per claimer:\n * - `claim_tx` - Claim transaction\n * - `assert_tx` - Assert transaction\n * - `payout_tx` - Payout transaction\n *\n * You must sign the Payout transaction for each claimer:\n * - {@link PayoutManager.signPayoutTransaction} - uses assert_tx as input reference\n *\n * Submit all signatures to the vault provider to drive the contract to\n * `VERIFIED` (and then activate by revealing the HTLC secret, which is a\n * services-layer step outside this manager).\n *\n * @see {@link PayoutManager} - Required for Step 5 (payout authorization)\n * @see {@link buildPrePeginPsbt} - Lower-level primitive for custom implementations\n * @see {@link https://github.com/babylonlabs-io/babylon-toolkit/blob/main/packages/babylon-ts-sdk/docs/quickstart/managers.md | Managers Quickstart}\n */\n/**\n * Maximum time (ms) to wait for a transaction receipt before timing out.\n * Matches the prior vault-service polling timeout so users see a clear error\n * instead of an indefinite hang when a transaction is dropped from the mempool.\n */\nconst RECEIPT_TIMEOUT_MS = 120_000;\n\nexport class PeginManager {\n private readonly config: PeginManagerConfig;\n\n /**\n * Creates a new PeginManager instance.\n *\n * @param config - Manager configuration including wallets and contract addresses\n */\n constructor(config: PeginManagerConfig) {\n this.config = config;\n }\n\n /**\n * Prepare a peg-in: sizing pass → vault-root derivation (one wallet\n * popup) → per-vault WOTS / hashlock derivation → commit pass with\n * batch PSBT signing (one popup). Returns broadcast-ready txs, the\n * pubkey snapshot, and the sensitive derived material.\n *\n * @throws If the wallet rejects, insufficient funds, or an internal\n * invariant violation.\n */\n async preparePegin(\n params: PreparePeginParams,\n ): Promise<PreparePeginResult> {\n if (params.amounts.length === 0) {\n throw new Error(\"amounts must contain at least one entry\");\n }\n\n // Raw form for `signInputs[].publicKey` (UniSat/OKX/OneKey reject\n // x-only); x-only form for protocol/HTLC use. One snapshot binds\n // sizing, root derivation, and PSBT signing to one identity.\n const depositorBtcPubkeyRaw =\n await this.config.btcWallet.getPublicKeyHex();\n const depositorBtcPubkey = normalizeXOnlyPubkey(depositorBtcPubkeyRaw);\n\n // Sizing pass uses a placeholder for the auth-anchor hash because\n // the wallet popup that produces the real anchor hasn't run yet.\n // The OP_RETURN's byte length is invariant under content swap, so\n // UTXO selection and fees match the commit pass.\n const sizing = await this.prepareSizing(depositorBtcPubkey, params);\n\n const fundingOutpoints: FundingOutpoint[] = sizing.selectedUTXOs.map(\n (u) => ({\n txid: hexToUint8Array(u.txid),\n vout: u.vout,\n }),\n );\n const root = await deriveVaultRoot(this.config.btcWallet, {\n depositorBtcPubkey: hexToUint8Array(depositorBtcPubkey),\n fundingOutpoints,\n });\n\n // Take ownership of the auth anchor before per-vault expansion (which\n // zeros `root`). Convert to hex immediately, then zero the buffer.\n // `authAnchorHex` is a JS string — immutable, GC-only — and lives\n // until the result is dropped. If anything in this window throws,\n // `expandPerVaultSecrets` won't run to zero `root`, so we wipe it\n // here on the throw path.\n let authAnchorHex: string;\n let authAnchorHash: string;\n try {\n const authAnchorBytes = expandAuthAnchor(root);\n try {\n authAnchorHex = uint8ArrayToHex(authAnchorBytes);\n authAnchorHash = uint8ArrayToHex(sha256(authAnchorBytes));\n } finally {\n authAnchorBytes.fill(0);\n }\n } catch (err) {\n root.fill(0);\n throw err;\n }\n\n const derived = await expandPerVaultSecrets(root, params.amounts.length);\n const { perVaultWotsKeys, wotsPkHashes, htlcSecretHexes, hashlocks } =\n derived;\n\n const commit = await this.preparePeginCommit({\n depositorBtcPubkeyRaw,\n depositorBtcPubkey,\n hashlocks,\n authAnchorHash,\n sizing,\n params,\n });\n\n // Downstream consumers look up per-vault secrets by index; pin the\n // contract so a future WASM output-ordering change fails loud.\n for (let i = 0; i < commit.perVault.length; i++) {\n if (commit.perVault[i].htlcVout !== i) {\n throw new Error(\n `Internal invariant violation: htlcVout/index mismatch at vault ${i} ` +\n `(expected ${i}, got ${commit.perVault[i].htlcVout})`,\n );\n }\n }\n\n // Structural guarantee that the broadcast tx actually carries the\n // OP_RETURN we'll later reveal a preimage for. Without this assertion\n // a malicious WASM build could emit no OP_RETURN, the VP would still\n // issue a token (if mis-configured) on a tx with no on-chain\n // commitment, and the auth flow would degrade to a pure shared\n // secret. Fail closed.\n assertAuthAnchorOpReturn(\n commit.fundedPrePeginTxHex,\n params.amounts.length,\n authAnchorHash,\n );\n\n return {\n transaction: {\n ...commit,\n selectedUTXOs: sizing.selectedUTXOs,\n fee: sizing.fee,\n changeAmount: sizing.changeAmount,\n },\n depositorBtcPubkey,\n derivedSecrets: {\n perVaultWotsKeys,\n wotsPkHashes,\n htlcSecretHexes,\n authAnchorHex,\n },\n };\n }\n\n /**\n * Build unfunded Pre-PegIn + select UTXOs. No PSBT signing.\n *\n * Returns the full selection result (UTXOs, fee, changeAmount) so the\n * commit pass funds the broadcast tx with the exact same set used to\n * build the vault-context funding-outpoints commitment. Re-running\n * `selectUtxosForPegin` in the commit pass would be deterministic given\n * the same inputs, but threading the result through guarantees the\n * domain separator structurally matches the funded tx inputs.\n *\n * Sizing runs before the wallet popup, so neither the real per-vault\n * hashlocks nor the real `authAnchorHash` are known yet. Both slots\n * are filled with a 32-byte placeholder; the commit pass swaps in the\n * real values. Output budget is identical (32-byte push regardless of\n * content), so UTXO selection is invariant under substitution.\n */\n private async prepareSizing(\n depositorBtcPubkey: string,\n params: PreparePeginParams,\n ): Promise<{ selectedUTXOs: UTXO[]; fee: bigint; changeAmount: bigint }> {\n const placeholderHashlocks = params.amounts.map(\n () => SIZING_PASS_PLACEHOLDER_BYTES32_HEX,\n );\n const numLocalChallengers = params.vaultKeeperBtcPubkeys.length;\n\n const prePegin = await buildPrePeginPsbt({\n depositorPubkey: depositorBtcPubkey,\n vaultProviderPubkey: stripHexPrefix(params.vaultProviderBtcPubkey),\n vaultKeeperPubkeys: params.vaultKeeperBtcPubkeys.map(stripHexPrefix),\n universalChallengerPubkeys:\n params.universalChallengerBtcPubkeys.map(stripHexPrefix),\n hashlocks: placeholderHashlocks,\n timelockRefund: params.timelockRefund,\n pegInAmounts: params.amounts,\n feeRate: params.protocolFeeRate,\n numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: this.config.btcNetwork,\n authAnchorHash: SIZING_PASS_PLACEHOLDER_BYTES32_HEX,\n });\n\n const selection = selectUtxosForPegin(\n [...params.availableUTXOs],\n prePegin.totalOutputValue,\n params.mempoolFeeRate,\n peginOutputCount(\n prePegin.htlcValues.length,\n SIZING_PASS_PLACEHOLDER_BYTES32_HEX,\n ),\n );\n\n return {\n selectedUTXOs: selection.selectedUTXOs,\n fee: selection.fee,\n changeAmount: selection.changeAmount,\n };\n }\n\n /** Build PegIn txs and batch-sign their inputs with real hashlocks. */\n private async preparePeginCommit(args: {\n depositorBtcPubkeyRaw: string;\n depositorBtcPubkey: string;\n hashlocks: readonly string[];\n authAnchorHash: string;\n sizing: { selectedUTXOs: UTXO[]; fee: bigint; changeAmount: bigint };\n params: PreparePeginParams;\n }): Promise<{\n fundedPrePeginTxHex: string;\n prePeginTxid: string;\n perVault: PerVaultPeginData[];\n }> {\n const {\n depositorBtcPubkeyRaw,\n depositorBtcPubkey,\n hashlocks,\n authAnchorHash,\n sizing,\n params,\n } = args;\n\n // Refuse to build the broadcast tx if the orchestrator forgot to\n // substitute real values for the sizing-pass placeholder. A\n // placeholder-zero hashlock would produce an HTLC that no real\n // preimage can spend; a placeholder-zero auth anchor would let\n // the depositor reveal a known-public preimage to the VP. Fail\n // before signing, not after broadcast.\n const placeholderLower = SIZING_PASS_PLACEHOLDER_BYTES32_HEX.toLowerCase();\n for (let i = 0; i < hashlocks.length; i++) {\n if (hashlocks[i].toLowerCase() === placeholderLower) {\n throw new Error(\n `preparePeginCommit refusing to build with sizing-pass placeholder ` +\n `hashlock at vault ${i} — internal substitution bug`,\n );\n }\n }\n if (authAnchorHash.toLowerCase() === placeholderLower) {\n throw new Error(\n `preparePeginCommit refusing to build with sizing-pass placeholder ` +\n `auth-anchor hash — internal substitution bug`,\n );\n }\n\n const vaultProviderBtcPubkey = stripHexPrefix(params.vaultProviderBtcPubkey);\n const vaultKeeperBtcPubkeys = params.vaultKeeperBtcPubkeys.map(stripHexPrefix);\n const universalChallengerBtcPubkeys =\n params.universalChallengerBtcPubkeys.map(stripHexPrefix);\n const numLocalChallengers = vaultKeeperBtcPubkeys.length;\n\n const prePeginParams: PrePeginParams = {\n depositorPubkey: depositorBtcPubkey,\n vaultProviderPubkey: vaultProviderBtcPubkey,\n vaultKeeperPubkeys: vaultKeeperBtcPubkeys,\n universalChallengerPubkeys: universalChallengerBtcPubkeys,\n hashlocks,\n timelockRefund: params.timelockRefund,\n pegInAmounts: params.amounts,\n feeRate: params.protocolFeeRate,\n numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: this.config.btcNetwork,\n authAnchorHash,\n };\n\n const prePeginResult = await buildPrePeginPsbt(prePeginParams);\n\n const network = getNetwork(this.config.btcNetwork);\n const fundedPrePeginTxHex = fundPeginTransaction({\n unfundedTxHex: prePeginResult.psbtHex,\n selectedUTXOs: sizing.selectedUTXOs,\n changeAddress: params.changeAddress,\n changeAmount: sizing.changeAmount,\n network,\n });\n\n const prePeginTxid = stripHexPrefix(calculateBtcTxHash(fundedPrePeginTxHex));\n\n const peginTxResults: Array<{\n txHex: string;\n txid: string;\n vaultScriptPubKey: string;\n }> = [];\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n\n for (let i = 0; i < hashlocks.length; i++) {\n const peginTxResult = await buildPeginTxFromFundedPrePegin({\n prePeginParams,\n timelockPegin: params.timelockPegin,\n fundedPrePeginTxHex,\n htlcVout: i,\n });\n\n const peginInputPsbtResult = await buildPeginInputPsbt({\n peginTxHex: peginTxResult.txHex,\n fundedPrePeginTxHex,\n depositorPubkey: depositorBtcPubkey,\n vaultProviderPubkey: vaultProviderBtcPubkey,\n vaultKeeperPubkeys: vaultKeeperBtcPubkeys,\n universalChallengerPubkeys: universalChallengerBtcPubkeys,\n hashlock: hashlocks[i],\n timelockRefund: params.timelockRefund,\n network: this.config.btcNetwork,\n });\n\n peginTxResults.push(peginTxResult);\n psbtsToSign.push(peginInputPsbtResult.psbtHex);\n signOptions.push(\n createTaprootScriptPathSignOptions(depositorBtcPubkeyRaw, 1),\n );\n }\n\n const signedPsbts = await signPsbtsWithFallback(\n this.config.btcWallet,\n psbtsToSign,\n signOptions,\n );\n\n const perVault: PerVaultPeginData[] = [];\n for (let i = 0; i < signedPsbts.length; i++) {\n const peginInputSignature = extractPeginInputSignature(\n signedPsbts[i],\n depositorBtcPubkey,\n );\n\n const depositorSignedPeginTxHex = finalizePeginInputPsbt(signedPsbts[i]);\n\n perVault.push({\n htlcVout: i,\n htlcValue: prePeginResult.htlcValues[i],\n peginTxHex: depositorSignedPeginTxHex,\n peginTxid: peginTxResults[i].txid,\n peginInputSignature,\n vaultScriptPubKey: peginTxResults[i].vaultScriptPubKey,\n });\n }\n\n return {\n fundedPrePeginTxHex,\n prePeginTxid,\n perVault,\n };\n }\n\n\n /**\n * Signs and broadcasts a funded peg-in transaction to the Bitcoin network.\n *\n * This method:\n * 1. Parses the funded transaction hex\n * 2. Fetches UTXO data from mempool for each input\n * 3. Creates a PSBT with proper witnessUtxo/tapInternalKey\n * 4. Signs via btcWallet.signPsbt()\n * 5. Finalizes and extracts the transaction\n * 6. Broadcasts via mempool API\n *\n * @param params - Transaction hex and depositor public key\n * @returns The broadcasted Bitcoin transaction ID\n * @throws Error if signing or broadcasting fails\n */\n async signAndBroadcast(params: SignAndBroadcastParams): Promise<string> {\n const { fundedPrePeginTxHex, depositorBtcPubkey } = params;\n\n // Step 1: Parse the funded transaction\n const cleanHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const tx = Transaction.fromHex(cleanHex);\n\n if (tx.ins.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Step 2: Create PSBT and add inputs with UTXO data from mempool\n const psbt = new Psbt();\n psbt.setVersion(tx.version);\n psbt.setLocktime(tx.locktime);\n\n const publicKeyNoCoord = Buffer.from(\n normalizeXOnlyPubkey(depositorBtcPubkey),\n \"hex\",\n );\n const apiUrl = this.config.mempoolApiUrl;\n\n // Resolve prevout data for each input (local cache or mempool API)\n const utxoDataPromises = tx.ins.map((input) => {\n const txid = Buffer.from(input.hash).reverse().toString(\"hex\");\n const vout = input.index;\n return resolveUtxoInfo(txid, vout, params.localPrevouts, apiUrl).then(\n (utxoData) => ({ input, utxoData, txid, vout }),\n );\n });\n\n const inputsWithUtxoData = await Promise.all(utxoDataPromises);\n\n // Cross-validate: total input value must cover total output value.\n // A mismatch indicates the mempool API returned manipulated UTXO data,\n // which could lead to fee-siphoning or invalid signatures.\n const totalInputValue = inputsWithUtxoData.reduce(\n (sum, i) => sum + BigInt(i.utxoData.value),\n 0n,\n );\n const totalOutputValue = tx.outs.reduce(\n (sum, out) => sum + BigInt(out.value),\n 0n,\n );\n if (totalInputValue < totalOutputValue) {\n throw new Error(\n `UTXO value mismatch: total input value (${totalInputValue} sat) is less than ` +\n `total output value (${totalOutputValue} sat). ` +\n `This may indicate the mempool API returned manipulated UTXO data.`,\n );\n }\n\n const impliedFee = totalInputValue - totalOutputValue;\n if (impliedFee > MAX_REASONABLE_FEE_SATS) {\n throw new Error(\n `Implied transaction fee (${impliedFee} sat) exceeds maximum reasonable fee ` +\n `(${MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`,\n );\n }\n\n // Add inputs with proper PSBT fields based on script type\n for (const { input, utxoData, txid, vout } of inputsWithUtxoData) {\n const psbtInputFields = getPsbtInputFields(\n {\n txid,\n vout,\n value: utxoData.value,\n scriptPubKey: utxoData.scriptPubKey,\n },\n publicKeyNoCoord,\n );\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n ...psbtInputFields,\n });\n }\n\n // Step 3: Add outputs\n for (const output of tx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n // Step 4: Sign PSBT via wallet\n const signedPsbtHex = await this.config.btcWallet.signPsbt(psbt.toHex());\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n // Step 5: Finalize and extract transaction\n try {\n signedPsbt.finalizeAllInputs();\n } catch (e) {\n // Some wallets (e.g. UniSat, OKX) auto-finalize PSBTs before returning them.\n // Attempting to finalize again throws, which is expected and safe to skip —\n // but verify the wallet actually finalized all inputs.\n const allFinalized = signedPsbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n const signedTxHex = signedPsbt.extractTransaction().toHex();\n\n // Step 6: Broadcast to Bitcoin network\n const btcTxid = await pushTx(signedTxHex, apiUrl);\n\n return btcTxid;\n }\n\n /**\n * Registers a peg-in on Ethereum by calling the BTCVaultRegistry contract.\n *\n * This method:\n * 1. Re-verifies the PopSignature against the currently connected ETH\n * and BTC wallets — refuses to proceed if either has changed\n * 2. Derives vault ID and checks if it already exists (pre-flight)\n * 3. Encodes the contract call using viem\n * 4. Estimates gas (catches contract errors early with proper revert\n * reasons)\n * 5. Sends transaction with pre-estimated gas via\n * ethWallet.sendTransaction()\n *\n * The PopSignature must be obtained via\n * {@link signProofOfPossession} before this call.\n *\n * @param params - Registration parameters including the PopSignature\n * and the prepared Pre-PegIn / PegIn transactions\n * @returns Result containing Ethereum transaction hash and vault ID\n * @throws Error if the PopSignature does not match the connected wallets\n * @throws Error if the vault already exists\n * @throws Error if contract simulation fails (e.g., invalid signature,\n * unauthorized)\n */\n async registerPeginOnChain(\n params: RegisterPeginParams,\n ): Promise<RegisterPeginResult> {\n const {\n unsignedPrePeginTx,\n depositorSignedPeginTx,\n vaultProvider,\n hashlock,\n htlcVout,\n depositorPayoutBtcAddress,\n depositorWotsPkHash,\n popSignature,\n } = params;\n\n // Step 1: Re-verify the PoP artifact against the currently connected\n // wallets so a mid-flow account/wallet switch fails here instead of\n // surfacing downstream as an opaque contract revert.\n if (!this.config.ethWallet.account) {\n throw new Error(\"Ethereum wallet account not found\");\n }\n const depositorEthAddress = this.config.ethWallet.account.address;\n if (!isAddressEqual(popSignature.depositorEthAddress, depositorEthAddress)) {\n throw new Error(\n `Proof of possession was signed for ${popSignature.depositorEthAddress} ` +\n `but the Ethereum wallet is currently connected to ${depositorEthAddress}. ` +\n `Reconnect the original account or call signProofOfPossession() again.`,\n );\n }\n await this.assertPopMatchesBtcWallet(popSignature);\n const btcPopSignature = popSignature.btcPopSignature;\n\n // Step 2: Format parameters for contract call\n const depositorBtcPubkeyHex = ensureHexPrefix(popSignature.depositorBtcPubkey);\n const unsignedPrePeginTxHex = ensureHexPrefix(unsignedPrePeginTx);\n const depositorSignedPeginTxHex = ensureHexPrefix(depositorSignedPeginTx);\n\n const payoutScriptPubKey = await this.resolvePayoutScriptPubKey(\n depositorPayoutBtcAddress,\n );\n\n // Step 3: Calculate pegin tx hash and derive vault ID, then check if it already exists\n const peginTxHash = calculateBtcTxHash(depositorSignedPeginTxHex);\n const derivedVaultIdHex = await deriveVaultId(\n stripHexPrefix(peginTxHash),\n stripHexPrefix(depositorEthAddress),\n );\n const vaultId = ensureHexPrefix(derivedVaultIdHex) as Hex;\n const exists = await this.checkVaultExists(vaultId);\n\n if (exists) {\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 // Step 4: Query required pegin fee from the contract\n const publicClient = createPublicClient({\n chain: this.config.ethChain,\n transport: http(),\n });\n\n let peginFee: bigint;\n try {\n peginFee = (await publicClient.readContract({\n address: this.config.vaultContracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n } catch {\n throw new Error(\n \"Failed to query pegin fee from the contract. \" +\n \"Please check your network connection and that the contract address is correct.\",\n );\n }\n\n // Step 5: Encode the contract call data\n const callData = encodeFunctionData({\n abi: BTCVaultRegistryABI,\n functionName: \"submitPeginRequest\",\n args: [\n depositorEthAddress,\n depositorBtcPubkeyHex,\n btcPopSignature,\n unsignedPrePeginTxHex,\n depositorSignedPeginTxHex,\n vaultProvider,\n hashlock,\n htlcVout,\n payoutScriptPubKey,\n depositorWotsPkHash,\n ],\n });\n\n // Step 6: Estimate gas first to catch contract errors before showing wallet popup\n // This ensures users see actual contract revert reasons instead of gas errors\n // The gas estimate is then passed to sendTransaction to avoid double estimation\n let gasEstimate: bigint;\n try {\n gasEstimate = await publicClient.estimateGas({\n to: this.config.vaultContracts.btcVaultRegistry,\n data: callData,\n value: peginFee,\n account: this.config.ethWallet.account.address,\n });\n } catch (error) {\n // Estimation failed - handle contract error with actual revert reason\n handleContractError(error); // always throws (return type: never)\n }\n\n // Step 7: Submit peg-in request to contract (estimation passed)\n let ethTxHash: Hex;\n try {\n // Send transaction with pre-estimated gas to skip internal estimation\n // Note: viem's sendTransaction uses `gas`, not `gasLimit`\n ethTxHash = await this.config.ethWallet.sendTransaction({\n to: this.config.vaultContracts.btcVaultRegistry,\n data: callData,\n value: peginFee,\n account: this.config.ethWallet.account,\n chain: this.config.ethChain,\n gas: gasEstimate,\n });\n } catch (error) {\n // Use proper error handler for better error messages\n handleContractError(error); // always throws (return type: never)\n }\n\n // Step 8: Wait for transaction receipt and verify it was not reverted\n const receipt = await publicClient.waitForTransactionReceipt({\n hash: ethTxHash,\n timeout: RECEIPT_TIMEOUT_MS,\n });\n if (receipt.status === \"reverted\") {\n handleContractError(\n new Error(\n `Transaction reverted. Hash: ${ethTxHash}. ` +\n `Check the transaction on block explorer for details.`,\n ),\n );\n }\n\n return {\n ethTxHash: receipt.transactionHash,\n vaultId,\n peginTxHash,\n };\n }\n\n /**\n * Register multiple pegins on Ethereum in a single transaction.\n *\n * Uses the contract's submitPeginRequestBatch() to submit all vault\n * registrations atomically. All vaults must share the same vault provider.\n * The PoP signature is signed once and included in each request.\n *\n * @param params - Batch registration parameters\n * @returns Batch result with per-vault IDs and single ETH tx hash\n */\n async registerPeginBatchOnChain(\n params: RegisterPeginBatchParams,\n ): Promise<RegisterPeginBatchResult> {\n const { vaultProvider, unsignedPrePeginTx, requests, popSignature } =\n params;\n\n if (requests.length === 0) {\n throw new Error(\"Batch pegin requires at least one request\");\n }\n\n // Step 1: Re-verify the PoP (same reasoning as registerPeginOnChain).\n if (!this.config.ethWallet.account) {\n throw new Error(\"Ethereum wallet account not found\");\n }\n const depositorEthAddress = this.config.ethWallet.account.address;\n if (!isAddressEqual(popSignature.depositorEthAddress, depositorEthAddress)) {\n throw new Error(\n `Proof of possession was signed for ${popSignature.depositorEthAddress} ` +\n `but the Ethereum wallet is currently connected to ${depositorEthAddress}. ` +\n `Reconnect the original account or call signProofOfPossession() again.`,\n );\n }\n await this.assertPopMatchesBtcWallet(popSignature);\n const btcPopSignature = popSignature.btcPopSignature;\n\n // Step 2: Resolve per-request payout scriptPubKey.\n const resolvedPayoutScripts: Hex[] = [];\n for (const req of requests) {\n resolvedPayoutScripts.push(\n await this.resolvePayoutScriptPubKey(req.depositorPayoutBtcAddress),\n );\n }\n\n // Step 3: Pre-compute vault IDs and check for duplicates\n const vaultResults: BatchPeginResultItem[] = [];\n for (const req of requests) {\n const depositorSignedPeginTxHex = ensureHexPrefix(\n req.depositorSignedPeginTx,\n );\n const peginTxHash = calculateBtcTxHash(depositorSignedPeginTxHex);\n const derivedVaultIdHex = await deriveVaultId(\n stripHexPrefix(peginTxHash),\n stripHexPrefix(depositorEthAddress),\n );\n const vaultId = ensureHexPrefix(derivedVaultIdHex) as Hex;\n const exists = await this.checkVaultExists(vaultId);\n if (exists) {\n throw new Error(\n `Vault already exists (ID: ${vaultId}, peginTxHash: ${peginTxHash}). ` +\n `To create a new vault, use different UTXOs or a different amount.`,\n );\n }\n vaultResults.push({ vaultId, peginTxHash });\n }\n\n // Step 4: Query pegin fee and compute total\n const publicClient = createPublicClient({\n chain: this.config.ethChain,\n transport: http(),\n });\n\n let peginFee: bigint;\n try {\n peginFee = (await publicClient.readContract({\n address: this.config.vaultContracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n } catch {\n throw new Error(\n \"Failed to query pegin fee from the contract. \" +\n \"Please check your network connection and that the contract address is correct.\",\n );\n }\n const totalFee = peginFee * BigInt(requests.length);\n\n // Step 5: Build BatchPeginRequest[] tuple array. Depositor BTC pubkey,\n // PoP, and Pre-PegIn tx hex are shared across the batch (carried on\n // the top-level params / PopSignature, not per request).\n const depositorBtcPubkeyHex = ensureHexPrefix(\n popSignature.depositorBtcPubkey,\n ) as Hex;\n const unsignedPrePeginTxHex = ensureHexPrefix(unsignedPrePeginTx) as Hex;\n const batchRequests = requests.map((req, i) => ({\n depositorBtcPubKey: depositorBtcPubkeyHex,\n btcPopSignature,\n unsignedPrePeginTx: unsignedPrePeginTxHex,\n depositorSignedPeginTx: ensureHexPrefix(\n req.depositorSignedPeginTx,\n ) as Hex,\n hashlock: req.hashlock,\n htlcVout: req.htlcVout,\n referralCode: NO_REFERRAL_CODE,\n depositorPayoutBtcAddress: resolvedPayoutScripts[i],\n depositorWotsPkHash: req.depositorWotsPkHash,\n }));\n\n // Step 6: Encode batch call data\n const callData = encodeFunctionData({\n abi: BTCVaultRegistryABI,\n functionName: \"submitPeginRequestBatch\",\n args: [depositorEthAddress, vaultProvider, batchRequests],\n });\n\n // Step 7: Estimate gas\n let gasEstimate: bigint;\n try {\n gasEstimate = await publicClient.estimateGas({\n to: this.config.vaultContracts.btcVaultRegistry,\n data: callData,\n value: totalFee,\n account: this.config.ethWallet.account.address,\n });\n } catch (error) {\n handleContractError(error); // always throws (return type: never)\n }\n\n // Step 8: Submit batch transaction\n let ethTxHash: Hex;\n try {\n ethTxHash = await this.config.ethWallet.sendTransaction({\n to: this.config.vaultContracts.btcVaultRegistry,\n data: callData,\n value: totalFee,\n account: this.config.ethWallet.account,\n chain: this.config.ethChain,\n gas: gasEstimate,\n });\n } catch (error) {\n handleContractError(error); // always throws (return type: never)\n }\n\n // Step 9: Wait for receipt\n const receipt = await publicClient.waitForTransactionReceipt({\n hash: ethTxHash,\n timeout: RECEIPT_TIMEOUT_MS,\n });\n if (receipt.status === \"reverted\") {\n handleContractError(\n new Error(\n `Batch transaction reverted. Hash: ${ethTxHash}. ` +\n `Check the transaction on block explorer for details.`,\n ),\n );\n }\n\n return {\n ethTxHash: receipt.transactionHash,\n vaults: vaultResults,\n };\n }\n\n /**\n * Check if a vault already exists for a given vault ID.\n *\n * @param vaultId - The Bitcoin transaction hash (vault ID)\n * @returns True if vault exists, false otherwise\n */\n private async checkVaultExists(vaultId: Hex): Promise<boolean> {\n try {\n // Create a public client to read from the contract\n const publicClient = createPublicClient({\n chain: this.config.ethChain,\n transport: http(),\n });\n\n const result = (await publicClient.readContract({\n address: this.config.vaultContracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as { depositor: Address };\n\n return result.depositor !== zeroAddress;\n } catch {\n // If reading fails, assume vault doesn't exist and let contract handle it\n return false;\n }\n }\n\n /**\n * Resolve the BTC payout address to a scriptPubKey hex for the contract.\n *\n * If a payout address is provided, converts it directly.\n * If omitted, uses the wallet's address and validates it against the\n * wallet's public key to guard against a compromised wallet provider.\n */\n private async resolvePayoutScriptPubKey(\n depositorPayoutBtcAddress?: string,\n ): Promise<Hex> {\n let address: string;\n\n if (depositorPayoutBtcAddress) {\n address = depositorPayoutBtcAddress;\n } else {\n address = await this.config.btcWallet.getAddress();\n const walletPubkey = await this.config.btcWallet.getPublicKeyHex();\n if (\n !isAddressFromPublicKey(\n address,\n walletPubkey,\n this.config.btcNetwork,\n )\n ) {\n throw new Error(\n \"The BTC address from your wallet does not match the wallet's public key. \" +\n \"Please ensure your wallet is using a supported address type (Taproot or Native SegWit).\",\n );\n }\n }\n\n const network = getNetwork(this.config.btcNetwork);\n try {\n return `0x${bitcoin.address.toOutputScript(address, network).toString(\"hex\")}` as Hex;\n } catch {\n throw new Error(\n `Invalid BTC payout address: \"${address}\". ` +\n `Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`,\n );\n }\n }\n\n /**\n * Sign a BIP-322 BTC Proof-of-Possession binding the connected BTC\n * wallet to the connected ETH account for this chain and vault\n * registry. The returned {@link PopSignature} can be reused across\n * every register call in the same session.\n */\n async signProofOfPossession(): Promise<PopSignature> {\n if (!this.config.ethWallet.account) {\n throw new Error(\"Ethereum wallet account not found\");\n }\n const depositorEthAddress = this.config.ethWallet.account.address;\n\n const depositorBtcPubkey = normalizeXOnlyPubkey(\n await this.config.btcWallet.getPublicKeyHex(),\n );\n\n // Message format matches BTCProofOfPossession.sol buildMessage()\n const verifyingContract = this.config.vaultContracts.btcVaultRegistry;\n const popMessage = `${depositorEthAddress.toLowerCase()}:${this.config.ethChain.id}:pegin:${verifyingContract.toLowerCase()}`;\n const raw = await this.config.btcWallet.signMessage(\n popMessage,\n \"bip322-simple\",\n );\n\n return {\n btcPopSignature: normalizePopSignature(raw),\n depositorEthAddress,\n depositorBtcPubkey,\n };\n }\n\n private async assertPopMatchesBtcWallet(\n popSignature: PopSignature,\n ): Promise<void> {\n const currentBtcPubkey = normalizeXOnlyPubkey(\n await this.config.btcWallet.getPublicKeyHex(),\n );\n // Normalize the PoP-embedded key the same way in case a consumer\n // serialized it through a path that changed casing or re-added 0x.\n const popBtcPubkey = normalizeXOnlyPubkey(popSignature.depositorBtcPubkey);\n if (currentBtcPubkey !== popBtcPubkey) {\n throw new Error(\n `Proof of possession was signed with BTC pubkey ${popBtcPubkey} ` +\n `but the BTC wallet is currently connected to ${currentBtcPubkey}. ` +\n `Reconnect the original wallet or call signProofOfPossession() again.`,\n );\n }\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.btcNetwork;\n }\n\n /**\n * Gets the configured BTCVaultRegistry contract address.\n *\n * @returns The Ethereum address of the BTCVaultRegistry contract\n */\n getVaultContractAddress(): Address {\n return this.config.vaultContracts.btcVaultRegistry;\n }\n}\n"],"names":["U32_MASK64","_32n","fromBig","n","le","split","lst","len","Ah","Al","i","h","l","rotlSH","s","rotlSL","rotlBH","rotlBL","OP_RETURN","OP_PUSH32","OP_RETURN_PUSH32_SCRIPT_LEN","assertAuthAnchorOpReturn","fundedPrePeginTxHex","vaultCount","expectedAuthAnchorHashHex","cleanHex","stripHexPrefix","tx","bitcoin","opReturnOutput","script","pushedHex","_HMAC","hash","key","__publicField","ahash","abytes","blockLen","pad","clean","buf","aexists","out","to","oHash","iHash","finished","destroyed","outputLen","hmac","message","HKDF_COUNTER","EMPTY_BUFFER","expand","prk","info","length","anumber","olen","blocks","okm","HMAC","HMACTmp","T","counter","DOMAIN_TAG_BYTES","MAX_LABEL_LEN","MAX_CTX_LEN","CTX_LEN_PREFIX_SIZE","LABEL_HASHLOCK","LABEL_AUTH_ANCHOR","LABEL_WOTS_SEED","i2osp4","value","buildInfo","label","ctx","labelBytes","total","offset","ROOT_SIZE","AUTH_ANCHOR_SIZE","HASHLOCK_SIZE","WOTS_SEED_SIZE","assertRoot","root","expandAuthAnchor","hkdfExpand","sha256","expandHashlockSecret","htlcVout","expandWotsSeed","DEPOSITOR_PUBKEY_SIZE","TXID_SIZE","OUTPOINT_SIZE","COMMITMENT_SIZE","FIELD_LEN_PREFIX_SIZE","VAULT_CONTEXT_SIZE","writeUint32BE","serializeOutpoint","outpoint","compareBytes","a","b","buildFundingOutpointsCommitment","outpoints","serialized","flat","buildVaultContext","input","commitment","VAULT_APP_NAME","ROOT_OUTPUT_BYTES","ROOT_OUTPUT_HEX_LEN","LOWERCASE_HEX_RE","deriveVaultRoot","wallet","vaultContext","contextHex","uint8ArrayToHex","rootHex","hexToUint8Array","Rho160","Id160","_","Pi160","idxLR","res","j","k","idxL","idxR","shifts160","shiftsL160","idx","shiftsR160","Kl160","Kr160","ripemd_f","group","x","y","z","BUF_160","_RIPEMD160","HashMD","h0","h1","h2","h3","h4","view","al","ar","bl","br","cl","cr","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sl","sr","tl","rotl","tr","ripemd160","createHasher","_0n","_1n","_2n","_7n","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","R","t","IOTAS","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","keccakP","rounds","B","idx1","idx0","B0","B1","Th","Tl","curH","curL","shift","PI","Keccak","suffix","enableXOF","u32","swap32IfBE","data","state","pos","take","bufferOut","bytes","aoutput","genKeccak","keccak_256","CHAIN_ELEMENT_SIZE","WOTS_DIGIT_BITS","WOTS_CHECKSUM_DIGITS","CHECKSUM_MINOR_DIGIT_INDEX","CHECKSUM_MAJOR_DIGIT_INDEX","ASSERT_WOTS_BLOCK_DIGIT_COUNTS","toHex","hash160","maxDigitValue","d","defaultChecksumRadix","wMax","radix","createWotsConfig","chainStartForDigit","seed","digitIndex","suffixBytes","preimage","computeChainTerminal","start","steps","current","deriveBlockPublicKey","blockSeed","config","checksumMinorMax","checksumMajorMax","messageTerminals","digit","terminal","checksumMinorStart","checksumMinorTerminal","checksumMajorStart","checksumMajorTerminal","deriveWotsBlocksFromSeed","blockIdx","blockSeedInput","block","validateTerminal","computeWotsBlockPublicKeysHash","publicKeys","pk","totalTips","buffer","digest","isWotsMismatchError","error","msg","expandPerVaultSecrets","perVaultWotsKeys","wotsPkHashes","htlcSecretHexes","hashlocks","wotsSeed","wotsPublicKeys","secretBytes","secretHex","computeHashlock","ensureHexPrefix","HEX_SIGNATURE_REGEX","UNPREFIXED_HEX_SIGNATURE_REGEX","BASE64_SIGNATURE_REGEX","normalizeXOnlyPubkey","raw","processPublicKeyToXOnly","normalizePopSignature","Buffer","signPsbtsWithFallback","psbtsHexes","options","signedPsbts","signed","CONTRACT_ERRORS","extractErrorData","err","depth","maxDepth","cause","hexMatch","getContractErrorMessage","errorData","selector","isKnownContractError","handleContractError","knownError","errorMsg","errorHint","NO_REFERRAL_CODE","SIZING_PASS_PLACEHOLDER_BYTES32_HEX","resolveUtxoInfo","txid","vout","localPrevouts","apiUrl","local","getUtxoInfo","RECEIPT_TIMEOUT_MS","PeginManager","params","depositorBtcPubkeyRaw","depositorBtcPubkey","sizing","fundingOutpoints","u","authAnchorHex","authAnchorHash","authAnchorBytes","derived","commit","placeholderHashlocks","numLocalChallengers","prePegin","buildPrePeginPsbt","selection","selectUtxosForPegin","peginOutputCount","args","placeholderLower","vaultProviderBtcPubkey","vaultKeeperBtcPubkeys","universalChallengerBtcPubkeys","prePeginParams","prePeginResult","network","getNetwork","fundPeginTransaction","prePeginTxid","calculateBtcTxHash","peginTxResults","psbtsToSign","signOptions","peginTxResult","buildPeginTxFromFundedPrePegin","peginInputPsbtResult","buildPeginInputPsbt","createTaprootScriptPathSignOptions","perVault","peginInputSignature","extractPeginInputSignature","depositorSignedPeginTxHex","finalizePeginInputPsbt","Transaction","psbt","Psbt","publicKeyNoCoord","utxoDataPromises","utxoData","inputsWithUtxoData","totalInputValue","sum","totalOutputValue","impliedFee","MAX_REASONABLE_FEE_SATS","psbtInputFields","getPsbtInputFields","output","signedPsbtHex","signedPsbt","e","inp","signedTxHex","pushTx","unsignedPrePeginTx","depositorSignedPeginTx","vaultProvider","hashlock","depositorPayoutBtcAddress","depositorWotsPkHash","popSignature","depositorEthAddress","isAddressEqual","btcPopSignature","depositorBtcPubkeyHex","unsignedPrePeginTxHex","payoutScriptPubKey","peginTxHash","derivedVaultIdHex","deriveVaultId","vaultId","publicClient","createPublicClient","http","peginFee","BTCVaultRegistryABI","callData","encodeFunctionData","gasEstimate","ethTxHash","receipt","requests","resolvedPayoutScripts","req","vaultResults","totalFee","batchRequests","zeroAddress","address","walletPubkey","isAddressFromPublicKey","verifyingContract","popMessage","currentBtcPubkey","popBtcPubkey"],"mappings":"m/BAKMA,EAA6B,OAAO,GAAK,GAAK,CAAC,EAC/CC,GAAuB,OAAO,EAAE,EACtC,SAASC,GAAQC,EAAGC,EAAK,GAAO,CAC5B,OAAIA,EACO,CAAE,EAAG,OAAOD,EAAIH,CAAU,EAAG,EAAG,OAAQG,GAAKF,GAAQD,CAAU,CAAC,EACpE,CAAE,EAAG,OAAQG,GAAKF,GAAQD,CAAU,EAAI,EAAG,EAAG,OAAOG,EAAIH,CAAU,EAAI,CAAC,CACnF,CACA,SAASK,GAAMC,EAAKF,EAAK,GAAO,CAC5B,MAAMG,EAAMD,EAAI,OAChB,IAAIE,EAAK,IAAI,YAAYD,CAAG,EACxBE,EAAK,IAAI,YAAYF,CAAG,EAC5B,QAASG,EAAI,EAAGA,EAAIH,EAAKG,IAAK,CAC1B,KAAM,CAAE,EAAAC,EAAG,EAAAC,CAAC,EAAKV,GAAQI,EAAII,CAAC,EAAGN,CAAE,EACnC,CAACI,EAAGE,CAAC,EAAGD,EAAGC,CAAC,CAAC,EAAI,CAACC,EAAGC,CAAC,CAC1B,CACA,MAAO,CAACJ,EAAIC,CAAE,CAClB,CAeA,MAAMI,GAAS,CAACF,EAAGC,EAAGE,IAAOH,GAAKG,EAAMF,IAAO,G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