@babylonlabs-io/ts-sdk 0.51.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/{PayoutManager-D26nGR-e.js → PayoutManager-BwrV3xFW.js} +2 -2
  2. package/dist/{PayoutManager-D26nGR-e.js.map → PayoutManager-BwrV3xFW.js.map} +1 -1
  3. package/dist/{PayoutManager-BZVEyi10.cjs → PayoutManager-CBfHfLfz.cjs} +2 -2
  4. package/dist/{PayoutManager-BZVEyi10.cjs.map → PayoutManager-CBfHfLfz.cjs.map} +1 -1
  5. package/dist/{PeginManager-COxRVrxa.js → PeginManager-BGWNJYPk.js} +4 -4
  6. package/dist/{PeginManager-COxRVrxa.js.map → PeginManager-BGWNJYPk.js.map} +1 -1
  7. package/dist/{PeginManager-BvxfSwsr.cjs → PeginManager-DDp-ZRIa.cjs} +2 -2
  8. package/dist/{PeginManager-BvxfSwsr.cjs.map → PeginManager-DDp-ZRIa.cjs.map} +1 -1
  9. package/dist/buildAndBroadcastRefund-3MLyCOtv.cjs +2 -0
  10. package/dist/buildAndBroadcastRefund-3MLyCOtv.cjs.map +1 -0
  11. package/dist/{buildAndBroadcastRefund-Bmz9WJuN.js → buildAndBroadcastRefund-BAT5A6MP.js} +111 -110
  12. package/dist/buildAndBroadcastRefund-BAT5A6MP.js.map +1 -0
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +191 -188
  15. package/dist/noPayout-ChPNKTbm.cjs +2 -0
  16. package/dist/noPayout-ChPNKTbm.cjs.map +1 -0
  17. package/dist/{noPayout-C1WCsqfd.js → noPayout-DVx3zxUz.js} +24 -22
  18. package/dist/noPayout-DVx3zxUz.js.map +1 -0
  19. package/dist/{peginInput-BPRB9tUi.js → peginInput-B5XDDHpy.js} +17 -15
  20. package/dist/peginInput-B5XDDHpy.js.map +1 -0
  21. package/dist/peginInput-De0C6aSj.cjs +2 -0
  22. package/dist/peginInput-De0C6aSj.cjs.map +1 -0
  23. package/dist/{peginState-CBAlxgXk.js → peginState-BB81JI6I.js} +17 -12
  24. package/dist/{peginState-CBAlxgXk.js.map → peginState-BB81JI6I.js.map} +1 -1
  25. package/dist/peginState-CBBJw4Za.cjs +2 -0
  26. package/dist/{peginState-BijNNT15.cjs.map → peginState-CBBJw4Za.cjs.map} +1 -1
  27. package/dist/{reservation-xTL2a9Q-.cjs → reservation-ClEs2X0H.cjs} +2 -2
  28. package/dist/{reservation-xTL2a9Q-.cjs.map → reservation-ClEs2X0H.cjs.map} +1 -1
  29. package/dist/{reservation-BxvKbQH2.js → reservation-cHDRn4DA.js} +2 -2
  30. package/dist/{reservation-BxvKbQH2.js.map → reservation-cHDRn4DA.js.map} +1 -1
  31. package/dist/tbv/core/index.cjs +1 -1
  32. package/dist/tbv/core/index.js +189 -186
  33. package/dist/tbv/core/managers/index.cjs +1 -1
  34. package/dist/tbv/core/managers/index.js +2 -2
  35. package/dist/tbv/core/primitives/__tests__/txGraphVersion.test.d.ts +7 -0
  36. package/dist/tbv/core/primitives/__tests__/txGraphVersion.test.d.ts.map +1 -0
  37. package/dist/tbv/core/primitives/index.cjs +1 -1
  38. package/dist/tbv/core/primitives/index.d.ts +2 -1
  39. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  40. package/dist/tbv/core/primitives/index.js +34 -32
  41. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
  42. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  43. package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
  44. package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
  45. package/dist/tbv/core/primitives/scripts/payout.d.ts.map +1 -1
  46. package/dist/tbv/core/primitives/txGraphVersion.d.ts +11 -0
  47. package/dist/tbv/core/primitives/txGraphVersion.d.ts.map +1 -0
  48. package/dist/tbv/core/services/deposit/index.d.ts +1 -1
  49. package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
  50. package/dist/tbv/core/services/deposit/peginState.d.ts +11 -0
  51. package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -1
  52. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  53. package/dist/tbv/core/services/index.cjs +1 -1
  54. package/dist/tbv/core/services/index.js +19 -18
  55. package/dist/tbv/core/utils/index.cjs +1 -1
  56. package/dist/tbv/core/utils/index.js +1 -1
  57. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts +5 -2
  58. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts.map +1 -1
  59. package/dist/tbv/index.cjs +1 -1
  60. package/dist/tbv/index.js +189 -186
  61. package/dist/{verifyScriptPathSchnorrSignature-CeZp6tMw.js → verifyScriptPathSchnorrSignature-BKECXOpa.js} +108 -97
  62. package/dist/verifyScriptPathSchnorrSignature-BKECXOpa.js.map +1 -0
  63. package/dist/verifyScriptPathSchnorrSignature-CVPh04ZI.cjs +2 -0
  64. package/dist/verifyScriptPathSchnorrSignature-CVPh04ZI.cjs.map +1 -0
  65. package/package.json +3 -3
  66. package/dist/buildAndBroadcastRefund-Bmz9WJuN.js.map +0 -1
  67. package/dist/buildAndBroadcastRefund-ob1n2iB3.cjs +0 -2
  68. package/dist/buildAndBroadcastRefund-ob1n2iB3.cjs.map +0 -1
  69. package/dist/noPayout-C1WCsqfd.js.map +0 -1
  70. package/dist/noPayout-lyIRiUyG.cjs +0 -2
  71. package/dist/noPayout-lyIRiUyG.cjs.map +0 -1
  72. package/dist/peginInput-BPRB9tUi.js.map +0 -1
  73. package/dist/peginInput-DH6X4ITS.cjs +0 -2
  74. package/dist/peginInput-DH6X4ITS.cjs.map +0 -1
  75. package/dist/peginState-BijNNT15.cjs +0 -2
  76. package/dist/verifyScriptPathSchnorrSignature-CeZp6tMw.js.map +0 -1
  77. package/dist/verifyScriptPathSchnorrSignature-Cl7tu77P.cjs +0 -2
  78. package/dist/verifyScriptPathSchnorrSignature-Cl7tu77P.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"noPayout-DVx3zxUz.js","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n assertPositiveBigintArray,\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { TX_GRAPH_VERSION_V1 } from \"../txGraphVersion\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Phase-1 pin: refunds reconstruct the v1 template (matches the graph\n // every existing Pre-PegIn was built with).\n const unfundedTx = new WasmPrePeginTx(\n TX_GRAPH_VERSION_V1,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against the funded\n // transaction: the WASM template's HTLC scriptPubKey at `htlcVout`\n // must equal the bytes the funded tx carries at the same output.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const expectedHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: TX_GRAPH_VERSION_V1,\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","WasmPrePeginTx","TX_GRAPH_VERSION_V1","assertPositiveBigintArray","fundedTx","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":";;;;;AA0EA,eAAsBA,EACpBC,GACgC;AAChC,QAAMC,EAAA;AAEN,QAAM,EAAE,gBAAAC,GAAgB,qBAAAC,GAAqB,UAAAC,GAAU,WAAAC,GAAW,UAAAC,MAChEN,GAYIO,IAA2BC;AAAA,IAC/BN,EAAe;AAAA,EAAA,GAIXO,IAAa,IAAIC;AAAA,IACrBC;AAAA,IACAT,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACf,CAAC,GAAGA,EAAe,SAAS;AAAA,IAC5B,IAAI;AAAA,MACFU,EAA0BV,EAAe,cAAc,cAAc;AAAA,IAAA;AAAA,IAEvEA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfK;AAAA,EAAA;AAGF,MAAIM,IAAkC;AACtC,MAAI;AASF,UAAMC,IAA2BL,EAC9B,oBAAoBL,CAAQ,EAC5B,YAAA,GAMGW,IAAoBN,EAAW,aAAaL,CAAQ;AAE1D,IAAAS,IAAWJ,EAAW,sBAAsBN,CAAmB;AAE/D,UAAMa,IAAcH,EAAS,cAAcR,GAAWD,CAAQ,GAExDa,IAAgB,MAAMC,EAA6B;AAAA,MACvD,gBAAgBP;AAAA,MAChB,iBAAiBT,EAAe;AAAA,MAChC,qBAAqBA,EAAe;AAAA,MACpC,oBAAoBA,EAAe;AAAA,MACnC,4BAA4BA,EAAe;AAAA,MAC3C,UAAAI;AAAA,MACA,gBAAgBJ,EAAe;AAAA,MAC/B,SAASA,EAAe;AAAA,IAAA,CACzB,GAEKiB,IAAmBhB,EAAoB,WAAW,IAAI,IACxDA,EAAoB,MAAM,CAAC,IAC3BA,GACEiB,IAAaC,EAAY,QAAQF,CAAgB,GAEjDG,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I;AAAA,MACR,wDAAwDA,EAAG,KAAK,MAAM;AAAA,IAAA;AAI1E,QAAMC,IAAQzB,EAAgB0B,EAAwBJ,CAAgB,CAAC,GACjE,EAAE,QAAQK,MAAmBC,EAAS,KAAK;AAAA,IAC/C,gBAAgB7B,EAAO,KAAK0B,CAAK;AAAA,IACjC,SAASI,EAAWN,CAAO;AAAA,EAAA,CAC5B;AACD,MAAI,CAACI;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,MAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc;AAC1C,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGN;"}
@@ -2,8 +2,10 @@ import { getPrePeginHtlcConnectorInfo as k, tapInternalPubkey as y } from "@baby
2
2
  import { Buffer as u } from "buffer";
3
3
  import { Transaction as P, Psbt as p } from "bitcoinjs-lib";
4
4
  import { s as d, u as x, h as l, T as I } from "./bitcoin-B5aNKtsk.js";
5
- async function m(t) {
5
+ import { T as b } from "./verifyScriptPathSchnorrSignature-BKECXOpa.js";
6
+ async function B(t) {
6
7
  const r = d(t.peginTxHex), a = d(t.fundedPrePeginTxHex), n = await k({
8
+ txGraphVersion: b,
7
9
  depositorPubkey: t.depositorPubkey,
8
10
  vaultProviderPubkey: t.vaultProviderPubkey,
9
11
  vaultKeeperPubkeys: t.vaultKeeperPubkeys,
@@ -16,12 +18,12 @@ async function m(t) {
16
18
  throw new Error(
17
19
  `PegIn transaction must have exactly 1 input, got ${e.ins.length}`
18
20
  );
19
- const o = e.ins[0], f = i.getId(), g = x(
21
+ const o = e.ins[0], f = i.getId(), h = x(
20
22
  new Uint8Array(o.hash).slice().reverse()
21
23
  );
22
- if (g !== f)
24
+ if (h !== f)
23
25
  throw new Error(
24
- `PegIn input does not reference the Pre-PegIn transaction. Expected ${f}, got ${g}`
26
+ `PegIn input does not reference the Pre-PegIn transaction. Expected ${f}, got ${h}`
25
27
  );
26
28
  const c = i.outs[o.index];
27
29
  if (!c)
@@ -47,14 +49,14 @@ async function m(t) {
47
49
  tapInternalKey: u.from(y)
48
50
  // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot
49
51
  });
50
- for (const h of e.outs)
52
+ for (const g of e.outs)
51
53
  s.addOutput({
52
- script: h.script,
53
- value: h.value
54
+ script: g.script,
55
+ value: g.value
54
56
  });
55
57
  return { psbtHex: s.toHex() };
56
58
  }
57
- function B(t, r) {
59
+ function $(t, r) {
58
60
  const n = p.fromHex(t).data.inputs[0];
59
61
  if (!n)
60
62
  throw new Error("PegIn PSBT has no inputs");
@@ -64,7 +66,7 @@ function B(t, r) {
64
66
  );
65
67
  for (const i of n.tapScriptSig)
66
68
  if (i.pubkey.equals(e))
67
- return b(i.signature);
69
+ return T(i.signature);
68
70
  throw new Error(
69
71
  `No PegIn input signature found for depositor pubkey: ${r}`
70
72
  );
@@ -75,7 +77,7 @@ function B(t, r) {
75
77
  "No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT"
76
78
  );
77
79
  }
78
- function A(t) {
80
+ function z(t) {
79
81
  const r = p.fromHex(t);
80
82
  try {
81
83
  r.finalizeAllInputs();
@@ -89,7 +91,7 @@ function A(t) {
89
91
  }
90
92
  return r.extractTransaction().toHex();
91
93
  }
92
- function b(t) {
94
+ function T(t) {
93
95
  if (t.length === 64)
94
96
  return x(new Uint8Array(t));
95
97
  throw t.length === 65 ? new Error(
@@ -97,8 +99,8 @@ function b(t) {
97
99
  ) : new Error(`Unexpected PegIn input signature length: ${t.length}`);
98
100
  }
99
101
  export {
100
- m as b,
101
- B as e,
102
- A as f
102
+ B as b,
103
+ $ as e,
104
+ z as f
103
105
  };
104
- //# sourceMappingURL=peginInput-BPRB9tUi.js.map
106
+ //# sourceMappingURL=peginInput-B5XDDHpy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peginInput-B5XDDHpy.js","sources":["../src/tbv/core/primitives/psbt/peginInput.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport { TX_GRAPH_VERSION_V1 } from \"../txGraphVersion\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: TX_GRAPH_VERSION_V1,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.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 return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","TX_GRAPH_VERSION_V1","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig"],"mappings":";;;;;AAgFA,eAAsBA,EACpBC,GACoC;AACpC,QAAMC,IAAaC,EAAeF,EAAO,UAAU,GAC7CG,IAAsBD,EAAeF,EAAO,mBAAmB,GAE/DI,IAAgB,MAAMC,EAA6B;AAAA,IACvD,gBAAgBC;AAAA,IAChB,iBAAiBN,EAAO;AAAA,IACxB,qBAAqBA,EAAO;AAAA,IAC5B,oBAAoBA,EAAO;AAAA,IAC3B,4BAA4BA,EAAO;AAAA,IACnC,UAAUA,EAAO;AAAA,IACjB,gBAAgBA,EAAO;AAAA,IACvB,SAASA,EAAO;AAAA,EAAA,CACjB,GAEKO,IAAUC,EAAY,QAAQP,CAAU,GACxCQ,IAAaD,EAAY,QAAQL,CAAmB;AAE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+ "use strict";const P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),l=require("buffer"),a=require("bitcoinjs-lib"),i=require("./bitcoin-CHfKAhcI.cjs"),S=require("./verifyScriptPathSchnorrSignature-CVPh04ZI.cjs");async function b(t){const r=i.stripHexPrefix(t.peginTxHex),c=i.stripHexPrefix(t.fundedPrePeginTxHex),n=await P.getPrePeginHtlcConnectorInfo({txGraphVersion:S.TX_GRAPH_VERSION_V1,depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:t.hashlock,timelockRefund:t.timelockRefund,network:t.network}),e=a.Transaction.fromHex(r),o=a.Transaction.fromHex(c);if(e.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${e.ins.length}`);const s=e.ins[0],f=o.getId(),g=i.uint8ArrayToHex(new Uint8Array(s.hash).slice().reverse());if(g!==f)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${f}, got ${g}`);const p=o.outs[s.index];if(!p)throw new Error(`Pre-PegIn output ${s.index} not found (Pre-PegIn has ${o.outs.length} outputs)`);const d=i.hexToUint8Array(n.hashlockScript),x=i.hexToUint8Array(n.hashlockControlBlock),u=new a.Psbt;u.setVersion(e.version),u.setLocktime(e.locktime),u.addInput({hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:p.script,value:p.value},tapLeafScript:[{leafVersion:i.TAPSCRIPT_LEAF_VERSION,script:l.Buffer.from(d),controlBlock:l.Buffer.from(x)}],tapInternalKey:l.Buffer.from(P.tapInternalPubkey)});for(const h of e.outs)u.addOutput({script:h.script,value:h.value});return{psbtHex:u.toHex()}}function w(t,r){const n=a.Psbt.fromHex(t).data.inputs[0];if(!n)throw new Error("PegIn PSBT has no inputs");if(n.tapScriptSig&&n.tapScriptSig.length>0){const e=l.Buffer.from(i.hexToUint8Array(r));for(const o of n.tapScriptSig)if(o.pubkey.equals(e))return I(o.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${r}`)}throw n.finalScriptWitness&&n.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function y(t){const r=a.Psbt.fromHex(t);try{r.finalizeAllInputs()}catch(c){if(!r.data.inputs.every(e=>e.finalScriptWitness||e.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${c}`)}return r.extractTransaction().toHex()}function I(t){if(t.length===64)return i.uint8ArrayToHex(new Uint8Array(t));throw t.length===65?new Error(`Unexpected sighash byte 0x${t[64].toString(16).padStart(2,"0")} in PegIn input signature. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected PegIn input signature length: ${t.length}`)}exports.buildPeginInputPsbt=b;exports.extractPeginInputSignature=w;exports.finalizePeginInputPsbt=y;
2
+ //# sourceMappingURL=peginInput-De0C6aSj.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peginInput-De0C6aSj.cjs","sources":["../src/tbv/core/primitives/psbt/peginInput.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport { TX_GRAPH_VERSION_V1 } from \"../txGraphVersion\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: TX_GRAPH_VERSION_V1,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.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 return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","TX_GRAPH_VERSION_V1","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig"],"mappings":"sNAgFA,eAAsBA,EACpBC,EACoC,CACpC,MAAMC,EAAaC,EAAAA,eAAeF,EAAO,UAAU,EAC7CG,EAAsBD,EAAAA,eAAeF,EAAO,mBAAmB,EAE/DI,EAAgB,MAAMC,+BAA6B,CACvD,eAAgBC,EAAAA,oBAChB,gBAAiBN,EAAO,gBACxB,oBAAqBA,EAAO,oBAC5B,mBAAoBA,EAAO,mBAC3B,2BAA4BA,EAAO,2BACnC,SAAUA,EAAO,SACjB,eAAgBA,EAAO,eACvB,QAASA,EAAO,OAAA,CACjB,EAEKO,EAAUC,EAAAA,YAAY,QAAQP,CAAU,EACxCQ,EAAaD,EAAAA,YAAY,QAAQL,CAAmB,EAE1D,GAAII,EAAQ,IAAI,SAAW,EACzB,MAAM,IAAI,MACR,oDAAoDA,EAAQ,IAAI,MAAM,EAAA,EAI1E,MAAMG,EAAaH,EAAQ,IAAI,CAAC,EAG1BI,EAAeF,EAAW,MAAA,EAC1BG,EAAiBC,EAAAA,gBACrB,IAAI,WAAWH,EAAW,IAAI,EAAE,MAAA,EAAQ,QAAA,CAAQ,EAGlD,GAAIE,IAAmBD,EACrB,MAAM,IAAI,MACR,sEACcA,CAAY,SAASC,CAAc,EAAA,EAIrD,MAAME,EAAaL,EAAW,KAAKC,EAAW,KAAK,EACnD,GAAI,CAACI,EACH,MAAM,IAAI,MACR,oBAAoBJ,EAAW,KAAK,6BAChBD,EAAW,KAAK,MAAM,WAAA,E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MP,EAAOC,EAAAA,KAAK,QAAQM,CAAa,EAKvC,GAAI,CACFP,EAAK,kBAAA,CACP,OAASc,EAAG,CAIV,GAAI,CAHiBd,EAAK,KAAK,OAAO,MACnCe,GAAQA,EAAI,oBAAsBA,EAAI,cAAA,EAGvC,MAAM,IAAI,MACR,8DAA8DD,CAAC,EAAA,CAGrE,CAEA,OAAOd,EAAK,mBAAA,EAAqB,MAAA,CACnC,CASO,SAASY,EAAkBI,EAAyB,CACzD,GAAIA,EAAI,SAAW,GACjB,OAAOrB,kBAAgB,IAAI,WAAWqB,CAAG,CAAC,EAE5C,MAAIA,EAAI,SAAW,GACX,IAAI,MACR,6BAA6BA,EAAI,EAAE,EAAE,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CAAC,sFAAA,EAIhE,IAAI,MAAM,4CAA4CA,EAAI,MAAM,EAAE,CAC1E"}
@@ -1,25 +1,25 @@
1
1
  var _ = /* @__PURE__ */ ((i) => (i[i.PENDING = 0] = "PENDING", i[i.VERIFIED = 1] = "VERIFIED", i[i.ACTIVE = 2] = "ACTIVE", i[i.REDEEMED = 3] = "REDEEMED", i[i.LIQUIDATED = 4] = "LIQUIDATED", i[i.INVALID = 5] = "INVALID", i[i.DEPOSITOR_WITHDRAWN = 6] = "DEPOSITOR_WITHDRAWN", i[i.EXPIRED = 7] = "EXPIRED", i))(_ || {}), D = /* @__PURE__ */ ((i) => (i.SUBMIT_WOTS_KEY = "SUBMIT_WOTS_KEY", i.SIGN_PAYOUT_TRANSACTIONS = "SIGN_PAYOUT_TRANSACTIONS", i.SIGN_AND_BROADCAST_TO_BITCOIN = "SIGN_AND_BROADCAST_TO_BITCOIN", i.ACTIVATE_VAULT = "ACTIVATE_VAULT", i.REFUND_HTLC = "REFUND_HTLC", i))(D || {});
2
- function N(i, A = {}) {
2
+ function N(i, e = {}) {
3
3
  const {
4
- transactionsReady: e,
5
- needsWotsKey: I,
6
- pendingIngestion: T,
4
+ transactionsReady: A,
5
+ needsWotsKey: T,
6
+ pendingIngestion: I,
7
7
  canRefund: l,
8
8
  hasProviderTerminalFailure: E
9
- } = A;
10
- return i === 0 ? E ? { contractStatus: i, availableActions: [] } : I ? {
9
+ } = e;
10
+ return i === 0 ? E ? { contractStatus: i, availableActions: [] } : T ? {
11
11
  contractStatus: i,
12
12
  availableActions: [
13
13
  "SUBMIT_WOTS_KEY"
14
14
  /* SUBMIT_WOTS_KEY */
15
15
  ]
16
- } : T === !0 && !e ? {
16
+ } : I === !0 && !A ? {
17
17
  contractStatus: i,
18
18
  availableActions: [
19
19
  "SIGN_AND_BROADCAST_TO_BITCOIN"
20
20
  /* SIGN_AND_BROADCAST_TO_BITCOIN */
21
21
  ]
22
- } : T === void 0 && !e ? { contractStatus: i, availableActions: [] } : e ? {
22
+ } : I === void 0 && !A ? { contractStatus: i, availableActions: [] } : A ? {
23
23
  contractStatus: i,
24
24
  availableActions: [
25
25
  "SIGN_PAYOUT_TRANSACTIONS"
@@ -39,13 +39,18 @@ function N(i, A = {}) {
39
39
  ] : []
40
40
  } : i === 5 ? { contractStatus: i, availableActions: [] } : i === 6 ? { contractStatus: i, availableActions: [] } : { contractStatus: i, availableActions: [] };
41
41
  }
42
- function O(i, A) {
43
- return i.availableActions.includes(A);
42
+ function O(i, e) {
43
+ return i.availableActions.includes(e);
44
+ }
45
+ function v(i) {
46
+ const { currentBlock: e, createdAtBlock: A, pegInActivationTimeout: T } = i;
47
+ return e > A + T;
44
48
  }
45
49
  export {
46
50
  _ as C,
47
51
  D as P,
48
52
  O as c,
49
- N as g
53
+ N as g,
54
+ v as i
50
55
  };
51
- //# sourceMappingURL=peginState-CBAlxgXk.js.map
56
+ //# sourceMappingURL=peginState-BB81JI6I.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"peginState-CBAlxgXk.js","sources":["../src/tbv/core/services/deposit/peginState.ts"],"sourcesContent":["// ============================================================================\n// State Definitions\n// ============================================================================\n\n/**\n * Vault status — combines on-chain contract status (0-4) with indexer-derived\n * statuses (5-7). The contract enum (BTCVaultRegistry.sol BTCVaultStatus) only\n * has: Pending(0), Verified(1), Active(2), Redeemed(3), Expired(4).\n * The indexer maps these and adds extra statuses for UI display.\n *\n * IMPORTANT: With the new contract architecture:\n * - Core vault status (BTCVaultRegistry) does NOT change when used by applications\n * - Vaults remain at ACTIVE status even when used in DeFi positions\n * - Application usage status is tracked separately by each integration controller\n */\nexport enum ContractStatus {\n /** Status 0: Request submitted, waiting for ACKs */\n PENDING = 0,\n /** Status 1: All ACKs collected, ready for secret activation */\n VERIFIED = 1,\n /** Status 2: HTLC secret revealed, vault is active and usable (stays here even when used by apps) */\n ACTIVE = 2,\n /** Status 3: Vault has been redeemed, BTC is claimable */\n REDEEMED = 3,\n /** Status 4 (indexer-only): Vault was liquidated (collateral seized due to unpaid debt) */\n LIQUIDATED = 4,\n /** Status 5 (indexer-only): Vault is invalid — BTC UTXOs were spent in a different transaction */\n INVALID = 5,\n /** Status 6 (indexer-only): Depositor has withdrawn their BTC (redemption complete) */\n DEPOSITOR_WITHDRAWN = 6,\n /** Status 7 (indexer-only): Vault expired due to AckTimeout or ActivationTimeout */\n EXPIRED = 7,\n}\n\n/** Reason why a vault expired */\nexport type ExpirationReason =\n | \"ack_timeout\"\n | \"proof_timeout\"\n | \"activation_timeout\";\n\n// ============================================================================\n// Protocol State Model\n// ============================================================================\n\n/**\n * Available actions user can take\n */\nexport enum PeginAction {\n /** Submit WOTS key (re-derives via wallet `deriveContextHash`) */\n SUBMIT_WOTS_KEY = \"SUBMIT_WOTS_KEY\",\n /** Sign payout transactions */\n SIGN_PAYOUT_TRANSACTIONS = \"SIGN_PAYOUT_TRANSACTIONS\",\n /** Sign and broadcast peg-in transaction to Bitcoin */\n SIGN_AND_BROADCAST_TO_BITCOIN = \"SIGN_AND_BROADCAST_TO_BITCOIN\",\n /** Reveal HTLC secret on Ethereum to activate vault */\n ACTIVATE_VAULT = \"ACTIVATE_VAULT\",\n /** Sign and broadcast HTLC refund transaction for an expired vault */\n REFUND_HTLC = \"REFUND_HTLC\",\n}\n\n/**\n * Protocol-level peg-in state (framework-agnostic)\n */\nexport interface PeginProtocolState {\n /** Smart contract status (source of truth for on-chain state) */\n contractStatus: ContractStatus;\n /** Available user actions (empty array when no action is available) */\n availableActions: PeginAction[];\n}\n\n/**\n * Options for getPeginProtocolState function.\n *\n * All fields represent protocol-level state from the vault provider or\n * on-chain contracts. Client-side tracking (localStorage, polling state)\n * is NOT included — consumers handle that in their own layer.\n */\nexport interface GetPeginProtocolStateOptions {\n /** Whether claim/payout transactions are ready from VP */\n transactionsReady?: boolean;\n /** Whether the vault provider is waiting for the depositor's WOTS public key */\n needsWotsKey?: boolean;\n /** Whether the vault provider hasn't ingested this peg-in yet */\n pendingIngestion?: boolean;\n /** Whether the depositor can refund the HTLC (Pre-PegIn tx available) */\n canRefund?: boolean;\n /** Whether the vault provider reported a terminal failure */\n hasProviderTerminalFailure?: boolean;\n}\n\n// ============================================================================\n// State Machine Logic\n// ============================================================================\n\n/**\n * Determine the current protocol state and available actions based on contract\n * status and vault provider state. Framework-agnostic: returns only\n * protocol-level data with no display labels, messages, or UI concerns.\n *\n * Client-side tracking overrides (e.g. suppressing actions after the user\n * has already acted but on-chain state hasn't caught up) are the caller's\n * responsibility.\n *\n * @param contractStatus - On-chain contract status (source of truth)\n * @param options - Vault provider state\n * @returns Protocol state with available actions\n */\nexport function getPeginProtocolState(\n contractStatus: ContractStatus,\n options: GetPeginProtocolStateOptions = {},\n): PeginProtocolState {\n const {\n transactionsReady,\n needsWotsKey,\n pendingIngestion,\n canRefund,\n hasProviderTerminalFailure,\n } = options;\n\n if (contractStatus === ContractStatus.PENDING) {\n if (hasProviderTerminalFailure) {\n return { contractStatus, availableActions: [] };\n }\n\n if (needsWotsKey) {\n return {\n contractStatus,\n availableActions: [PeginAction.SUBMIT_WOTS_KEY],\n };\n }\n\n if (pendingIngestion === true && !transactionsReady) {\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_AND_BROADCAST_TO_BITCOIN],\n };\n }\n\n if (pendingIngestion === undefined && !transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n if (!transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_PAYOUT_TRANSACTIONS],\n };\n }\n\n if (contractStatus === ContractStatus.VERIFIED) {\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_VAULT],\n };\n }\n\n if (contractStatus === ContractStatus.ACTIVE) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.REDEEMED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.LIQUIDATED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.EXPIRED) {\n return {\n contractStatus,\n availableActions: canRefund ? [PeginAction.REFUND_HTLC] : [],\n };\n }\n\n if (contractStatus === ContractStatus.INVALID) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.DEPOSITOR_WITHDRAWN) {\n return { contractStatus, availableActions: [] };\n }\n\n return { contractStatus, availableActions: [] };\n}\n\n/**\n * Check if a specific action is available in the current state\n */\nexport function canPerformAction(\n state: PeginProtocolState,\n action: PeginAction,\n): boolean {\n return state.availableActions.includes(action);\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","canPerformAction","state","action"],"mappings":"AAeO,IAAKA,sBAAAA,OAEVA,EAAAA,EAAA,UAAU,CAAA,IAAV,WAEAA,EAAAA,EAAA,WAAW,CAAA,IAAX,YAEAA,EAAAA,EAAA,SAAS,CAAA,IAAT,UAEAA,EAAAA,EAAA,WAAW,CAAA,IAAX,YAEAA,EAAAA,EAAA,aAAa,CAAA,IAAb,cAEAA,EAAAA,EAAA,UAAU,CAAA,IAAV,WAEAA,EAAAA,EAAA,sBAAsB,CAAA,IAAtB,uBAEAA,EAAAA,EAAA,UAA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B,CAAA;AAAA,EAAC,IAI3DL,MAAmB,IACd,EAAE,gBAAAA,GAAgB,kBAAkB,GAAC,IAG1CA,MAAmB,IACd,EAAE,gBAAAA,GAAgB,kBAAkB,GAAC,IAGvC,EAAE,gBAAAA,GAAgB,kBAAkB,GAAC;AAC9C;AAKO,SAASO,EACdC,GACAC,GACS;AACT,SAAOD,EAAM,iBAAiB,SAASC,CAAM;AAC/C;"}
1
+ {"version":3,"file":"peginState-BB81JI6I.js","sources":["../src/tbv/core/services/deposit/peginState.ts"],"sourcesContent":["// ============================================================================\n// State Definitions\n// ============================================================================\n\n/**\n * Vault status — combines on-chain contract status (0-4) with indexer-derived\n * statuses (5-7). The contract enum (BTCVaultRegistry.sol BTCVaultStatus) only\n * has: Pending(0), Verified(1), Active(2), Redeemed(3), Expired(4).\n * The indexer maps these and adds extra statuses for UI display.\n *\n * IMPORTANT: With the new contract architecture:\n * - Core vault status (BTCVaultRegistry) does NOT change when used by applications\n * - Vaults remain at ACTIVE status even when used in DeFi positions\n * - Application usage status is tracked separately by each integration controller\n */\nexport enum ContractStatus {\n /** Status 0: Request submitted, waiting for ACKs */\n PENDING = 0,\n /** Status 1: All ACKs collected, ready for secret activation */\n VERIFIED = 1,\n /** Status 2: HTLC secret revealed, vault is active and usable (stays here even when used by apps) */\n ACTIVE = 2,\n /** Status 3: Vault has been redeemed, BTC is claimable */\n REDEEMED = 3,\n /** Status 4 (indexer-only): Vault was liquidated (collateral seized due to unpaid debt) */\n LIQUIDATED = 4,\n /** Status 5 (indexer-only): Vault is invalid — BTC UTXOs were spent in a different transaction */\n INVALID = 5,\n /** Status 6 (indexer-only): Depositor has withdrawn their BTC (redemption complete) */\n DEPOSITOR_WITHDRAWN = 6,\n /** Status 7 (indexer-only): Vault expired due to AckTimeout or ActivationTimeout */\n EXPIRED = 7,\n}\n\n/** Reason why a vault expired */\nexport type ExpirationReason =\n | \"ack_timeout\"\n | \"proof_timeout\"\n | \"activation_timeout\";\n\n// ============================================================================\n// Protocol State Model\n// ============================================================================\n\n/**\n * Available actions user can take\n */\nexport enum PeginAction {\n /** Submit WOTS key (re-derives via wallet `deriveContextHash`) */\n SUBMIT_WOTS_KEY = \"SUBMIT_WOTS_KEY\",\n /** Sign payout transactions */\n SIGN_PAYOUT_TRANSACTIONS = \"SIGN_PAYOUT_TRANSACTIONS\",\n /** Sign and broadcast peg-in transaction to Bitcoin */\n SIGN_AND_BROADCAST_TO_BITCOIN = \"SIGN_AND_BROADCAST_TO_BITCOIN\",\n /** Reveal HTLC secret on Ethereum to activate vault */\n ACTIVATE_VAULT = \"ACTIVATE_VAULT\",\n /** Sign and broadcast HTLC refund transaction for an expired vault */\n REFUND_HTLC = \"REFUND_HTLC\",\n}\n\n/**\n * Protocol-level peg-in state (framework-agnostic)\n */\nexport interface PeginProtocolState {\n /** Smart contract status (source of truth for on-chain state) */\n contractStatus: ContractStatus;\n /** Available user actions (empty array when no action is available) */\n availableActions: PeginAction[];\n}\n\n/**\n * Options for getPeginProtocolState function.\n *\n * All fields represent protocol-level state from the vault provider or\n * on-chain contracts. Client-side tracking (localStorage, polling state)\n * is NOT included — consumers handle that in their own layer.\n */\nexport interface GetPeginProtocolStateOptions {\n /** Whether claim/payout transactions are ready from VP */\n transactionsReady?: boolean;\n /** Whether the vault provider is waiting for the depositor's WOTS public key */\n needsWotsKey?: boolean;\n /** Whether the vault provider hasn't ingested this peg-in yet */\n pendingIngestion?: boolean;\n /** Whether the depositor can refund the HTLC (Pre-PegIn tx available) */\n canRefund?: boolean;\n /** Whether the vault provider reported a terminal failure */\n hasProviderTerminalFailure?: boolean;\n}\n\n// ============================================================================\n// State Machine Logic\n// ============================================================================\n\n/**\n * Determine the current protocol state and available actions based on contract\n * status and vault provider state. Framework-agnostic: returns only\n * protocol-level data with no display labels, messages, or UI concerns.\n *\n * Client-side tracking overrides (e.g. suppressing actions after the user\n * has already acted but on-chain state hasn't caught up) are the caller's\n * responsibility.\n *\n * @param contractStatus - On-chain contract status (source of truth)\n * @param options - Vault provider state\n * @returns Protocol state with available actions\n */\nexport function getPeginProtocolState(\n contractStatus: ContractStatus,\n options: GetPeginProtocolStateOptions = {},\n): PeginProtocolState {\n const {\n transactionsReady,\n needsWotsKey,\n pendingIngestion,\n canRefund,\n hasProviderTerminalFailure,\n } = options;\n\n if (contractStatus === ContractStatus.PENDING) {\n if (hasProviderTerminalFailure) {\n return { contractStatus, availableActions: [] };\n }\n\n if (needsWotsKey) {\n return {\n contractStatus,\n availableActions: [PeginAction.SUBMIT_WOTS_KEY],\n };\n }\n\n if (pendingIngestion === true && !transactionsReady) {\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_AND_BROADCAST_TO_BITCOIN],\n };\n }\n\n if (pendingIngestion === undefined && !transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n if (!transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_PAYOUT_TRANSACTIONS],\n };\n }\n\n if (contractStatus === ContractStatus.VERIFIED) {\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_VAULT],\n };\n }\n\n if (contractStatus === ContractStatus.ACTIVE) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.REDEEMED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.LIQUIDATED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.EXPIRED) {\n return {\n contractStatus,\n availableActions: canRefund ? [PeginAction.REFUND_HTLC] : [],\n };\n }\n\n if (contractStatus === ContractStatus.INVALID) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.DEPOSITOR_WITHDRAWN) {\n return { contractStatus, availableActions: [] };\n }\n\n return { contractStatus, availableActions: [] };\n}\n\n/**\n * Check if a specific action is available in the current state\n */\nexport function canPerformAction(\n state: PeginProtocolState,\n action: PeginAction,\n): boolean {\n return state.availableActions.includes(action);\n}\n\n// ============================================================================\n// Activation deadline\n// ============================================================================\n\n/**\n * Whether a vault's on-chain activation window has closed. Mirrors the\n * BTCVaultRegistry check that reverts `ActivationDeadlineExpired`:\n * `block.number > createdAt + pegInActivationTimeout` — strict `>`, so a\n * boundary-equal block is NOT expired. All values are Ethereum block numbers.\n */\nexport function isActivationDeadlinePassedOnChain(params: {\n currentBlock: bigint;\n createdAtBlock: bigint;\n pegInActivationTimeout: bigint;\n}): boolean {\n const { currentBlock, createdAtBlock, pegInActivationTimeout } = params;\n return currentBlock > createdAtBlock + pegInActivationTimeout;\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","canPerformAction","state","action","isActivationDeadlinePassedOnChain","params","currentBlock","createdAtBlock","pegInActivationTimeout"],"mappings":"AAeO,IAAKA,sBAAAA,OAEVA,EAAAA,EAAA,UAAU,CAAA,IAAV,WAEAA,EAAAA,EAAA,WAAW,CAAA,IAAX,YAEAA,EAAAA,EAAA,SAAS,CAAA,IAAT,UAEAA,EAAAA,EAAA,WAAW,CAAA,IAAX,YAEAA,EAAAA,EAAA,aAAa,CAAA,IAAb,cAEAA,EAAAA,EAAA,UAAU,CAAA,IAAV,WAEAA,EAAAA,EAAA,sBAAsB,CAAA,IAAtB,uBAEAA,EAAAA,EAAA,UAAU,CAAA,IAAV,WAhBUA,IAAAA,KAAA,CAAA,CAAA,GAgCAC,sBAAAA,OAEVA,EAAA,kBAAkB,mBAElBA,EAAA,2BAA2B,4BAE3BA,EAAA,gCAAgC,iCAEhCA,EAAA,iBAAiB,kBAEjBA,EAAA,cAAc,eAVJA,IAAAA,KAAA,CAAA,CAAA;AA4DL,SAASC,EACdC,GACAC,IAAwC,IACpB;AACpB,QAAM;AAAA,IACJ,mBAAAC;AAAA,IACA,cAAAC;AAAA,IACA,kBAAAC;AAAA,IACA,WAAAC;AAAA,IACA,4BAAAC;AAAA,EAAA,IACEL;AAEJ,SAAID,MAAmB,IAC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,0 +1,2 @@
1
+ "use strict";var l=(i=>(i[i.PENDING=0]="PENDING",i[i.VERIFIED=1]="VERIFIED",i[i.ACTIVE=2]="ACTIVE",i[i.REDEEMED=3]="REDEEMED",i[i.LIQUIDATED=4]="LIQUIDATED",i[i.INVALID=5]="INVALID",i[i.DEPOSITOR_WITHDRAWN=6]="DEPOSITOR_WITHDRAWN",i[i.EXPIRED=7]="EXPIRED",i))(l||{}),E=(i=>(i.SUBMIT_WOTS_KEY="SUBMIT_WOTS_KEY",i.SIGN_PAYOUT_TRANSACTIONS="SIGN_PAYOUT_TRANSACTIONS",i.SIGN_AND_BROADCAST_TO_BITCOIN="SIGN_AND_BROADCAST_TO_BITCOIN",i.ACTIVATE_VAULT="ACTIVATE_VAULT",i.REFUND_HTLC="REFUND_HTLC",i))(E||{});function N(i,e={}){const{transactionsReady:A,needsWotsKey:T,pendingIngestion:I,canRefund:_,hasProviderTerminalFailure:D}=e;return i===0?D?{contractStatus:i,availableActions:[]}:T?{contractStatus:i,availableActions:["SUBMIT_WOTS_KEY"]}:I===!0&&!A?{contractStatus:i,availableActions:["SIGN_AND_BROADCAST_TO_BITCOIN"]}:I===void 0&&!A?{contractStatus:i,availableActions:[]}:A?{contractStatus:i,availableActions:["SIGN_PAYOUT_TRANSACTIONS"]}:{contractStatus:i,availableActions:[]}:i===1?{contractStatus:i,availableActions:["ACTIVATE_VAULT"]}:i===2?{contractStatus:i,availableActions:[]}:i===3?{contractStatus:i,availableActions:[]}:i===4?{contractStatus:i,availableActions:[]}:i===7?{contractStatus:i,availableActions:_?["REFUND_HTLC"]:[]}:i===5?{contractStatus:i,availableActions:[]}:i===6?{contractStatus:i,availableActions:[]}:{contractStatus:i,availableActions:[]}}function n(i,e){return i.availableActions.includes(e)}function O(i){const{currentBlock:e,createdAtBlock:A,pegInActivationTimeout:T}=i;return e>A+T}exports.ContractStatus=l;exports.PeginAction=E;exports.canPerformAction=n;exports.getPeginProtocolState=N;exports.isActivationDeadlinePassedOnChain=O;
2
+ //# sourceMappingURL=peginState-CBBJw4Za.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"peginState-BijNNT15.cjs","sources":["../src/tbv/core/services/deposit/peginState.ts"],"sourcesContent":["// ============================================================================\n// State Definitions\n// ============================================================================\n\n/**\n * Vault status — combines on-chain contract status (0-4) with indexer-derived\n * statuses (5-7). The contract enum (BTCVaultRegistry.sol BTCVaultStatus) only\n * has: Pending(0), Verified(1), Active(2), Redeemed(3), Expired(4).\n * The indexer maps these and adds extra statuses for UI display.\n *\n * IMPORTANT: With the new contract architecture:\n * - Core vault status (BTCVaultRegistry) does NOT change when used by applications\n * - Vaults remain at ACTIVE status even when used in DeFi positions\n * - Application usage status is tracked separately by each integration controller\n */\nexport enum ContractStatus {\n /** Status 0: Request submitted, waiting for ACKs */\n PENDING = 0,\n /** Status 1: All ACKs collected, ready for secret activation */\n VERIFIED = 1,\n /** Status 2: HTLC secret revealed, vault is active and usable (stays here even when used by apps) */\n ACTIVE = 2,\n /** Status 3: Vault has been redeemed, BTC is claimable */\n REDEEMED = 3,\n /** Status 4 (indexer-only): Vault was liquidated (collateral seized due to unpaid debt) */\n LIQUIDATED = 4,\n /** Status 5 (indexer-only): Vault is invalid — BTC UTXOs were spent in a different transaction */\n INVALID = 5,\n /** Status 6 (indexer-only): Depositor has withdrawn their BTC (redemption complete) */\n DEPOSITOR_WITHDRAWN = 6,\n /** Status 7 (indexer-only): Vault expired due to AckTimeout or ActivationTimeout */\n EXPIRED = 7,\n}\n\n/** Reason why a vault expired */\nexport type ExpirationReason =\n | \"ack_timeout\"\n | \"proof_timeout\"\n | \"activation_timeout\";\n\n// ============================================================================\n// Protocol State Model\n// ============================================================================\n\n/**\n * Available actions user can take\n */\nexport enum PeginAction {\n /** Submit WOTS key (re-derives via wallet `deriveContextHash`) */\n SUBMIT_WOTS_KEY = \"SUBMIT_WOTS_KEY\",\n /** Sign payout transactions */\n SIGN_PAYOUT_TRANSACTIONS = \"SIGN_PAYOUT_TRANSACTIONS\",\n /** Sign and broadcast peg-in transaction to Bitcoin */\n SIGN_AND_BROADCAST_TO_BITCOIN = \"SIGN_AND_BROADCAST_TO_BITCOIN\",\n /** Reveal HTLC secret on Ethereum to activate vault */\n ACTIVATE_VAULT = \"ACTIVATE_VAULT\",\n /** Sign and broadcast HTLC refund transaction for an expired vault */\n REFUND_HTLC = \"REFUND_HTLC\",\n}\n\n/**\n * Protocol-level peg-in state (framework-agnostic)\n */\nexport interface PeginProtocolState {\n /** Smart contract status (source of truth for on-chain state) */\n contractStatus: ContractStatus;\n /** Available user actions (empty array when no action is available) */\n availableActions: PeginAction[];\n}\n\n/**\n * Options for getPeginProtocolState function.\n *\n * All fields represent protocol-level state from the vault provider or\n * on-chain contracts. Client-side tracking (localStorage, polling state)\n * is NOT included — consumers handle that in their own layer.\n */\nexport interface GetPeginProtocolStateOptions {\n /** Whether claim/payout transactions are ready from VP */\n transactionsReady?: boolean;\n /** Whether the vault provider is waiting for the depositor's WOTS public key */\n needsWotsKey?: boolean;\n /** Whether the vault provider hasn't ingested this peg-in yet */\n pendingIngestion?: boolean;\n /** Whether the depositor can refund the HTLC (Pre-PegIn tx available) */\n canRefund?: boolean;\n /** Whether the vault provider reported a terminal failure */\n hasProviderTerminalFailure?: boolean;\n}\n\n// ============================================================================\n// State Machine Logic\n// ============================================================================\n\n/**\n * Determine the current protocol state and available actions based on contract\n * status and vault provider state. Framework-agnostic: returns only\n * protocol-level data with no display labels, messages, or UI concerns.\n *\n * Client-side tracking overrides (e.g. suppressing actions after the user\n * has already acted but on-chain state hasn't caught up) are the caller's\n * responsibility.\n *\n * @param contractStatus - On-chain contract status (source of truth)\n * @param options - Vault provider state\n * @returns Protocol state with available actions\n */\nexport function getPeginProtocolState(\n contractStatus: ContractStatus,\n options: GetPeginProtocolStateOptions = {},\n): PeginProtocolState {\n const {\n transactionsReady,\n needsWotsKey,\n pendingIngestion,\n canRefund,\n hasProviderTerminalFailure,\n } = options;\n\n if (contractStatus === ContractStatus.PENDING) {\n if (hasProviderTerminalFailure) {\n return { contractStatus, availableActions: [] };\n }\n\n if (needsWotsKey) {\n return {\n contractStatus,\n availableActions: [PeginAction.SUBMIT_WOTS_KEY],\n };\n }\n\n if (pendingIngestion === true && !transactionsReady) {\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_AND_BROADCAST_TO_BITCOIN],\n };\n }\n\n if (pendingIngestion === undefined && !transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n if (!transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_PAYOUT_TRANSACTIONS],\n };\n }\n\n if (contractStatus === ContractStatus.VERIFIED) {\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_VAULT],\n };\n }\n\n if (contractStatus === ContractStatus.ACTIVE) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.REDEEMED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.LIQUIDATED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.EXPIRED) {\n return {\n contractStatus,\n availableActions: canRefund ? [PeginAction.REFUND_HTLC] : [],\n };\n }\n\n if (contractStatus === ContractStatus.INVALID) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.DEPOSITOR_WITHDRAWN) {\n return { contractStatus, availableActions: [] };\n }\n\n return { contractStatus, availableActions: [] };\n}\n\n/**\n * Check if a specific action is available in the current state\n */\nexport function canPerformAction(\n state: PeginProtocolState,\n action: PeginAction,\n): boolean {\n return state.availableActions.includes(action);\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","canPerformAction","state","action"],"mappings":"aAeO,IAAKA,GAAAA,IAEVA,EAAAA,EAAA,QAAU,CAAA,EAAV,UAEAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WAEAA,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,CAAC,EAI3DL,IAAmB,EACd,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,EAG1CA,IAAmB,EACd,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,EAGvC,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,CAC9C,CAKO,SAASO,EACdC,EACAC,EACS,CACT,OAAOD,EAAM,iBAAiB,SAASC,CAAM,CAC/C"}
1
+ {"version":3,"file":"peginState-CBBJw4Za.cjs","sources":["../src/tbv/core/services/deposit/peginState.ts"],"sourcesContent":["// ============================================================================\n// State Definitions\n// ============================================================================\n\n/**\n * Vault status — combines on-chain contract status (0-4) with indexer-derived\n * statuses (5-7). The contract enum (BTCVaultRegistry.sol BTCVaultStatus) only\n * has: Pending(0), Verified(1), Active(2), Redeemed(3), Expired(4).\n * The indexer maps these and adds extra statuses for UI display.\n *\n * IMPORTANT: With the new contract architecture:\n * - Core vault status (BTCVaultRegistry) does NOT change when used by applications\n * - Vaults remain at ACTIVE status even when used in DeFi positions\n * - Application usage status is tracked separately by each integration controller\n */\nexport enum ContractStatus {\n /** Status 0: Request submitted, waiting for ACKs */\n PENDING = 0,\n /** Status 1: All ACKs collected, ready for secret activation */\n VERIFIED = 1,\n /** Status 2: HTLC secret revealed, vault is active and usable (stays here even when used by apps) */\n ACTIVE = 2,\n /** Status 3: Vault has been redeemed, BTC is claimable */\n REDEEMED = 3,\n /** Status 4 (indexer-only): Vault was liquidated (collateral seized due to unpaid debt) */\n LIQUIDATED = 4,\n /** Status 5 (indexer-only): Vault is invalid — BTC UTXOs were spent in a different transaction */\n INVALID = 5,\n /** Status 6 (indexer-only): Depositor has withdrawn their BTC (redemption complete) */\n DEPOSITOR_WITHDRAWN = 6,\n /** Status 7 (indexer-only): Vault expired due to AckTimeout or ActivationTimeout */\n EXPIRED = 7,\n}\n\n/** Reason why a vault expired */\nexport type ExpirationReason =\n | \"ack_timeout\"\n | \"proof_timeout\"\n | \"activation_timeout\";\n\n// ============================================================================\n// Protocol State Model\n// ============================================================================\n\n/**\n * Available actions user can take\n */\nexport enum PeginAction {\n /** Submit WOTS key (re-derives via wallet `deriveContextHash`) */\n SUBMIT_WOTS_KEY = \"SUBMIT_WOTS_KEY\",\n /** Sign payout transactions */\n SIGN_PAYOUT_TRANSACTIONS = \"SIGN_PAYOUT_TRANSACTIONS\",\n /** Sign and broadcast peg-in transaction to Bitcoin */\n SIGN_AND_BROADCAST_TO_BITCOIN = \"SIGN_AND_BROADCAST_TO_BITCOIN\",\n /** Reveal HTLC secret on Ethereum to activate vault */\n ACTIVATE_VAULT = \"ACTIVATE_VAULT\",\n /** Sign and broadcast HTLC refund transaction for an expired vault */\n REFUND_HTLC = \"REFUND_HTLC\",\n}\n\n/**\n * Protocol-level peg-in state (framework-agnostic)\n */\nexport interface PeginProtocolState {\n /** Smart contract status (source of truth for on-chain state) */\n contractStatus: ContractStatus;\n /** Available user actions (empty array when no action is available) */\n availableActions: PeginAction[];\n}\n\n/**\n * Options for getPeginProtocolState function.\n *\n * All fields represent protocol-level state from the vault provider or\n * on-chain contracts. Client-side tracking (localStorage, polling state)\n * is NOT included — consumers handle that in their own layer.\n */\nexport interface GetPeginProtocolStateOptions {\n /** Whether claim/payout transactions are ready from VP */\n transactionsReady?: boolean;\n /** Whether the vault provider is waiting for the depositor's WOTS public key */\n needsWotsKey?: boolean;\n /** Whether the vault provider hasn't ingested this peg-in yet */\n pendingIngestion?: boolean;\n /** Whether the depositor can refund the HTLC (Pre-PegIn tx available) */\n canRefund?: boolean;\n /** Whether the vault provider reported a terminal failure */\n hasProviderTerminalFailure?: boolean;\n}\n\n// ============================================================================\n// State Machine Logic\n// ============================================================================\n\n/**\n * Determine the current protocol state and available actions based on contract\n * status and vault provider state. Framework-agnostic: returns only\n * protocol-level data with no display labels, messages, or UI concerns.\n *\n * Client-side tracking overrides (e.g. suppressing actions after the user\n * has already acted but on-chain state hasn't caught up) are the caller's\n * responsibility.\n *\n * @param contractStatus - On-chain contract status (source of truth)\n * @param options - Vault provider state\n * @returns Protocol state with available actions\n */\nexport function getPeginProtocolState(\n contractStatus: ContractStatus,\n options: GetPeginProtocolStateOptions = {},\n): PeginProtocolState {\n const {\n transactionsReady,\n needsWotsKey,\n pendingIngestion,\n canRefund,\n hasProviderTerminalFailure,\n } = options;\n\n if (contractStatus === ContractStatus.PENDING) {\n if (hasProviderTerminalFailure) {\n return { contractStatus, availableActions: [] };\n }\n\n if (needsWotsKey) {\n return {\n contractStatus,\n availableActions: [PeginAction.SUBMIT_WOTS_KEY],\n };\n }\n\n if (pendingIngestion === true && !transactionsReady) {\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_AND_BROADCAST_TO_BITCOIN],\n };\n }\n\n if (pendingIngestion === undefined && !transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n if (!transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_PAYOUT_TRANSACTIONS],\n };\n }\n\n if (contractStatus === ContractStatus.VERIFIED) {\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_VAULT],\n };\n }\n\n if (contractStatus === ContractStatus.ACTIVE) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.REDEEMED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.LIQUIDATED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.EXPIRED) {\n return {\n contractStatus,\n availableActions: canRefund ? [PeginAction.REFUND_HTLC] : [],\n };\n }\n\n if (contractStatus === ContractStatus.INVALID) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.DEPOSITOR_WITHDRAWN) {\n return { contractStatus, availableActions: [] };\n }\n\n return { contractStatus, availableActions: [] };\n}\n\n/**\n * Check if a specific action is available in the current state\n */\nexport function canPerformAction(\n state: PeginProtocolState,\n action: PeginAction,\n): boolean {\n return state.availableActions.includes(action);\n}\n\n// ============================================================================\n// Activation deadline\n// ============================================================================\n\n/**\n * Whether a vault's on-chain activation window has closed. Mirrors the\n * BTCVaultRegistry check that reverts `ActivationDeadlineExpired`:\n * `block.number > createdAt + pegInActivationTimeout` — strict `>`, so a\n * boundary-equal block is NOT expired. All values are Ethereum block numbers.\n */\nexport function isActivationDeadlinePassedOnChain(params: {\n currentBlock: bigint;\n createdAtBlock: bigint;\n pegInActivationTimeout: bigint;\n}): boolean {\n const { currentBlock, createdAtBlock, pegInActivationTimeout } = params;\n return currentBlock > createdAtBlock + pegInActivationTimeout;\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","canPerformAction","state","action","isActivationDeadlinePassedOnChain","params","currentBlock","createdAtBlock","pegInActivationTimeout"],"mappings":"aAeO,IAAKA,GAAAA,IAEVA,EAAAA,EAAA,QAAU,CAAA,EAAV,UAEAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WAEAA,EAAAA,EAAA,OAAS,CAAA,EAAT,SAEAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WAEAA,EAAAA,EAAA,WAAa,CAAA,EAAb,aAEAA,EAAAA,EAAA,QAAU,CAAA,EAAV,UAEAA,EAAAA,EAAA,oBAAsB,CAAA,EAAtB,sBAEAA,EAAAA,EAAA,QAAU,CAAA,EAAV,UAhBUA,IAAAA,GAAA,CAAA,CAAA,EAgCAC,GAAAA,IAEVA,EAAA,gBAAkB,kBAElBA,EAAA,yBAA2B,2BAE3BA,EAAA,8BAAgC,gCAEhCA,EAAA,eAAiB,iBAEjBA,EAAA,YAAc,cAVJA,IAAAA,GAAA,CAAA,CAAA,EA4DL,SAASC,EACdC,EACAC,EAAwC,GACpB,CACpB,KAAM,CACJ,kBAAAC,EACA,aAAAC,EACA,iBAAAC,EACA,UAAAC,EACA,2BAAAC,CAAA,EACEL,EAEJ,OAAID,IAAmB,EACjBM,EACK,CAAE,eAAAN,EAAgB,iBAAkB,EAAC,EAG1CG,EACK,CACL,eAAAH,EACA,iBAAkB,CAAC,iBAAA,CAA2B,EAI9CI,IAAqB,IAAQ,CAACF,EACzB,CACL,eAAAF,EACA,iBAAkB,CAAC,+BAAA,CAAyC,EAI5DI,IAAqB,QAAa,CAACF,EAC9B,CAAE,eAAAF,EAAgB,iBAAkB,EAAC,EAGzCE,EAIE,CACL,eAAAF,EACA,iBAAkB,CAAC,0BAAA,CAAoC,EALhD,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,EAS5CA,IAAmB,EACd,CACL,eAAAA,EACA,iBAAkB,CAAC,gBAAA,CAA0B,EAI7CA,IAAmB,EACd,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,EAG1CA,IAAmB,EACd,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,EAG1CA,IAAmB,EACd,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,EAG1CA,IAAmB,EACd,CACL,eAAAA,EACA,iBAAkBK,EAAY,CAAC,eAA2B,CAAA,CAAC,EAI3DL,IAAmB,EACd,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,EAG1CA,IAAmB,EACd,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,EAGvC,CAAE,eAAAA,EAAgB,iBAAkB,EAAC,CAC9C,CAKO,SAASO,EACdC,EACAC,EACS,CACT,OAAOD,EAAM,iBAAiB,SAASC,CAAM,CAC/C,CAYO,SAASC,EAAkCC,EAItC,CACV,KAAM,CAAE,aAAAC,EAAc,eAAAC,EAAgB,uBAAAC,CAAA,EAA2BH,EACjE,OAAOC,EAAeC,EAAiBC,CACzC"}
@@ -1,2 +1,2 @@
1
- "use strict";var b=Object.defineProperty;var T=(e,n,t)=>n in e?b(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var l=(e,n,t)=>T(e,typeof n!="symbol"?n+"":n,t);const d=require("bitcoinjs-lib"),x=require("buffer"),U=require("./bitcoin-CHfKAhcI.cjs"),$=require("./peginState-BijNNT15.cjs");class p extends Error{constructor(t){const r=t.length,a=r===1?"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.":`${r} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;super(a);l(this,"missingUtxos");this.name="UtxoNotAvailableError",this.missingUtxos=t}}function h(e){const n=e.startsWith("0x")?e.slice(2):e;let t;try{t=d.Transaction.fromHex(n)}catch(r){throw new Error(`Failed to parse BTC transaction: ${r instanceof Error?r.message:String(r)}`)}return t.ins.map(r=>({txid:x.Buffer.from(r.hash).reverse().toString("hex"),vout:r.index}))}function v(e,n){const t=h(e);if(t.length===0)throw new Error("Transaction has no inputs");const r=new Set;for(const o of t){const i=`${o.txid.toLowerCase()}:${o.vout}`;if(r.has(i))throw new Error(`Transaction contains duplicate input ${o.txid}:${o.vout}. This would produce an invalid Bitcoin transaction.`);r.add(i)}const a=new Set(n.map(o=>`${o.txid.toLowerCase()}:${o.vout}`)),c=[];for(const o of t){const i=`${o.txid.toLowerCase()}:${o.vout}`;a.has(i)||c.push({txid:o.txid,vout:o.vout})}return{allAvailable:c.length===0,missingUtxos:c,totalInputs:t.length}}function S(e,n){const t=v(e,n);if(!t.allAvailable)throw new p(t.missingUtxos)}function y(e){try{return d.Transaction.fromHex(U.stripHexPrefix(e)).ins.map(t=>({txid:x.Buffer.from(t.hash).reverse().toString("hex"),vout:t.index}))}catch{return[]}}function f(e){return`${e.txid.toLowerCase()}:${e.vout}`}function A(e){const{selectedOutpoints:n,vaults:t=[],pendingPegins:r=[]}=e,a=new Set(n.map(f));if(a.size===0)return[];const c=new Set,o=new Set,i=(s,g)=>{if(!s)return;const u=s.toLowerCase();if(c.has(u))return;c.add(u);const w=y(g);for(const m of w)if(a.has(f(m))){o.add(s);return}};for(const s of t)s.status===$.ContractStatus.PENDING&&i(s.id,s.unsignedPrePeginTx);for(const s of r)s.unsignedTxHex&&i(s.id,s.unsignedTxHex);return Array.from(o)}exports.UtxoNotAvailableError=p;exports.assertUtxosAvailable=S;exports.extractInputsFromTransaction=h;exports.findOverlappingPendingVaults=A;exports.validateUtxosAvailable=v;
2
- //# sourceMappingURL=reservation-xTL2a9Q-.cjs.map
1
+ "use strict";var b=Object.defineProperty;var T=(e,n,t)=>n in e?b(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var l=(e,n,t)=>T(e,typeof n!="symbol"?n+"":n,t);const d=require("bitcoinjs-lib"),x=require("buffer"),U=require("./bitcoin-CHfKAhcI.cjs"),$=require("./peginState-CBBJw4Za.cjs");class p extends Error{constructor(t){const r=t.length,a=r===1?"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.":`${r} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;super(a);l(this,"missingUtxos");this.name="UtxoNotAvailableError",this.missingUtxos=t}}function h(e){const n=e.startsWith("0x")?e.slice(2):e;let t;try{t=d.Transaction.fromHex(n)}catch(r){throw new Error(`Failed to parse BTC transaction: ${r instanceof Error?r.message:String(r)}`)}return t.ins.map(r=>({txid:x.Buffer.from(r.hash).reverse().toString("hex"),vout:r.index}))}function v(e,n){const t=h(e);if(t.length===0)throw new Error("Transaction has no inputs");const r=new Set;for(const o of t){const i=`${o.txid.toLowerCase()}:${o.vout}`;if(r.has(i))throw new Error(`Transaction contains duplicate input ${o.txid}:${o.vout}. This would produce an invalid Bitcoin transaction.`);r.add(i)}const a=new Set(n.map(o=>`${o.txid.toLowerCase()}:${o.vout}`)),c=[];for(const o of t){const i=`${o.txid.toLowerCase()}:${o.vout}`;a.has(i)||c.push({txid:o.txid,vout:o.vout})}return{allAvailable:c.length===0,missingUtxos:c,totalInputs:t.length}}function S(e,n){const t=v(e,n);if(!t.allAvailable)throw new p(t.missingUtxos)}function y(e){try{return d.Transaction.fromHex(U.stripHexPrefix(e)).ins.map(t=>({txid:x.Buffer.from(t.hash).reverse().toString("hex"),vout:t.index}))}catch{return[]}}function f(e){return`${e.txid.toLowerCase()}:${e.vout}`}function A(e){const{selectedOutpoints:n,vaults:t=[],pendingPegins:r=[]}=e,a=new Set(n.map(f));if(a.size===0)return[];const c=new Set,o=new Set,i=(s,g)=>{if(!s)return;const u=s.toLowerCase();if(c.has(u))return;c.add(u);const w=y(g);for(const m of w)if(a.has(f(m))){o.add(s);return}};for(const s of t)s.status===$.ContractStatus.PENDING&&i(s.id,s.unsignedPrePeginTx);for(const s of r)s.unsignedTxHex&&i(s.id,s.unsignedTxHex);return Array.from(o)}exports.UtxoNotAvailableError=p;exports.assertUtxosAvailable=S;exports.extractInputsFromTransaction=h;exports.findOverlappingPendingVaults=A;exports.validateUtxosAvailable=v;
2
+ //# sourceMappingURL=reservation-ClEs2X0H.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"reservation-xTL2a9Q-.cjs","sources":["../src/tbv/core/utils/utxo/availability.ts","../src/tbv/core/utils/utxo/reservation.ts"],"sourcesContent":["/**\n * UTXO Availability Validation\n *\n * Validates that UTXOs referenced in a pre-pegin transaction are still unspent\n * BEFORE asking the user to sign. This prevents wasted signing effort when\n * UTXOs have already been spent by unrelated transactions.\n *\n * These functions are pure — they accept pre-fetched UTXOs and perform no I/O.\n * The vault service wrapper is responsible for fetching UTXOs from the mempool.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Reference to a Bitcoin UTXO by its outpoint (txid + vout).\n *\n * Used by the availability check to compare a Pre-PegIn transaction's\n * declared inputs against the wallet's current spendable set. Txids are\n * compared case-insensitively; callers should treat the txid as opaque\n * lowercase hex.\n */\nexport interface UtxoRef {\n txid: string;\n vout: number;\n}\n\n/**\n * Information about a missing/spent UTXO.\n */\nexport interface MissingUtxoInfo {\n /** Transaction ID of the missing UTXO */\n txid: string;\n /** Output index of the missing UTXO */\n vout: number;\n}\n\n/**\n * Result of UTXO validation.\n */\nexport interface UtxoValidationResult {\n /** Whether all UTXOs are still available */\n allAvailable: boolean;\n /** List of missing UTXOs (if any) */\n missingUtxos: MissingUtxoInfo[];\n /** Total number of inputs checked */\n totalInputs: number;\n}\n\n/**\n * Error thrown when UTXOs are not available.\n */\nexport class UtxoNotAvailableError extends Error {\n public readonly missingUtxos: MissingUtxoInfo[];\n\n constructor(missingUtxos: MissingUtxoInfo[]) {\n const count = missingUtxos.length;\n const message =\n count === 1\n ? \"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.\"\n : `${count} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;\n\n super(message);\n this.name = \"UtxoNotAvailableError\";\n this.missingUtxos = missingUtxos;\n }\n}\n\n/**\n * Extract input references (txid:vout) from an unsigned transaction.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @returns Array of input references\n */\nexport function extractInputsFromTransaction(\n unsignedTxHex: string,\n): Array<{ txid: string; vout: number }> {\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n\n let tx: Transaction;\n try {\n tx = Transaction.fromHex(cleanHex);\n } catch (error) {\n throw new Error(\n `Failed to parse BTC transaction: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n return tx.ins.map((input) => ({\n // Bitcoin stores txid in reverse byte order\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n}\n\n/**\n * Validate that all UTXOs in a transaction are still available.\n *\n * Pure function — accepts pre-fetched UTXOs instead of making network calls.\n * This should be called BEFORE signing to avoid wasting user effort\n * signing a transaction that will fail to broadcast.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @returns Validation result with missing UTXO details\n */\nexport function validateUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): UtxoValidationResult {\n const inputs = extractInputsFromTransaction(unsignedTxHex);\n\n if (inputs.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Detect duplicate inputs (same txid:vout referenced more than once).\n // This would produce an invalid Bitcoin transaction.\n const inputKeys = new Set<string>();\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (inputKeys.has(key)) {\n throw new Error(\n `Transaction contains duplicate input ${input.txid}:${input.vout}. ` +\n `This would produce an invalid Bitcoin transaction.`,\n );\n }\n inputKeys.add(key);\n }\n\n // Set of available outpoints for O(1) lookup. Lowercased so the comparison\n // is case-insensitive against whatever case the wallet returned.\n const availableSet = new Set(\n availableUtxos.map((utxo) => `${utxo.txid.toLowerCase()}:${utxo.vout}`),\n );\n\n // Check which inputs are missing\n const missingUtxos: MissingUtxoInfo[] = [];\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (!availableSet.has(key)) {\n missingUtxos.push({\n txid: input.txid,\n vout: input.vout,\n });\n }\n }\n\n return {\n allAvailable: missingUtxos.length === 0,\n missingUtxos,\n totalInputs: inputs.length,\n };\n}\n\n/**\n * Validate UTXOs and throw if any are not available.\n *\n * Pure convenience function that combines validation and error throwing.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @throws UtxoNotAvailableError if any UTXOs are not available\n * @throws Error if validation fails\n */\nexport function assertUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): void {\n const result = validateUtxosAvailable(unsignedTxHex, availableUtxos);\n\n if (!result.allAvailable) {\n throw new UtxoNotAvailableError(result.missingUtxos);\n }\n}\n","/**\n * Pending-vault outpoint overlap detection.\n *\n * Given the depositor's pending vaults (indexer + local cache) and the\n * outpoints a new deposit's coin selector picked, return the set of\n * pending vault ids whose Pre-PegIn BTC tx shares an input. Advisory\n * only — used to warn the user before signing.\n *\n * Only `PENDING` vaults contribute: VERIFIED+ have their Pre-PegIn\n * already confirmed on-chain, so those inputs cannot still appear in\n * the wallet's spendable set.\n */\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { ContractStatus } from \"../../services/deposit/peginState\";\n\nimport { type UtxoRef } from \"./availability\";\n\n/** Locally-known pending pegin. `id` is the bytes32 vault id. */\nexport interface PendingPeginLike {\n id?: string;\n unsignedTxHex?: string;\n}\n\n/** On-chain vault row from the indexer. */\nexport interface VaultLike {\n id?: string;\n status: number;\n unsignedPrePeginTx: string;\n}\n\nexport interface FindOverlappingPendingVaultsParams {\n selectedOutpoints: ReadonlyArray<UtxoRef>;\n vaults?: ReadonlyArray<VaultLike>;\n pendingPegins?: ReadonlyArray<PendingPeginLike>;\n}\n\nfunction extractInputUtxoRefs(txHex: string): UtxoRef[] {\n try {\n const tx = Transaction.fromHex(stripHexPrefix(txHex));\n return tx.ins.map((input) => ({\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n } catch {\n return [];\n }\n}\n\nfunction outpointKey(o: UtxoRef): string {\n return `${o.txid.toLowerCase()}:${o.vout}`;\n}\n\n/**\n * Return the ids of pending vaults whose committed Pre-PegIn inputs\n * overlap any of the just-selected outpoints. On-chain `PENDING` vaults\n * take precedence over a same-id local pegin entry.\n */\nexport function findOverlappingPendingVaults(\n params: FindOverlappingPendingVaultsParams,\n): string[] {\n const { selectedOutpoints, vaults = [], pendingPegins = [] } = params;\n\n const selectedSet = new Set(selectedOutpoints.map(outpointKey));\n if (selectedSet.size === 0) return [];\n\n const seenIds = new Set<string>();\n const impacted = new Set<string>();\n\n const consider = (id: string | undefined, txHex: string): void => {\n if (!id) return;\n const idLower = id.toLowerCase();\n if (seenIds.has(idLower)) return;\n seenIds.add(idLower);\n const inputs = extractInputUtxoRefs(txHex);\n for (const input of inputs) {\n if (selectedSet.has(outpointKey(input))) {\n impacted.add(id);\n return;\n }\n }\n };\n\n // On-chain wins on id collision.\n for (const v of vaults) {\n if (v.status !== ContractStatus.PENDING) continue;\n consider(v.id, v.unsignedPrePeginTx);\n }\n for (const p of pendingPegins) {\n if (!p.unsignedTxHex) continue;\n consider(p.id, p.unsignedTxHex);\n }\n\n return Array.from(impacted);\n}\n"],"names":["UtxoNotAvailableError","missingUtxos","count","message","__publicField","extractInputsFromTransaction","unsignedTxHex","cleanHex","tx","Transaction","error","input","Buffer","validateUtxosAvailable","availableUtxos","inputs","inputKeys","key","availableSet","utxo","assertUtxosAvailable","result","extractInputUtxoRefs","txHex","stripHexPrefix","outpointKey","o","findOverlappingPendingVaults","params","selectedOutpoints","vaults","pendingPegins","selectedSet","seenIds","impacted","consider","id","idLower","v","ContractStatus","p"],"mappings":"iTAoDO,MAAMA,UAA8B,KAAM,CAG/C,YAAYC,EAAiC,CAC3C,MAAMC,EAAQD,EAAa,OACrBE,EACJD,IAAU,EACN,4JACA,GAAGA,CAAK,qIAEd,MAAMC,CAAO,EATCC,EAAA,qBAUd,KAAK,KAAO,wBACZ,KAAK,aAAeH,CACtB,CACF,CAQO,SAASI,EACdC,EACuC,CACvC,MAAMC,EAAWD,EAAc,WAAW,IAAI,EAC1CA,EAAc,MAAM,CAAC,EACrBA,EAEJ,IAAIE,EACJ,GAAI,CACFA,EAAKC,EAAAA,YAAY,QAAQF,CAAQ,CACnC,OAASG,EAAO,CACd,MAAM,IAAI,MACR,oCAAoCA,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAA,CAE9F,CAEA,OAAOF,EAAG,IAAI,IAAKG,IAAW,CAE5B,KAAMC,EAAAA,OAAO,KAAKD,EAAM,IAAI,EAAE,QAAA,EAAU,SAAS,KAAK,EACtD,KAAMA,EAAM,KAAA,EACZ,CACJ,CAaO,SAASE,EACdP,EACAQ,EACsB,CACtB,MAAMC,EAASV,EAA6BC,CAAa,EAEzD,GAAIS,EAAO,SAAW,EACpB,MAAM,IAAI,MAAM,2BAA2B,EAK7C,MAAMC,MAAgB,IACtB,UAAWL,KAASI,EAAQ,CAC1B,MAAME,EAAM,GAAGN,EAAM,KAAK,aAAa,IAAIA,EAAM,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EAAY,OAAS,EAAG,MAAO,CAAA,EAEnC,MAAMC,MAAc,IACdC,MAAe,IAEfC,EAAW,CAACC,EAAwBb,IAAwB,CAChE,GAAI,CAACa,EAAI,OACT,MAAMC,EAAUD,EAAG,YAAA,EACnB,GAAIH,EAAQ,IAAII,CAAO,EAAG,OAC1BJ,EAAQ,IAAII,CAAO,EACnB,MAAMtB,EAASO,EAAqBC,CAAK,EACzC,UAAWZ,KAASI,EAClB,GAAIiB,EAAY,IAAIP,EAAYd,CAAK,CAAC,EAAG,CACvCuB,EAAS,IAAIE,CAAE,EACf,MACF,CAEJ,EAGA,UAAWE,KAAKR,EACVQ,EAAE,SAAWC,EAAAA,eAAe,SAChCJ,EAASG,EAAE,GAAIA,EAAE,kBAAkB,EAErC,UAAWE,KAAKT,EACTS,EAAE,eACPL,EAASK,EAAE,GAAIA,EAAE,aAAa,EAGhC,OAAO,MAAM,KAAKN,CAAQ,CAC5B"}
1
+ {"version":3,"file":"reservation-ClEs2X0H.cjs","sources":["../src/tbv/core/utils/utxo/availability.ts","../src/tbv/core/utils/utxo/reservation.ts"],"sourcesContent":["/**\n * UTXO Availability Validation\n *\n * Validates that UTXOs referenced in a pre-pegin transaction are still unspent\n * BEFORE asking the user to sign. This prevents wasted signing effort when\n * UTXOs have already been spent by unrelated transactions.\n *\n * These functions are pure — they accept pre-fetched UTXOs and perform no I/O.\n * The vault service wrapper is responsible for fetching UTXOs from the mempool.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Reference to a Bitcoin UTXO by its outpoint (txid + vout).\n *\n * Used by the availability check to compare a Pre-PegIn transaction's\n * declared inputs against the wallet's current spendable set. Txids are\n * compared case-insensitively; callers should treat the txid as opaque\n * lowercase hex.\n */\nexport interface UtxoRef {\n txid: string;\n vout: number;\n}\n\n/**\n * Information about a missing/spent UTXO.\n */\nexport interface MissingUtxoInfo {\n /** Transaction ID of the missing UTXO */\n txid: string;\n /** Output index of the missing UTXO */\n vout: number;\n}\n\n/**\n * Result of UTXO validation.\n */\nexport interface UtxoValidationResult {\n /** Whether all UTXOs are still available */\n allAvailable: boolean;\n /** List of missing UTXOs (if any) */\n missingUtxos: MissingUtxoInfo[];\n /** Total number of inputs checked */\n totalInputs: number;\n}\n\n/**\n * Error thrown when UTXOs are not available.\n */\nexport class UtxoNotAvailableError extends Error {\n public readonly missingUtxos: MissingUtxoInfo[];\n\n constructor(missingUtxos: MissingUtxoInfo[]) {\n const count = missingUtxos.length;\n const message =\n count === 1\n ? \"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.\"\n : `${count} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;\n\n super(message);\n this.name = \"UtxoNotAvailableError\";\n this.missingUtxos = missingUtxos;\n }\n}\n\n/**\n * Extract input references (txid:vout) from an unsigned transaction.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @returns Array of input references\n */\nexport function extractInputsFromTransaction(\n unsignedTxHex: string,\n): Array<{ txid: string; vout: number }> {\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n\n let tx: Transaction;\n try {\n tx = Transaction.fromHex(cleanHex);\n } catch (error) {\n throw new Error(\n `Failed to parse BTC transaction: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n return tx.ins.map((input) => ({\n // Bitcoin stores txid in reverse byte order\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n}\n\n/**\n * Validate that all UTXOs in a transaction are still available.\n *\n * Pure function — accepts pre-fetched UTXOs instead of making network calls.\n * This should be called BEFORE signing to avoid wasting user effort\n * signing a transaction that will fail to broadcast.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @returns Validation result with missing UTXO details\n */\nexport function validateUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): UtxoValidationResult {\n const inputs = extractInputsFromTransaction(unsignedTxHex);\n\n if (inputs.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Detect duplicate inputs (same txid:vout referenced more than once).\n // This would produce an invalid Bitcoin transaction.\n const inputKeys = new Set<string>();\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (inputKeys.has(key)) {\n throw new Error(\n `Transaction contains duplicate input ${input.txid}:${input.vout}. ` +\n `This would produce an invalid Bitcoin transaction.`,\n );\n }\n inputKeys.add(key);\n }\n\n // Set of available outpoints for O(1) lookup. Lowercased so the comparison\n // is case-insensitive against whatever case the wallet returned.\n const availableSet = new Set(\n availableUtxos.map((utxo) => `${utxo.txid.toLowerCase()}:${utxo.vout}`),\n );\n\n // Check which inputs are missing\n const missingUtxos: MissingUtxoInfo[] = [];\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (!availableSet.has(key)) {\n missingUtxos.push({\n txid: input.txid,\n vout: input.vout,\n });\n }\n }\n\n return {\n allAvailable: missingUtxos.length === 0,\n missingUtxos,\n totalInputs: inputs.length,\n };\n}\n\n/**\n * Validate UTXOs and throw if any are not available.\n *\n * Pure convenience function that combines validation and error throwing.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @throws UtxoNotAvailableError if any UTXOs are not available\n * @throws Error if validation fails\n */\nexport function assertUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): void {\n const result = validateUtxosAvailable(unsignedTxHex, availableUtxos);\n\n if (!result.allAvailable) {\n throw new UtxoNotAvailableError(result.missingUtxos);\n }\n}\n","/**\n * Pending-vault outpoint overlap detection.\n *\n * Given the depositor's pending vaults (indexer + local cache) and the\n * outpoints a new deposit's coin selector picked, return the set of\n * pending vault ids whose Pre-PegIn BTC tx shares an input. Advisory\n * only — used to warn the user before signing.\n *\n * Only `PENDING` vaults contribute: VERIFIED+ have their Pre-PegIn\n * already confirmed on-chain, so those inputs cannot still appear in\n * the wallet's spendable set.\n */\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { ContractStatus } from \"../../services/deposit/peginState\";\n\nimport { type UtxoRef } from \"./availability\";\n\n/** Locally-known pending pegin. `id` is the bytes32 vault id. */\nexport interface PendingPeginLike {\n id?: string;\n unsignedTxHex?: string;\n}\n\n/** On-chain vault row from the indexer. */\nexport interface VaultLike {\n id?: string;\n status: number;\n unsignedPrePeginTx: string;\n}\n\nexport interface FindOverlappingPendingVaultsParams {\n selectedOutpoints: ReadonlyArray<UtxoRef>;\n vaults?: ReadonlyArray<VaultLike>;\n pendingPegins?: ReadonlyArray<PendingPeginLike>;\n}\n\nfunction extractInputUtxoRefs(txHex: string): UtxoRef[] {\n try {\n const tx = Transaction.fromHex(stripHexPrefix(txHex));\n return tx.ins.map((input) => ({\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n } catch {\n return [];\n }\n}\n\nfunction outpointKey(o: UtxoRef): string {\n return `${o.txid.toLowerCase()}:${o.vout}`;\n}\n\n/**\n * Return the ids of pending vaults whose committed Pre-PegIn inputs\n * overlap any of the just-selected outpoints. On-chain `PENDING` vaults\n * take precedence over a same-id local pegin entry.\n */\nexport function findOverlappingPendingVaults(\n params: FindOverlappingPendingVaultsParams,\n): string[] {\n const { selectedOutpoints, vaults = [], pendingPegins = [] } = params;\n\n const selectedSet = new Set(selectedOutpoints.map(outpointKey));\n if (selectedSet.size === 0) return [];\n\n const seenIds = new Set<string>();\n const impacted = new Set<string>();\n\n const consider = (id: string | undefined, txHex: string): void => {\n if (!id) return;\n const idLower = id.toLowerCase();\n if (seenIds.has(idLower)) return;\n seenIds.add(idLower);\n const inputs = extractInputUtxoRefs(txHex);\n for (const input of inputs) {\n if (selectedSet.has(outpointKey(input))) {\n impacted.add(id);\n return;\n }\n }\n };\n\n // On-chain wins on id collision.\n for (const v of vaults) {\n if (v.status !== ContractStatus.PENDING) continue;\n consider(v.id, v.unsignedPrePeginTx);\n }\n for (const p of pendingPegins) {\n if (!p.unsignedTxHex) continue;\n consider(p.id, p.unsignedTxHex);\n }\n\n return Array.from(impacted);\n}\n"],"names":["UtxoNotAvailableError","missingUtxos","count","message","__publicField","extractInputsFromTransaction","unsignedTxHex","cleanHex","tx","Transaction","error","input","Buffer","validateUtxosAvailable","availableUtxos","inputs","inputKeys","key","availableSet","utxo","assertUtxosAvailable","result","extractInputUtxoRefs","txHex","stripHexPrefix","outpointKey","o","findOverlappingPendingVaults","params","selectedOutpoints","vaults","pendingPegins","selectedSet","seenIds","impacted","consider","id","idLower","v","ContractStatus","p"],"mappings":"iTAoDO,MAAMA,UAA8B,KAAM,CAG/C,YAAYC,EAAiC,CAC3C,MAAMC,EAAQD,EAAa,OACrBE,EACJD,IAAU,EACN,4JACA,GAAGA,CAAK,qIAEd,MAAMC,CAAO,EATCC,EAAA,qBAUd,KAAK,KAAO,wBACZ,KAAK,aAAeH,CACtB,CACF,CAQO,SAASI,EACdC,EACuC,CACvC,MAAMC,EAAWD,EAAc,WAAW,IAAI,EAC1CA,EAAc,MAAM,CAAC,EACrBA,EAEJ,IAAIE,EACJ,GAAI,CACFA,EAAKC,EAAAA,YAAY,QAAQF,CAAQ,CACnC,OAASG,EAAO,CACd,MAAM,IAAI,MACR,oCAAoCA,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAA,CAE9F,CAEA,OAAOF,EAAG,IAAI,IAAKG,IAAW,CAE5B,KAAMC,EAAAA,OAAO,KAAKD,EAAM,IAAI,EAAE,QAAA,EAAU,SAAS,KAAK,EACtD,KAAMA,EAAM,KAAA,EACZ,CACJ,CAaO,SAASE,EACdP,EACAQ,EACsB,CACtB,MAAMC,EAASV,EAA6BC,CAAa,EAEzD,GAAIS,EAAO,SAAW,EACpB,MAAM,IAAI,M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AC,EAAS,CAAA,EAAI,cAAAC,EAAgB,CAAA,GAAOH,EAEzDI,EAAc,IAAI,IAAIH,EAAkB,IAAIJ,CAAW,CAAC,EAC9D,GAAIO,EAAY,OAAS,EAAG,MAAO,CAAA,EAEnC,MAAMC,MAAc,IACdC,MAAe,IAEfC,EAAW,CAACC,EAAwBb,IAAwB,CAChE,GAAI,CAACa,EAAI,OACT,MAAMC,EAAUD,EAAG,YAAA,EACnB,GAAIH,EAAQ,IAAII,CAAO,EAAG,OAC1BJ,EAAQ,IAAII,CAAO,EACnB,MAAMtB,EAASO,EAAqBC,CAAK,EACzC,UAAWZ,KAASI,EAClB,GAAIiB,EAAY,IAAIP,EAAYd,CAAK,CAAC,EAAG,CACvCuB,EAAS,IAAIE,CAAE,EACf,MACF,CAEJ,EAGA,UAAWE,KAAKR,EACVQ,EAAE,SAAWC,EAAAA,eAAe,SAChCJ,EAASG,EAAE,GAAIA,EAAE,kBAAkB,EAErC,UAAWE,KAAKT,EACTS,EAAE,eACPL,EAASK,EAAE,GAAIA,EAAE,aAAa,EAGhC,OAAO,MAAM,KAAKN,CAAQ,CAC5B"}
@@ -4,7 +4,7 @@ var f = (e, n, t) => g(e, typeof n != "symbol" ? n + "" : n, t);
4
4
  import { Transaction as p } from "bitcoinjs-lib";
5
5
  import { Buffer as d } from "buffer";
6
6
  import { s as w } from "./bitcoin-B5aNKtsk.js";
7
- import { C as T } from "./peginState-CBAlxgXk.js";
7
+ import { C as T } from "./peginState-BB81JI6I.js";
8
8
  class U extends Error {
9
9
  constructor(t) {
10
10
  const r = t.length, a = r === 1 ? "The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO." : `${r} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;
@@ -104,4 +104,4 @@ export {
104
104
  L as f,
105
105
  b as v
106
106
  };
107
- //# sourceMappingURL=reservation-BxvKbQH2.js.map
107
+ //# sourceMappingURL=reservation-cHDRn4DA.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reservation-BxvKbQH2.js","sources":["../src/tbv/core/utils/utxo/availability.ts","../src/tbv/core/utils/utxo/reservation.ts"],"sourcesContent":["/**\n * UTXO Availability Validation\n *\n * Validates that UTXOs referenced in a pre-pegin transaction are still unspent\n * BEFORE asking the user to sign. This prevents wasted signing effort when\n * UTXOs have already been spent by unrelated transactions.\n *\n * These functions are pure — they accept pre-fetched UTXOs and perform no I/O.\n * The vault service wrapper is responsible for fetching UTXOs from the mempool.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Reference to a Bitcoin UTXO by its outpoint (txid + vout).\n *\n * Used by the availability check to compare a Pre-PegIn transaction's\n * declared inputs against the wallet's current spendable set. Txids are\n * compared case-insensitively; callers should treat the txid as opaque\n * lowercase hex.\n */\nexport interface UtxoRef {\n txid: string;\n vout: number;\n}\n\n/**\n * Information about a missing/spent UTXO.\n */\nexport interface MissingUtxoInfo {\n /** Transaction ID of the missing UTXO */\n txid: string;\n /** Output index of the missing UTXO */\n vout: number;\n}\n\n/**\n * Result of UTXO validation.\n */\nexport interface UtxoValidationResult {\n /** Whether all UTXOs are still available */\n allAvailable: boolean;\n /** List of missing UTXOs (if any) */\n missingUtxos: MissingUtxoInfo[];\n /** Total number of inputs checked */\n totalInputs: number;\n}\n\n/**\n * Error thrown when UTXOs are not available.\n */\nexport class UtxoNotAvailableError extends Error {\n public readonly missingUtxos: MissingUtxoInfo[];\n\n constructor(missingUtxos: MissingUtxoInfo[]) {\n const count = missingUtxos.length;\n const message =\n count === 1\n ? \"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.\"\n : `${count} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;\n\n super(message);\n this.name = \"UtxoNotAvailableError\";\n this.missingUtxos = missingUtxos;\n }\n}\n\n/**\n * Extract input references (txid:vout) from an unsigned transaction.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @returns Array of input references\n */\nexport function extractInputsFromTransaction(\n unsignedTxHex: string,\n): Array<{ txid: string; vout: number }> {\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n\n let tx: Transaction;\n try {\n tx = Transaction.fromHex(cleanHex);\n } catch (error) {\n throw new Error(\n `Failed to parse BTC transaction: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n return tx.ins.map((input) => ({\n // Bitcoin stores txid in reverse byte order\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n}\n\n/**\n * Validate that all UTXOs in a transaction are still available.\n *\n * Pure function — accepts pre-fetched UTXOs instead of making network calls.\n * This should be called BEFORE signing to avoid wasting user effort\n * signing a transaction that will fail to broadcast.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @returns Validation result with missing UTXO details\n */\nexport function validateUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): UtxoValidationResult {\n const inputs = extractInputsFromTransaction(unsignedTxHex);\n\n if (inputs.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Detect duplicate inputs (same txid:vout referenced more than once).\n // This would produce an invalid Bitcoin transaction.\n const inputKeys = new Set<string>();\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (inputKeys.has(key)) {\n throw new Error(\n `Transaction contains duplicate input ${input.txid}:${input.vout}. ` +\n `This would produce an invalid Bitcoin transaction.`,\n );\n }\n inputKeys.add(key);\n }\n\n // Set of available outpoints for O(1) lookup. Lowercased so the comparison\n // is case-insensitive against whatever case the wallet returned.\n const availableSet = new Set(\n availableUtxos.map((utxo) => `${utxo.txid.toLowerCase()}:${utxo.vout}`),\n );\n\n // Check which inputs are missing\n const missingUtxos: MissingUtxoInfo[] = [];\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (!availableSet.has(key)) {\n missingUtxos.push({\n txid: input.txid,\n vout: input.vout,\n });\n }\n }\n\n return {\n allAvailable: missingUtxos.length === 0,\n missingUtxos,\n totalInputs: inputs.length,\n };\n}\n\n/**\n * Validate UTXOs and throw if any are not available.\n *\n * Pure convenience function that combines validation and error throwing.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @throws UtxoNotAvailableError if any UTXOs are not available\n * @throws Error if validation fails\n */\nexport function assertUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): void {\n const result = validateUtxosAvailable(unsignedTxHex, availableUtxos);\n\n if (!result.allAvailable) {\n throw new UtxoNotAvailableError(result.missingUtxos);\n }\n}\n","/**\n * Pending-vault outpoint overlap detection.\n *\n * Given the depositor's pending vaults (indexer + local cache) and the\n * outpoints a new deposit's coin selector picked, return the set of\n * pending vault ids whose Pre-PegIn BTC tx shares an input. Advisory\n * only — used to warn the user before signing.\n *\n * Only `PENDING` vaults contribute: VERIFIED+ have their Pre-PegIn\n * already confirmed on-chain, so those inputs cannot still appear in\n * the wallet's spendable set.\n */\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { ContractStatus } from \"../../services/deposit/peginState\";\n\nimport { type UtxoRef } from \"./availability\";\n\n/** Locally-known pending pegin. `id` is the bytes32 vault id. */\nexport interface PendingPeginLike {\n id?: string;\n unsignedTxHex?: string;\n}\n\n/** On-chain vault row from the indexer. */\nexport interface VaultLike {\n id?: string;\n status: number;\n unsignedPrePeginTx: string;\n}\n\nexport interface FindOverlappingPendingVaultsParams {\n selectedOutpoints: ReadonlyArray<UtxoRef>;\n vaults?: ReadonlyArray<VaultLike>;\n pendingPegins?: ReadonlyArray<PendingPeginLike>;\n}\n\nfunction extractInputUtxoRefs(txHex: string): UtxoRef[] {\n try {\n const tx = Transaction.fromHex(stripHexPrefix(txHex));\n return tx.ins.map((input) => ({\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n } catch {\n return [];\n }\n}\n\nfunction outpointKey(o: UtxoRef): string {\n return `${o.txid.toLowerCase()}:${o.vout}`;\n}\n\n/**\n * Return the ids of pending vaults whose committed Pre-PegIn inputs\n * overlap any of the just-selected outpoints. On-chain `PENDING` vaults\n * take precedence over a same-id local pegin entry.\n */\nexport function findOverlappingPendingVaults(\n params: FindOverlappingPendingVaultsParams,\n): string[] {\n const { selectedOutpoints, vaults = [], pendingPegins = [] } = params;\n\n const selectedSet = new Set(selectedOutpoints.map(outpointKey));\n if (selectedSet.size === 0) return [];\n\n const seenIds = new Set<string>();\n const impacted = new Set<string>();\n\n const consider = (id: string | undefined, txHex: string): void => {\n if (!id) return;\n const idLower = id.toLowerCase();\n if (seenIds.has(idLower)) return;\n seenIds.add(idLower);\n const inputs = extractInputUtxoRefs(txHex);\n for (const input of inputs) {\n if (selectedSet.has(outpointKey(input))) {\n impacted.add(id);\n return;\n }\n }\n };\n\n // On-chain wins on id collision.\n for (const v of vaults) {\n if (v.status !== ContractStatus.PENDING) continue;\n consider(v.id, v.unsignedPrePeginTx);\n }\n for (const p of pendingPegins) {\n if (!p.unsignedTxHex) continue;\n consider(p.id, p.unsignedTxHex);\n }\n\n return Array.from(impacted);\n}\n"],"names":["UtxoNotAvailableError","missingUtxos","count","message","__publicField","extractInputsFromTransaction","unsignedTxHex","cleanHex","tx","Transaction","error","input","Buffer","validateUtxosAvailable","availableUtxos","inputs","inputKeys","key","availableSet","utxo","assertUtxosAvailable","result","extractInputUtxoRefs","txHex","stripHexPrefix","outpointKey","o","findOverlappingPendingVaults","params","selectedOutpoints","vaults","pendingPegins","selectedSet","seenIds","impacted","consider","id","idLower","v","ContractStatus","p"],"mappings":";;;;;;;AAoDO,MAAMA,UAA8B,MAAM;AAAA,EAG/C,YAAYC,GAAiC;AAC3C,UAAMC,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CAAK;AACzC,eAAWZ,KAASI;AAClB,UAAIiB,EAAY,IAAIP,EAAYd,CAAK,CAAC,GAAG;AACvC,QAAAuB,EAAS,IAAIE,CAAE;AACf;AAAA,MACF;AAAA,EAEJ;AAGA,aAAWE,KAAKR;AACd,IAAIQ,EAAE,WAAWC,EAAe,WAChCJ,EAASG,EAAE,IAAIA,EAAE,kBAAkB;AAErC,aAAWE,KAAKT;AACd,IAAKS,EAAE,iBACPL,EAASK,EAAE,IAAIA,EAAE,aAAa;AAGhC,SAAO,MAAM,KAAKN,CAAQ;AAC5B;"}
1
+ {"version":3,"file":"reservation-cHDRn4DA.js","sources":["../src/tbv/core/utils/utxo/availability.ts","../src/tbv/core/utils/utxo/reservation.ts"],"sourcesContent":["/**\n * UTXO Availability Validation\n *\n * Validates that UTXOs referenced in a pre-pegin transaction are still unspent\n * BEFORE asking the user to sign. This prevents wasted signing effort when\n * UTXOs have already been spent by unrelated transactions.\n *\n * These functions are pure — they accept pre-fetched UTXOs and perform no I/O.\n * The vault service wrapper is responsible for fetching UTXOs from the mempool.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Reference to a Bitcoin UTXO by its outpoint (txid + vout).\n *\n * Used by the availability check to compare a Pre-PegIn transaction's\n * declared inputs against the wallet's current spendable set. Txids are\n * compared case-insensitively; callers should treat the txid as opaque\n * lowercase hex.\n */\nexport interface UtxoRef {\n txid: string;\n vout: number;\n}\n\n/**\n * Information about a missing/spent UTXO.\n */\nexport interface MissingUtxoInfo {\n /** Transaction ID of the missing UTXO */\n txid: string;\n /** Output index of the missing UTXO */\n vout: number;\n}\n\n/**\n * Result of UTXO validation.\n */\nexport interface UtxoValidationResult {\n /** Whether all UTXOs are still available */\n allAvailable: boolean;\n /** List of missing UTXOs (if any) */\n missingUtxos: MissingUtxoInfo[];\n /** Total number of inputs checked */\n totalInputs: number;\n}\n\n/**\n * Error thrown when UTXOs are not available.\n */\nexport class UtxoNotAvailableError extends Error {\n public readonly missingUtxos: MissingUtxoInfo[];\n\n constructor(missingUtxos: MissingUtxoInfo[]) {\n const count = missingUtxos.length;\n const message =\n count === 1\n ? \"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.\"\n : `${count} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;\n\n super(message);\n this.name = \"UtxoNotAvailableError\";\n this.missingUtxos = missingUtxos;\n }\n}\n\n/**\n * Extract input references (txid:vout) from an unsigned transaction.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @returns Array of input references\n */\nexport function extractInputsFromTransaction(\n unsignedTxHex: string,\n): Array<{ txid: string; vout: number }> {\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n\n let tx: Transaction;\n try {\n tx = Transaction.fromHex(cleanHex);\n } catch (error) {\n throw new Error(\n `Failed to parse BTC transaction: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n return tx.ins.map((input) => ({\n // Bitcoin stores txid in reverse byte order\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n}\n\n/**\n * Validate that all UTXOs in a transaction are still available.\n *\n * Pure function — accepts pre-fetched UTXOs instead of making network calls.\n * This should be called BEFORE signing to avoid wasting user effort\n * signing a transaction that will fail to broadcast.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @returns Validation result with missing UTXO details\n */\nexport function validateUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): UtxoValidationResult {\n const inputs = extractInputsFromTransaction(unsignedTxHex);\n\n if (inputs.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Detect duplicate inputs (same txid:vout referenced more than once).\n // This would produce an invalid Bitcoin transaction.\n const inputKeys = new Set<string>();\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (inputKeys.has(key)) {\n throw new Error(\n `Transaction contains duplicate input ${input.txid}:${input.vout}. ` +\n `This would produce an invalid Bitcoin transaction.`,\n );\n }\n inputKeys.add(key);\n }\n\n // Set of available outpoints for O(1) lookup. Lowercased so the comparison\n // is case-insensitive against whatever case the wallet returned.\n const availableSet = new Set(\n availableUtxos.map((utxo) => `${utxo.txid.toLowerCase()}:${utxo.vout}`),\n );\n\n // Check which inputs are missing\n const missingUtxos: MissingUtxoInfo[] = [];\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (!availableSet.has(key)) {\n missingUtxos.push({\n txid: input.txid,\n vout: input.vout,\n });\n }\n }\n\n return {\n allAvailable: missingUtxos.length === 0,\n missingUtxos,\n totalInputs: inputs.length,\n };\n}\n\n/**\n * Validate UTXOs and throw if any are not available.\n *\n * Pure convenience function that combines validation and error throwing.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @throws UtxoNotAvailableError if any UTXOs are not available\n * @throws Error if validation fails\n */\nexport function assertUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): void {\n const result = validateUtxosAvailable(unsignedTxHex, availableUtxos);\n\n if (!result.allAvailable) {\n throw new UtxoNotAvailableError(result.missingUtxos);\n }\n}\n","/**\n * Pending-vault outpoint overlap detection.\n *\n * Given the depositor's pending vaults (indexer + local cache) and the\n * outpoints a new deposit's coin selector picked, return the set of\n * pending vault ids whose Pre-PegIn BTC tx shares an input. Advisory\n * only — used to warn the user before signing.\n *\n * Only `PENDING` vaults contribute: VERIFIED+ have their Pre-PegIn\n * already confirmed on-chain, so those inputs cannot still appear in\n * the wallet's spendable set.\n */\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { ContractStatus } from \"../../services/deposit/peginState\";\n\nimport { type UtxoRef } from \"./availability\";\n\n/** Locally-known pending pegin. `id` is the bytes32 vault id. */\nexport interface PendingPeginLike {\n id?: string;\n unsignedTxHex?: string;\n}\n\n/** On-chain vault row from the indexer. */\nexport interface VaultLike {\n id?: string;\n status: number;\n unsignedPrePeginTx: string;\n}\n\nexport interface FindOverlappingPendingVaultsParams {\n selectedOutpoints: ReadonlyArray<UtxoRef>;\n vaults?: ReadonlyArray<VaultLike>;\n pendingPegins?: ReadonlyArray<PendingPeginLike>;\n}\n\nfunction extractInputUtxoRefs(txHex: string): UtxoRef[] {\n try {\n const tx = Transaction.fromHex(stripHexPrefix(txHex));\n return tx.ins.map((input) => ({\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n } catch {\n return [];\n }\n}\n\nfunction outpointKey(o: UtxoRef): string {\n return `${o.txid.toLowerCase()}:${o.vout}`;\n}\n\n/**\n * Return the ids of pending vaults whose committed Pre-PegIn inputs\n * overlap any of the just-selected outpoints. On-chain `PENDING` vaults\n * take precedence over a same-id local pegin entry.\n */\nexport function findOverlappingPendingVaults(\n params: FindOverlappingPendingVaultsParams,\n): string[] {\n const { selectedOutpoints, vaults = [], pendingPegins = [] } = params;\n\n const selectedSet = new Set(selectedOutpoints.map(outpointKey));\n if (selectedSet.size === 0) return [];\n\n const seenIds = new Set<string>();\n const impacted = new Set<string>();\n\n const consider = (id: string | undefined, txHex: string): void => {\n if (!id) return;\n const idLower = id.toLowerCase();\n if (seenIds.has(idLower)) return;\n seenIds.add(idLower);\n const inputs = extractInputUtxoRefs(txHex);\n for (const input of inputs) {\n if (selectedSet.has(outpointKey(input))) {\n impacted.add(id);\n return;\n }\n }\n };\n\n // On-chain wins on id collision.\n for (const v of vaults) {\n if (v.status !== ContractStatus.PENDING) continue;\n consider(v.id, v.unsignedPrePeginTx);\n }\n for (const p of pendingPegins) {\n if (!p.unsignedTxHex) continue;\n consider(p.id, p.unsignedTxHex);\n }\n\n return Array.from(impacted);\n}\n"],"names":["UtxoNotAvailableError","missingUtxos","count","message","__publicField","extractInputsFromTransaction","unsignedTxHex","cleanHex","tx","Transaction","error","input","Buffer","validateUtxosAvailable","availableUtxos","inputs","inputKeys","key","availableSet","utxo","assertUtxosAvailable","result","extractInputUtxoRefs","txHex","stripHexPrefix","outpointKey","o","findOverlappingPendingVaults","params","selectedOutpoints","vaults","pendingPegins","selectedSet","seenIds","impacted","consider","id","idLower","v","ContractStatus","p"],"mappings":";;;;;;;AAoDO,MAAMA,UAA8B,MAAM;AAAA,EAG/C,YAAYC,GAAiC;AAC3C,UAAMC,IAAQD,EAAa,QACrBE,IACJD,MAAU,IACN,8JACA,GAAGA,CAAK;AAEd,UAAMC,CAAO;AATC,IAAAC,EAAA;AAUd,SAAK,OAAO,yBACZ,KAAK,eAAeH;AAAA,EACtB;AACF;AAQO,SAASI,EACdC,GACuC;AACvC,QAAMC,IAAWD,EAAc,WAAW,IAAI,IAC1CA,EAAc,MAAM,CAAC,IACrBA;AAEJ,MAAIE;AACJ,MAAI;AACF,IAAAA,IAAKC,EAAY,QAAQF,CAAQ;AAAA,EACnC,SAASG,GAAO;AACd,UAAM,IAAI;AAAA,MACR,oCAAoCA,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK,CAAC;AAAA,IAAA;AAAA,EAE9F;AAEA,SAAOF,EAAG,IAAI,IAAI,CAACG,OAAW;AAAA;AAAA,IAE5B,MAAMC,EAAO,KAAKD,EAAM,IAAI,EAAE,QAAA,EAAU,SAAS,KAAK;AAAA,IACtD,MAAMA,EAAM;AAAA,EAAA,EACZ;AACJ;AAaO,SAASE,EACdP,GACAQ,GACsB;AACtB,QAAMC,IAASV,EAA6BC,CAAa;AAEzD,MAAIS,EAAO,WAAW;AACpB,UAAM,IAAI,MAAM,2BAA2B;AAK7C,QAAMC,wBAAgB,IAAA;AACtB,aAAWL,KAASI,GAAQ;AAC1B,UAAME,IAAM,GAAGN,EAAM,KAAK,aAAa,IAAIA,EAAM,IAAI;AACrD,QAAIK,EAAU,IAAIC,C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OH,GAEzDI,IAAc,IAAI,IAAIH,EAAkB,IAAIJ,CAAW,CAAC;AAC9D,MAAIO,EAAY,SAAS,EAAG,QAAO,CAAA;AAEnC,QAAMC,wBAAc,IAAA,GACdC,wBAAe,IAAA,GAEfC,IAAW,CAACC,GAAwBb,MAAwB;AAChE,QAAI,CAACa,EAAI;AACT,UAAMC,IAAUD,EAAG,YAAA;AACnB,QAAIH,EAAQ,IAAII,CAAO,EAAG;AAC1B,IAAAJ,EAAQ,IAAII,CAAO;AACnB,UAAMtB,IAASO,EAAqBC,CAAK;AACzC,eAAWZ,KAASI;AAClB,UAAIiB,EAAY,IAAIP,EAAYd,CAAK,CAAC,GAAG;AACvC,QAAAuB,EAAS,IAAIE,CAAE;AACf;AAAA,MACF;AAAA,EAEJ;AAGA,aAAWE,KAAKR;AACd,IAAIQ,EAAE,WAAWC,EAAe,WAChCJ,EAASG,EAAE,IAAIA,EAAE,kBAAkB;AAErC,aAAWE,KAAKT;AACd,IAAKS,EAAE,iBACPL,EAASK,EAAE,IAAIA,EAAE,aAAa;AAGhC,SAAO,MAAM,KAAKN,CAAQ;AAC5B;"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("../../challengeAssert-HNbugpqL.cjs"),l=require("@babylonlabs-io/babylon-tbv-rust-wasm"),n=require("../../verifyScriptPathSchnorrSignature-Cl7tu77P.cjs"),S=require("../../peginInput-DH6X4ITS.cjs"),A=require("../../noPayout-lyIRiUyG.cjs"),r=require("../../bitcoin-CHfKAhcI.cjs"),R=require("../../signing-Bnsro0hE.cjs"),c=require("../../validation-u8W7Lp2x.cjs"),u=require("../../PeginManager-BvxfSwsr.cjs"),p=require("../../PayoutManager-BZVEyi10.cjs"),_=require("../../ApplicationRegistry.abi-BAPhJch3.cjs"),m=require("../../BTCVaultRegistry.abi-JdeqLz4x.cjs"),P=require("../../errors-CGcNP0rV.cjs"),o=require("../../waitForTransactionReceiptSmartAware-U706oKTc.cjs"),t=require("../../fundPeginTransaction-DuMwnytD.cjs"),d=require("../../reservation-xTL2a9Q-.cjs"),i=require("../../mempoolApi-NMiYQAXI.cjs"),a=require("../../primeVpAuth-yTddDmGy.cjs"),s=require("../../types-WA0LrDk1.cjs"),g=require("../../errors-Bu0H-dZD.cjs"),e=require("../../buildAndBroadcastRefund-ob1n2iB3.cjs"),T=require("../../peginState-BijNNT15.cjs");exports.buildChallengeAssertPsbt=E.buildChallengeAssertPsbt;exports.buildDepositorPayoutPsbt=E.buildDepositorPayoutPsbt;exports.computeNumLocalChallengers=E.computeNumLocalChallengers;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>l.computeMinClaimValue});Object.defineProperty(exports,"computeMinPeginFee",{enumerable:!0,get:()=>l.computeMinPeginFee});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>l.deriveVaultId});Object.defineProperty(exports,"expandAuthAnchor",{enumerable:!0,get:()=>l.expandAuthAnchor});Object.defineProperty(exports,"expandHashlockSecret",{enumerable:!0,get:()=>l.expandHashlockSecret});Object.defineProperty(exports,"expandWotsSeed",{enumerable:!0,get:()=>l.expandWotsSeed});exports.PsbtSubstitutionError=n.PsbtSubstitutionError;exports.assertPsbtUnsignedTxMatches=n.assertPsbtUnsignedTxMatches;exports.assertScriptPathSchnorrSignature=n.assertScriptPathSchnorrSignature;exports.buildPayoutPsbt=n.buildPayoutPsbt;exports.buildPeginTxFromFundedPrePegin=n.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=n.buildPrePeginPsbt;exports.createPayoutScript=n.createPayoutScript;exports.extractPayoutSignature=n.extractPayoutSignature;exports.buildPeginInputPsbt=S.buildPeginInputPsbt;exports.extractPeginInputSignature=S.extractPeginInputSignature;exports.finalizePeginInputPsbt=S.finalizePeginInputPsbt;exports.buildNoPayoutPsbt=A.buildNoPayoutPsbt;exports.buildRefundPsbt=A.buildRefundPsbt;exports.deriveBip86ScriptPubKeyHex=r.deriveBip86ScriptPubKeyHex;exports.deriveNativeSegwitAddress=r.deriveNativeSegwitAddress;exports.deriveTaprootAddress=r.deriveTaprootAddress;exports.ensureHexPrefix=r.ensureHexPrefix;exports.formatSatoshisToBtc=r.formatSatoshisToBtc;exports.getNetwork=r.getNetwork;exports.getSortedXOnlyPubkeys=r.getSortedXOnlyPubkeys;exports.hexToUint8Array=r.hexToUint8Array;exports.isAddressFromPublicKey=r.isAddressFromPublicKey;exports.isValidHex=r.isValidHex;exports.processPublicKeyToXOnly=r.processPublicKeyToXOnly;exports.stripHexPrefix=r.stripHexPrefix;exports.toXOnly=r.toXOnly;exports.uint8ArrayToHex=r.uint8ArrayToHex;exports.validateWalletPubkey=r.validateWalletPubkey;exports.createTaprootScriptPathSignOptions=R.createTaprootScriptPathSignOptions;exports.BITCOIN_ADDRESS_RE=c.BITCOIN_ADDRESS_RE;exports.HEX_RE=c.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=c.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=c.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=c.TXID_RE;exports.PeginManager=u.PeginManager;exports.VAULT_APP_NAME=u.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=u.buildFundingOutpointsCommitment;exports.buildVaultContext=u.buildVaultContext;exports.computeWotsBlockPublicKeysHash=u.computeWotsBlockPublicKeysHash;exports.deriveVaultRoot=u.deriveVaultRoot;exports.deriveWotsBlocksFromSeed=u.deriveWotsBlocksFromSeed;exports.estimateSubmitPeginRequestBatchGas=u.estimateSubmitPeginRequestBatchGas;exports.PayoutManager=p.PayoutManager;exports.computeHashlock=p.computeHashlock;exports.validateSecretAgainstHashlock=p.validateSecretAgainstHashlock;exports.ApplicationRegistryABI=_.ApplicationRegistryABI;exports.ProtocolParamsABI=_.ProtocolParamsABI;exports.BTCVaultRegistryABI=m.BTCVaultRegistryABI;exports.CONTRACT_ERRORS=P.CONTRACT_ERRORS;exports.extractErrorData=P.extractErrorData;exports.getContractErrorMessage=P.getContractErrorMessage;exports.handleContractError=P.handleContractError;exports.isKnownContractError=P.isKnownContractError;exports.BitcoinScriptType=o.BitcoinScriptType;exports.applyChangeOutputPolicy=o.applyChangeOutputPolicy;exports.calculateBtcTxHash=o.calculateBtcTxHash;exports.computeChangeOutputFeeSats=o.computeChangeOutputFeeSats;exports.computeMaxDeposit=o.computeMaxDeposit;exports.computePeginBaseFeeSats=o.computePeginBaseFeeSats;exports.getDustThreshold=o.getDustThreshold;exports.getPsbtInputFields=o.getPsbtInputFields;exports.getScriptType=o.getScriptType;exports.selectUtxosForPegin=o.selectUtxosForPegin;exports.shouldAddChangeOutput=o.shouldAddChangeOutput;exports.waitForTransactionReceiptSmartAware=o.waitForTransactionReceiptSmartAware;exports.BTC_DUST_SAT=t.BTC_DUST_SAT;exports.DUST_THRESHOLD=t.DUST_THRESHOLD;exports.FEE_SAFETY_MARGIN=t.FEE_SAFETY_MARGIN;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=t.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=t.MAX_NON_LEGACY_OUTPUT_SIZE;exports.MAX_REASONABLE_PEGIN_VBYTES=t.MAX_REASONABLE_PEGIN_VBYTES;exports.P2TR_INPUT_SIZE=t.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=t.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=t.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=t.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=t.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=t.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=t.fundPeginTransaction;exports.parseUnfundedWasmTransaction=t.parseUnfundedWasmTransaction;exports.peginOutputCount=t.peginOutputCount;exports.rateBasedTxBufferFee=t.rateBasedTxBufferFee;exports.UtxoNotAvailableError=d.UtxoNotAvailableError;exports.assertUtxosAvailable=d.assertUtxosAvailable;exports.extractInputsFromTransaction=d.extractInputsFromTransaction;exports.findOverlappingPendingVaults=d.findOverlappingPendingVaults;exports.validateUtxosAvailable=d.validateUtxosAvailable;exports.MEMPOOL_API_URLS=i.MEMPOOL_API_URLS;exports.ViemVaultRegistryReader=i.ViemVaultRegistryReader;exports.getAddressTxs=i.getAddressTxs;exports.getAddressUtxos=i.getAddressUtxos;exports.getMempoolApiUrl=i.getMempoolApiUrl;exports.getNetworkFees=i.getNetworkFees;exports.getOutspend=i.getOutspend;exports.getTipHeight=i.getTipHeight;exports.getTxHex=i.getTxHex;exports.getTxInfo=i.getTxInfo;exports.getUtxoInfo=i.getUtxoInfo;exports.pushTx=i.pushTx;exports.validateOffchainParams=i.validateOffchainParams;exports.validatePegInConfiguration=i.validatePegInConfiguration;exports.validateTBVProtocolParams=i.validateTBVProtocolParams;exports.OnChainBtcVaultStatus=a.OnChainBtcVaultStatus;exports.ServerIdentityError=a.ServerIdentityError;exports.VaultProviderRpcClient=a.VaultProviderRpcClient;exports.ViemProtocolParamsReader=a.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=a.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=a.ViemVaultKeeperReader;exports.VpResponseValidationError=a.VpResponseValidationError;exports.VpTokenRegistry=a.VpTokenRegistry;exports.batchPollByProvider=a.batchPollByProvider;exports.createAuthenticatedVpClient=a.createAuthenticatedVpClient;exports.primeVpTokenRegistry=a.primeVpTokenRegistry;exports.resolveProtocolAddresses=a.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=a.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=a.verifyServerIdentity;exports.vpTokenRegistry=a.vpTokenRegistry;exports.AUTH_EXPIRED_DATA_KIND=s.AUTH_EXPIRED_DATA_KIND;exports.DaemonStatus=s.DaemonStatus;exports.JSON_RPC_ERROR_CODES=s.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=s.JsonRpcClient;exports.JsonRpcError=s.JsonRpcError;exports.POST_WOTS_STATUSES=s.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=s.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=s.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=s.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=s.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=s.VP_TRANSIENT_STATUSES;exports.isWotsMismatchError=g.isWotsMismatchError;exports.parseFundingOutpointsFromTx=g.parseFundingOutpointsFromTx;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=e.ClaimerPegoutStatusValue;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=e.REFUND_MAX_FEE_FRACTION_DENOMINATOR;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=e.REFUND_MAX_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_RATE_SATS_VB=e.REFUND_MAX_FEE_RATE_SATS_VB;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.RegisteredVaultVersionMismatchError=e.RegisteredVaultVersionMismatchError;exports.activateVault=e.activateVault;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isPegoutTerminalStatus=e.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=e.isRecognizedPegoutStatus;exports.isRegisteredVaultVersionMismatchError=e.isRegisteredVaultVersionMismatchError;exports.runDepositorPresignFlow=e.runDepositorPresignFlow;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateOnChainParticipantKeys=e.validateOnChainParticipantKeys;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.verifyRegisteredVaultVersions=e.verifyRegisteredVaultVersions;exports.waitForPeginStatus=e.waitForPeginStatus;exports.ContractStatus=T.ContractStatus;exports.PeginAction=T.PeginAction;exports.canPerformAction=T.canPerformAction;exports.getPeginProtocolState=T.getPeginProtocolState;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("../../challengeAssert-HNbugpqL.cjs"),n=require("../../verifyScriptPathSchnorrSignature-CVPh04ZI.cjs"),l=require("@babylonlabs-io/babylon-tbv-rust-wasm"),E=require("../../peginInput-De0C6aSj.cjs"),A=require("../../noPayout-ChPNKTbm.cjs"),r=require("../../bitcoin-CHfKAhcI.cjs"),R=require("../../signing-Bnsro0hE.cjs"),d=require("../../validation-u8W7Lp2x.cjs"),u=require("../../PeginManager-DDp-ZRIa.cjs"),S=require("../../PayoutManager-CBfHfLfz.cjs"),_=require("../../ApplicationRegistry.abi-BAPhJch3.cjs"),m=require("../../BTCVaultRegistry.abi-JdeqLz4x.cjs"),P=require("../../errors-CGcNP0rV.cjs"),o=require("../../waitForTransactionReceiptSmartAware-U706oKTc.cjs"),t=require("../../fundPeginTransaction-DuMwnytD.cjs"),c=require("../../reservation-ClEs2X0H.cjs"),i=require("../../mempoolApi-NMiYQAXI.cjs"),a=require("../../primeVpAuth-yTddDmGy.cjs"),s=require("../../types-WA0LrDk1.cjs"),g=require("../../errors-Bu0H-dZD.cjs"),e=require("../../buildAndBroadcastRefund-3MLyCOtv.cjs"),T=require("../../peginState-CBBJw4Za.cjs");exports.buildChallengeAssertPsbt=p.buildChallengeAssertPsbt;exports.buildDepositorPayoutPsbt=p.buildDepositorPayoutPsbt;exports.computeNumLocalChallengers=p.computeNumLocalChallengers;exports.PsbtSubstitutionError=n.PsbtSubstitutionError;exports.TX_GRAPH_VERSION_V1=n.TX_GRAPH_VERSION_V1;exports.assertPsbtUnsignedTxMatches=n.assertPsbtUnsignedTxMatches;exports.assertScriptPathSchnorrSignature=n.assertScriptPathSchnorrSignature;exports.buildPayoutPsbt=n.buildPayoutPsbt;exports.buildPeginTxFromFundedPrePegin=n.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=n.buildPrePeginPsbt;exports.createPayoutScript=n.createPayoutScript;exports.extractPayoutSignature=n.extractPayoutSignature;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>l.computeMinClaimValue});Object.defineProperty(exports,"computeMinPeginFee",{enumerable:!0,get:()=>l.computeMinPeginFee});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>l.deriveVaultId});Object.defineProperty(exports,"expandAuthAnchor",{enumerable:!0,get:()=>l.expandAuthAnchor});Object.defineProperty(exports,"expandHashlockSecret",{enumerable:!0,get:()=>l.expandHashlockSecret});Object.defineProperty(exports,"expandWotsSeed",{enumerable:!0,get:()=>l.expandWotsSeed});Object.defineProperty(exports,"supportedTxGraphVersions",{enumerable:!0,get:()=>l.supportedTxGraphVersions});exports.buildPeginInputPsbt=E.buildPeginInputPsbt;exports.extractPeginInputSignature=E.extractPeginInputSignature;exports.finalizePeginInputPsbt=E.finalizePeginInputPsbt;exports.buildNoPayoutPsbt=A.buildNoPayoutPsbt;exports.buildRefundPsbt=A.buildRefundPsbt;exports.deriveBip86ScriptPubKeyHex=r.deriveBip86ScriptPubKeyHex;exports.deriveNativeSegwitAddress=r.deriveNativeSegwitAddress;exports.deriveTaprootAddress=r.deriveTaprootAddress;exports.ensureHexPrefix=r.ensureHexPrefix;exports.formatSatoshisToBtc=r.formatSatoshisToBtc;exports.getNetwork=r.getNetwork;exports.getSortedXOnlyPubkeys=r.getSortedXOnlyPubkeys;exports.hexToUint8Array=r.hexToUint8Array;exports.isAddressFromPublicKey=r.isAddressFromPublicKey;exports.isValidHex=r.isValidHex;exports.processPublicKeyToXOnly=r.processPublicKeyToXOnly;exports.stripHexPrefix=r.stripHexPrefix;exports.toXOnly=r.toXOnly;exports.uint8ArrayToHex=r.uint8ArrayToHex;exports.validateWalletPubkey=r.validateWalletPubkey;exports.createTaprootScriptPathSignOptions=R.createTaprootScriptPathSignOptions;exports.BITCOIN_ADDRESS_RE=d.BITCOIN_ADDRESS_RE;exports.HEX_RE=d.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=d.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=d.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=d.TXID_RE;exports.PeginManager=u.PeginManager;exports.VAULT_APP_NAME=u.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=u.buildFundingOutpointsCommitment;exports.buildVaultContext=u.buildVaultContext;exports.computeWotsBlockPublicKeysHash=u.computeWotsBlockPublicKeysHash;exports.deriveVaultRoot=u.deriveVaultRoot;exports.deriveWotsBlocksFromSeed=u.deriveWotsBlocksFromSeed;exports.estimateSubmitPeginRequestBatchGas=u.estimateSubmitPeginRequestBatchGas;exports.PayoutManager=S.PayoutManager;exports.computeHashlock=S.computeHashlock;exports.validateSecretAgainstHashlock=S.validateSecretAgainstHashlock;exports.ApplicationRegistryABI=_.ApplicationRegistryABI;exports.ProtocolParamsABI=_.ProtocolParamsABI;exports.BTCVaultRegistryABI=m.BTCVaultRegistryABI;exports.CONTRACT_ERRORS=P.CONTRACT_ERRORS;exports.extractErrorData=P.extractErrorData;exports.getContractErrorMessage=P.getContractErrorMessage;exports.handleContractError=P.handleContractError;exports.isKnownContractError=P.isKnownContractError;exports.BitcoinScriptType=o.BitcoinScriptType;exports.applyChangeOutputPolicy=o.applyChangeOutputPolicy;exports.calculateBtcTxHash=o.calculateBtcTxHash;exports.computeChangeOutputFeeSats=o.computeChangeOutputFeeSats;exports.computeMaxDeposit=o.computeMaxDeposit;exports.computePeginBaseFeeSats=o.computePeginBaseFeeSats;exports.getDustThreshold=o.getDustThreshold;exports.getPsbtInputFields=o.getPsbtInputFields;exports.getScriptType=o.getScriptType;exports.selectUtxosForPegin=o.selectUtxosForPegin;exports.shouldAddChangeOutput=o.shouldAddChangeOutput;exports.waitForTransactionReceiptSmartAware=o.waitForTransactionReceiptSmartAware;exports.BTC_DUST_SAT=t.BTC_DUST_SAT;exports.DUST_THRESHOLD=t.DUST_THRESHOLD;exports.FEE_SAFETY_MARGIN=t.FEE_SAFETY_MARGIN;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=t.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=t.MAX_NON_LEGACY_OUTPUT_SIZE;exports.MAX_REASONABLE_PEGIN_VBYTES=t.MAX_REASONABLE_PEGIN_VBYTES;exports.P2TR_INPUT_SIZE=t.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=t.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=t.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=t.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=t.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=t.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=t.fundPeginTransaction;exports.parseUnfundedWasmTransaction=t.parseUnfundedWasmTransaction;exports.peginOutputCount=t.peginOutputCount;exports.rateBasedTxBufferFee=t.rateBasedTxBufferFee;exports.UtxoNotAvailableError=c.UtxoNotAvailableError;exports.assertUtxosAvailable=c.assertUtxosAvailable;exports.extractInputsFromTransaction=c.extractInputsFromTransaction;exports.findOverlappingPendingVaults=c.findOverlappingPendingVaults;exports.validateUtxosAvailable=c.validateUtxosAvailable;exports.MEMPOOL_API_URLS=i.MEMPOOL_API_URLS;exports.ViemVaultRegistryReader=i.ViemVaultRegistryReader;exports.getAddressTxs=i.getAddressTxs;exports.getAddressUtxos=i.getAddressUtxos;exports.getMempoolApiUrl=i.getMempoolApiUrl;exports.getNetworkFees=i.getNetworkFees;exports.getOutspend=i.getOutspend;exports.getTipHeight=i.getTipHeight;exports.getTxHex=i.getTxHex;exports.getTxInfo=i.getTxInfo;exports.getUtxoInfo=i.getUtxoInfo;exports.pushTx=i.pushTx;exports.validateOffchainParams=i.validateOffchainParams;exports.validatePegInConfiguration=i.validatePegInConfiguration;exports.validateTBVProtocolParams=i.validateTBVProtocolParams;exports.OnChainBtcVaultStatus=a.OnChainBtcVaultStatus;exports.ServerIdentityError=a.ServerIdentityError;exports.VaultProviderRpcClient=a.VaultProviderRpcClient;exports.ViemProtocolParamsReader=a.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=a.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=a.ViemVaultKeeperReader;exports.VpResponseValidationError=a.VpResponseValidationError;exports.VpTokenRegistry=a.VpTokenRegistry;exports.batchPollByProvider=a.batchPollByProvider;exports.createAuthenticatedVpClient=a.createAuthenticatedVpClient;exports.primeVpTokenRegistry=a.primeVpTokenRegistry;exports.resolveProtocolAddresses=a.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=a.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=a.verifyServerIdentity;exports.vpTokenRegistry=a.vpTokenRegistry;exports.AUTH_EXPIRED_DATA_KIND=s.AUTH_EXPIRED_DATA_KIND;exports.DaemonStatus=s.DaemonStatus;exports.JSON_RPC_ERROR_CODES=s.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=s.JsonRpcClient;exports.JsonRpcError=s.JsonRpcError;exports.POST_WOTS_STATUSES=s.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=s.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=s.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=s.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=s.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=s.VP_TRANSIENT_STATUSES;exports.isWotsMismatchError=g.isWotsMismatchError;exports.parseFundingOutpointsFromTx=g.parseFundingOutpointsFromTx;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=e.ClaimerPegoutStatusValue;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=e.REFUND_MAX_FEE_FRACTION_DENOMINATOR;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=e.REFUND_MAX_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_RATE_SATS_VB=e.REFUND_MAX_FEE_RATE_SATS_VB;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.RegisteredVaultVersionMismatchError=e.RegisteredVaultVersionMismatchError;exports.activateVault=e.activateVault;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isPegoutTerminalStatus=e.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=e.isRecognizedPegoutStatus;exports.isRegisteredVaultVersionMismatchError=e.isRegisteredVaultVersionMismatchError;exports.runDepositorPresignFlow=e.runDepositorPresignFlow;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateOnChainParticipantKeys=e.validateOnChainParticipantKeys;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.verifyRegisteredVaultVersions=e.verifyRegisteredVaultVersions;exports.waitForPeginStatus=e.waitForPeginStatus;exports.ContractStatus=T.ContractStatus;exports.PeginAction=T.PeginAction;exports.canPerformAction=T.canPerformAction;exports.getPeginProtocolState=T.getPeginProtocolState;exports.isActivationDeadlinePassedOnChain=T.isActivationDeadlinePassedOnChain;
2
2
  //# sourceMappingURL=index.cjs.map