@babylonlabs-io/ts-sdk 0.33.3 → 0.33.5

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 (153) hide show
  1. package/dist/BTCVaultRegistry.abi-DbJ5lsFJ.js +417 -0
  2. package/dist/BTCVaultRegistry.abi-DbJ5lsFJ.js.map +1 -0
  3. package/dist/BTCVaultRegistry.abi-ZdPpION2.cjs +2 -0
  4. package/dist/BTCVaultRegistry.abi-ZdPpION2.cjs.map +1 -0
  5. package/dist/PayoutManager-C9XHKZ5j.js +200 -0
  6. package/dist/PayoutManager-C9XHKZ5j.js.map +1 -0
  7. package/dist/PayoutManager-DDnNB0mj.cjs +2 -0
  8. package/dist/PayoutManager-DDnNB0mj.cjs.map +1 -0
  9. package/dist/PeginManager-BXg2S1mH.cjs +2 -0
  10. package/dist/PeginManager-BXg2S1mH.cjs.map +1 -0
  11. package/dist/{PeginManager-C-L3huRO.js → PeginManager-C5HaMAcw.js} +328 -437
  12. package/dist/PeginManager-C5HaMAcw.js.map +1 -0
  13. package/dist/ProtocolParams.abi-BmvHwQJV.cjs +2 -0
  14. package/dist/ProtocolParams.abi-BmvHwQJV.cjs.map +1 -0
  15. package/dist/ProtocolParams.abi-DXu8L0Fn.js +382 -0
  16. package/dist/ProtocolParams.abi-DXu8L0Fn.js.map +1 -0
  17. package/dist/buildAndBroadcastRefund-B332dykQ.cjs +2 -0
  18. package/dist/buildAndBroadcastRefund-B332dykQ.cjs.map +1 -0
  19. package/dist/buildAndBroadcastRefund-CPjXNaMi.js +782 -0
  20. package/dist/buildAndBroadcastRefund-CPjXNaMi.js.map +1 -0
  21. package/dist/challengeAssert-BzxQmdZy.js +128 -0
  22. package/dist/challengeAssert-BzxQmdZy.js.map +1 -0
  23. package/dist/challengeAssert-Yyyj-EdR.cjs +2 -0
  24. package/dist/challengeAssert-Yyyj-EdR.cjs.map +1 -0
  25. package/dist/errors-9AkghWyk.js +22 -0
  26. package/dist/errors-9AkghWyk.js.map +1 -0
  27. package/dist/errors-BP73_stm.cjs +2 -0
  28. package/dist/errors-BP73_stm.cjs.map +1 -0
  29. package/dist/errors-Bu0H-dZD.cjs +2 -0
  30. package/dist/errors-Bu0H-dZD.cjs.map +1 -0
  31. package/dist/errors-CznAK5NB.js +96 -0
  32. package/dist/errors-CznAK5NB.js.map +1 -0
  33. package/dist/index.cjs +1 -1
  34. package/dist/index.js +159 -147
  35. package/dist/index.js.map +1 -1
  36. package/dist/mempoolApi-CAIge7Nj.js +205 -0
  37. package/dist/mempoolApi-CAIge7Nj.js.map +1 -0
  38. package/dist/mempoolApi-YNkKjQCU.cjs +2 -0
  39. package/dist/mempoolApi-YNkKjQCU.cjs.map +1 -0
  40. package/dist/noPayout-BXeUw0Qq.cjs +2 -0
  41. package/dist/noPayout-BXeUw0Qq.cjs.map +1 -0
  42. package/dist/noPayout-DBX6G96_.js +141 -0
  43. package/dist/noPayout-DBX6G96_.js.map +1 -0
  44. package/dist/payout-BNFMBXS6.js +193 -0
  45. package/dist/payout-BNFMBXS6.js.map +1 -0
  46. package/dist/payout-DQ_fmJUA.cjs +2 -0
  47. package/dist/payout-DQ_fmJUA.cjs.map +1 -0
  48. package/dist/peginInput-C2QPvuhR.js +177 -0
  49. package/dist/peginInput-C2QPvuhR.js.map +1 -0
  50. package/dist/peginInput-tbw9BpZy.cjs +2 -0
  51. package/dist/peginInput-tbw9BpZy.cjs.map +1 -0
  52. package/dist/peginState-BijNNT15.cjs +2 -0
  53. package/dist/peginState-BijNNT15.cjs.map +1 -0
  54. package/dist/peginState-CBAlxgXk.js +51 -0
  55. package/dist/peginState-CBAlxgXk.js.map +1 -0
  56. package/dist/psbtInputFields-2224j2ZY.js +128 -0
  57. package/dist/psbtInputFields-2224j2ZY.js.map +1 -0
  58. package/dist/psbtInputFields-B1lrwYzH.cjs +2 -0
  59. package/dist/psbtInputFields-B1lrwYzH.cjs.map +1 -0
  60. package/dist/reservation-CHUGW0F_.js +142 -0
  61. package/dist/reservation-CHUGW0F_.js.map +1 -0
  62. package/dist/reservation-ho7mjW3X.cjs +2 -0
  63. package/dist/reservation-ho7mjW3X.cjs.map +1 -0
  64. package/dist/signing-Bnsro0hE.cjs +2 -0
  65. package/dist/signing-Bnsro0hE.cjs.map +1 -0
  66. package/dist/signing-DaLvGwQe.js +16 -0
  67. package/dist/signing-DaLvGwQe.js.map +1 -0
  68. package/dist/tbv/core/clients/index.cjs +1 -1
  69. package/dist/tbv/core/clients/index.js +35 -32
  70. package/dist/tbv/core/clients/index.js.map +1 -1
  71. package/dist/tbv/core/clients/vault-provider/__tests__/batchAttribution.test.d.ts +2 -0
  72. package/dist/tbv/core/clients/vault-provider/__tests__/batchAttribution.test.d.ts.map +1 -0
  73. package/dist/tbv/core/clients/vault-provider/__tests__/batchPoll.test.d.ts +2 -0
  74. package/dist/tbv/core/clients/vault-provider/__tests__/batchPoll.test.d.ts.map +1 -0
  75. package/dist/tbv/core/clients/vault-provider/api.d.ts +13 -4
  76. package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -1
  77. package/dist/tbv/core/clients/vault-provider/batchAttribution.d.ts +45 -0
  78. package/dist/tbv/core/clients/vault-provider/batchAttribution.d.ts.map +1 -0
  79. package/dist/tbv/core/clients/vault-provider/batchPoll.d.ts +55 -0
  80. package/dist/tbv/core/clients/vault-provider/batchPoll.d.ts.map +1 -0
  81. package/dist/tbv/core/clients/vault-provider/index.d.ts +2 -0
  82. package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -1
  83. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +3 -3
  84. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
  85. package/dist/tbv/core/clients/vault-provider/types.d.ts +68 -24
  86. package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -1
  87. package/dist/tbv/core/clients/vault-provider/validators.d.ts +12 -2
  88. package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
  89. package/dist/tbv/core/contracts/index.cjs +2 -0
  90. package/dist/tbv/core/contracts/index.cjs.map +1 -0
  91. package/dist/tbv/core/contracts/index.js +14 -0
  92. package/dist/tbv/core/contracts/index.js.map +1 -0
  93. package/dist/tbv/core/index.cjs +1 -1
  94. package/dist/tbv/core/index.js +157 -145
  95. package/dist/tbv/core/index.js.map +1 -1
  96. package/dist/tbv/core/managers/index.cjs +2 -0
  97. package/dist/tbv/core/managers/index.cjs.map +1 -0
  98. package/dist/tbv/core/managers/index.js +7 -0
  99. package/dist/tbv/core/managers/index.js.map +1 -0
  100. package/dist/tbv/core/primitives/index.cjs +1 -1
  101. package/dist/tbv/core/primitives/index.js +31 -29
  102. package/dist/tbv/core/primitives/index.js.map +1 -1
  103. package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts.map +1 -1
  104. package/dist/tbv/core/services/index.cjs +1 -1
  105. package/dist/tbv/core/services/index.js +28 -27
  106. package/dist/tbv/core/services/index.js.map +1 -1
  107. package/dist/tbv/core/services/pegout/state.d.ts +1 -1
  108. package/dist/tbv/core/utils/index.cjs +1 -1
  109. package/dist/tbv/core/utils/index.js +21 -20
  110. package/dist/tbv/core/utils/index.js.map +1 -1
  111. package/dist/tbv/index.cjs +1 -1
  112. package/dist/tbv/index.js +157 -145
  113. package/dist/tbv/index.js.map +1 -1
  114. package/dist/types-DnyyBNcC.cjs +2 -0
  115. package/dist/types-DnyyBNcC.cjs.map +1 -0
  116. package/dist/types-TiIjyo2b.js +320 -0
  117. package/dist/types-TiIjyo2b.js.map +1 -0
  118. package/dist/vault-registry-reader-BDFpXeH7.js +1152 -0
  119. package/dist/vault-registry-reader-BDFpXeH7.js.map +1 -0
  120. package/dist/vault-registry-reader-ejm2UYzk.cjs +2 -0
  121. package/dist/vault-registry-reader-ejm2UYzk.cjs.map +1 -0
  122. package/package.json +11 -1
  123. package/dist/PeginManager-C-L3huRO.js.map +0 -1
  124. package/dist/PeginManager-DmPmzPHz.cjs +0 -2
  125. package/dist/PeginManager-DmPmzPHz.cjs.map +0 -1
  126. package/dist/buildAndBroadcastRefund-Dx09Zbla.js +0 -965
  127. package/dist/buildAndBroadcastRefund-Dx09Zbla.js.map +0 -1
  128. package/dist/buildAndBroadcastRefund-PmJMNrhO.cjs +0 -2
  129. package/dist/buildAndBroadcastRefund-PmJMNrhO.cjs.map +0 -1
  130. package/dist/challengeAssert-D3tHnLWb.js +0 -298
  131. package/dist/challengeAssert-D3tHnLWb.js.map +0 -1
  132. package/dist/challengeAssert-Dp9d1bg1.cjs +0 -2
  133. package/dist/challengeAssert-Dp9d1bg1.cjs.map +0 -1
  134. package/dist/noPayout-BnsetBKW.js +0 -327
  135. package/dist/noPayout-BnsetBKW.js.map +0 -1
  136. package/dist/noPayout-DWaCtpMU.cjs +0 -2
  137. package/dist/noPayout-DWaCtpMU.cjs.map +0 -1
  138. package/dist/psbtInputFields-6sRcZqdb.cjs +0 -2
  139. package/dist/psbtInputFields-6sRcZqdb.cjs.map +0 -1
  140. package/dist/psbtInputFields-C5QPn1YK.js +0 -264
  141. package/dist/psbtInputFields-C5QPn1YK.js.map +0 -1
  142. package/dist/signing-BZigafm0.js +0 -64
  143. package/dist/signing-BZigafm0.js.map +0 -1
  144. package/dist/signing-DHSXjhLM.cjs +0 -2
  145. package/dist/signing-DHSXjhLM.cjs.map +0 -1
  146. package/dist/types-PthVHz5q.cjs +0 -2
  147. package/dist/types-PthVHz5q.cjs.map +0 -1
  148. package/dist/types-SYvSQWnc.js +0 -732
  149. package/dist/types-SYvSQWnc.js.map +0 -1
  150. package/dist/vault-registry-reader-CKe9TbX6.cjs +0 -2
  151. package/dist/vault-registry-reader-CKe9TbX6.cjs.map +0 -1
  152. package/dist/vault-registry-reader-CWGbw_wZ.js +0 -1567
  153. package/dist/vault-registry-reader-CWGbw_wZ.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"psbtInputFields-C5QPn1YK.js","sources":["../src/tbv/core/utils/utxo/availability.ts","../src/tbv/core/utils/utxo/reservation.ts","../src/tbv/core/utils/utxo/selectUtxos.ts","../src/tbv/core/utils/transaction/btcTxHash.ts","../src/tbv/core/utils/btc/scriptType.ts","../src/tbv/core/utils/btc/psbtInputFields.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\nimport type { UtxoRef } from \"./reservation\";\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 // Create a set of available UTXOs for O(1) lookup (lowercase for consistency with reservation.ts)\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 * UTXO reservation utilities for vault deposits.\n *\n * Handles tracking which UTXOs are already in use by pending deposits\n * and selecting available UTXOs with smart fallback logic.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { ContractStatus } from \"../../services/deposit/peginState\";\nimport {\n FEE_SAFETY_MARGIN,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"../fee/constants\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** A txid:vout pair uniquely identifying a UTXO (outpoint). */\nexport interface UtxoRef {\n txid: string;\n vout: number;\n}\n\n/** Narrow structural type for pending pegin data. */\nexport interface PendingPeginLike {\n /**\n * Optional vault id. When present, used to skip pending pegins that are\n * already indexed on-chain so the canonical vault copy wins over a\n * tamperable off-chain entry.\n */\n id?: string;\n selectedUTXOs?: Array<{ txid: string; vout: number }>;\n unsignedTxHex?: string;\n}\n\n/** Narrow structural type for vault data. */\nexport interface VaultLike {\n /**\n * Optional vault id. When present, enables on-chain correlation with\n * pending pegins sharing the same id.\n */\n id?: string;\n status: number;\n unsignedPrePeginTx: string;\n}\n\nexport interface SelectUtxosForDepositParams<\n T extends { txid: string; vout: number; value: number },\n> {\n /** All available UTXOs from the wallet. */\n availableUtxos: T[];\n /** UTXOs that are reserved/in-flight and should be avoided if possible. */\n reservedUtxoRefs: UtxoRef[];\n /** Required deposit amount in satoshis (excluding fees). */\n requiredAmount: bigint;\n /** Fee rate in sat/vB. Used to estimate fee buffer for sufficiency check. */\n feeRate: number;\n}\n\n/** Narrow structural type for early UTXO reservations (pre-ETH-registration). */\nexport interface UtxoReservationLike {\n unsignedTxHex: string;\n}\n\nexport interface CollectReservedUtxoRefsParams {\n vaults?: VaultLike[];\n pendingPegins?: PendingPeginLike[];\n utxoReservations?: UtxoReservationLike[];\n}\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n/**\n * Parse a transaction hex and return the UTXO references of all inputs.\n *\n * Parse failures are logged and yield no refs. A malformed hex from an\n * untrusted source (e.g. off-chain storage) must not silently collapse the\n * reservation set — logging makes tampering visible in telemetry instead\n * of swallowing the error.\n */\nfunction extractInputUtxoRefs(txHex: string): UtxoRef[] {\n try {\n const tx = Transaction.fromHex(stripHexPrefix(txHex));\n return tx.ins.map((input) => {\n const txid = Buffer.from(input.hash).reverse().toString(\"hex\");\n return { txid, vout: input.index };\n });\n } catch (error) {\n console.warn(\n \"[utxoReservation] Failed to parse transaction hex; skipping inputs\",\n {\n category: \"utxoReservation\",\n error: error instanceof Error ? error.message : String(error),\n },\n );\n return [];\n }\n}\n\n/** Check if a UTXO matches any reserved ref (case-insensitive txid comparison). */\nfunction isUtxoReserved(\n utxo: { txid: string; vout: number },\n reservedRefs: UtxoRef[],\n): boolean {\n const txidLower = utxo.txid.toLowerCase();\n return reservedRefs.some(\n (ref) => ref.txid.toLowerCase() === txidLower && ref.vout === utxo.vout,\n );\n}\n\n/**\n * Estimate minimum fee buffer for UTXO pre-selection.\n *\n * WARNING: This is a ROUGH ESTIMATE used only to check if unreserved UTXOs\n * are likely sufficient BEFORE the actual signing flow begins. The actual\n * fee calculation happens in the SDK's `selectUtxosForPegin` during signing.\n *\n * Assumptions:\n * - 2 inputs (conservative estimate for most deposits)\n * - 1 vault output (P2TR, 43 vBytes)\n * - 1 change output (P2TR, 43 vBytes)\n * - Transaction overhead (11 vBytes)\n * - 10% safety margin\n */\nfunction estimateMinimumFeeBuffer(feeRate: number): bigint {\n const ASSUMED_INPUTS = 2;\n\n const estimatedTxSize =\n ASSUMED_INPUTS * P2TR_INPUT_SIZE +\n MAX_NON_LEGACY_OUTPUT_SIZE + // vault output\n MAX_NON_LEGACY_OUTPUT_SIZE + // change output\n TX_BUFFER_SIZE_OVERHEAD;\n\n const estimatedFee = Math.ceil(estimatedTxSize * feeRate * FEE_SAFETY_MARGIN);\n return BigInt(estimatedFee);\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Collect UTXO refs from in-flight deposits (PENDING/VERIFIED vaults and\n * pending pegins).\n *\n * On-chain vault data is canonical: for any pending pegin whose `id` matches\n * an indexed on-chain vault, the pending-pegin copy is ignored entirely —\n * the `vaults` branch below extracts refs from the indexer-supplied\n * `unsignedPrePeginTx` so tampered off-chain data cannot poison the\n * reservation set once the vault is indexed.\n *\n * For pegins not yet indexed, refs are derived from the stored\n * `unsignedTxHex` only. The `selectedUTXOs` sidecar is NOT used for\n * reservation: if it disagreed with the transaction's inputs (e.g. because\n * the off-chain source was tampered), trusting it would poison the reserved\n * set. The transaction hex must be validated at the source boundary before\n * being handed to this function; parsing and using its inputs is the single\n * source of truth here.\n */\nexport function collectReservedUtxoRefs(\n params: CollectReservedUtxoRefsParams,\n): UtxoRef[] {\n const reserved: UtxoRef[] = [];\n const {\n vaults = [],\n pendingPegins = [],\n utxoReservations = [],\n } = params;\n\n const onChainVaultIds = new Set(\n vaults\n .map((v) => v.id?.toLowerCase())\n .filter((id): id is string => id !== undefined),\n );\n\n for (const pending of pendingPegins) {\n if (pending.id && onChainVaultIds.has(pending.id.toLowerCase())) {\n continue;\n }\n if (pending.unsignedTxHex) {\n reserved.push(...extractInputUtxoRefs(pending.unsignedTxHex));\n }\n }\n\n for (const vault of vaults) {\n if (\n vault.status !== ContractStatus.PENDING &&\n vault.status !== ContractStatus.VERIFIED\n ) {\n continue;\n }\n reserved.push(...extractInputUtxoRefs(vault.unsignedPrePeginTx));\n }\n\n // Early reservations written before ETH registration to prevent cross-tab\n // UTXO conflicts. These are cleaned up when the deposit completes or fails.\n for (const reservation of utxoReservations) {\n reserved.push(...extractInputUtxoRefs(reservation.unsignedTxHex));\n }\n\n return reserved;\n}\n\n/**\n * Select UTXOs for a deposit, filtering out reserved ones.\n *\n * Logic:\n * 1. Filter out reserved UTXOs from the available pool\n * 2. If unreserved UTXOs are sufficient for the required amount + estimated fee, return them\n * 3. Otherwise, throw — never silently reuse reserved UTXOs, as this risks double-spend\n * failures that strand registered-but-unbroadcastable vaults\n *\n * @param params - Selection parameters\n * @returns Array of unreserved UTXOs to use for the deposit\n * @throws When all UTXOs are reserved or unreserved UTXOs are insufficient\n */\nexport function selectUtxosForDeposit<\n T extends { txid: string; vout: number; value: number },\n>(params: SelectUtxosForDepositParams<T>): T[] {\n const { availableUtxos, reservedUtxoRefs, requiredAmount, feeRate } = params;\n\n // Edge case: no UTXOs available\n if (!availableUtxos || availableUtxos.length === 0) {\n return [];\n }\n\n // Edge case: no reservations, return all\n if (reservedUtxoRefs.length === 0) {\n return availableUtxos;\n }\n\n // Filter out reserved UTXOs\n const unreserved = availableUtxos.filter(\n (utxo) => !isUtxoReserved(utxo, reservedUtxoRefs),\n );\n\n if (unreserved.length === 0) {\n throw new Error(\n \"All available UTXOs are reserved by pending deposits. \" +\n \"Wait for pending deposits to confirm or cancel them before starting a new deposit.\",\n );\n }\n\n const feeBuffer = estimateMinimumFeeBuffer(feeRate);\n const totalRequired = requiredAmount + feeBuffer;\n const unreservedTotal = unreserved.reduce(\n (sum, u) => sum + BigInt(u.value),\n 0n,\n );\n if (unreservedTotal < totalRequired) {\n throw new Error(\n \"Insufficient unreserved UTXOs for this deposit amount. \" +\n \"Wait for pending deposits to confirm or cancel them.\",\n );\n }\n\n return unreserved;\n}\n","/**\n * UTXO selection utilities for peg-in transactions.\n * Follows btc-staking-ts methodology with iterative fee calculation.\n */\n\nimport { script as bitcoinScript } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport {\n BTC_DUST_SAT,\n DUST_THRESHOLD,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n rateBasedTxBufferFee,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"../fee/constants\";\n\n/**\n * Unspent Transaction Output (UTXO) for funding peg-in transactions.\n */\nexport interface UTXO {\n /**\n * Transaction ID of the UTXO (64-char hex without 0x prefix).\n */\n txid: string;\n\n /**\n * Output index within the transaction.\n */\n vout: number;\n\n /**\n * Value in satoshis.\n */\n value: number;\n\n /**\n * Script public key hex.\n */\n scriptPubKey: string;\n}\n\nexport interface UTXOSelectionResult {\n selectedUTXOs: UTXO[];\n totalValue: bigint;\n fee: bigint;\n changeAmount: bigint;\n}\n\n/**\n * Assert that no two UTXOs share the same txid:vout outpoint.\n * Duplicates from a buggy or compromised UTXO source would produce\n * an invalid Bitcoin transaction that double-spends the same outpoint.\n */\nfunction assertNoDuplicateUtxos(utxos: UTXO[]): void {\n const seen = new Set<string>();\n for (const utxo of utxos) {\n const key = `${utxo.txid.toLowerCase()}:${utxo.vout}`;\n if (seen.has(key)) {\n throw new Error(\n `Duplicate UTXO detected: ${utxo.txid}:${utxo.vout}. ` +\n `This indicates a data integrity issue with the UTXO source.`,\n );\n }\n seen.add(key);\n }\n}\n\n/**\n * Selects UTXOs to fund a peg-in transaction with iterative fee calculation.\n *\n * This function implements the btc-staking-ts approach:\n * 1. Filter UTXOs for script validity (no minimum value filter)\n * 2. Sort by value (largest first) to minimize number of inputs\n * 3. Iteratively add UTXOs and recalculate fee until we have enough\n *\n * The fee recalculation is critical because:\n * - Each UTXO added increases transaction size → increases fee\n * - More fee needed might require another UTXO\n * - Change output detection affects fee (adds output size if needed)\n *\n * @param availableUTXOs - All available UTXOs from wallet\n * @param peginAmount - Amount to peg in (satoshis)\n * @param feeRate - Fee rate (sat/vbyte)\n * @param numOutputs - Number of outputs in the unfunded transaction (HTLC + CPFP anchor, before change)\n * @returns Selected UTXOs, total value, calculated fee, and change amount\n * @throws Error if insufficient funds or no valid UTXOs\n */\nexport function selectUtxosForPegin(\n availableUTXOs: UTXO[],\n peginAmount: bigint,\n feeRate: number,\n numOutputs: number,\n): UTXOSelectionResult {\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `Invalid numOutputs: expected a positive integer, got ${numOutputs}`,\n );\n }\n\n if (availableUTXOs.length === 0) {\n throw new Error(\"Insufficient funds: no UTXOs available\");\n }\n\n assertNoDuplicateUtxos(availableUTXOs);\n\n // Filter for script validity ONLY (matching btc-staking-ts approach)\n // No minimum value filter - we accept any UTXO with valid script\n const validUTXOs = availableUTXOs.filter((utxo) => {\n const script = Buffer.from(utxo.scriptPubKey, \"hex\");\n const decompiledScript = bitcoinScript.decompile(script);\n return !!decompiledScript;\n });\n\n if (validUTXOs.length === 0) {\n throw new Error(\n \"Insufficient funds: no valid UTXOs available (all have invalid scripts)\",\n );\n }\n\n // Sort by value: HIGHEST to LOWEST (use big UTXOs first)\n // Use spread to avoid mutating the original array\n const sortedUTXOs = [...validUTXOs].sort((a, b) => b.value - a.value);\n\n const selectedUTXOs: UTXO[] = [];\n let accumulatedValue = 0n;\n let estimatedFee = 0n;\n\n // Iteratively select UTXOs and recalculate fee\n for (const utxo of sortedUTXOs) {\n selectedUTXOs.push(utxo);\n accumulatedValue += BigInt(utxo.value);\n\n // Recalculate fee based on CURRENT number of inputs\n const inputSize = selectedUTXOs.length * P2TR_INPUT_SIZE;\n const outputSize = numOutputs * MAX_NON_LEGACY_OUTPUT_SIZE;\n const baseTxSize = inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD;\n\n // Calculate base fee with buffer\n estimatedFee =\n BigInt(Math.ceil(baseTxSize * feeRate)) +\n BigInt(rateBasedTxBufferFee(feeRate));\n\n // Check if there will be change left after pegin amount and fee\n const changeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n // If change is above dust, add fee for change output\n if (changeAmount > DUST_THRESHOLD) {\n const changeOutputFee = BigInt(\n Math.ceil(MAX_NON_LEGACY_OUTPUT_SIZE * feeRate),\n );\n estimatedFee += changeOutputFee;\n }\n\n // Check if we have enough to cover pegin amount + fees\n if (accumulatedValue >= peginAmount + estimatedFee) {\n // Success! We have enough funds\n const finalChangeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n return {\n selectedUTXOs,\n totalValue: accumulatedValue,\n fee: estimatedFee,\n changeAmount: finalChangeAmount,\n };\n }\n }\n\n // If we get here, we don't have enough funds\n throw new Error(\n `Insufficient funds: need ${peginAmount + estimatedFee} sats (${peginAmount} pegin + ${estimatedFee} fee), have ${accumulatedValue} sats`,\n );\n}\n\n/**\n * Checks if change amount is above dust threshold.\n *\n * @param changeAmount - Change amount in satoshis\n * @returns true if change should be added as output, false if it should go to miners\n */\nexport function shouldAddChangeOutput(changeAmount: bigint): boolean {\n return changeAmount > DUST_THRESHOLD;\n}\n\n/**\n * Gets the dust threshold value.\n *\n * @returns Dust threshold in satoshis\n */\nexport function getDustThreshold(): number {\n return BTC_DUST_SAT;\n}\n","/**\n * Bitcoin Transaction Hash Utilities\n *\n * Provides utilities for calculating Bitcoin transaction hashes in a way that matches\n * the contract's BtcUtils.hashBtcTx() implementation.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport type { Hex } from \"viem\";\n\n/**\n * Calculate Bitcoin transaction hash\n *\n * This matches the contract's BtcUtils.hashBtcTx() implementation:\n * 1. Double SHA256 the transaction bytes\n * 2. Reverse the byte order (Bitcoin convention)\n *\n * The resulting hash is used as the unique vault identifier in the BTCVaultRegistry contract.\n *\n * @param txHex - Transaction hex (with or without 0x prefix)\n * @returns The transaction hash as Hex (with 0x prefix)\n */\nexport function calculateBtcTxHash(txHex: string): Hex {\n // Remove 0x prefix if present\n const cleanHex = txHex.startsWith(\"0x\") ? txHex.slice(2) : txHex;\n\n // Use bitcoinjs-lib to calculate transaction ID (already does double SHA256 + reverse)\n const tx = Transaction.fromHex(cleanHex);\n const txid = tx.getId();\n\n // Return with 0x prefix to match Ethereum hex format\n return `0x${txid}` as Hex;\n}\n","/**\n * Bitcoin Script Type Detection\n *\n * Utilities to detect Bitcoin script types for proper PSBT input construction.\n *\n * @module utils/btc/scriptType\n */\n\n/**\n * Bitcoin script types.\n */\nexport enum BitcoinScriptType {\n P2PKH = \"P2PKH\",\n P2SH = \"P2SH\",\n P2WPKH = \"P2WPKH\",\n P2WSH = \"P2WSH\",\n P2TR = \"P2TR\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/**\n * Detect the type of a Bitcoin script.\n *\n * @param scriptPubKey - The script public key buffer\n * @returns The detected script type\n *\n * @example\n * ```typescript\n * const scriptType = getScriptType(Buffer.from(scriptPubKeyHex, 'hex'));\n * if (scriptType === BitcoinScriptType.P2TR) {\n * // Handle Taproot input\n * }\n * ```\n */\nexport function getScriptType(scriptPubKey: Buffer): BitcoinScriptType {\n const length = scriptPubKey.length;\n\n // P2PKH: OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG (25 bytes)\n if (\n length === 25 &&\n scriptPubKey[0] === 0x76 && // OP_DUP\n scriptPubKey[1] === 0xa9 && // OP_HASH160\n scriptPubKey[2] === 0x14 && // Push 20 bytes\n scriptPubKey[23] === 0x88 && // OP_EQUALVERIFY\n scriptPubKey[24] === 0xac // OP_CHECKSIG\n ) {\n return BitcoinScriptType.P2PKH;\n }\n\n // P2SH: OP_HASH160 <20 bytes> OP_EQUAL (23 bytes)\n if (\n length === 23 &&\n scriptPubKey[0] === 0xa9 && // OP_HASH160\n scriptPubKey[1] === 0x14 && // Push 20 bytes\n scriptPubKey[22] === 0x87 // OP_EQUAL\n ) {\n return BitcoinScriptType.P2SH;\n }\n\n // P2WPKH: OP_0 <20 bytes> (22 bytes)\n if (\n length === 22 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x14 // Push 20 bytes\n ) {\n return BitcoinScriptType.P2WPKH;\n }\n\n // P2WSH: OP_0 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2WSH;\n }\n\n // P2TR (Taproot): OP_1 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x51 && // OP_1\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2TR;\n }\n\n return BitcoinScriptType.UNKNOWN;\n}\n\n","/**\n * PSBT Input Field Construction\n *\n * Constructs the correct PSBT input fields for a given UTXO based on its script type.\n *\n * @module utils/btc/psbtInputFields\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { BitcoinScriptType, getScriptType } from \"./scriptType\";\n\n/**\n * PSBT input fields for supported script types (P2TR, P2WPKH, P2WSH).\n */\nexport interface PsbtInputFields {\n witnessUtxo?: {\n script: Buffer;\n value: number;\n };\n witnessScript?: Buffer;\n tapInternalKey?: Buffer;\n}\n\n/**\n * UTXO information for PSBT construction.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n */\nexport interface UtxoForPsbt {\n /** Transaction ID of the UTXO */\n txid: string;\n /** Output index (vout) of the UTXO */\n vout: number;\n /** Value of the UTXO in satoshis */\n value: number;\n /** ScriptPubKey of the UTXO (hex string) */\n scriptPubKey: string;\n /** Witness script (required for P2WSH) */\n witnessScript?: string;\n}\n\n/**\n * Get PSBT input fields for a given UTXO based on its script type.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param utxo - The unspent transaction output to process\n * @param publicKeyNoCoord - The x-only public key (32 bytes) for Taproot signing\n * @returns PSBT input fields object containing the necessary data\n * @throws Error if required input data is missing or unsupported script type\n */\nexport function getPsbtInputFields(\n utxo: UtxoForPsbt,\n publicKeyNoCoord?: Buffer,\n): PsbtInputFields {\n const scriptPubKey = Buffer.from(utxo.scriptPubKey, \"hex\");\n const type = getScriptType(scriptPubKey);\n\n switch (type) {\n case BitcoinScriptType.P2WPKH: {\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n };\n }\n\n case BitcoinScriptType.P2WSH: {\n if (!utxo.witnessScript) {\n throw new Error(\"Missing witnessScript for P2WSH input\");\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n witnessScript: Buffer.from(utxo.witnessScript, \"hex\"),\n };\n }\n\n case BitcoinScriptType.P2TR: {\n if (publicKeyNoCoord && publicKeyNoCoord.length !== 32) {\n throw new Error(\n `Invalid tapInternalKey length: expected 32 bytes, got ${publicKeyNoCoord.length}`,\n );\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n // tapInternalKey is needed for Taproot signing\n ...(publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }),\n };\n }\n\n default:\n throw new Error(`Unsupported script type: ${type}`);\n }\n}\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","isUtxoReserved","reservedRefs","txidLower","ref","estimateMinimumFeeBuffer","feeRate","estimatedTxSize","P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","estimatedFee","FEE_SAFETY_MARGIN","collectReservedUtxoRefs","params","reserved","vaults","pendingPegins","utxoReservations","onChainVaultIds","v","_a","id","pending","vault","ContractStatus","reservation","selectUtxosForDeposit","reservedUtxoRefs","requiredAmount","unreserved","feeBuffer","totalRequired","sum","u","assertNoDuplicateUtxos","utxos","seen","selectUtxosForPegin","availableUTXOs","peginAmount","numOutputs","validUTXOs","script","bitcoinScript","sortedUTXOs","a","b","selectedUTXOs","accumulatedValue","inputSize","outputSize","baseTxSize","rateBasedTxBufferFee","DUST_THRESHOLD","changeOutputFee","finalChangeAmount","shouldAddChangeOutput","changeAmount","getDustThreshold","BTC_DUST_SAT","calculateBtcTxHash","BitcoinScriptType","getScriptType","scriptPubKey","length","getPsbtInputFields","publicKeyNoCoord","type"],"mappings":";;;;;;;;AAyCO,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,CAAG;AACnB,YAAM,IAAI;AAAA,QACR,wCAAwCN,EAAM,IAAI,IAAIA,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,aAAa;AAAA,UACX,QAAQH;AAAA,UACR,OAAOrE,EAAK;AAAA,QAAA;AAAA;AAAA,QAGd,GAAIwE,KAAoB,EAAE,gBAAgBA,EAAA;AAAA,MAAiB;AAAA,IAE/D;AAAA,IAEA;AACE,YAAM,IAAI,MAAM,4BAA4BC,CAAI,EAAE;AAAA,EAAA;AAExD;"}
@@ -1,64 +0,0 @@
1
- var _ = /* @__PURE__ */ ((e) => (e[e.PENDING = 0] = "PENDING", e[e.VERIFIED = 1] = "VERIFIED", e[e.ACTIVE = 2] = "ACTIVE", e[e.REDEEMED = 3] = "REDEEMED", e[e.LIQUIDATED = 4] = "LIQUIDATED", e[e.INVALID = 5] = "INVALID", e[e.DEPOSITOR_WITHDRAWN = 6] = "DEPOSITOR_WITHDRAWN", e[e.EXPIRED = 7] = "EXPIRED", e))(_ || {}), N = /* @__PURE__ */ ((e) => (e.SUBMIT_WOTS_KEY = "SUBMIT_WOTS_KEY", e.SIGN_PAYOUT_TRANSACTIONS = "SIGN_PAYOUT_TRANSACTIONS", e.SIGN_AND_BROADCAST_TO_BITCOIN = "SIGN_AND_BROADCAST_TO_BITCOIN", e.ACTIVATE_VAULT = "ACTIVATE_VAULT", e.REFUND_HTLC = "REFUND_HTLC", e))(N || {});
2
- function D(e, i = {}) {
3
- const {
4
- transactionsReady: A,
5
- needsWotsKey: T,
6
- pendingIngestion: I,
7
- canRefund: l,
8
- hasProviderTerminalFailure: E
9
- } = i;
10
- return e === 0 ? E ? { contractStatus: e, availableActions: [] } : T ? {
11
- contractStatus: e,
12
- availableActions: [
13
- "SUBMIT_WOTS_KEY"
14
- /* SUBMIT_WOTS_KEY */
15
- ]
16
- } : I === !0 && !A ? {
17
- contractStatus: e,
18
- availableActions: [
19
- "SIGN_AND_BROADCAST_TO_BITCOIN"
20
- /* SIGN_AND_BROADCAST_TO_BITCOIN */
21
- ]
22
- } : I === void 0 && !A ? { contractStatus: e, availableActions: [] } : A ? {
23
- contractStatus: e,
24
- availableActions: [
25
- "SIGN_PAYOUT_TRANSACTIONS"
26
- /* SIGN_PAYOUT_TRANSACTIONS */
27
- ]
28
- } : { contractStatus: e, availableActions: [] } : e === 1 ? {
29
- contractStatus: e,
30
- availableActions: [
31
- "ACTIVATE_VAULT"
32
- /* ACTIVATE_VAULT */
33
- ]
34
- } : e === 2 ? { contractStatus: e, availableActions: [] } : e === 3 ? { contractStatus: e, availableActions: [] } : e === 4 ? { contractStatus: e, availableActions: [] } : e === 7 ? {
35
- contractStatus: e,
36
- availableActions: l ? [
37
- "REFUND_HTLC"
38
- /* REFUND_HTLC */
39
- ] : []
40
- } : e === 5 ? { contractStatus: e, availableActions: [] } : e === 6 ? { contractStatus: e, availableActions: [] } : { contractStatus: e, availableActions: [] };
41
- }
42
- function r(e, i) {
43
- return e.availableActions.includes(i);
44
- }
45
- function O(e, i) {
46
- if (!Number.isInteger(i) || i < 1)
47
- throw new Error(`inputCount must be a positive integer, got ${i}`);
48
- return {
49
- autoFinalized: !1,
50
- signInputs: Array.from({ length: i }, (A, T) => ({
51
- index: T,
52
- publicKey: e,
53
- useTweakedSigner: !1
54
- }))
55
- };
56
- }
57
- export {
58
- _ as C,
59
- N as P,
60
- r as a,
61
- O as c,
62
- D as g
63
- };
64
- //# sourceMappingURL=signing-BZigafm0.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"signing-BZigafm0.js","sources":["../src/tbv/core/services/deposit/peginState.ts","../src/tbv/core/utils/signing.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","import type { SignPsbtOptions } from \"../../../shared/wallets/interfaces\";\n\n/**\n * Create SignPsbtOptions for Taproot script-path PSBT signing.\n *\n * All vault protocol signing operations are Taproot script-path spends that\n * require `useTweakedSigner: false` (untweaked key) and `autoFinalized: false`\n * (to preserve tapScriptSig for Schnorr signature extraction).\n *\n * @param publicKey - Signer's BTC public key (hex). Accepts both compressed\n * (66-char) and x-only (64-char) formats — the wallet connector handles both.\n * @param inputCount - Number of inputs to sign. Generates entries\n * for indices 0 through inputCount-1.\n */\nexport function createTaprootScriptPathSignOptions(\n publicKey: string,\n inputCount: number,\n): SignPsbtOptions {\n if (!Number.isInteger(inputCount) || inputCount < 1) {\n throw new Error(`inputCount must be a positive integer, got ${inputCount}`);\n }\n\n return {\n autoFinalized: false,\n signInputs: Array.from({ length: inputCount }, (_, i) => ({\n index: i,\n publicKey,\n useTweakedSigner: false,\n })),\n };\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","canPerformAction","state","action","createTaprootScriptP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EY="SUBMIT_WOTS_KEY",e.SIGN_PAYOUT_TRANSACTIONS="SIGN_PAYOUT_TRANSACTIONS",e.SIGN_AND_BROADCAST_TO_BITCOIN="SIGN_AND_BROADCAST_TO_BITCOIN",e.ACTIVATE_VAULT="ACTIVATE_VAULT",e.REFUND_HTLC="REFUND_HTLC",e))(E||{});function N(e,i={}){const{transactionsReady:A,needsWotsKey:T,pendingIngestion:I,canRefund:r,hasProviderTerminalFailure:_}=i;return e===0?_?{contractStatus:e,availableActions:[]}:T?{contractStatus:e,availableActions:["SUBMIT_WOTS_KEY"]}:I===!0&&!A?{contractStatus:e,availableActions:["SIGN_AND_BROADCAST_TO_BITCOIN"]}:I===void 0&&!A?{contractStatus:e,availableActions:[]}:A?{contractStatus:e,availableActions:["SIGN_PAYOUT_TRANSACTIONS"]}:{contractStatus:e,availableActions:[]}:e===1?{contractStatus:e,availableActions:["ACTIVATE_VAULT"]}:e===2?{contractStatus:e,availableActions:[]}:e===3?{contractStatus:e,availableActions:[]}:e===4?{contractStatus:e,availableActions:[]}:e===7?{contractStatus:e,availableActions:r?["REFUND_HTLC"]:[]}:e===5?{contractStatus:e,availableActions:[]}:e===6?{contractStatus:e,availableActions:[]}:{contractStatus:e,availableActions:[]}}function D(e,i){return e.availableActions.includes(i)}function n(e,i){if(!Number.isInteger(i)||i<1)throw new Error(`inputCount must be a positive integer, got ${i}`);return{autoFinalized:!1,signInputs:Array.from({length:i},(A,T)=>({index:T,publicKey:e,useTweakedSigner:!1}))}}exports.ContractStatus=l;exports.PeginAction=E;exports.canPerformAction=D;exports.createTaprootScriptPathSignOptions=n;exports.getPeginProtocolState=N;
2
- //# sourceMappingURL=signing-DHSXjhLM.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"signing-DHSXjhLM.cjs","sources":["../src/tbv/core/services/deposit/peginState.ts","../src/tbv/core/utils/signing.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","import type { SignPsbtOptions } from \"../../../shared/wallets/interfaces\";\n\n/**\n * Create SignPsbtOptions for Taproot script-path PSBT signing.\n *\n * All vault protocol signing operations are Taproot script-path spends that\n * require `useTweakedSigner: false` (untweaked key) and `autoFinalized: false`\n * (to preserve tapScriptSig for Schnorr signature extraction).\n *\n * @param publicKey - Signer's BTC public key (hex). Accepts both compressed\n * (66-char) and x-only (64-char) formats — the wallet connector handles both.\n * @param inputCount - Number of inputs to sign. Generates entries\n * for indices 0 through inputCount-1.\n */\nexport function createTaprootScriptPathSignOptions(\n publicKey: string,\n inputCount: number,\n): SignPsbtOptions {\n if (!Number.isInteger(inputCount) || inputCount < 1) {\n throw new Error(`inputCount must be a positive integer, got ${inputCount}`);\n }\n\n return {\n autoFinalized: false,\n signInputs: Array.from({ length: inputCount }, (_, i) => ({\n index: i,\n publicKey,\n useTweakedSigner: false,\n })),\n };\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","canPerformAction","state","action","createTaprootScriptPathSignOptions","publicKey","inputCount","_","i"],"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,CCvLO,SAASC,EACdC,EACAC,EACiB,CACjB,GAAI,CAAC,OAAO,UAAUA,CAAU,GAAKA,EAAa,EAChD,MAAM,IAAI,MAAM,8CAA8CA,CAAU,EAAE,EAG5E,MAAO,CACL,cAAe,GACf,WAAY,MAAM,KAAK,CAAE,OAAQA,GAAc,CAACC,EAAGC,KAAO,CACxD,MAAOA,EACP,UAAAH,EACA,iBAAkB,EAAA,EAClB,CAAA,CAEN"}
@@ -1,2 +0,0 @@
1
- "use strict";var _=Object.defineProperty;var N=(e,t,n)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var p=(e,t,n)=>N(e,typeof t!="symbol"?t+"":t,n);const O=[{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequestBatch",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"requests",type:"tuple[]",internalType:"struct IBTCVaultRegistry.BatchPeginRequest[]",components:[{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}]}],outputs:[{name:"vaultIds",type:"bytes32[]",internalType:"bytes32[]"}],stateMutability:"payable"},{type:"function",name:"activateVaultWithSecret",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"},{name:"s",type:"bytes32",internalType:"bytes32"},{name:"activationMetadata",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"getPegInFee",inputs:[{name:"vaultProvider",type:"address",internalType:"address"}],outputs:[{name:"totalFee",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getVaultProviderBTCKey",inputs:[{name:"vpAddr",type:"address",internalType:"address"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"getBtcVaultBasicInfo",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"vBasic",type:"tuple",internalType:"struct BTCVaultTypes.BTCVaultBasicInfo",components:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"status",type:"uint8",internalType:"enum IBTCVaultRegistry.BTCVaultStatus"},{name:"applicationEntryPoint",type:"address",internalType:"address"},{name:"createdAt",type:"uint256",internalType:"uint256"}]}],stateMutability:"view"},{type:"error",name:"InvalidPeginFee",inputs:[{name:"provided",type:"uint256",internalType:"uint256"},{name:"required",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidSecret",inputs:[]},{type:"error",name:"ActivationDeadlineExpired",inputs:[]},{type:"error",name:"InvalidHashlock",inputs:[]},{type:"error",name:"DuplicateHashlock",inputs:[]},{type:"error",name:"CapExceeded",inputs:[]},{type:"error",name:"InvalidOutputIndex",inputs:[]},{type:"error",name:"PeginSignaturesIncomplete",inputs:[]},{type:"function",name:"getBtcVaultProtocolInfo",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"vProtocol",type:"tuple",internalType:"struct BTCVaultRegistryTypes.BTCVaultProtocolInfo",components:[{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"universalChallengersVersion",type:"uint16",internalType:"uint16"},{name:"appVaultKeepersVersion",type:"uint16",internalType:"uint16"},{name:"offchainParamsVersion",type:"uint16",internalType:"uint16"},{name:"verifiedAt",type:"uint256",internalType:"uint256"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPopSignature",type:"bytes",internalType:"bytes"},{name:"prePeginTxHash",type:"bytes32",internalType:"bytes32"},{name:"vaultProviderCommissionBps",type:"uint16",internalType:"uint16"}]}],stateMutability:"view"},{type:"function",name:"protocolParams",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IProtocolParams"}],stateMutability:"view"},{type:"function",name:"applicationRegistry",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IApplicationRegistry"}],stateMutability:"view"}];class u extends Error{constructor(t,n,r="local",i){super(n),this.code=t,this.source=r,this.data=i,this.name="JsonRpcError"}}const c={TIMEOUT:-32e3,NETWORK:-32001,PROXY_TIMEOUT:-32002,PROXY_UNAVAILABLE:-32003,INVALID_RESPONSE:-32700,RESPONSE_TOO_LARGE:-32701},g="2.0",v=3,f=1e3,w=2*1024*1024,D=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),B=new Set([408,429,500,502,503,504]),L=new Set(["vaultProvider_getPeginStatus","vaultProvider_getPegoutStatus","vaultProvider_requestDepositorPresignTransactions"]);function V(e){return L.has(e)}const C="auth_expired";function U(e){if(!(e instanceof u)||e.source!=="wire")return!1;const t=e.data;return t===null||typeof t!="object"?!1:t.kind===C}class x{constructor(t){p(this,"baseUrl");p(this,"timeout");p(this,"headers");p(this,"requestId",0);p(this,"retries");p(this,"retryDelay");p(this,"maxResponseBytes");p(this,"retryableFor");p(this,"tokenProvider");if(this.baseUrl=t.baseUrl.replace(/\/$/,""),this.timeout=t.timeout,this.headers={"Content-Type":"application/json",...t.headers},this.retries=t.retries??v,this.retryDelay=t.retryDelay??f,this.maxResponseBytes=t.maxResponseBytes??w,!Number.isFinite(this.maxResponseBytes)||this.maxResponseBytes<=0)throw new Error("maxResponseBytes must be a positive finite number");this.retryableFor=t.retryableFor??V,this.tokenProvider=t.tokenProvider}async buildHeaders(t){const n={...this.headers};if(this.tokenProvider){const r=await this.tokenProvider.getToken(t);r&&(n.Authorization=`Bearer ${r}`)}return n}async call(t,n,r){try{return await this.callOnce(t,n,r)}catch(i){if(this.tokenProvider&&U(i))return this.tokenProvider.invalidate(),await this.callOnce(t,n,r);throw i}}async callOnce(t,n,r){const i=await this.fetchWithRetry(t,n,r);let s;try{const a=D.has(t)?await i.text():await k(i,this.maxResponseBytes);s=JSON.parse(a)}catch(a){throw a instanceof u?a:new u(c.INVALID_RESPONSE,"Invalid JSON-RPC response: body is not valid JSON","local")}if(s===null||typeof s!="object"||Array.isArray(s))throw new u(c.INVALID_RESPONSE,`Invalid JSON-RPC response: expected an object, got ${typeof s}`,"local");const o=s;if("error"in o&&o.error!=null){const a=o.error;throw new u(a.code??c.INVALID_RESPONSE,a.message??"Unknown RPC error","wire",a.data)}if(!("result"in o))throw new u(c.INVALID_RESPONSE,'Invalid JSON-RPC response: missing "result" field',"local");return o.result}async callRaw(t,n,r){return this.fetchWithRetry(t,n,r)}async fetchWithRetry(t,n,r){const i=++this.requestId,s=this.retryableFor(t)?this.retries:0,a=JSON.stringify({jsonrpc:g,method:t,params:[n],id:i});let P=null;for(let d=0;d<=s;d++){const b=new AbortController,E=setTimeout(()=>b.abort(),this.timeout),T=r?G(r,b.signal):null,A=T?T.signal:b.signal;try{const y=await this.buildHeaders(t),l=await fetch(this.baseUrl,{method:"POST",headers:y,body:a,signal:A});if(clearTimeout(E),T==null||T.cleanup(),!l.ok){if(d<s&&B.has(l.status)){const I=this.retryDelay*Math.pow(2,d);await this.sleep(I,r);continue}throw new Error(`HTTP error: ${l.status} ${l.statusText}`)}return l}catch(y){if(clearTimeout(E),T==null||T.cleanup(),P=y instanceof Error?y:new Error(String(y)),r!=null&&r.aborted)throw new Error("Request aborted");if(y instanceof Error&&y.name==="AbortError"){if(d<s){const l=this.retryDelay*Math.pow(2,d);await this.sleep(l,r);continue}throw new u(c.TIMEOUT,`Request timeout after ${this.timeout}ms (${s+1} attempts)`,"local")}if(y instanceof TypeError){if(d<s){const l=this.retryDelay*Math.pow(2,d);await this.sleep(l,r);continue}throw new u(c.NETWORK,`Network error: ${y.message} (${s+1} attempts)`,"local")}throw y}}throw P||new Error("Unknown error after retries")}sleep(t,n){return new Promise((r,i)=>{if(n!=null&&n.aborted){i(new Error("Request aborted"));return}const s=setTimeout(()=>{n==null||n.removeEventListener("abort",o),r()},t),o=()=>{clearTimeout(s),i(new Error("Request aborted"))};n==null||n.addEventListener("abort",o,{once:!0})})}getBaseUrl(){return this.baseUrl}}function G(e,t){if(e.aborted)return{signal:e,cleanup:()=>{}};if(t.aborted)return{signal:t,cleanup:()=>{}};const n=new AbortController,r=()=>{t.removeEventListener("abort",i),n.abort()},i=()=>{e.removeEventListener("abort",r),n.abort()};e.addEventListener("abort",r,{once:!0}),t.addEventListener("abort",i,{once:!0});const s=()=>{e.removeEventListener("abort",r),t.removeEventListener("abort",i)};return{signal:n.signal,cleanup:s}}async function k(e,t){const n=e.headers.get("content-length");if(n!==null){const a=Number(n);if(Number.isFinite(a)&&a>t)throw m(t)}if(!e.body)return"";const r=e.body.getReader(),i=new TextDecoder;let s=0,o="";try{for(;;){const{done:a,value:P}=await r.read();if(a)break;if(P){if(s+=P.byteLength,s>t)throw await r.cancel(),m(t);o+=i.decode(P,{stream:!0})}}}finally{r.releaseLock()}return o+i.decode()}function m(e){return new u(c.RESPONSE_TOO_LARGE,`JSON-RPC response exceeds maximum size of ${e} bytes`,"local")}var R=(e=>(e.PENDING_INGESTION="PendingIngestion",e.PENDING_DEPOSITOR_WOTS_PK="PendingDepositorWotsPK",e.PENDING_BABE_SETUP="PendingBabeSetup",e.PENDING_CHALLENGER_PRESIGNING="PendingChallengerPresigning",e.PENDING_PEGIN_SIGS_AVAILABILITY="PendingPeginSigsAvailability",e.PENDING_PRE_PEGIN_CONFIRMATIONS="PendingPrePegInConfirmations",e.PENDING_DEPOSITOR_SIGNATURES="PendingDepositorSignatures",e.PENDING_ACKS="PendingACKs",e.PENDING_ACTIVATION="PendingActivation",e.ACTIVATED="Activated",e.EXPIRED="Expired",e.CLAIM_POSTED="ClaimPosted",e.PEGGED_OUT="PeggedOut",e))(R||{});const M=["PendingIngestion","PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations"],H=["PendingACKs","PendingActivation","Activated"],h=new Set(["PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations",...H]),q=new Set(["Expired","ClaimPosted","PeggedOut"]),F=new Set([...h,"PendingDepositorSignatures"]);var S=(e=>(e[e.DATABASE_ERROR=-32005]="DATABASE_ERROR",e[e.PRESIGN_ERROR=-32006]="PRESIGN_ERROR",e[e.JSON_SERIALIZATION_ERROR=-32007]="JSON_SERIALIZATION_ERROR",e[e.TX_GRAPH_ERROR=-32008]="TX_GRAPH_ERROR",e[e.INVALID_GRAPH=-32009]="INVALID_GRAPH",e[e.VALIDATION_ERROR=-32010]="VALIDATION_ERROR",e[e.NOT_FOUND=-32011]="NOT_FOUND",e[e.INTERNAL_ERROR=-32603]="INTERNAL_ERROR",e))(S||{});exports.BTCVaultRegistryABI=O;exports.DaemonStatus=R;exports.JSON_RPC_ERROR_CODES=c;exports.JsonRpcClient=x;exports.JsonRpcError=u;exports.POST_WOTS_STATUSES=F;exports.PRE_DEPOSITOR_SIGNATURES_STATES=M;exports.RpcErrorCode=S;exports.VP_TERMINAL_STATUSES=q;exports.VP_TRANSIENT_STATUSES=h;
2
- //# sourceMappingURL=types-PthVHz5q.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types-PthVHz5q.cjs","sources":["../src/tbv/core/contracts/abis/BTCVaultRegistry.abi.ts","../src/tbv/core/clients/vault-provider/json-rpc-client.ts","../src/tbv/core/clients/vault-provider/types.ts"],"sourcesContent":["/**\n * BTCVaultRegistry Contract ABI\n *\n * Minimal ABI containing only the functions needed by the SDK.\n * Full ABI is available in the vault service package.\n *\n * @module contracts/abis/BTCVaultRegistry\n */\n\n/**\n * Minimal ABI for BTCVaultRegistry contract.\n * Contains submitPeginRequest, submitPeginRequestBatch, activateVaultWithSecret, getPegInFee, and getBtcVaultBasicInfo.\n */\nexport const BTCVaultRegistryABI = [\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"referralCode\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequestBatch\",\n inputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n {\n name: \"requests\",\n type: \"tuple[]\",\n internalType: \"struct IBTCVaultRegistry.BatchPeginRequest[]\",\n components: [\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"btcPopSignature\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"unsignedPrePeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorSignedPeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"hashlock\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"htlcVout\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"referralCode\", type: \"uint32\", internalType: \"uint32\" },\n { name: \"depositorPayoutBtcAddress\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorWotsPkHash\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n },\n ],\n outputs: [\n { name: \"vaultIds\", type: \"bytes32[]\", internalType: \"bytes32[]\" },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"activateVaultWithSecret\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"s\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"activationMetadata\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getPegInFee\",\n inputs: [\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"totalFee\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getVaultProviderBTCKey\",\n inputs: [\n { name: \"vpAddr\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [\n { name: \"\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getBtcVaultBasicInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"vBasic\",\n type: \"tuple\",\n internalType: \"struct BTCVaultTypes.BTCVaultBasicInfo\",\n components: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"status\",\n type: \"uint8\",\n internalType: \"enum IBTCVaultRegistry.BTCVaultStatus\",\n },\n {\n name: \"applicationEntryPoint\",\n type: \"address\",\n internalType: \"address\",\n },\n { name: \"createdAt\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"error\",\n name: \"InvalidPeginFee\",\n inputs: [\n {\n name: \"provided\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"required\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n },\n {\n type: \"error\",\n name: \"InvalidSecret\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"ActivationDeadlineExpired\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"DuplicateHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"CapExceeded\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidOutputIndex\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"PeginSignaturesIncomplete\",\n inputs: [],\n },\n {\n type: \"function\",\n name: \"getBtcVaultProtocolInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"vProtocol\",\n type: \"tuple\",\n internalType:\n \"struct BTCVaultRegistryTypes.BTCVaultProtocolInfo\",\n components: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"protocolParams\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IProtocolParams\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"applicationRegistry\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IApplicationRegistry\",\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n","/**\n * Generic JSON-RPC 2.0 HTTP Client\n *\n * Framework-agnostic client using `fetch()` — works in browsers and Node.js 18+.\n * Includes configurable retry policy and AbortSignal passthrough.\n */\n\nexport interface JsonRpcRequest<T = unknown> {\n jsonrpc: \"2.0\";\n method: string;\n params: T;\n id: number | string;\n}\n\nexport interface JsonRpcSuccessResponse<T = unknown> {\n jsonrpc: \"2.0\";\n result: T;\n id: number | string;\n}\n\nexport interface JsonRpcErrorResponse {\n jsonrpc: \"2.0\";\n error: {\n code: number;\n message: string;\n data?: unknown;\n };\n id: number | string;\n}\n\nexport type JsonRpcResponse<T = unknown> =\n | JsonRpcSuccessResponse<T>\n | JsonRpcErrorResponse;\n\n/**\n * Injects bearer tokens into requests for auth-gated methods, and is\n * notified on auth-expired responses so it can invalidate its cache.\n *\n * The `JsonRpcClient` is agnostic to which methods are auth-gated —\n * the provider's `getToken(method)` decides. Returning `null` means\n * \"no auth required for this method\"; the client then sends the\n * request with no `Authorization` header.\n */\nexport interface BearerTokenProvider {\n /**\n * Return the bearer token to inject for `method`, or `null` if the\n * method does not require auth.\n */\n getToken(method: string): Promise<string | null>;\n /**\n * Drop the cached token. Next call to `getToken` must re-acquire.\n * Called by the client on reactive-refresh-trigger responses.\n */\n invalidate(): void;\n}\n\nexport interface JsonRpcClientConfig {\n /** Base URL of the RPC service */\n baseUrl: string;\n /** Timeout in milliseconds per request attempt */\n timeout: number;\n /** Optional custom headers */\n headers?: Record<string, string>;\n /** Number of retry attempts for transient errors (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /**\n * Maximum response body size, in bytes, for typed JSON-RPC calls.\n * `callRaw` intentionally returns the unparsed Response and is not capped here.\n * Default: 2 MiB.\n */\n maxResponseBytes?: number;\n /**\n * Predicate that decides which methods retry on transient errors.\n * Default retries only `getPeginStatus`, `getPegoutStatus`, and\n * `requestDepositorPresignTransactions`. Write methods are not\n * retried by default.\n */\n retryableFor?: (method: string) => boolean;\n /**\n * Per-request bearer-token source. A non-null return attaches\n * `Authorization: Bearer <token>`; `null` skips auth. `call`\n * additionally retries once on wire `auth_expired` (invalidate +\n * refetch + retry). `callRaw` skips reactive refresh.\n */\n tokenProvider?: BearerTokenProvider;\n}\n\n/**\n * Identifies whether an error was produced locally (timeout, network\n * failure, malformed response) or parsed from a wire-format JSON-RPC\n * error envelope returned by the server.\n *\n * This matters for anyone inspecting the shared `-32001` code: the SDK\n * uses it internally for network failures AND the server uses it for\n * auth-middleware rejections. The `source` field disambiguates.\n */\nexport type JsonRpcErrorSource = \"wire\" | \"local\";\n\nexport class JsonRpcError extends Error {\n constructor(\n public code: number,\n message: string,\n /** \"wire\" for server-returned envelopes; \"local\" for SDK-side failures. */\n public source: JsonRpcErrorSource = \"local\",\n /** Structured data from the server `error.data` field, if any. */\n public data?: unknown,\n ) {\n super(message);\n this.name = \"JsonRpcError\";\n }\n}\n\nexport const JSON_RPC_ERROR_CODES = {\n TIMEOUT: -32000,\n NETWORK: -32001,\n /** VP proxy: request timed out at proxy level */\n PROXY_TIMEOUT: -32002,\n /** VP proxy: VP unreachable / DNS failure / response too large */\n PROXY_UNAVAILABLE: -32003,\n /** SDK client: response missing \"result\" field (malformed JSON-RPC) */\n INVALID_RESPONSE: -32700,\n /** SDK client: response body exceeded the configured byte limit */\n RESPONSE_TOO_LARGE: -32701,\n} as const;\n\n/** JSON-RPC protocol version */\nconst JSON_RPC_VERSION = \"2.0\" as const;\n\n/** Default number of retry attempts for transient errors */\nconst DEFAULT_RETRY_ATTEMPTS = 3;\n\n/** Default initial retry delay in milliseconds */\nconst DEFAULT_RETRY_DELAY_MS = 1000;\n\n/** Default maximum JSON-RPC response size for typed calls (2 MiB) */\nconst DEFAULT_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;\n\n/**\n * TODO: Temporary typed-call exceptions for methods that currently return large\n * artifact payloads as JSON-RPC results.\n */\nconst UNCAPPED_TYPED_RESPONSE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n\n/** HTTP status codes that indicate transient server errors and are safe to retry */\nconst RETRYABLE_HTTP_STATUS_CODES: ReadonlySet<number> = new Set([\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n]);\n\n/** Default retry predicate: only retry read-only / idempotent methods */\nconst DEFAULT_RETRYABLE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_getPeginStatus\",\n \"vaultProvider_getPegoutStatus\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nfunction defaultRetryableFor(method: string): boolean {\n return DEFAULT_RETRYABLE_METHODS.has(method);\n}\n\n/**\n * Token-expired marker the server emits in `error.data.kind`. When\n * present on a wire-origin error, the client invalidates its cached\n * token and retries the request once with a freshly-acquired bearer.\n *\n * Kept in sync with btc-vault's auth middleware. Absence of the marker\n * means the server does not support reactive refresh yet; we fall back\n * to proactive-only refresh via `BearerTokenProvider.getToken()` TTL\n * checks.\n */\nconst AUTH_EXPIRED_DATA_KIND = \"auth_expired\";\n\nfunction isAuthExpiredError(error: unknown): boolean {\n if (!(error instanceof JsonRpcError)) return false;\n if (error.source !== \"wire\") return false;\n const data = error.data;\n if (data === null || typeof data !== \"object\") return false;\n const kind = (data as { kind?: unknown }).kind;\n return kind === AUTH_EXPIRED_DATA_KIND;\n}\n\n/**\n * Generic JSON-RPC 2.0 HTTP client with safe retry policy.\n */\nexport class JsonRpcClient {\n private baseUrl: string;\n private timeout: number;\n private headers: Record<string, string>;\n private requestId = 0;\n private retries: number;\n private retryDelay: number;\n private maxResponseBytes: number;\n private retryableFor: (method: string) => boolean;\n private tokenProvider?: BearerTokenProvider;\n\n constructor(config: JsonRpcClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, \"\");\n this.timeout = config.timeout;\n this.headers = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n this.retries = config.retries ?? DEFAULT_RETRY_ATTEMPTS;\n this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;\n this.maxResponseBytes =\n config.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;\n if (!Number.isFinite(this.maxResponseBytes) || this.maxResponseBytes <= 0) {\n throw new Error(\"maxResponseBytes must be a positive finite number\");\n }\n this.retryableFor = config.retryableFor ?? defaultRetryableFor;\n this.tokenProvider = config.tokenProvider;\n }\n\n private async buildHeaders(method: string): Promise<Record<string, string>> {\n const headers: Record<string, string> = { ...this.headers };\n if (this.tokenProvider) {\n const token = await this.tokenProvider.getToken(method);\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n }\n return headers;\n }\n\n /**\n * Make a JSON-RPC request with optional retry for safe methods.\n *\n * If the request fails with a wire-origin `auth_expired` error and a\n * `tokenProvider` is configured, the client invalidates its cached\n * token and retries the request once with a freshly-acquired bearer.\n *\n * @param method - The RPC method name\n * @param params - The method parameters\n * @param signal - Optional AbortSignal for caller-controlled cancellation\n * @returns The result from the RPC method\n * @throws JsonRpcError if the RPC call fails\n */\n async call<TParams, TResult>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<TResult> {\n try {\n return await this.callOnce<TParams, TResult>(method, params, signal);\n } catch (error) {\n // The auth-expired retry fires for ALL methods, including mutating\n // ones. This is intentional and safe: the server's auth middleware\n // validates the bearer token BEFORE dispatching to the method\n // handler, so an `auth_expired` error means the handler never ran\n // and no state was mutated. Confirmed against btc-vault at\n // `crates/btc-auth/src/middleware/jsonrpc.rs` — token validation\n // is pre-handler only. The `retryableFor` guard on\n // HTTP-transient-error retries doesn't apply here because that\n // guard is about retrying after a request the server may have\n // started processing; auth_expired is categorically different.\n if (this.tokenProvider && isAuthExpiredError(error)) {\n this.tokenProvider.invalidate();\n return await this.callOnce<TParams, TResult>(method, params, signal);\n }\n throw error;\n }\n }\n\n private async callOnce<TParams, TResult>(\n method: string,\n params: TParams,\n signal: AbortSignal | undefined,\n ): Promise<TResult> {\n const response = await this.fetchWithRetry(method, params, signal);\n\n let jsonResponse: unknown;\n try {\n const responseText = UNCAPPED_TYPED_RESPONSE_METHODS.has(method)\n ? await response.text()\n : await readResponseTextWithLimit(response, this.maxResponseBytes);\n jsonResponse = JSON.parse(responseText);\n } catch (error) {\n if (error instanceof JsonRpcError) {\n throw error;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n \"Invalid JSON-RPC response: body is not valid JSON\",\n \"local\",\n );\n }\n\n if (\n jsonResponse === null ||\n typeof jsonResponse !== \"object\" ||\n Array.isArray(jsonResponse)\n ) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: expected an object, got ${typeof jsonResponse}`,\n \"local\",\n );\n }\n\n const rpcResponse = jsonResponse as Record<string, unknown>;\n\n if (\"error\" in rpcResponse && rpcResponse.error != null) {\n const err = rpcResponse.error as {\n code?: number;\n message?: string;\n data?: unknown;\n };\n throw new JsonRpcError(\n err.code ?? JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n err.message ?? \"Unknown RPC error\",\n \"wire\",\n err.data,\n );\n }\n\n if (!(\"result\" in rpcResponse)) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: missing \"result\" field`,\n \"local\",\n );\n }\n\n return rpcResponse.result as TResult;\n }\n\n /**\n * Make a JSON-RPC request returning the raw Response (unparsed body).\n *\n * Bearer tokens are injected identically to `call`. **Reactive refresh\n * is NOT performed here** — the response body may be unbounded (e.g.\n * claimer-artifact downloads), so the client refuses to parse it to\n * detect auth errors. Callers relying on token-expired retries for\n * large downloads must read the body themselves and re-invoke\n * `callRaw` after `tokenProvider.invalidate()`.\n */\n async callRaw<TParams>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<Response> {\n return this.fetchWithRetry(method, params, signal);\n }\n\n private async fetchWithRetry<TParams>(\n method: string,\n params: TParams,\n callerSignal?: AbortSignal,\n ): Promise<Response> {\n const requestId = ++this.requestId;\n const maxRetries = this.retryableFor(method) ? this.retries : 0;\n\n // jsonrpsee (Rust backend) expects params as an array (positional parameters)\n const request: JsonRpcRequest<TParams[]> = {\n jsonrpc: JSON_RPC_VERSION,\n method,\n params: [params],\n id: requestId,\n };\n\n const body = JSON.stringify(request);\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n // Merge caller signal with per-request timeout signal\n const timeoutController = new AbortController();\n const timeoutId = setTimeout(\n () => timeoutController.abort(),\n this.timeout,\n );\n\n const merged = callerSignal\n ? mergeAbortSignals(callerSignal, timeoutController.signal)\n : null;\n const signal = merged ? merged.signal : timeoutController.signal;\n\n try {\n // Build headers per-attempt so the token provider can return a\n // freshly-acquired bearer after a prior invalidate() on this\n // request (retry loop path) without plumbing state through.\n const headers = await this.buildHeaders(method);\n\n const response = await fetch(this.baseUrl, {\n method: \"POST\",\n headers,\n body,\n signal,\n });\n\n clearTimeout(timeoutId);\n merged?.cleanup();\n\n if (!response.ok) {\n const shouldRetry =\n attempt < maxRetries &&\n RETRYABLE_HTTP_STATUS_CODES.has(response.status);\n\n if (shouldRetry) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n\n throw new Error(\n `HTTP error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n merged?.cleanup();\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if caller aborted (not our timeout)\n if (callerSignal?.aborted) {\n throw new Error(\"Request aborted\");\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.TIMEOUT,\n `Request timeout after ${this.timeout}ms (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Handle network errors (CORS, connection refused, etc.)\n if (error instanceof TypeError) {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.NETWORK,\n `Network error: ${error.message} (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Don't retry JSON-RPC errors (business logic errors)\n throw error;\n }\n }\n\n throw lastError || new Error(\"Unknown error after retries\");\n }\n\n private sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"Request aborted\"));\n return;\n }\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(new Error(\"Request aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n getBaseUrl(): string {\n return this.baseUrl;\n }\n}\n\ninterface MergedSignal {\n signal: AbortSignal;\n /** Remove listeners from the source signals. Call after the request completes. */\n cleanup: () => void;\n}\n\n/**\n * Merge two AbortSignals — the returned signal aborts if either input aborts.\n * Returns a cleanup function to remove listeners when the request completes\n * normally, preventing listener accumulation in long-lived polling flows.\n */\nfunction mergeAbortSignals(a: AbortSignal, b: AbortSignal): MergedSignal {\n if (a.aborted) return { signal: a, cleanup: () => {} };\n if (b.aborted) return { signal: b, cleanup: () => {} };\n\n const controller = new AbortController();\n const onAbortA = () => {\n b.removeEventListener(\"abort\", onAbortB);\n controller.abort();\n };\n const onAbortB = () => {\n a.removeEventListener(\"abort\", onAbortA);\n controller.abort();\n };\n a.addEventListener(\"abort\", onAbortA, { once: true });\n b.addEventListener(\"abort\", onAbortB, { once: true });\n\n const cleanup = () => {\n a.removeEventListener(\"abort\", onAbortA);\n b.removeEventListener(\"abort\", onAbortB);\n };\n\n return { signal: controller.signal, cleanup };\n}\n\nasync function readResponseTextWithLimit(\n response: Response,\n maxBytes: number,\n): Promise<string> {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength !== null) {\n const parsedContentLength = Number(contentLength);\n if (\n Number.isFinite(parsedContentLength) &&\n parsedContentLength > maxBytes\n ) {\n throw responseTooLargeError(maxBytes);\n }\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let totalBytes = 0;\n let responseText = \"\";\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n\n totalBytes += value.byteLength;\n if (totalBytes > maxBytes) {\n await reader.cancel();\n throw responseTooLargeError(maxBytes);\n }\n responseText += decoder.decode(value, { stream: true });\n }\n } finally {\n reader.releaseLock();\n }\n\n return responseText + decoder.decode();\n}\n\nfunction responseTooLargeError(maxBytes: number): JsonRpcError {\n return new JsonRpcError(\n JSON_RPC_ERROR_CODES.RESPONSE_TOO_LARGE,\n `JSON-RPC response exceeds maximum size of ${maxBytes} bytes`,\n \"local\",\n );\n}\n","/**\n * Type definitions for Vault Provider JSON-RPC API.\n *\n * These types match the `vaultProvider_*` RPC namespace defined by the\n * btc-vault daemon. They are the SDK's canonical copy of the VP protocol\n * contract, independent of any frontend framework.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\n// ============================================================================\n// Daemon Status\n// ============================================================================\n\n/**\n * Backend daemon status (vault provider database).\n * Source: btc-vault crates/vaultd/src/workers/claimer/mod.rs PegInStatus enum\n *\n * State flow (happy path):\n * PendingIngestion -> PendingDepositorWotsPK -> PendingBabeSetup -> PendingChallengerPresigning\n * -> PendingPeginSigsAvailability -> PendingPrePegInConfirmations\n * -> PendingDepositorSignatures -> PendingACKs -> PendingActivation -> Activated\n *\n * Terminal / branching states:\n * - Expired: vault timed out before activation\n * - ClaimPosted: claim transaction posted on-chain\n * - PeggedOut: BTC has been returned to the depositor\n */\nexport enum DaemonStatus {\n PENDING_INGESTION = \"PendingIngestion\",\n PENDING_DEPOSITOR_WOTS_PK = \"PendingDepositorWotsPK\",\n PENDING_BABE_SETUP = \"PendingBabeSetup\",\n PENDING_CHALLENGER_PRESIGNING = \"PendingChallengerPresigning\",\n PENDING_PEGIN_SIGS_AVAILABILITY = \"PendingPeginSigsAvailability\",\n PENDING_PRE_PEGIN_CONFIRMATIONS = \"PendingPrePegInConfirmations\",\n PENDING_DEPOSITOR_SIGNATURES = \"PendingDepositorSignatures\",\n PENDING_ACKS = \"PendingACKs\",\n PENDING_ACTIVATION = \"PendingActivation\",\n ACTIVATED = \"Activated\",\n EXPIRED = \"Expired\",\n CLAIM_POSTED = \"ClaimPosted\",\n PEGGED_OUT = \"PeggedOut\",\n}\n\n// ============================================================================\n// Status Groups\n// ============================================================================\n\n/**\n * States where the VP is still processing (no depositor action needed).\n * Excludes PENDING_DEPOSITOR_WOTS_PK (requires depositor action).\n */\nexport const PRE_DEPOSITOR_SIGNATURES_STATES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_INGESTION,\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n];\n\n/** States after PendingDepositorSignatures where the depositor has no action. */\nconst POST_PAYOUT_SIGNATURE_STATUSES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_ACKS,\n DaemonStatus.PENDING_ACTIVATION,\n DaemonStatus.ACTIVATED,\n];\n\n/**\n * Statuses where no depositor action is needed (VP processing or already past\n * depositor interaction). Excludes PENDING_INGESTION and PENDING_DEPOSITOR_WOTS_PK.\n */\nexport const VP_TRANSIENT_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n ...POST_PAYOUT_SIGNATURE_STATUSES,\n]);\n\n/**\n * Terminal VP statuses where no further progress is possible.\n * If the VP reaches one of these states while polling, polling should\n * stop immediately with an error rather than waiting for timeout.\n */\nexport const VP_TERMINAL_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.EXPIRED,\n DaemonStatus.CLAIM_POSTED,\n DaemonStatus.PEGGED_OUT,\n]);\n\n/**\n * Statuses that come after WOTS key submission.\n * If the VP is already in one of these states, the WOTS key was already\n * submitted and we can skip.\n */\nexport const POST_WOTS_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n ...VP_TRANSIENT_STATUSES,\n DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,\n]);\n\n// ============================================================================\n// WOTS Types (needed by SubmitDepositorWotsKeyParams)\n// ============================================================================\n\n/**\n * WOTS configuration for a single block.\n * Matches Rust `babe::wots::Config` serde format.\n */\nexport interface WotsConfig {\n /** Digit bit-width (e.g. 4 → base-16 digits). */\n d: number;\n /** Number of message digits in this block. */\n n: number;\n /** Radix used for the checksum computation. */\n checksum_radix: number;\n}\n\n/**\n * A single block of WOTS public keys.\n * Chain values are arrays of byte values (matching Rust `[u8; 20]`).\n */\nexport interface WotsBlockPublicKey {\n config: WotsConfig;\n message_terminals: number[][];\n checksum_major_terminal: number[];\n checksum_minor_terminal: number[];\n}\n\n// ============================================================================\n// Request Parameter Types\n// ============================================================================\n\n/** Params for requesting the payout/claim/assert transactions to pre-sign. */\nexport interface RequestDepositorPresignTransactionsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for submitting the depositor's WOTS public key to the VP. */\nexport interface SubmitDepositorWotsKeyParams {\n pegin_txid: string;\n depositor_pk: string;\n wots_public_keys: WotsBlockPublicKey[];\n}\n\n/** Per-challenger signatures for the depositor-as-claimer flow. */\nexport interface DepositorPreSigsPerChallenger {\n nopayout_signature: string;\n}\n\n/** Depositor-as-claimer pre-signatures (payout + per-challenger). */\nexport interface DepositorAsClaimerPresignatures {\n payout_signatures: ClaimerSignatures;\n per_challenger: Record<string, DepositorPreSigsPerChallenger>;\n}\n\n/** Params for submitting depositor pre-signatures including claimer presignatures. */\nexport interface SubmitDepositorPresignaturesParams {\n pegin_txid: string;\n depositor_pk: string;\n signatures: Record<string, ClaimerSignatures>;\n depositor_claimer_presignatures: DepositorAsClaimerPresignatures;\n}\n\n/** Payout signatures per claimer. */\nexport interface ClaimerSignatures {\n payout_signature: string;\n}\n\n/** Params for requesting BaBe DecryptorArtifacts from the VP. */\nexport interface RequestDepositorClaimerArtifactsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for querying pegin status. Either pegin_txid or vault_id must be provided. */\nexport type GetPeginStatusParams =\n | { pegin_txid: string; vault_id?: never }\n | { vault_id: string; pegin_txid?: never };\n\n// ============================================================================\n// Response Types\n// ============================================================================\n\n/** A raw Bitcoin transaction with its hex encoding. */\nexport interface TransactionData {\n tx_hex: string;\n}\n\n/** Set of transactions the depositor must pre-sign for a single claimer. */\nexport interface ClaimerTransactions {\n claimer_pubkey: string;\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n}\n\n/** Per-segment connector data for ChallengeAssert inputs. */\nexport interface ChallengeAssertConnectorData {\n wots_pks_json: string;\n gc_wots_keys_json: string;\n}\n\n/** Challenger-specific transactions and signing data for the depositor graph. */\nexport interface PresignDataPerChallenger {\n challenger_pubkey: string;\n challenge_assert_x_tx: TransactionData;\n challenge_assert_y_tx: TransactionData;\n nopayout_tx: TransactionData;\n nopayout_psbt: string;\n challenge_assert_connectors: ChallengeAssertConnectorData[];\n output_label_hashes: string[];\n}\n\n/** Depositor-as-claimer TxGraph transactions. */\nexport interface DepositorGraphTransactions {\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n challenger_presign_data: PresignDataPerChallenger[];\n offchain_params_version: number;\n}\n\n/** Response from `requestDepositorPresignTransactions`. */\nexport interface RequestDepositorPresignTransactionsResponse {\n txs: ClaimerTransactions[];\n depositor_graph: DepositorGraphTransactions;\n}\n\n/** BaBe garbled-circuit session data for a single challenger. */\nexport interface BaBeSessionData {\n decryptor_artifacts_hex: string;\n}\n\n/** Response from `requestDepositorClaimerArtifacts`. */\nexport interface RequestDepositorClaimerArtifactsResponse {\n tx_graph_json: string;\n verifying_key_hex: string;\n babe_sessions: Record<string, BaBeSessionData>;\n}\n\n/** Progress tracker for a multi-challenger operation. */\nexport interface ChallengerProgress {\n total_challengers: number;\n completed_challengers: number;\n completed_challenger_pubkeys: string[];\n pending_challenger_pubkeys: string[];\n}\n\nexport type GcDataProgress = ChallengerProgress;\nexport type AckCollectionProgress = ChallengerProgress;\n\n/** Extended presigning progress with all 3 concurrent phases. */\nexport interface PresigningProgress extends ChallengerProgress {\n depositor_graph_created?: boolean;\n vk_challenger_presigning_completed?: number;\n vk_challenger_presigning_total?: number;\n}\n\n/** Detailed progress breakdown for an in-progress pegin. */\nexport interface PeginProgressDetails {\n gc_data?: GcDataProgress;\n presigning?: PresigningProgress;\n ack_collection?: AckCollectionProgress;\n claimer_graphs?: ClaimerGraphStatus[];\n}\n\n/** Per-claimer graph status (challenger perspective). */\nexport interface ClaimerGraphStatus {\n claimer_pubkey: string;\n presigned: boolean;\n}\n\n/** Response from `getPeginStatus`. */\nexport interface GetPeginStatusResponse {\n pegin_txid: string;\n status: string;\n progress: PeginProgressDetails;\n health_info: string;\n last_error?: string;\n}\n\n// ============================================================================\n// Pegout Types\n// ============================================================================\n\n/** Params for querying pegout status from the VP daemon. */\nexport interface GetPegoutStatusParams {\n pegin_txid: string;\n}\n\n/** Claimer-side pegout progress. */\nexport interface ClaimerPegoutStatus {\n status: string;\n failed: boolean;\n claim_txid?: string;\n claimer_pubkey?: string;\n challenger_pubkey?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Challenger-side pegout progress. */\nexport interface ChallengerPegoutStatus {\n status: string;\n claim_txid?: string;\n claimer_pubkey?: string;\n assert_txid?: string;\n challenge_assert_txid?: string;\n nopayout_txid?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Response from `getPegoutStatus`. */\nexport interface GetPegoutStatusResponse {\n pegin_txid: string;\n found: boolean;\n claimer?: ClaimerPegoutStatus;\n challenger?: ChallengerPegoutStatus;\n}\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/** JSON-RPC error codes returned by the vault provider. */\nexport enum RpcErrorCode {\n DATABASE_ERROR = -32005,\n PRESIGN_ERROR = -32006,\n JSON_SERIALIZATION_ERROR = -32007,\n TX_GRAPH_ERROR = -32008,\n INVALID_GRAPH = -32009,\n VALIDATION_ERROR = -32010,\n NOT_FOUND = -32011,\n INTERNAL_ERROR = -32603,\n}\n"],"names":["BTCVaultRegistryABI","JsonRpcError","code","message","source","data","JSON_RPC_ERROR_CODES","JSON_RPC_VERSION","DEFAULT_RETRY_ATTEMPTS","DEFAULT_RETRY_DELAY_MS","DEFAULT_MAX_RESPONSE_BYTES","UNCAPPED_TYPED_RESPONSE_METHODS","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","AUTH_EXPIRED_DATA_KIND","isAuthExpiredError","error","JsonRpcClient","config","__publicField","headers","token","params","signal","response","jsonResponse","responseText","readResponseTextWithLimit","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","maxBytes","contentLength","parsedContentLength","responseTooLargeError","reader","decoder","totalBytes","done","value","DaemonStatus","PRE_DEPOSITOR_SIGNATURES_STATES","POST_PAYOUT_SIGNATURE_STATUSES","VP_TRANSIENT_STATUSES","VP_TERMINAL_STATUSES","POST_WOTS_STATUSES","RpcErrorCode"],"mappings":"iLAaO,MAAMA,EAAsB,CACjC,CACE,KAAM,WACN,KAAM,qBACN,OAAQ,CACN,CACE,KAAM,YACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,qBACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,kBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,qBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,yBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,gBACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,WACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,WACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,4BACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,sBACN,KAAM,UACN,aAAc,SAAA,CAChB,EAEF,QAAS,CACP,CACE,KAAM,GACN,KAAM,UACN,aAAc,SAAA,CAChB,EAEF,gBAAiB,SAAA,EAEnB,CACE,KAAM,WACN,KAAM,qBACN,OAAQ,CACN,CACE,KAAM,YACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,qBACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,kBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,qBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,yBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,gBACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,WACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KA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