@babylonlabs-io/ts-sdk 0.32.0 → 0.33.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/PeginManager-D2pBM0E-.cjs +2 -0
  2. package/dist/PeginManager-D2pBM0E-.cjs.map +1 -0
  3. package/dist/{PeginManager-DUR1BTKM.js → PeginManager-LeGYbRN2.js} +137 -125
  4. package/dist/PeginManager-LeGYbRN2.js.map +1 -0
  5. package/dist/{buildAndBroadcastRefund-CIHhUmRv.cjs → buildAndBroadcastRefund-BXjYAqdb.cjs} +2 -2
  6. package/dist/buildAndBroadcastRefund-BXjYAqdb.cjs.map +1 -0
  7. package/dist/{buildAndBroadcastRefund-DwrX_IBf.js → buildAndBroadcastRefund-CK8MbGQh.js} +39 -39
  8. package/dist/buildAndBroadcastRefund-CK8MbGQh.js.map +1 -0
  9. package/dist/challengeAssert-06GLZtV8.cjs +2 -0
  10. package/dist/challengeAssert-06GLZtV8.cjs.map +1 -0
  11. package/dist/{challengeAssert-DSlCIBoT.js → challengeAssert-KGVKQh0J.js} +64 -70
  12. package/dist/challengeAssert-KGVKQh0J.js.map +1 -0
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +75 -71
  15. package/dist/{noPayout-DohtepqZ.js → noPayout-BmMd4NNH.js} +44 -50
  16. package/dist/{noPayout-DohtepqZ.js.map → noPayout-BmMd4NNH.js.map} +1 -1
  17. package/dist/noPayout-Bp2TYA_X.cjs +2 -0
  18. package/dist/{noPayout-CDhbGn_B.cjs.map → noPayout-Bp2TYA_X.cjs.map} +1 -1
  19. package/dist/tbv/core/clients/eth/index.d.ts +1 -1
  20. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
  21. package/dist/tbv/core/clients/eth/types.d.ts +13 -0
  22. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  23. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +8 -1
  24. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  25. package/dist/tbv/core/clients/index.cjs +1 -1
  26. package/dist/tbv/core/clients/index.js +30 -27
  27. package/dist/tbv/core/clients/vault-provider/api.d.ts +13 -2
  28. package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -1
  29. package/dist/tbv/core/clients/vault-provider/auth/__tests__/createAuthenticatedVpClient.test.d.ts +11 -0
  30. package/dist/tbv/core/clients/vault-provider/auth/__tests__/createAuthenticatedVpClient.test.d.ts.map +1 -0
  31. package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenRegistry.test.d.ts +2 -0
  32. package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenRegistry.test.d.ts.map +1 -0
  33. package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts +16 -0
  34. package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts.map +1 -0
  35. package/dist/tbv/core/clients/vault-provider/auth/gatedMethods.d.ts +10 -0
  36. package/dist/tbv/core/clients/vault-provider/auth/gatedMethods.d.ts.map +1 -0
  37. package/dist/tbv/core/clients/vault-provider/auth/index.d.ts +5 -2
  38. package/dist/tbv/core/clients/vault-provider/auth/index.d.ts.map +1 -1
  39. package/dist/tbv/core/clients/vault-provider/auth/innerTokenClient.d.ts +4 -0
  40. package/dist/tbv/core/clients/vault-provider/auth/innerTokenClient.d.ts.map +1 -0
  41. package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts +11 -0
  42. package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts.map +1 -0
  43. package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts +18 -23
  44. package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts.map +1 -1
  45. package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts +48 -0
  46. package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts.map +1 -0
  47. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +8 -12
  48. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
  49. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +14 -0
  50. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  51. package/dist/tbv/core/index.cjs +1 -1
  52. package/dist/tbv/core/index.js +66 -62
  53. package/dist/tbv/core/managers/index.d.ts +1 -1
  54. package/dist/tbv/core/primitives/index.cjs +1 -1
  55. package/dist/tbv/core/primitives/index.js +2 -2
  56. package/dist/tbv/core/primitives/psbt/__tests__/peginInput.test.d.ts +3 -3
  57. package/dist/tbv/core/primitives/psbt/payout.d.ts +3 -2
  58. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  59. package/dist/tbv/core/primitives/psbt/peginInput.d.ts +11 -5
  60. package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
  61. package/dist/tbv/core/services/deposit/__tests__/runDepositorPresignFlow.test.d.ts +2 -0
  62. package/dist/tbv/core/services/deposit/__tests__/runDepositorPresignFlow.test.d.ts.map +1 -0
  63. package/dist/tbv/core/services/deposit/index.d.ts +2 -2
  64. package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
  65. package/dist/tbv/core/services/deposit/{signAndSubmitPayouts.d.ts → runDepositorPresignFlow.d.ts} +3 -3
  66. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -0
  67. package/dist/tbv/core/services/index.cjs +1 -1
  68. package/dist/tbv/core/services/index.js +11 -11
  69. package/dist/tbv/core/vault-secrets/__tests__/parseFundingOutpoints.test.d.ts +2 -0
  70. package/dist/tbv/core/vault-secrets/__tests__/parseFundingOutpoints.test.d.ts.map +1 -0
  71. package/dist/tbv/core/vault-secrets/index.d.ts +1 -0
  72. package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
  73. package/dist/tbv/core/vault-secrets/parseFundingOutpoints.d.ts +3 -0
  74. package/dist/tbv/core/vault-secrets/parseFundingOutpoints.d.ts.map +1 -0
  75. package/dist/tbv/index.cjs +1 -1
  76. package/dist/tbv/index.js +66 -62
  77. package/dist/{types-jmEyzzhY.cjs → types-C2IUB0Jd.cjs} +2 -2
  78. package/dist/types-C2IUB0Jd.cjs.map +1 -0
  79. package/dist/{types-CnG3JsRs.js → types-D1o_3Q__.js} +20 -9
  80. package/dist/types-D1o_3Q__.js.map +1 -0
  81. package/dist/{vault-registry-reader-CG6bea1S.js → vault-registry-reader-BeIEh62N.js} +436 -292
  82. package/dist/vault-registry-reader-BeIEh62N.js.map +1 -0
  83. package/dist/vault-registry-reader-DdUgC5IF.cjs +2 -0
  84. package/dist/vault-registry-reader-DdUgC5IF.cjs.map +1 -0
  85. package/package.json +1 -1
  86. package/dist/PeginManager-CTRPJo8m.cjs +0 -2
  87. package/dist/PeginManager-CTRPJo8m.cjs.map +0 -1
  88. package/dist/PeginManager-DUR1BTKM.js.map +0 -1
  89. package/dist/buildAndBroadcastRefund-CIHhUmRv.cjs.map +0 -1
  90. package/dist/buildAndBroadcastRefund-DwrX_IBf.js.map +0 -1
  91. package/dist/challengeAssert-DSlCIBoT.js.map +0 -1
  92. package/dist/challengeAssert-DuhkzZG-.cjs +0 -2
  93. package/dist/challengeAssert-DuhkzZG-.cjs.map +0 -1
  94. package/dist/noPayout-CDhbGn_B.cjs +0 -2
  95. package/dist/tbv/core/services/deposit/__tests__/signAndSubmitPayouts.test.d.ts +0 -2
  96. package/dist/tbv/core/services/deposit/__tests__/signAndSubmitPayouts.test.d.ts.map +0 -1
  97. package/dist/tbv/core/services/deposit/signAndSubmitPayouts.d.ts.map +0 -1
  98. package/dist/types-CnG3JsRs.js.map +0 -1
  99. package/dist/types-jmEyzzhY.cjs.map +0 -1
  100. package/dist/vault-registry-reader-BBS1_AON.cjs +0 -2
  101. package/dist/vault-registry-reader-BBS1_AON.cjs.map +0 -1
  102. package/dist/vault-registry-reader-CG6bea1S.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"challengeAssert-DSlCIBoT.js","sources":["../src/tbv/core/primitives/challengers.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/primitives/psbt/constants.ts","../src/tbv/core/primitives/psbt/depositorPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * Challenger counting utilities.\n *\n * Used for UI-level validation (e.g. computing minimum deposit amounts)\n * where the depositor's identity is known. The transaction builders use\n * `vaultKeeperBtcPubkeys.length` to match the VP's current validation.\n */\n\nimport { processPublicKeyToXOnly } from \"./utils/bitcoin\";\n\n/**\n * Normalize a public key to lowercase x-only hex for reliable comparison.\n *\n * Handles `0x` prefixes, compressed (33-byte), and uncompressed (65-byte) keys.\n */\nfunction normalizeKey(key: string): string {\n return processPublicKeyToXOnly(key).toLowerCase();\n}\n\n/**\n * Compute the number of local challengers for a vault.\n *\n * Mirrors the VP's `compute_num_challengers()` logic:\n * local challengers = {vault_provider} ∪ {vault_keepers} − {depositor}\n *\n * Keys are normalized to x-only lowercase hex before comparison, so\n * `0x`-prefixed, compressed, or mixed-case keys are handled correctly.\n *\n * @param vaultProviderPubkey - Vault provider BTC public key\n * @param vaultKeeperPubkeys - Vault keeper BTC public keys\n * @param depositorPubkey - Depositor (claimer) BTC public key\n * @returns Number of local challengers\n */\nexport function computeNumLocalChallengers(\n vaultProviderPubkey: string,\n vaultKeeperPubkeys: string[],\n depositorPubkey: string,\n): number {\n const localSet = new Set<string>();\n localSet.add(normalizeKey(vaultProviderPubkey));\n for (const vk of vaultKeeperPubkeys) {\n localSet.add(normalizeKey(vk));\n }\n localSet.delete(normalizeKey(depositorPubkey));\n return localSet.size;\n}\n","/**\n * Pre-PegIn PSBT Builder Primitive\n *\n * This module provides pure functions for building unfunded Pre-PegIn transactions\n * and deriving PegIn transactions from them, using the WASM implementation from\n * @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * Pre-PegIn Flow:\n * 1. buildPrePeginPsbt() — creates unfunded Pre-PegIn tx (HTLC output)\n * 2. [caller funds Pre-PegIn tx and computes txid]\n * 3. buildPeginTxFromFundedPrePegin() — derives PegIn tx spending the HTLC\n * 4. buildPeginInputPsbt() — PSBT for depositor to sign PegIn HTLC leaf 0 input\n *\n * @module primitives/psbt/pegin\n */\n\nimport {\n buildPeginTxFromPrePegin,\n createPrePeginTransaction,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\nimport { parseUnfundedWasmTransaction } from \"../../utils/transaction/fundPeginTransaction\";\n\n/**\n * Parameters for building an unfunded Pre-PegIn PSBT\n */\nexport interface PrePeginParams {\n /** Depositor's BTC public key (x-only, 64-char hex without 0x prefix) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Array of vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Array of universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment(s) (64 hex chars = 32 bytes each) */\n hashlocks: readonly string[];\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Amounts to peg in (satoshis), one per deposit */\n pegInAmounts: readonly bigint[];\n /** Fee rate in sat/vB from contract offchain params */\n feeRate: bigint;\n /** Number of local challengers (from contract params) */\n numLocalChallengers: number;\n /** M in M-of-N council multisig (from contract params) */\n councilQuorum: number;\n /** N in M-of-N council multisig (from contract params) */\n councilSize: number;\n /** Bitcoin network */\n network: Network;\n /**\n * Optional 32-byte `SHA256(auth_anchor)` commitment (64-char hex, no\n * `0x` prefix). If provided, the Pre-PegIn tx will include an\n * `OP_RETURN <PUSH32 authAnchorHash>` output at vout =\n * `hashlocks.length`, binding the depositor's bearer-token\n * `auth_anchor` preimage to this Pre-PegIn.\n */\n authAnchorHash?: string;\n}\n\n/**\n * Byte length of an `auth_anchor_hash` commitment when encoded as a\n * lowercase hex string (32 bytes → 64 hex chars).\n */\nconst AUTH_ANCHOR_HASH_HEX_LEN = 64;\n\nconst HEX_PATTERN = /^[0-9a-fA-F]+$/;\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC outputs + optional\n * auth-anchor OP_RETURN + CPFP anchor).\n *\n * The caller is responsible for:\n * - Selecting UTXOs covering totalOutputValue + network fees\n * - Funding the transaction (add inputs and change output)\n * - Calling buildPeginTxFromFundedPrePegin() with the funded tx hex\n */\n psbtHex: string;\n /** Sum of all unfunded outputs — use this for UTXO selection */\n totalOutputValue: bigint;\n /** HTLC output values in satoshis, one per deposit (each includes peginAmount + depositorClaimValue + minPeginFee) */\n htlcValues: readonly bigint[];\n /** HTLC output scriptPubKeys (hex encoded), one per deposit */\n htlcScriptPubKeys: readonly string[];\n /** HTLC Taproot addresses, one per deposit */\n htlcAddresses: readonly string[];\n /** Pegin amounts in satoshis, one per deposit */\n peginAmounts: readonly bigint[];\n /** Depositor claim value computed by WASM from contract parameters */\n depositorClaimValue: bigint;\n /**\n * Vout index of the auth-anchor `OP_RETURN` output if one was\n * included (i.e. `authAnchorHash` was provided), or `null` if not.\n * Always equals `htlcValues.length` when present.\n */\n authAnchorVout: number | null;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn tx\n */\nexport interface BuildPeginTxParams {\n /** Same PrePeginParams used to create the Pre-PegIn transaction */\n prePeginParams: PrePeginParams;\n /** CSV timelock in blocks for the PegIn vault output */\n timelockPegin: number;\n /** Hex-encoded funded Pre-PegIn transaction */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output to spend */\n htlcVout: number;\n}\n\n/**\n * Result of building the PegIn transaction\n */\nexport interface PeginTxResult {\n /** PegIn transaction hex (1 input spending HTLC, 1 vault output) */\n txHex: string;\n /** PegIn transaction ID */\n txid: string;\n /** Vault output scriptPubKey (hex encoded) */\n vaultScriptPubKey: string;\n /** Vault output value in satoshis */\n vaultValue: bigint;\n}\n\n/**\n * Build unfunded Pre-PegIn transaction using WASM.\n *\n * Creates a Bitcoin transaction template with no inputs, an HTLC output, and a\n * CPFP anchor output. The HTLC value is computed internally from the contract\n * parameters — the caller does not need to compute depositorClaimValue separately.\n *\n * @param params - Pre-PegIn parameters\n * @returns Unfunded Pre-PegIn transaction details with HTLC output information\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPrePeginPsbt(\n params: PrePeginParams,\n): Promise<PrePeginPsbtResult> {\n const authAnchorHash = normalizeAuthAnchorHash(params.authAnchorHash);\n\n const result = await createPrePeginTransaction({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlocks: [...params.hashlocks],\n timelockRefund: params.timelockRefund,\n pegInAmounts: [...params.pegInAmounts],\n feeRate: params.feeRate,\n numLocalChallengers: params.numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: params.network,\n authAnchorHash,\n });\n\n // Parse the unfunded tx to sum all output values\n // (HTLCs + optional OP_RETURN + CPFP anchor). This is the amount\n // UTXOs must cover before adding network fees.\n const parsed = parseUnfundedWasmTransaction(result.txHex);\n const totalOutputValue = parsed.outputs.reduce(\n (sum, o) => sum + BigInt(o.value),\n 0n,\n );\n\n // The WASM places the OP_RETURN commitment immediately after the\n // HTLC outputs when authAnchorHash is provided.\n const authAnchorVout =\n authAnchorHash !== undefined ? result.htlcValues.length : null;\n\n return {\n psbtHex: result.txHex,\n totalOutputValue,\n htlcValues: result.htlcValues,\n htlcScriptPubKeys: result.htlcScriptPubKeys,\n htlcAddresses: result.htlcAddresses,\n peginAmounts: result.peginAmounts,\n depositorClaimValue: result.depositorClaimValue,\n authAnchorVout,\n };\n}\n\n/**\n * Validate and normalize an `authAnchorHash` hex string before passing\n * it to the WASM boundary. WASM expects exactly 64 lowercase hex chars.\n */\nfunction normalizeAuthAnchorHash(\n value: string | undefined,\n): string | undefined {\n if (value === undefined) return undefined;\n const cleaned =\n value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (\n cleaned.length !== AUTH_ANCHOR_HASH_HEX_LEN ||\n !HEX_PATTERN.test(cleaned)\n ) {\n throw new Error(\n `authAnchorHash must be 32-byte hex (${AUTH_ANCHOR_HASH_HEX_LEN} chars, no 0x prefix); got length ${cleaned.length}`,\n );\n }\n return cleaned.toLowerCase();\n}\n\n/**\n * Build the PegIn transaction from a funded Pre-PegIn transaction.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output at htlcVout via the\n * hashlock + all-party script (leaf 0).\n *\n * @param params - Build parameters including Pre-PegIn params and funded tx hex\n * @returns PegIn transaction details\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPeginTxFromFundedPrePegin(\n params: BuildPeginTxParams,\n): Promise<PeginTxResult> {\n // WASM reconstructs the Pre-PegIn template from these params to\n // decode the funded tx. Must pass `authAnchorHash` (normalized\n // identically to buildPrePeginPsbt) so the reconstruction matches\n // the original outputs, including the OP_RETURN at vout =\n // hashlocks.length.\n const result = await buildPeginTxFromPrePegin(\n {\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys:\n params.prePeginParams.universalChallengerPubkeys,\n hashlocks: [...params.prePeginParams.hashlocks],\n timelockRefund: params.prePeginParams.timelockRefund,\n pegInAmounts: [...params.prePeginParams.pegInAmounts],\n feeRate: params.prePeginParams.feeRate,\n numLocalChallengers: params.prePeginParams.numLocalChallengers,\n councilQuorum: params.prePeginParams.councilQuorum,\n councilSize: params.prePeginParams.councilSize,\n network: params.prePeginParams.network,\n authAnchorHash: normalizeAuthAnchorHash(\n params.prePeginParams.authAnchorHash,\n ),\n },\n params.timelockPegin,\n params.fundedPrePeginTxHex,\n params.htlcVout,\n );\n\n return {\n txHex: result.txHex,\n txid: result.txid,\n vaultScriptPubKey: result.vaultScriptPubKey,\n vaultValue: result.vaultValue,\n };\n}\n","/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports both non-finalized PSBTs (tapScriptSig) and finalized PSBTs (witness).\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Accepts 64-byte sigs (implicit SIGHASH_DEFAULT) and 65-byte sigs with\n * SIGHASH_ALL (0x01). Rejects all other sighash types including 0x00, which\n * is consensus-invalid per BIP-342 when explicitly appended.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n const sighashByte = sig[64];\n // Only accept SIGHASH_ALL (0x01). Per BIP-342, SIGHASH_DEFAULT is signaled\n // by omitting the sighash byte (64-byte sig). A 65-byte sig with byte 64\n // set to 0x00 is consensus-invalid: Bitcoin Core rejects it with\n // SCRIPT_ERR_SCHNORR_SIG_HASHTYPE. Accepting 0x00 here would let\n // extractPeginInputSignature succeed (stripping the byte) while\n // finalizePeginInputPsbt passes the raw 65-byte sig into the witness,\n // producing a BTC transaction that can never confirm.\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n `Expected SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n\n","/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Payout input index bound to the graph Assert tx (NOT signed). */\nexport const PAYOUT_ASSERT_INPUT_INDEX = 1;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by NoPayout input 0 (signed). */\nexport const ASSERT_NOPAYOUT_OUTPUT_INDEX = 0;\n","/**\n * Depositor Payout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's own Payout transaction\n * (depositor-as-claimer path). The depositor signs input 0 using the\n * payout taproot script from WasmPeginPayoutConnector (PegIn vault UTXO).\n *\n * Input 0 spends PegIn:0 (the vault UTXO) — the same connector used for\n * VP/VK payout signing. The VP verifies this signature using the\n * PeginPayoutConnector's payout script.\n *\n * @module primitives/psbt/depositorPayout\n * @see btc-vault crates/vault/src/sign.rs — verify_depositor_signature / get_payout_tap_leaf_hash\n */\n\nimport {\n type PayoutConnectorParams,\n getPeginPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_PAYOUT_OUTPUT_INDEX,\n DEPOSITOR_PAYOUT_INPUT_COUNT,\n PEGIN_VAULT_OUTPUT_INDEX,\n} from \"./constants\";\n\n/**\n * Parameters for building a depositor Payout PSBT\n */\nexport interface DepositorPayoutParams {\n /** Payout transaction hex (unsigned) */\n payoutTxHex: string;\n /** Authoritative PegIn transaction hex — input 0 must spend PegIn:0 */\n peginTxHex: string;\n /** Authoritative Assert transaction hex — input 1 must spend Assert:0 */\n assertTxHex: string;\n /** Parameters for the PeginPayout connector (depositor, VP, VKs, UCs, timelock) */\n connectorParams: PayoutConnectorParams;\n}\n\n/**\n * Build unsigned depositor Payout PSBT.\n *\n * The depositor's payout transaction has 2 inputs:\n * - Input 0: PegIn:0 (vault UTXO) — depositor signs using PeginPayoutConnector payout script\n * - Input 1: Assert:0 — NOT signed by depositor\n *\n * Both inputs must be present in the PSBT because Taproot SIGHASH_DEFAULT\n * commits to all input prevouts. Prevout script_pubkey/value are derived\n * from the authoritative parent transactions, not trusted from external input.\n *\n * @param params - Depositor payout parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference peginTxHex at output index 0\n * @throws If input 1 does not reference assertTxHex at output index 0\n */\nexport async function buildDepositorPayoutPsbt(\n params: DepositorPayoutParams,\n): Promise<string> {\n const payoutTx = Transaction.fromHex(stripHexPrefix(params.payoutTxHex));\n const peginTx = Transaction.fromHex(stripHexPrefix(params.peginTxHex));\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n\n if (payoutTx.ins.length !== DEPOSITOR_PAYOUT_INPUT_COUNT) {\n throw new Error(\n `Depositor Payout transaction must have exactly ${DEPOSITOR_PAYOUT_INPUT_COUNT} inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n const input0Txid = inputTxidHex(input0);\n const peginTxid = peginTx.getId();\n if (input0Txid !== peginTxid || input0.index !== PEGIN_VAULT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 0 must spend PegIn:${PEGIN_VAULT_OUTPUT_INDEX}. ` +\n `Expected ${peginTxid}:${PEGIN_VAULT_OUTPUT_INDEX}, got ${input0Txid}:${input0.index}`,\n );\n }\n\n const input1Txid = inputTxidHex(input1);\n const assertTxid = assertTx.getId();\n if (input1Txid !== assertTxid || input1.index !== ASSERT_PAYOUT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 1 must spend Assert:${ASSERT_PAYOUT_OUTPUT_INDEX}. ` +\n `Expected ${assertTxid}:${ASSERT_PAYOUT_OUTPUT_INDEX}, got ${input1Txid}:${input1.index}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n const assertPrevOut = assertTx.outs[input1.index];\n\n const { payoutScript, payoutControlBlock } = await getPeginPayoutScriptInfo(\n params.connectorParams,\n );\n const scriptBytes = hexToUint8Array(payoutScript);\n const controlBlock = hexToUint8Array(payoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n });\n\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n","/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction\n * (depositor-as-claimer path, per challenger). The ChallengeAssert tx has\n * NUM_UTXOS_FOR_CHALLENGE_ASSERT (3) inputs, each spending a different Assert\n * output segment. The depositor signs ALL inputs, each with its own taproot\n * script derived from the per-segment connector params.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssert connector (NUM_UTXOS_FOR_CHALLENGE_ASSERT=3)\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) */\n challengeAssertTxHex: string;\n /** Authoritative Assert transaction hex — every input must spend an Assert output */\n assertTxHex: string;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * The ChallengeAssert transaction has 3 inputs (one per Assert output segment).\n * Each input has its own taproot script derived from its connector params.\n * The depositor signs all inputs. Every prevout is derived from the\n * authoritative Assert transaction, never trusted from external input.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the number of connector params does not match the number of inputs\n * @throws If any input does not reference assertTxHex\n * @throws If any referenced Assert output is missing\n * @throws If two inputs reference the same Assert output index\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTx = Transaction.fromHex(\n stripHexPrefix(params.challengeAssertTxHex),\n );\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n const assertTxid = assertTx.getId();\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n const seenAssertOutputs = new Set<number>();\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const inputTxid = inputTxidHex(input);\n if (inputTxid !== assertTxid) {\n throw new Error(\n `ChallengeAssert input ${i} must spend an Assert output. ` +\n `Expected txid ${assertTxid}, got ${inputTxid}`,\n );\n }\n if (!assertTx.outs[input.index]) {\n throw new Error(\n `Assert output ${input.index} not found for ChallengeAssert input ${i} (txid: ${assertTxid})`,\n );\n }\n if (seenAssertOutputs.has(input.index)) {\n throw new Error(\n `ChallengeAssert input ${i} duplicates Assert output index ${input.index}`,\n );\n }\n seenAssertOutputs.add(input.index);\n }\n\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const assertPrevOut = assertTx.outs[input.index];\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n"],"names":["normalizeKey","key","processPublicKeyToXOnly","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","depositorPubkey","localSet","vk","AUTH_ANCHOR_HASH_HEX_LEN","HEX_PATTERN","buildPrePeginPsbt","params","authAnchorHash","normalizeAuthAnchorHash","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","authAnchorVout","value","cleaned","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","buildPeginInputPsbt","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","sighashByte","DEPOSITOR_PAYOUT_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","buildDepositorPayoutPsbt","payoutTx","assertTx","input0","input1","input0Txid","inputTxidHex","peginTxid","input1Txid","assertTxid","peginPrevOut","assertPrevOut","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","buildChallengeAssertPsbt","challengeAssertTx","seenAssertOutputs","i","inputTxid","scriptInfos","cp","getChallengeAssertScriptInfo","script","controlBlockBytes"],"mappings":";;;;;AAeA,SAASA,EAAaC,GAAqB;AACzC,SAAOC,EAAwBD,CAAG,EAAE,YAAA;AACtC;AAgBO,SAASE,EACdC,GACAC,GACAC,GACQ;AACR,QAAMC,wBAAe,IAAA;AACrB,EAAAA,EAAS,IAAIP,EAAaI,CAAmB,CAAC;AAC9C,aAAWI,KAAMH;AACf,IAAAE,EAAS,IAAIP,EAAaQ,CAAE,CAAC;AAE/B,SAAAD,EAAS,OAAOP,EAAaM,CAAe,CAAC,GACtCC,EAAS;AAClB;ACqBA,MAAME,IAA2B,IAE3BC,IAAc;AA2EpB,eAAsBC,EACpBC,GAC6B;AAC7B,QAAMC,IAAiBC,EAAwBF,EAAO,cAAc,GAE9DG,IAAS,MAAMC,EAA0B;AAAA,IAC7C,iBAAiBJ,EAAO;AAAA,IACxB,qBAAqBA,EAAO;AAAA,IAC5B,oBAAoBA,EAAO;AAAA,IAC3B,4BAA4BA,EAAO;AAAA,IACnC,WAAW,CAAC,GAAGA,EAAO,SAAS;AAAA,IAC/B,gBAAgBA,EAAO;AAAA,IACvB,cAAc,CAAC,GAAGA,EAAO,YAAY;AAAA,IACrC,SAASA,EAAO;AAAA,IAChB,qBAAqBA,EAAO;AAAA,IAC5B,eAAeA,EAAO;AAAA,IACtB,aAAaA,EAAO;AAAA,IACpB,SAASA,EAAO;AAAA,IAChB,gBAAAC;AAAA,EAAA,CACD,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nC;AAEA,QAAMkC,IAAc,MAAM,QAAQ;AAAA,IAChCxE,EAAO,wBAAwB,IAAI,CAACyE,MAAOC,EAA6BD,CAAE,CAAC;AAAA,EAAA,GAGvE3C,IAAO,IAAIC,EAAA;AACjB,EAAAD,EAAK,WAAWsC,EAAkB,OAAO,GACzCtC,EAAK,YAAYsC,EAAkB,QAAQ;AAE3C,WAASE,IAAI,GAAGA,IAAIF,EAAkB,IAAI,QAAQE,KAAK;AACrD,UAAMhC,IAAQ8B,EAAkB,IAAIE,CAAC,GAC/BT,IAAgBT,EAAS,KAAKd,EAAM,KAAK,GAEzC,EAAE,QAAAqC,GAAQ,cAAAT,MAAiBM,EAAYF,CAAC,GACxCL,IAAcrC,EAAgB+C,CAAM,GACpCC,IAAoBhD,EAAgBsC,CAAY;AAEtD,IAAApC,EAAK,SAAS;AAAA,MACZ,MAAMQ,EAAM;AAAA,MACZ,OAAOA,EAAM;AAAA,MACb,UAAUA,EAAM;AAAA,MAChB,aAAa;AAAA,QACX,QAAQuB,EAAc;AAAA,QACtB,OAAOA,EAAc;AAAA,MAAA;AAAA,MAEvB,eAAe;AAAA,QACb;AAAA,UACE,aAAa7B;AAAA,UACb,QAAQC,EAAO,KAAKgC,CAAW;AAAA,UAC/B,cAAchC,EAAO,KAAK2C,CAAiB;AAAA,QAAA;AAAA,MAC7C;AAAA,MAEF,gBAAgB3C,EAAO,KAAKC,CAAiB;AAAA,IAAA,CAC9C;AAAA,EACH;AAEA,aAAWC,KAAUiC,EAAkB;AACrC,IAAAtC,EAAK,UAAU;AAAA,MACb,QAAQK,EAAO;AAAA,MACf,OAAOA,EAAO;AAAA,IAAA,CACf;AAGH,SAAOL,EAAK,MAAA;AACd;"}
@@ -1,2 +0,0 @@
1
- "use strict";const o=require("./bitcoin-EYBKDtEW.cjs"),d=require("@babylonlabs-io/babylon-tbv-rust-wasm"),m=require("./fundPeginTransaction-DaWoYCgO.cjs"),p=require("buffer"),l=require("bitcoinjs-lib");function T(e){return o.processPublicKeyToXOnly(e).toLowerCase()}function E(e,t,s){const i=new Set;i.add(T(e));for(const n of t)i.add(T(n));return i.delete(T(s)),i.size}const A=64,$=/^[0-9a-fA-F]+$/;async function C(e){const t=H(e.authAnchorHash),s=await d.createPrePeginTransaction({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlocks:[...e.hashlocks],timelockRefund:e.timelockRefund,pegInAmounts:[...e.pegInAmounts],feeRate:e.feeRate,numLocalChallengers:e.numLocalChallengers,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:e.network,authAnchorHash:t}),n=m.parseUnfundedWasmTransaction(s.txHex).outputs.reduce((c,r)=>c+BigInt(r.value),0n),u=t!==void 0?s.htlcValues.length:null;return{psbtHex:s.txHex,totalOutputValue:n,htlcValues:s.htlcValues,htlcScriptPubKeys:s.htlcScriptPubKeys,htlcAddresses:s.htlcAddresses,peginAmounts:s.peginAmounts,depositorClaimValue:s.depositorClaimValue,authAnchorVout:u}}function H(e){if(e===void 0)return;const t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length!==A||!$.test(t))throw new Error(`authAnchorHash must be 32-byte hex (${A} chars, no 0x prefix); got length ${t.length}`);return t.toLowerCase()}async function B(e){const t=await d.buildPeginTxFromPrePegin({depositorPubkey:e.prePeginParams.depositorPubkey,vaultProviderPubkey:e.prePeginParams.vaultProviderPubkey,vaultKeeperPubkeys:e.prePeginParams.vaultKeeperPubkeys,universalChallengerPubkeys:e.prePeginParams.universalChallengerPubkeys,hashlocks:[...e.prePeginParams.hashlocks],timelockRefund:e.prePeginParams.timelockRefund,pegInAmounts:[...e.prePeginParams.pegInAmounts],feeRate:e.prePeginParams.feeRate,numLocalChallengers:e.prePeginParams.numLocalChallengers,councilQuorum:e.prePeginParams.councilQuorum,councilSize:e.prePeginParams.councilSize,network:e.prePeginParams.network,authAnchorHash:H(e.prePeginParams.authAnchorHash)},e.timelockPegin,e.fundedPrePeginTxHex,e.htlcVout);return{txHex:t.txHex,txid:t.txid,vaultScriptPubKey:t.vaultScriptPubKey,vaultValue:t.vaultValue}}async function U(e){const t=o.stripHexPrefix(e.peginTxHex),s=o.stripHexPrefix(e.fundedPrePeginTxHex),i=await d.getPrePeginHtlcConnectorInfo({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:e.hashlock,timelockRefund:e.timelockRefund,network:e.network}),n=l.Transaction.fromHex(t),u=l.Transaction.fromHex(s);if(n.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${n.ins.length}`);const c=n.ins[0],r=u.getId(),a=o.uint8ArrayToHex(new Uint8Array(c.hash).slice().reverse());if(a!==r)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${r}, got ${a}`);const P=u.outs[c.index];if(!P)throw new Error(`Pre-PegIn output ${c.index} not found (Pre-PegIn has ${u.outs.length} outputs)`);const x=o.hexToUint8Array(i.hashlockScript),f=o.hexToUint8Array(i.hashlockControlBlock),h=new l.Psbt;h.setVersion(n.version),h.setLocktime(n.locktime),h.addInput({hash:c.hash,index:c.index,sequence:c.sequence,witnessUtxo:{script:P.script,value:P.value},tapLeafScript:[{leafVersion:o.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(x),controlBlock:p.Buffer.from(f)}],tapInternalKey:p.Buffer.from(d.tapInternalPubkey)});for(const g of n.outs)h.addOutput({script:g.script,value:g.value});return{psbtHex:h.toHex()}}function L(e,t){const i=l.Psbt.fromHex(e).data.inputs[0];if(!i)throw new Error("PegIn PSBT has no inputs");if(i.tapScriptSig&&i.tapScriptSig.length>0){const n=p.Buffer.from(o.hexToUint8Array(t));for(const u of i.tapScriptSig)if(u.pubkey.equals(n))return O(u.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${t}`)}throw i.finalScriptWitness&&i.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function _(e){const t=l.Psbt.fromHex(e);try{t.finalizeAllInputs()}catch(s){if(!t.data.inputs.every(n=>n.finalScriptWitness||n.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${s}`)}return t.extractTransaction().toHex()}function O(e){if(e.length===64)return o.uint8ArrayToHex(new Uint8Array(e));if(e.length===65){const t=e[64];if(t!==l.Transaction.SIGHASH_ALL)throw new Error(`Unexpected sighash type 0x${t.toString(16).padStart(2,"0")} in PegIn input signature. Expected SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).`);return o.uint8ArrayToHex(new Uint8Array(e.subarray(0,64)))}throw new Error(`Unexpected PegIn input signature length: ${e.length}`)}const S=2,b=0,k=0;async function R(e){const t=l.Transaction.fromHex(o.stripHexPrefix(e.payoutTxHex)),s=l.Transaction.fromHex(o.stripHexPrefix(e.peginTxHex)),i=l.Transaction.fromHex(o.stripHexPrefix(e.assertTxHex));if(t.ins.length!==S)throw new Error(`Depositor Payout transaction must have exactly ${S} inputs, got ${t.ins.length}`);const n=t.ins[0],u=t.ins[1],c=o.inputTxidHex(n),r=s.getId();if(c!==r||n.index!==b)throw new Error(`Depositor Payout input 0 must spend PegIn:${b}. Expected ${r}:${b}, got ${c}:${n.index}`);const a=o.inputTxidHex(u),P=i.getId();if(a!==P||u.index!==k)throw new Error(`Depositor Payout input 1 must spend Assert:${k}. Expected ${P}:${k}, got ${a}:${u.index}`);const x=s.outs[n.index],f=i.outs[u.index],{payoutScript:h,payoutControlBlock:g}=await d.getPeginPayoutScriptInfo(e.connectorParams),I=o.hexToUint8Array(h),v=o.hexToUint8Array(g),y=new l.Psbt;y.setVersion(t.version),y.setLocktime(t.locktime),y.addInput({hash:n.hash,index:n.index,sequence:n.sequence,witnessUtxo:{script:x.script,value:x.value},tapLeafScript:[{leafVersion:o.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(I),controlBlock:p.Buffer.from(v)}],tapInternalKey:p.Buffer.from(d.tapInternalPubkey)}),y.addInput({hash:u.hash,index:u.index,sequence:u.sequence,witnessUtxo:{script:f.script,value:f.value}});for(const w of t.outs)y.addOutput({script:w.script,value:w.value});return y.toHex()}async function V(e){const t=l.Transaction.fromHex(o.stripHexPrefix(e.challengeAssertTxHex)),s=l.Transaction.fromHex(o.stripHexPrefix(e.assertTxHex)),i=s.getId();if(e.connectorParamsPerInput.length!==t.ins.length)throw new Error(`Expected ${t.ins.length} connector params, got ${e.connectorParamsPerInput.length}`);const n=new Set;for(let r=0;r<t.ins.length;r++){const a=t.ins[r],P=o.inputTxidHex(a);if(P!==i)throw new Error(`ChallengeAssert input ${r} must spend an Assert output. Expected txid ${i}, got ${P}`);if(!s.outs[a.index])throw new Error(`Assert output ${a.index} not found for ChallengeAssert input ${r} (txid: ${i})`);if(n.has(a.index))throw new Error(`ChallengeAssert input ${r} duplicates Assert output index ${a.index}`);n.add(a.index)}const u=await Promise.all(e.connectorParamsPerInput.map(r=>d.getChallengeAssertScriptInfo(r))),c=new l.Psbt;c.setVersion(t.version),c.setLocktime(t.locktime);for(let r=0;r<t.ins.length;r++){const a=t.ins[r],P=s.outs[a.index],{script:x,controlBlock:f}=u[r],h=o.hexToUint8Array(x),g=o.hexToUint8Array(f);c.addInput({hash:a.hash,index:a.index,sequence:a.sequence,witnessUtxo:{script:P.script,value:P.value},tapLeafScript:[{leafVersion:o.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(h),controlBlock:p.Buffer.from(g)}],tapInternalKey:p.Buffer.from(d.tapInternalPubkey)})}for(const r of t.outs)c.addOutput({script:r.script,value:r.value});return c.toHex()}exports.buildChallengeAssertPsbt=V;exports.buildDepositorPayoutPsbt=R;exports.buildPeginInputPsbt=U;exports.buildPeginTxFromFundedPrePegin=B;exports.buildPrePeginPsbt=C;exports.computeNumLocalChallengers=E;exports.extractPeginInputSignature=L;exports.finalizePeginInputPsbt=_;
2
- //# sourceMappingURL=challengeAssert-DuhkzZG-.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"challengeAssert-DuhkzZG-.cjs","sources":["../src/tbv/core/primitives/challengers.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/primitives/psbt/constants.ts","../src/tbv/core/primitives/psbt/depositorPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * Challenger counting utilities.\n *\n * Used for UI-level validation (e.g. computing minimum deposit amounts)\n * where the depositor's identity is known. The transaction builders use\n * `vaultKeeperBtcPubkeys.length` to match the VP's current validation.\n */\n\nimport { processPublicKeyToXOnly } from \"./utils/bitcoin\";\n\n/**\n * Normalize a public key to lowercase x-only hex for reliable comparison.\n *\n * Handles `0x` prefixes, compressed (33-byte), and uncompressed (65-byte) keys.\n */\nfunction normalizeKey(key: string): string {\n return processPublicKeyToXOnly(key).toLowerCase();\n}\n\n/**\n * Compute the number of local challengers for a vault.\n *\n * Mirrors the VP's `compute_num_challengers()` logic:\n * local challengers = {vault_provider} ∪ {vault_keepers} − {depositor}\n *\n * Keys are normalized to x-only lowercase hex before comparison, so\n * `0x`-prefixed, compressed, or mixed-case keys are handled correctly.\n *\n * @param vaultProviderPubkey - Vault provider BTC public key\n * @param vaultKeeperPubkeys - Vault keeper BTC public keys\n * @param depositorPubkey - Depositor (claimer) BTC public key\n * @returns Number of local challengers\n */\nexport function computeNumLocalChallengers(\n vaultProviderPubkey: string,\n vaultKeeperPubkeys: string[],\n depositorPubkey: string,\n): number {\n const localSet = new Set<string>();\n localSet.add(normalizeKey(vaultProviderPubkey));\n for (const vk of vaultKeeperPubkeys) {\n localSet.add(normalizeKey(vk));\n }\n localSet.delete(normalizeKey(depositorPubkey));\n return localSet.size;\n}\n","/**\n * Pre-PegIn PSBT Builder Primitive\n *\n * This module provides pure functions for building unfunded Pre-PegIn transactions\n * and deriving PegIn transactions from them, using the WASM implementation from\n * @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * Pre-PegIn Flow:\n * 1. buildPrePeginPsbt() — creates unfunded Pre-PegIn tx (HTLC output)\n * 2. [caller funds Pre-PegIn tx and computes txid]\n * 3. buildPeginTxFromFundedPrePegin() — derives PegIn tx spending the HTLC\n * 4. buildPeginInputPsbt() — PSBT for depositor to sign PegIn HTLC leaf 0 input\n *\n * @module primitives/psbt/pegin\n */\n\nimport {\n buildPeginTxFromPrePegin,\n createPrePeginTransaction,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\nimport { parseUnfundedWasmTransaction } from \"../../utils/transaction/fundPeginTransaction\";\n\n/**\n * Parameters for building an unfunded Pre-PegIn PSBT\n */\nexport interface PrePeginParams {\n /** Depositor's BTC public key (x-only, 64-char hex without 0x prefix) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Array of vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Array of universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment(s) (64 hex chars = 32 bytes each) */\n hashlocks: readonly string[];\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Amounts to peg in (satoshis), one per deposit */\n pegInAmounts: readonly bigint[];\n /** Fee rate in sat/vB from contract offchain params */\n feeRate: bigint;\n /** Number of local challengers (from contract params) */\n numLocalChallengers: number;\n /** M in M-of-N council multisig (from contract params) */\n councilQuorum: number;\n /** N in M-of-N council multisig (from contract params) */\n councilSize: number;\n /** Bitcoin network */\n network: Network;\n /**\n * Optional 32-byte `SHA256(auth_anchor)` commitment (64-char hex, no\n * `0x` prefix). If provided, the Pre-PegIn tx will include an\n * `OP_RETURN <PUSH32 authAnchorHash>` output at vout =\n * `hashlocks.length`, binding the depositor's bearer-token\n * `auth_anchor` preimage to this Pre-PegIn.\n */\n authAnchorHash?: string;\n}\n\n/**\n * Byte length of an `auth_anchor_hash` commitment when encoded as a\n * lowercase hex string (32 bytes → 64 hex chars).\n */\nconst AUTH_ANCHOR_HASH_HEX_LEN = 64;\n\nconst HEX_PATTERN = /^[0-9a-fA-F]+$/;\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC outputs + optional\n * auth-anchor OP_RETURN + CPFP anchor).\n *\n * The caller is responsible for:\n * - Selecting UTXOs covering totalOutputValue + network fees\n * - Funding the transaction (add inputs and change output)\n * - Calling buildPeginTxFromFundedPrePegin() with the funded tx hex\n */\n psbtHex: string;\n /** Sum of all unfunded outputs — use this for UTXO selection */\n totalOutputValue: bigint;\n /** HTLC output values in satoshis, one per deposit (each includes peginAmount + depositorClaimValue + minPeginFee) */\n htlcValues: readonly bigint[];\n /** HTLC output scriptPubKeys (hex encoded), one per deposit */\n htlcScriptPubKeys: readonly string[];\n /** HTLC Taproot addresses, one per deposit */\n htlcAddresses: readonly string[];\n /** Pegin amounts in satoshis, one per deposit */\n peginAmounts: readonly bigint[];\n /** Depositor claim value computed by WASM from contract parameters */\n depositorClaimValue: bigint;\n /**\n * Vout index of the auth-anchor `OP_RETURN` output if one was\n * included (i.e. `authAnchorHash` was provided), or `null` if not.\n * Always equals `htlcValues.length` when present.\n */\n authAnchorVout: number | null;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn tx\n */\nexport interface BuildPeginTxParams {\n /** Same PrePeginParams used to create the Pre-PegIn transaction */\n prePeginParams: PrePeginParams;\n /** CSV timelock in blocks for the PegIn vault output */\n timelockPegin: number;\n /** Hex-encoded funded Pre-PegIn transaction */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output to spend */\n htlcVout: number;\n}\n\n/**\n * Result of building the PegIn transaction\n */\nexport interface PeginTxResult {\n /** PegIn transaction hex (1 input spending HTLC, 1 vault output) */\n txHex: string;\n /** PegIn transaction ID */\n txid: string;\n /** Vault output scriptPubKey (hex encoded) */\n vaultScriptPubKey: string;\n /** Vault output value in satoshis */\n vaultValue: bigint;\n}\n\n/**\n * Build unfunded Pre-PegIn transaction using WASM.\n *\n * Creates a Bitcoin transaction template with no inputs, an HTLC output, and a\n * CPFP anchor output. The HTLC value is computed internally from the contract\n * parameters — the caller does not need to compute depositorClaimValue separately.\n *\n * @param params - Pre-PegIn parameters\n * @returns Unfunded Pre-PegIn transaction details with HTLC output information\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPrePeginPsbt(\n params: PrePeginParams,\n): Promise<PrePeginPsbtResult> {\n const authAnchorHash = normalizeAuthAnchorHash(params.authAnchorHash);\n\n const result = await createPrePeginTransaction({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlocks: [...params.hashlocks],\n timelockRefund: params.timelockRefund,\n pegInAmounts: [...params.pegInAmounts],\n feeRate: params.feeRate,\n numLocalChallengers: params.numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: params.network,\n authAnchorHash,\n });\n\n // Parse the unfunded tx to sum all output values\n // (HTLCs + optional OP_RETURN + CPFP anchor). This is the amount\n // UTXOs must cover before adding network fees.\n const parsed = parseUnfundedWasmTransaction(result.txHex);\n const totalOutputValue = parsed.outputs.reduce(\n (sum, o) => sum + BigInt(o.value),\n 0n,\n );\n\n // The WASM places the OP_RETURN commitment immediately after the\n // HTLC outputs when authAnchorHash is provided.\n const authAnchorVout =\n authAnchorHash !== undefined ? result.htlcValues.length : null;\n\n return {\n psbtHex: result.txHex,\n totalOutputValue,\n htlcValues: result.htlcValues,\n htlcScriptPubKeys: result.htlcScriptPubKeys,\n htlcAddresses: result.htlcAddresses,\n peginAmounts: result.peginAmounts,\n depositorClaimValue: result.depositorClaimValue,\n authAnchorVout,\n };\n}\n\n/**\n * Validate and normalize an `authAnchorHash` hex string before passing\n * it to the WASM boundary. WASM expects exactly 64 lowercase hex chars.\n */\nfunction normalizeAuthAnchorHash(\n value: string | undefined,\n): string | undefined {\n if (value === undefined) return undefined;\n const cleaned =\n value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (\n cleaned.length !== AUTH_ANCHOR_HASH_HEX_LEN ||\n !HEX_PATTERN.test(cleaned)\n ) {\n throw new Error(\n `authAnchorHash must be 32-byte hex (${AUTH_ANCHOR_HASH_HEX_LEN} chars, no 0x prefix); got length ${cleaned.length}`,\n );\n }\n return cleaned.toLowerCase();\n}\n\n/**\n * Build the PegIn transaction from a funded Pre-PegIn transaction.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output at htlcVout via the\n * hashlock + all-party script (leaf 0).\n *\n * @param params - Build parameters including Pre-PegIn params and funded tx hex\n * @returns PegIn transaction details\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPeginTxFromFundedPrePegin(\n params: BuildPeginTxParams,\n): Promise<PeginTxResult> {\n // WASM reconstructs the Pre-PegIn template from these params to\n // decode the funded tx. Must pass `authAnchorHash` (normalized\n // identically to buildPrePeginPsbt) so the reconstruction matches\n // the original outputs, including the OP_RETURN at vout =\n // hashlocks.length.\n const result = await buildPeginTxFromPrePegin(\n {\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys:\n params.prePeginParams.universalChallengerPubkeys,\n hashlocks: [...params.prePeginParams.hashlocks],\n timelockRefund: params.prePeginParams.timelockRefund,\n pegInAmounts: [...params.prePeginParams.pegInAmounts],\n feeRate: params.prePeginParams.feeRate,\n numLocalChallengers: params.prePeginParams.numLocalChallengers,\n councilQuorum: params.prePeginParams.councilQuorum,\n councilSize: params.prePeginParams.councilSize,\n network: params.prePeginParams.network,\n authAnchorHash: normalizeAuthAnchorHash(\n params.prePeginParams.authAnchorHash,\n ),\n },\n params.timelockPegin,\n params.fundedPrePeginTxHex,\n params.htlcVout,\n );\n\n return {\n txHex: result.txHex,\n txid: result.txid,\n vaultScriptPubKey: result.vaultScriptPubKey,\n vaultValue: result.vaultValue,\n };\n}\n","/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports both non-finalized PSBTs (tapScriptSig) and finalized PSBTs (witness).\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Accepts 64-byte sigs (implicit SIGHASH_DEFAULT) and 65-byte sigs with\n * SIGHASH_ALL (0x01). Rejects all other sighash types including 0x00, which\n * is consensus-invalid per BIP-342 when explicitly appended.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n const sighashByte = sig[64];\n // Only accept SIGHASH_ALL (0x01). Per BIP-342, SIGHASH_DEFAULT is signaled\n // by omitting the sighash byte (64-byte sig). A 65-byte sig with byte 64\n // set to 0x00 is consensus-invalid: Bitcoin Core rejects it with\n // SCRIPT_ERR_SCHNORR_SIG_HASHTYPE. Accepting 0x00 here would let\n // extractPeginInputSignature succeed (stripping the byte) while\n // finalizePeginInputPsbt passes the raw 65-byte sig into the witness,\n // producing a BTC transaction that can never confirm.\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n `Expected SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n\n","/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Payout input index bound to the graph Assert tx (NOT signed). */\nexport const PAYOUT_ASSERT_INPUT_INDEX = 1;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by NoPayout input 0 (signed). */\nexport const ASSERT_NOPAYOUT_OUTPUT_INDEX = 0;\n","/**\n * Depositor Payout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's own Payout transaction\n * (depositor-as-claimer path). The depositor signs input 0 using the\n * payout taproot script from WasmPeginPayoutConnector (PegIn vault UTXO).\n *\n * Input 0 spends PegIn:0 (the vault UTXO) — the same connector used for\n * VP/VK payout signing. The VP verifies this signature using the\n * PeginPayoutConnector's payout script.\n *\n * @module primitives/psbt/depositorPayout\n * @see btc-vault crates/vault/src/sign.rs — verify_depositor_signature / get_payout_tap_leaf_hash\n */\n\nimport {\n type PayoutConnectorParams,\n getPeginPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_PAYOUT_OUTPUT_INDEX,\n DEPOSITOR_PAYOUT_INPUT_COUNT,\n PEGIN_VAULT_OUTPUT_INDEX,\n} from \"./constants\";\n\n/**\n * Parameters for building a depositor Payout PSBT\n */\nexport interface DepositorPayoutParams {\n /** Payout transaction hex (unsigned) */\n payoutTxHex: string;\n /** Authoritative PegIn transaction hex — input 0 must spend PegIn:0 */\n peginTxHex: string;\n /** Authoritative Assert transaction hex — input 1 must spend Assert:0 */\n assertTxHex: string;\n /** Parameters for the PeginPayout connector (depositor, VP, VKs, UCs, timelock) */\n connectorParams: PayoutConnectorParams;\n}\n\n/**\n * Build unsigned depositor Payout PSBT.\n *\n * The depositor's payout transaction has 2 inputs:\n * - Input 0: PegIn:0 (vault UTXO) — depositor signs using PeginPayoutConnector payout script\n * - Input 1: Assert:0 — NOT signed by depositor\n *\n * Both inputs must be present in the PSBT because Taproot SIGHASH_DEFAULT\n * commits to all input prevouts. Prevout script_pubkey/value are derived\n * from the authoritative parent transactions, not trusted from external input.\n *\n * @param params - Depositor payout parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference peginTxHex at output index 0\n * @throws If input 1 does not reference assertTxHex at output index 0\n */\nexport async function buildDepositorPayoutPsbt(\n params: DepositorPayoutParams,\n): Promise<string> {\n const payoutTx = Transaction.fromHex(stripHexPrefix(params.payoutTxHex));\n const peginTx = Transaction.fromHex(stripHexPrefix(params.peginTxHex));\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n\n if (payoutTx.ins.length !== DEPOSITOR_PAYOUT_INPUT_COUNT) {\n throw new Error(\n `Depositor Payout transaction must have exactly ${DEPOSITOR_PAYOUT_INPUT_COUNT} inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n const input0Txid = inputTxidHex(input0);\n const peginTxid = peginTx.getId();\n if (input0Txid !== peginTxid || input0.index !== PEGIN_VAULT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 0 must spend PegIn:${PEGIN_VAULT_OUTPUT_INDEX}. ` +\n `Expected ${peginTxid}:${PEGIN_VAULT_OUTPUT_INDEX}, got ${input0Txid}:${input0.index}`,\n );\n }\n\n const input1Txid = inputTxidHex(input1);\n const assertTxid = assertTx.getId();\n if (input1Txid !== assertTxid || input1.index !== ASSERT_PAYOUT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 1 must spend Assert:${ASSERT_PAYOUT_OUTPUT_INDEX}. ` +\n `Expected ${assertTxid}:${ASSERT_PAYOUT_OUTPUT_INDEX}, got ${input1Txid}:${input1.index}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n const assertPrevOut = assertTx.outs[input1.index];\n\n const { payoutScript, payoutControlBlock } = await getPeginPayoutScriptInfo(\n params.connectorParams,\n );\n const scriptBytes = hexToUint8Array(payoutScript);\n const controlBlock = hexToUint8Array(payoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n });\n\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n","/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction\n * (depositor-as-claimer path, per challenger). The ChallengeAssert tx has\n * NUM_UTXOS_FOR_CHALLENGE_ASSERT (3) inputs, each spending a different Assert\n * output segment. The depositor signs ALL inputs, each with its own taproot\n * script derived from the per-segment connector params.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssert connector (NUM_UTXOS_FOR_CHALLENGE_ASSERT=3)\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) */\n challengeAssertTxHex: string;\n /** Authoritative Assert transaction hex — every input must spend an Assert output */\n assertTxHex: string;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * The ChallengeAssert transaction has 3 inputs (one per Assert output segment).\n * Each input has its own taproot script derived from its connector params.\n * The depositor signs all inputs. Every prevout is derived from the\n * authoritative Assert transaction, never trusted from external input.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the number of connector params does not match the number of inputs\n * @throws If any input does not reference assertTxHex\n * @throws If any referenced Assert output is missing\n * @throws If two inputs reference the same Assert output index\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTx = Transaction.fromHex(\n stripHexPrefix(params.challengeAssertTxHex),\n );\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n const assertTxid = assertTx.getId();\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n const seenAssertOutputs = new Set<number>();\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const inputTxid = inputTxidHex(input);\n if (inputTxid !== assertTxid) {\n throw new Error(\n `ChallengeAssert input ${i} must spend an Assert output. ` +\n `Expected txid ${assertTxid}, got ${inputTxid}`,\n );\n }\n if (!assertTx.outs[input.index]) {\n throw new Error(\n `Assert output ${input.index} not found for ChallengeAssert input ${i} (txid: ${assertTxid})`,\n );\n }\n if (seenAssertOutputs.has(input.index)) {\n throw new Error(\n `ChallengeAssert input ${i} duplicates Assert output index ${input.index}`,\n );\n }\n seenAssertOutputs.add(input.index);\n }\n\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const assertPrevOut = assertTx.outs[input.index];\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n"],"names":["normalizeKey","key","processPublicKeyToXOnly","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","depositorPubkey","localSet","vk","AUTH_ANCHOR_HASH_HEX_LEN","HEX_PATTERN","buildPrePeginPsbt","params","authAnchorHash","normalizeAuthAnchorHash","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","o","authAnchorVout","value","cleaned","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","buildPeginInputPsbt","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","sighashByte","DEPOSITOR_PAYOUT_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","buildDepositorPayoutPsbt","payoutTx","assertTx","input0","input1","input0Txid","inputTxidHex","peginTxid","input1Txid","assertTxid","peginPrevOut","assertPrevOut","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","buildChallengeAssertPsbt","challengeAssertTx","seenAssertOutputs","i","inputTxid","scriptInfos","cp","getChallengeAssertScriptInfo","script","controlBlockBytes"],"mappings":"0MAeA,SAASA,EAAaC,EAAqB,CACzC,OAAOC,EAAAA,wBAAwBD,CAAG,EAAE,YAAA,CACtC,CAgBO,SAASE,EACdC,EACAC,EACAC,EACQ,CACR,MAAMC,MAAe,IACrBA,EAAS,IAAIP,EAAaI,CAAmB,CAAC,EAC9C,UAAWI,KAAMH,EACfE,EAAS,IAAIP,EAAaQ,CAAE,CAAC,EAE/B,OAAAD,EAAS,OAAOP,EAAaM,CAAe,CAAC,EACtCC,EAAS,IAClB,CCqBA,MAAME,EAA2B,GAE3BC,EAAc,iBA2EpB,eAAsBC,EACpBC,EAC6B,CAC7B,MAAMC,EAAiBC,EAAwBF,EAAO,cAAc,EAE9DG,EAAS,MAAMC,4BAA0B,CAC7C,gBAAiBJ,EAAO,gBACxB,oBAAqBA,EAAO,oBAC5B,mBAAoBA,EAAO,mBAC3B,2BAA4BA,EAAO,2BACnC,UAAW,CAAC,GAAGA,EAAO,SAAS,EAC/B,eAAgBA,EAAO,eACvB,aAAc,CAAC,GAAGA,EAAO,YAAY,EACrC,QAASA,EAAO,QAChB,oBAAqBA,EAAO,oBAC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,CAAY,EAEtDpC,EAAK,SAAS,CACZ,KAAMQ,EAAM,KACZ,MAAOA,EAAM,MACb,SAAUA,EAAM,SAChB,YAAa,CACX,OAAQuB,EAAc,OACtB,MAAOA,EAAc,KAAA,EAEvB,cAAe,CACb,CACE,YAAa7B,EAAAA,uBACb,OAAQC,EAAAA,OAAO,KAAKgC,CAAW,EAC/B,aAAchC,EAAAA,OAAO,KAAK2C,CAAiB,CAAA,CAC7C,EAEF,eAAgB3C,EAAAA,OAAO,KAAKC,EAAAA,iBAAiB,CAAA,CAC9C,CACH,CAEA,UAAWC,KAAUiC,EAAkB,KACrCtC,EAAK,UAAU,CACb,OAAQK,EAAO,OACf,MAAOA,EAAO,KAAA,CACf,EAGH,OAAOL,EAAK,MAAA,CACd"}
@@ -1,2 +0,0 @@
1
- "use strict";const w=require("@babylonlabs-io/babylon-tbv-rust-wasm"),p=require("buffer"),f=require("bitcoinjs-lib"),n=require("./bitcoin-EYBKDtEW.cjs");async function B(t){await w.initWasm();const{prePeginParams:r,fundedPrePeginTxHex:e,htlcVout:i,refundFee:a,hashlock:u}=t,s=new w.WasmPrePeginTx(r.depositorPubkey,r.vaultProviderPubkey,r.vaultKeeperPubkeys,r.universalChallengerPubkeys,[...r.hashlocks],new BigUint64Array(r.pegInAmounts),r.timelockRefund,r.feeRate,r.numLocalChallengers,r.councilQuorum,r.councilSize,r.network);let o=null;try{o=s.fromFundedTransaction(e);const c=o.buildRefundTx(a,i),y=await w.getPrePeginHtlcConnectorInfo({depositorPubkey:r.depositorPubkey,vaultProviderPubkey:r.vaultProviderPubkey,vaultKeeperPubkeys:r.vaultKeeperPubkeys,universalChallengerPubkeys:r.universalChallengerPubkeys,hashlock:u,timelockRefund:r.timelockRefund,network:r.network}),d=e.startsWith("0x")?e.slice(2):e,l=f.Transaction.fromHex(d),x=l.outs[i];if(!x)throw new Error(`HTLC output at vout ${i} not found in funded Pre-PegIn tx (tx has ${l.outs.length} outputs)`);const h=f.Transaction.fromHex(c);if(h.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${h.ins.length}`);const P=h.ins[0],v=l.getId(),b=n.uint8ArrayToHex(new Uint8Array(P.hash).slice().reverse());if(b!==v)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${v}, got ${b}`);if(P.index!==i)throw new Error(`Refund input index ${P.index} does not match expected htlcVout ${i}`);const g=new f.Psbt;g.setVersion(h.version),g.setLocktime(h.locktime),g.addInput({hash:P.hash,index:P.index,sequence:P.sequence,witnessUtxo:{script:x.script,value:x.value},tapLeafScript:[{leafVersion:n.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(n.hexToUint8Array(y.refundScript)),controlBlock:p.Buffer.from(n.hexToUint8Array(y.refundControlBlock))}],tapInternalKey:p.Buffer.from(w.tapInternalPubkey)});for(const T of h.outs)g.addOutput({script:T.script,value:T.value});return{psbtHex:g.toHex()}}finally{o==null||o.free(),s.free()}}async function m(t){const r=await w.createPayoutConnector({depositor:t.depositor,vaultProvider:t.vaultProvider,vaultKeepers:t.vaultKeepers,universalChallengers:t.universalChallengers,timelockPegin:t.timelockPegin},t.network);return{payoutScript:r.payoutScript,taprootScriptHash:r.taprootScriptHash,scriptPubKey:r.scriptPubKey,address:r.address,payoutControlBlock:r.payoutControlBlock}}const S=3;async function E(t){const r=n.stripHexPrefix(t.payoutTxHex),e=n.stripHexPrefix(t.peginTxHex),i=n.stripHexPrefix(t.assertTxHex),a=await m({depositor:t.depositorBtcPubkey,vaultProvider:t.vaultProviderBtcPubkey,vaultKeepers:t.vaultKeeperBtcPubkeys,universalChallengers:t.universalChallengerBtcPubkeys,timelockPegin:t.timelockPegin,network:t.network}),u=n.hexToUint8Array(a.payoutScript),s=n.hexToUint8Array(a.payoutControlBlock),o=f.Transaction.fromHex(r),c=f.Transaction.fromHex(e),y=f.Transaction.fromHex(i),d=new f.Psbt;if(d.setVersion(o.version),d.setLocktime(o.locktime),o.ins.length!==2)throw new Error(`Payout transaction must have exactly 2 inputs, got ${o.ins.length}`);const l=o.ins[0],x=o.ins[1],h=n.uint8ArrayToHex(new Uint8Array(l.hash).slice().reverse()),P=c.getId();if(h!==P)throw new Error(`Input 0 does not reference pegin transaction. Expected ${P}, got ${h}`);const v=n.uint8ArrayToHex(new Uint8Array(x.hash).slice().reverse()),b=y.getId();if(v!==b)throw new Error(`Input 1 does not reference assert transaction. Expected ${b}, got ${v}`);const g=c.outs[l.index];if(!g)throw new Error(`Previous output not found for input 0 (txid: ${h}, index: ${l.index})`);const T=y.outs[x.index];if(!T)throw new Error(`Previous output not found for input 1 (txid: ${v}, index: ${x.index})`);d.addInput({hash:l.hash,index:l.index,sequence:l.sequence,witnessUtxo:{script:g.script,value:g.value},tapLeafScript:[{leafVersion:n.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(u),controlBlock:p.Buffer.from(s)}],tapInternalKey:p.Buffer.from(w.tapInternalPubkey)}),d.addInput({hash:x.hash,index:x.index,sequence:x.sequence,witnessUtxo:{script:T.script,value:T.value}});for(const k of o.outs)d.addOutput({script:k.script,value:k.value});return{psbtHex:d.toHex()}}function $(t,r){if(!n.isValidHex(r))throw new Error("Invalid registeredPayoutScriptPubKey: not valid hex");const e=p.Buffer.from(n.stripHexPrefix(r),"hex"),i=f.Transaction.fromHex(n.stripHexPrefix(t));if(i.outs.length===0)throw new Error("Payout transaction has no outputs");if(!i.outs.reduce((u,s)=>s.value>u.value?s:u).script.equals(e))throw new Error("Payout transaction does not pay to the registered depositor payout address")}function A(t,r,e=0){const i=f.Psbt.fromHex(t);if(e>=i.data.inputs.length)throw new Error(`Input index ${e} out of range (${i.data.inputs.length} inputs)`);const a=i.data.inputs[e];if(a.tapScriptSig&&a.tapScriptSig.length>0){const u=n.hexToUint8Array(r);for(const s of a.tapScriptSig)if(s.pubkey.equals(p.Buffer.from(u)))return H(s.signature,e);throw new Error(`No signature found for depositor pubkey: ${r} at input ${e}`)}if(a.finalScriptWitness&&a.finalScriptWitness.length>0){const u=I(a.finalScriptWitness);if(u.length!==S)throw new Error(`Unexpected finalized witness stack size at input ${e}: expected ${S} items (signature, script, controlBlock), got ${u.length}`);return H(u[0],e)}throw new Error(`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${e}`)}function H(t,r){if(t.length===64)return n.uint8ArrayToHex(new Uint8Array(t));if(t.length===65){const e=t[64];if(e!==f.Transaction.SIGHASH_ALL)throw new Error(`Unexpected sighash type 0x${e.toString(16).padStart(2,"0")} at input ${r}. Expected SIGHASH_ALL (0x01).`);return n.uint8ArrayToHex(new Uint8Array(t.subarray(0,64)))}throw new Error(`Unexpected signature length at input ${r}: ${t.length}`)}function I(t){const r=[];let e=0;const i=s=>{if(e+s>t.length)throw new Error(`Malformed witness data: need ${s} byte(s) at offset ${e}, only ${t.length-e} remaining`)},a=()=>{i(1);const s=t[e++];if(s<253)return s;if(s===253){i(2);const o=(t[e]|t[e+1]<<8)>>>0;return e+=2,o}if(s===254){i(4);const o=(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0;return e+=4,o}throw new Error(`Malformed witness data: 8-byte varint (0xff) not supported at offset ${e-1}`)},u=a();for(let s=0;s<u;s++){const o=a();i(o),r.push(p.Buffer.from(t.subarray(e,e+o))),e+=o}if(e!==t.length)throw new Error(`Malformed witness data: ${t.length-e} trailing byte(s) after parsing ${u} item(s)`);return r}async function C(t){const r=n.stripHexPrefix(t.noPayoutTxHex),e=f.Transaction.fromHex(r),{noPayoutScript:i,noPayoutControlBlock:a}=await w.getAssertNoPayoutScriptInfo(t.connectorParams,t.challengerPubkey),u=n.hexToUint8Array(i),s=n.hexToUint8Array(a),o=new f.Psbt;o.setVersion(e.version),o.setLocktime(e.locktime);for(let c=0;c<e.ins.length;c++){const y=e.ins[c],d=t.prevouts[c];if(!d)throw new Error(`Missing prevout data for input ${c}`);const l={hash:y.hash,index:y.index,sequence:y.sequence,witnessUtxo:{script:p.Buffer.from(n.hexToUint8Array(n.stripHexPrefix(d.script_pubkey))),value:d.value}};c===0&&(l.tapLeafScript=[{leafVersion:n.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(u),controlBlock:p.Buffer.from(s)}],l.tapInternalKey=p.Buffer.from(w.tapInternalPubkey)),o.addInput(l)}for(const c of e.outs)o.addOutput({script:c.script,value:c.value});return o.toHex()}function R(t,r,e){const i=f.Transaction.fromHex(n.stripHexPrefix(t));if(i.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${i.outs.length}`);const a=n.hexToUint8Array(n.processPublicKeyToXOnly(r)),{output:u}=f.payments.p2tr({internalPubkey:p.Buffer.from(a),network:n.getNetwork(e)});if(!u)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!i.outs[0].script.equals(u))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=R;exports.assertPayoutOutputMatchesRegistered=$;exports.buildNoPayoutPsbt=C;exports.buildPayoutPsbt=E;exports.buildRefundPsbt=B;exports.createPayoutScript=m;exports.extractPayoutSignature=A;
2
- //# sourceMappingURL=noPayout-CDhbGn_B.cjs.map
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=signAndSubmitPayouts.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"signAndSubmitPayouts.test.d.ts","sourceRoot":"","sources":["../../../../../../src/tbv/core/services/deposit/__tests__/signAndSubmitPayouts.test.ts"],"names":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"signAndSubmitPayouts.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/services/deposit/signAndSubmitPayouts.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uCAAuC,CAAC;AAIrE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uCAAuC,CAAC;AAW3E,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AA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types-CnG3JsRs.js","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: \"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 * Predicate to determine if a method is safe to retry.\n * Default: only retry `vaultProvider_getPeginStatus` and `vaultProvider_getPegoutStatus`.\n * Write/mutating methods are NOT retried by default.\n */\n retryableFor?: (method: string) => boolean;\n /**\n * Optional bearer-token provider. If set, the client injects\n * `Authorization: Bearer <token>` for every method the provider\n * returns a non-null token for (`call` and `callRaw` alike).\n *\n * `call` also performs a one-shot reactive refresh when a wire-origin\n * JSON-RPC error carries `error.data.kind === \"auth_expired\"` —\n * it calls `invalidate()`, fetches a fresh token, and retries the\n * request once. `callRaw` does NOT perform reactive refresh (its\n * body may be unbounded; we don't parse it).\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} 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/** 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 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.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 jsonResponse = await response.json();\n } catch {\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","/**\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","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","AUTH_EXPIRED_DATA_KIND","isAuthExpiredError","error","JsonRpcClient","config","__publicField","headers","token","params","signal","response","jsonResponse","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","DaemonStatus","PRE_DEPOSITOR_SIGNATURES_STATES","POST_PAYOUT_SIGNATURE_STATUSES","VP_TRANSIENT_STATUSES","VP_TERMINAL_STATUSES","POST_WOTS_STATUSES","RpcErrorCode"],"mappings":";;;AAaO,MAAMA,IAAsB;AAAA,EACjC;AAAA,IACE,MAAM;AAAA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A,EAAAA,EAAA,iBAAiB,MAAA,IAAjB,kBACAA,EAAAA,EAAA,gBAAgB,MAAA,IAAhB,iBACAA,EAAAA,EAAA,2BAA2B,MAAA,IAA3B,4BACAA,EAAAA,EAAA,iBAAiB,MAAA,IAAjB,kBACAA,EAAAA,EAAA,gBAAgB,MAAA,IAAhB,iBACAA,EAAAA,EAAA,mBAAmB,MAAA,IAAnB,oBACAA,EAAAA,EAAA,YAAY,MAAA,IAAZ,aACAA,EAAAA,EAAA,iBAAiB,MAAA,IAAjB,kBARUA,IAAAA,KAAA,CAAA,CAAA;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types-jmEyzzhY.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: \"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 * Predicate to determine if a method is safe to retry.\n * Default: only retry `vaultProvider_getPeginStatus` and `vaultProvider_getPegoutStatus`.\n * Write/mutating methods are NOT retried by default.\n */\n retryableFor?: (method: string) => boolean;\n /**\n * Optional bearer-token provider. If set, the client injects\n * `Authorization: Bearer <token>` for every method the provider\n * returns a non-null token for (`call` and `callRaw` alike).\n *\n * `call` also performs a one-shot reactive refresh when a wire-origin\n * JSON-RPC error carries `error.data.kind === \"auth_expired\"` —\n * it calls `invalidate()`, fetches a fresh token, and retries the\n * request once. `callRaw` does NOT perform reactive refresh (its\n * body may be unbounded; we don't parse it).\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} 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/** 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 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.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 jsonResponse = await response.json();\n } catch {\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","/**\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","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","AUTH_EXPIRED_DATA_KIND","isAuthExpiredError","error","JsonRpcClient","config","__publicField","headers","token","params","signal","response","jsonResponse","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","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,EA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