@babylonlabs-io/ts-sdk 0.73.0 → 0.74.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 (145) hide show
  1. package/dist/{PeginManager-E-UHA1un.cjs → PeginManager-DEByBX5R.cjs} +2 -2
  2. package/dist/{PeginManager-E-UHA1un.cjs.map → PeginManager-DEByBX5R.cjs.map} +1 -1
  3. package/dist/{PeginManager-C9RPOd0L.js → PeginManager-DNimKlmw.js} +11 -11
  4. package/dist/{PeginManager-C9RPOd0L.js.map → PeginManager-DNimKlmw.js.map} +1 -1
  5. package/dist/{bip322Verify-D6sBBUHE.js → bip322Verify-DSco3Yhl.js} +2 -2
  6. package/dist/{bip322Verify-D6sBBUHE.js.map → bip322Verify-DSco3Yhl.js.map} +1 -1
  7. package/dist/buildAndBroadcastReclaim-Cqc6Jiqk.cjs +2 -0
  8. package/dist/{buildAndBroadcastReclaim-U-PyFfDg.cjs.map → buildAndBroadcastReclaim-Cqc6Jiqk.cjs.map} +1 -1
  9. package/dist/{buildAndBroadcastReclaim-BXclIcu_.js → buildAndBroadcastReclaim-DCGcupg7.js} +6 -6
  10. package/dist/{buildAndBroadcastReclaim-BXclIcu_.js.map → buildAndBroadcastReclaim-DCGcupg7.js.map} +1 -1
  11. package/dist/constants-BTZdyOuk.cjs +2 -0
  12. package/dist/constants-BTZdyOuk.cjs.map +1 -0
  13. package/dist/constants-D5vORbQE.js +29 -0
  14. package/dist/constants-D5vORbQE.js.map +1 -0
  15. package/dist/fundPeginTransaction-54-Rwb2k.cjs +2 -0
  16. package/dist/fundPeginTransaction-54-Rwb2k.cjs.map +1 -0
  17. package/dist/fundPeginTransaction-CwhRbCQC.js +88 -0
  18. package/dist/fundPeginTransaction-CwhRbCQC.js.map +1 -0
  19. package/dist/{index-Cs7_Evtk.cjs → index-CK1Xvq4K.cjs} +2 -2
  20. package/dist/{index-Cs7_Evtk.cjs.map → index-CK1Xvq4K.cjs.map} +1 -1
  21. package/dist/{index-LgmJhdEN.js → index-DQ5bfoT3.js} +2 -2
  22. package/dist/{index-LgmJhdEN.js.map → index-DQ5bfoT3.js.map} +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +166 -161
  25. package/dist/noPayout-4RZB2g1e.cjs +2 -0
  26. package/dist/noPayout-4RZB2g1e.cjs.map +1 -0
  27. package/dist/noPayout-DiGr4eas.js +361 -0
  28. package/dist/noPayout-DiGr4eas.js.map +1 -0
  29. package/dist/{parseFundingOutpoints-B67CoXpF.js → parseFundingOutpoints-BQWvINfm.js} +2 -2
  30. package/dist/{parseFundingOutpoints-B67CoXpF.js.map → parseFundingOutpoints-BQWvINfm.js.map} +1 -1
  31. package/dist/pegin-registration-client-CXK3B_D1.js +882 -0
  32. package/dist/pegin-registration-client-CXK3B_D1.js.map +1 -0
  33. package/dist/pegin-registration-client-DLsMNm8Z.cjs +2 -0
  34. package/dist/pegin-registration-client-DLsMNm8Z.cjs.map +1 -0
  35. package/dist/{primeVpAuth-DBHohVKM.cjs → primeVpAuth-BOGKniTl.cjs} +2 -2
  36. package/dist/{primeVpAuth-DBHohVKM.cjs.map → primeVpAuth-BOGKniTl.cjs.map} +1 -1
  37. package/dist/{primeVpAuth-DvaD45q_.js → primeVpAuth-DdfHSC53.js} +4 -4
  38. package/dist/{primeVpAuth-DvaD45q_.js.map → primeVpAuth-DdfHSC53.js.map} +1 -1
  39. package/dist/{psbtInputFields-BIxBpPj2.cjs → psbtInputFields-BrV_ZfL_.cjs} +2 -2
  40. package/dist/{psbtInputFields-BIxBpPj2.cjs.map → psbtInputFields-BrV_ZfL_.cjs.map} +1 -1
  41. package/dist/{psbtInputFields-B3e05Xe6.js → psbtInputFields-CCVyaQMi.js} +2 -2
  42. package/dist/{psbtInputFields-B3e05Xe6.js.map → psbtInputFields-CCVyaQMi.js.map} +1 -1
  43. package/dist/secp256k1-D-H9jmd7.js +1766 -0
  44. package/dist/secp256k1-D-H9jmd7.js.map +1 -0
  45. package/dist/secp256k1-DDHQ1_za.cjs +2 -0
  46. package/dist/secp256k1-DDHQ1_za.cjs.map +1 -0
  47. package/dist/{sha2-CrlWM5S8.js → sha2-CLpQd0Rd.js} +8 -8
  48. package/dist/{sha2-CrlWM5S8.js.map → sha2-CLpQd0Rd.js.map} +1 -1
  49. package/dist/{signPsbtsWithFallback-DMSpIQWH.cjs → signPsbtsWithFallback-DtwzL5AA.cjs} +2 -2
  50. package/dist/{signPsbtsWithFallback-DMSpIQWH.cjs.map → signPsbtsWithFallback-DtwzL5AA.cjs.map} +1 -1
  51. package/dist/{signPsbtsWithFallback-0VBALhjS.js → signPsbtsWithFallback-f7QLp0q8.js} +4 -4
  52. package/dist/{signPsbtsWithFallback-0VBALhjS.js.map → signPsbtsWithFallback-f7QLp0q8.js.map} +1 -1
  53. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  54. package/dist/tbv/core/clients/eth/index.js +3 -3
  55. package/dist/tbv/core/clients/index.cjs +1 -1
  56. package/dist/tbv/core/clients/index.js +5 -5
  57. package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
  58. package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
  59. package/dist/tbv/core/index.cjs +1 -1
  60. package/dist/tbv/core/index.d.ts +3 -0
  61. package/dist/tbv/core/index.d.ts.map +1 -1
  62. package/dist/tbv/core/index.js +159 -154
  63. package/dist/tbv/core/managers/index.cjs +1 -1
  64. package/dist/tbv/core/managers/index.js +2 -2
  65. package/dist/tbv/core/pegin-fingerprint/__tests__/peginFingerprint.golden.test.d.ts +62 -0
  66. package/dist/tbv/core/pegin-fingerprint/__tests__/peginFingerprint.golden.test.d.ts.map +1 -0
  67. package/dist/tbv/core/pegin-fingerprint/__tests__/peginFingerprint.test.d.ts +15 -0
  68. package/dist/tbv/core/pegin-fingerprint/__tests__/peginFingerprint.test.d.ts.map +1 -0
  69. package/dist/tbv/core/pegin-fingerprint/index.d.ts +14 -0
  70. package/dist/tbv/core/pegin-fingerprint/index.d.ts.map +1 -0
  71. package/dist/tbv/core/pegin-fingerprint/peginFingerprint.d.ts +141 -0
  72. package/dist/tbv/core/pegin-fingerprint/peginFingerprint.d.ts.map +1 -0
  73. package/dist/tbv/core/primitives/index.cjs +1 -1
  74. package/dist/tbv/core/primitives/index.js +4 -4
  75. package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts +5 -6
  76. package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts.map +1 -1
  77. package/dist/tbv/core/primitives/psbt/__tests__/assertWasmPeginSizing.test.d.ts +2 -2
  78. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +36 -14
  79. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
  80. package/dist/tbv/core/primitives/psbt/constants.d.ts +39 -0
  81. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  82. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  83. package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
  84. package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
  85. package/dist/tbv/core/services/index.cjs +1 -1
  86. package/dist/tbv/core/services/index.js +2 -2
  87. package/dist/tbv/core/utils/fee/constants.d.ts +4 -4
  88. package/dist/tbv/core/utils/index.cjs +1 -1
  89. package/dist/tbv/core/utils/index.js +2 -2
  90. package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts.map +1 -1
  91. package/dist/tbv/core/vault-secrets/index.js +1 -1
  92. package/dist/tbv/index.cjs +1 -1
  93. package/dist/tbv/index.js +159 -154
  94. package/dist/test/setup.browser.d.ts +2 -0
  95. package/dist/test/setup.browser.d.ts.map +1 -0
  96. package/dist/testing/index.js +1 -1
  97. package/dist/{toRefundInputs-BkcFhvDp.js → toRefundInputs-BNSXIymn.js} +238 -140
  98. package/dist/toRefundInputs-BNSXIymn.js.map +1 -0
  99. package/dist/toRefundInputs-meTyor7r.cjs +2 -0
  100. package/dist/toRefundInputs-meTyor7r.cjs.map +1 -0
  101. package/dist/{types-DSlcXtog.cjs → types-BzSOthHH.cjs} +2 -2
  102. package/dist/{types-DSlcXtog.cjs.map → types-BzSOthHH.cjs.map} +1 -1
  103. package/dist/{types-CPDLZm3l.js → types-C5DyrC8F.js} +2 -2
  104. package/dist/{types-CPDLZm3l.js.map → types-C5DyrC8F.js.map} +1 -1
  105. package/dist/verifyKeyPathSchnorrSignature-BVtNwgK6.js +360 -0
  106. package/dist/verifyKeyPathSchnorrSignature-BVtNwgK6.js.map +1 -0
  107. package/dist/verifyKeyPathSchnorrSignature-BjB8Znly.cjs +2 -0
  108. package/dist/verifyKeyPathSchnorrSignature-BjB8Znly.cjs.map +1 -0
  109. package/dist/verifyScriptPathSchnorrSignature-D_epga4j.js +1140 -0
  110. package/dist/verifyScriptPathSchnorrSignature-D_epga4j.js.map +1 -0
  111. package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs +2 -0
  112. package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs.map +1 -0
  113. package/package.json +5 -2
  114. package/dist/buildAndBroadcastReclaim-U-PyFfDg.cjs +0 -2
  115. package/dist/constants-Bh38W9mq.cjs +0 -2
  116. package/dist/constants-Bh38W9mq.cjs.map +0 -1
  117. package/dist/constants-CPzppOdq.js +0 -17
  118. package/dist/constants-CPzppOdq.js.map +0 -1
  119. package/dist/fundPeginTransaction-B2wyjqp0.js +0 -83
  120. package/dist/fundPeginTransaction-B2wyjqp0.js.map +0 -1
  121. package/dist/fundPeginTransaction-BLD8FRL9.cjs +0 -2
  122. package/dist/fundPeginTransaction-BLD8FRL9.cjs.map +0 -1
  123. package/dist/noPayout-DpGRzidi.js +0 -353
  124. package/dist/noPayout-DpGRzidi.js.map +0 -1
  125. package/dist/noPayout-zEifyecV.cjs +0 -2
  126. package/dist/noPayout-zEifyecV.cjs.map +0 -1
  127. package/dist/pegin-registration-client-6vLk2itL.cjs +0 -2
  128. package/dist/pegin-registration-client-6vLk2itL.cjs.map +0 -1
  129. package/dist/pegin-registration-client-BdRiR8br.js +0 -2635
  130. package/dist/pegin-registration-client-BdRiR8br.js.map +0 -1
  131. package/dist/toRefundInputs-BkcFhvDp.js.map +0 -1
  132. package/dist/toRefundInputs-CatCKniS.cjs +0 -2
  133. package/dist/toRefundInputs-CatCKniS.cjs.map +0 -1
  134. package/dist/vaultCoreVersion-DYfw3qed.cjs +0 -2
  135. package/dist/vaultCoreVersion-DYfw3qed.cjs.map +0 -1
  136. package/dist/vaultCoreVersion-D_fP9P3C.js +0 -10
  137. package/dist/vaultCoreVersion-D_fP9P3C.js.map +0 -1
  138. package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs +0 -2
  139. package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs.map +0 -1
  140. package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js +0 -372
  141. package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js.map +0 -1
  142. package/dist/verifyScriptPathSchnorrSignature-BfNUSgA7.cjs +0 -2
  143. package/dist/verifyScriptPathSchnorrSignature-BfNUSgA7.cjs.map +0 -1
  144. package/dist/verifyScriptPathSchnorrSignature-Ciq_xZhw.js +0 -951
  145. package/dist/verifyScriptPathSchnorrSignature-Ciq_xZhw.js.map +0 -1
@@ -1,2 +0,0 @@
1
- "use strict";const _=require("./tbv/core/wasm/index.cjs"),w=require("buffer"),y=require("bitcoinjs-lib"),t=require("./bitcoin-D-O2GjbC.cjs"),d=require("./verifyScriptPathSchnorrSignature-BfNUSgA7.cjs"),C=require("./fundPeginTransaction-BLD8FRL9.cjs"),L=require("./validation-C6XTfZak.cjs"),N=(1n<<64n)-1n;function U(r,u){if(!Array.isArray(r))throw new Error(`${u} must be an array of positive bigints (got ${typeof r}).`);if(r.length===0)throw new Error(`${u} must not be empty.`);return r.forEach((e,n)=>{if(typeof e!="bigint")throw new Error(`${u}[${n}] must be a bigint (got ${typeof e}); refusing to feed it into satoshi math.`);if(e<=0n)throw new Error(`${u}[${n}] must be > 0 (got ${e}).`);if(e>N)throw new Error(`${u}[${n}] must fit in a u64 (got ${e}); refusing to feed it into satoshi math.`)}),r}async function V(r){const{WasmPrePeginTx:u}=await _.loadRawTbvWasm(),{prePeginParams:e,fundedPrePeginTxHex:n,htlcVout:s,refundFee:f,hashlock:c}=r,l=d.normalizeAuthAnchorHash(e.authAnchorHash),o=new u(e.vaultCoreVersion,e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(U(e.pegInAmounts,"pegInAmounts")),e.timelockRefund,e.feeRate,e.minPeginFeeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,l);let i=null;try{const h=o.getHtlcScriptPubKey(s).toLowerCase(),a=o.getHtlcValue(s);i=o.fromFundedTransaction(n);const x=i.buildRefundTx(f,s),T=await _.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:c,timelockRefund:e.timelockRefund,network:e.network}),P=n.startsWith("0x")?n.slice(2):n,b=y.Transaction.fromHex(P),m=b.outs[s];if(!m)throw new Error(`HTLC output at vout ${s} not found in funded Pre-PegIn tx (tx has ${b.outs.length} outputs)`);const I=t.uint8ArrayToHex(new Uint8Array(m.script)).toLowerCase();if(I!==h)throw new Error(`HTLC scriptPubKey mismatch at vout ${s}: reconstructed template expects ${h}, funded tx carries ${I}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`);const E=BigInt(m.value);if(E!==a)throw new Error(`HTLC value mismatch at vout ${s}: reconstructed template expects ${a} sat, funded tx carries ${E} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`);const p=y.Transaction.fromHex(x);if(p.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${p.ins.length}`);const g=p.ins[0],R=b.getId(),S=t.uint8ArrayToHex(new Uint8Array(g.hash).slice().reverse());if(S!==R)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${R}, got ${S}`);if(g.index!==s)throw new Error(`Refund input index ${g.index} does not match expected htlcVout ${s}`);const $=new y.Psbt;if($.setVersion(p.version),$.setLocktime(p.locktime),$.addInput({hash:g.hash,index:g.index,sequence:g.sequence,witnessUtxo:{script:m.script,value:m.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:w.Buffer.from(t.hexToUint8Array(T.refundScript)),controlBlock:w.Buffer.from(t.hexToUint8Array(T.refundControlBlock))}],tapInternalKey:w.Buffer.from(_.tapInternalPubkey)}),p.outs.length!==1)throw new Error(`Refund transaction must have exactly 1 output, got ${p.outs.length}`);const v=p.outs[0],H=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(e.depositorPubkey)).toLowerCase(),O=t.uint8ArrayToHex(new Uint8Array(v.script)).toLowerCase();if(O!==H)throw new Error(`Refund output scriptPubKey ${O} does not match the depositor's BIP-86 address ${H}. Refund refused — the reclaimed funds would not return to the depositor.`);const A=E-f;if(BigInt(v.value)!==A)throw new Error(`Refund output value ${BigInt(v.value)} sat does not equal the HTLC value ${E} sat minus the requested fee ${f} sat (expected ${A} sat). Refund refused — the reclaimed amount would be burned as excess fee.`);return $.addOutput({script:v.script,value:v.value}),{psbtHex:$.toHex()}}finally{i==null||i.free(),o.free()}}const B=2,K=4294967293,M=214,D=299,q=4;function k(r){if(!Number.isInteger(r)||r<1)throw new Error(`Reclaim input count must be a positive integer, got ${r}.`);return Math.ceil((M+D*r)/q)}function G(r,u){if(!Number.isFinite(r)||r<=0)throw new Error(`Reclaim fee rate must be a positive number, got ${r}.`);return BigInt(Math.ceil(r*k(u)))}function X(r){const{depositorPubkey:u,inputs:e,feeSats:n}=r;if(e.length===0)throw new Error("Reclaim requires at least one input; got none.");if(n<=0n)throw new Error(`Reclaim fee must be positive, got ${n} sat. Refusing to build a transaction that would not relay.`);const s=d.deriveDepositorClaimDescriptor(u),f=t.uint8ArrayToHex(new Uint8Array(s.scriptPubKey)).toLowerCase(),c=new y.Psbt;c.setVersion(B),c.setLocktime(0);let l=0n;const o=new Set;if(e.forEach((a,x)=>{const T=y.Transaction.fromHex(t.stripHexPrefix(a.depositorSignedPeginTxHex)),P=T.getId(),b=T.outs[d.PEGIN_DEPOSITOR_CLAIM_VOUT];if(!b)throw new Error(`PegIn ${P} has no output at vout ${d.PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${T.outs.length}); there is no depositor-claim reserve to reclaim.`);const m=t.stripHexPrefix(a.observed.txid).toLowerCase();if(m!==P)throw new Error(`Input ${x}: the observation is of ${m}, but this input spends PegIn ${P}. Reclaim refused — the reserve that was looked up is not the one being swept.`);if(a.observed.vout!==d.PEGIN_DEPOSITOR_CLAIM_VOUT)throw new Error(`Input ${x}: the observation is of vout ${a.observed.vout}, but the depositor-claim reserve is at vout ${d.PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`);const I=t.uint8ArrayToHex(new Uint8Array(b.script)).toLowerCase();if(I!==f)throw new Error(`Input ${x}: PegIn ${P} vout ${d.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${I}, but the connected wallet's depositor-claim script is ${f}. Reclaim refused — this reserve belongs to a different wallet.`);const E=t.stripHexPrefix(a.observed.scriptPubKey).toLowerCase();if(E!==f)throw new Error(`Input ${x}: the observed UTXO ${P}:${d.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${E}, expected ${f}. Reclaim refused — chain state disagrees with the contract's PegIn.`);const p=BigInt(b.value);if(p!==a.observed.value)throw new Error(`Input ${x}: PegIn ${P} vout ${d.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${p} sat, but the observed UTXO carries ${a.observed.value} sat. Reclaim refused.`);if(p!==a.expectedValue)throw new Error(`Input ${x}: PegIn ${P} vout ${d.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${p} sat, but this vault's parameters compute a depositor-claim value of ${a.expectedValue} sat. Reclaim refused.`);const g=`${P}:${d.PEGIN_DEPOSITOR_CLAIM_VOUT}`;if(o.has(g))throw new Error(`Input ${x} repeats outpoint ${g}, which is already being swept by an earlier input. Reclaim refused.`);o.add(g),l+=p,c.addInput({hash:P,index:d.PEGIN_DEPOSITOR_CLAIM_VOUT,sequence:K,witnessUtxo:{script:b.script,value:b.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:s.leafScript,controlBlock:s.controlBlock}],tapInternalKey:s.internalKey})}),n>=l)throw new Error(`Reclaim fee ${n} sat is not less than the swept total ${l} sat. Refusing to build a transaction with no output.`);const i=l-n;if(i<=C.DUST_THRESHOLD)throw new Error(`Reclaim output ${i} sat is at or below the dust threshold ${C.DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it is until fee rates fall.`);const h=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(u));return c.addOutput({script:w.Buffer.from(t.hexToUint8Array(h)),value:Number(i)}),{psbtHex:c.toHex(),outputValue:i,totalInputValue:l}}function z(r){const{requestedPsbtHex:u,signaturesHex:e,signerXOnlyPubkeyHex:n}=r,s=t.stripHexPrefix(n);if(s.length!==L.X_ONLY_PUBKEY_HEX_LEN)throw new Error(`Signer x-only pubkey must be ${L.X_ONLY_PUBKEY_HEX_LEN} hex chars (32 bytes), got ${s.length}.`);const f=w.Buffer.from(t.hexToUint8Array(s)),c=y.Psbt.fromHex(u);if(e.length!==c.data.inputs.length)throw new Error(`Cannot finalize: got ${e.length} signature(s) for ${c.data.inputs.length} input(s). Every input must be signed — refusing to broadcast a partially signed transaction.`);return c.data.inputs.forEach((l,o)=>{if(l.tapKeySig)throw new Error(`Cannot finalize: input ${o} of the locally built PSBT carries a key-path signature. These outputs are script-path only.`);const i=l.tapLeafScript;if(!i||i.length!==1)throw new Error(`Cannot finalize: input ${o} must have exactly one tapLeafScript, got ${(i==null?void 0:i.length)??0}.`);const h=i[0];if(h.leafVersion!==t.TAPSCRIPT_LEAF_VERSION)throw new Error(`Cannot finalize: input ${o} tapLeafScript has leaf version 0x${h.leafVersion.toString(16)}, expected 0x${t.TAPSCRIPT_LEAF_VERSION.toString(16)}.`);const a=t.stripHexPrefix(e[o]);if(a.length!==t.SCHNORR_SIG_HEX_LEN)throw new Error(`Signature for input ${o} must be ${t.SCHNORR_SIG_HEX_LEN} hex chars (64 bytes), got ${a.length}.`);c.updateInput(o,{tapScriptSig:[{pubkey:f,leafHash:d.computeTapLeafHash(h.leafVersion,h.script),signature:w.Buffer.from(t.hexToUint8Array(a))}]})}),c.finalizeAllInputs(),c.extractTransaction().toHex()}async function F(r){const u=t.stripHexPrefix(r.noPayoutTxHex),e=y.Transaction.fromHex(u),{noPayoutScript:n,noPayoutControlBlock:s}=await _.getAssertNoPayoutScriptInfo(r.connectorParams,r.challengerPubkey),f=t.hexToUint8Array(n),c=t.hexToUint8Array(s),l=new y.Psbt;l.setVersion(e.version),l.setLocktime(e.locktime);for(let o=0;o<e.ins.length;o++){const i=e.ins[o],h=r.prevouts[o];if(!h)throw new Error(`Missing prevout data for input ${o}`);const a={hash:i.hash,index:i.index,sequence:i.sequence,witnessUtxo:{script:w.Buffer.from(t.hexToUint8Array(t.stripHexPrefix(h.script_pubkey))),value:h.value}};o===0&&(a.tapLeafScript=[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:w.Buffer.from(f),controlBlock:w.Buffer.from(c)}],a.tapInternalKey=w.Buffer.from(_.tapInternalPubkey)),l.addInput(a)}for(const o of e.outs)l.addOutput({script:o.script,value:o.value});return l.toHex()}function W(r,u,e){const n=y.Transaction.fromHex(t.stripHexPrefix(r));if(n.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${n.outs.length}`);const s=t.hexToUint8Array(t.processPublicKeyToXOnly(u)),{output:f}=y.payments.p2tr({internalPubkey:w.Buffer.from(s),network:t.getNetwork(e)});if(!f)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!n.outs[0].script.equals(f))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=W;exports.buildNoPayoutPsbt=F;exports.buildReclaimPsbt=X;exports.buildRefundPsbt=V;exports.estimateReclaimFeeSats=G;exports.finalizeScriptPathWithSignatures=z;exports.reclaimVsize=k;
2
- //# sourceMappingURL=noPayout-zEifyecV.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"noPayout-zEifyecV.cjs","sources":["../src/tbv/core/wasm/value-guards.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n loadRawTbvWasm,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n const { WasmPrePeginTx } = await loadRawTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against the funded\n // transaction: the WASM template's HTLC scriptPubKey at `htlcVout`\n // must equal the bytes the funded tx carries at the same output.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const expectedHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: prePeginParams.vaultCoreVersion,\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `tapLeafScript, got ${tapLeafScripts?.length ?? 0}.`,\n );\n }\n const leaf = tapLeafScripts[0];\n if (leaf.leafVersion !== TAPSCRIPT_LEAF_VERSION) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadRawTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","fundedTx","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"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"}
@@ -1,2 +0,0 @@
1
- "use strict";var _n=Object.defineProperty;var Rn=(t,e,r)=>e in t?_n(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var ht=(t,e,r)=>Rn(t,typeof e!="symbol"?e+"":e,r);const it=require("viem"),D=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),xt=require("./BTCVaultRegistryKeyEpochs.abi-CrQiTLfA.cjs"),Rt=require("./constants-Bh38W9mq.cjs"),$n=require("./tbv/core/utils/eth/index.cjs"),Pt=require("./onChainBtcPubkey-BbxRrbvg.cjs"),K=require("./sha2-DI0-0SHr.cjs"),Nn=require("./vaultCoreVersion-DYfw3qed.cjs"),$t=25,Ue=9999;function ne(t){if(!Number.isInteger(t)||t<0||t>=Rt.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`Quoted commissionBps must be an integer in [0, ${Rt.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${t}`);return Math.min(t+$t,Ue)}const kn=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ke=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),Hn=Ke.map(t=>(9*t+5)%16),Me=(()=>{const r=[[Ke],[Hn]];for(let n=0;n<4;n++)for(let o of r)o.push(o[n].map(s=>kn[s]));return r})(),Le=Me[0],Fe=Me[1],De=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),On=Le.map((t,e)=>t.map(r=>De[e][r])),qn=Fe.map((t,e)=>t.map(r=>De[e][r])),Un=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Kn=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function be(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const Tt=new Uint32Array(16);class Mn extends K.HashMD{constructor(){super(64,20,8,!0);ht(this,"h0",1732584193);ht(this,"h1",-271733879);ht(this,"h2",-1732584194);ht(this,"h3",271733878);ht(this,"h4",-1009589776)}get(){const{h0:r,h1:n,h2:o,h3:s,h4:i}=this;return[r,n,o,s,i]}set(r,n,o,s,i){this.h0=r|0,this.h1=n|0,this.h2=o|0,this.h3=s|0,this.h4=i|0}process(r,n){for(let h=0;h<16;h++,n+=4)Tt[h]=r.getUint32(n,!0);let o=this.h0|0,s=o,i=this.h1|0,a=i,u=this.h2|0,l=u,w=this.h3|0,m=w,c=this.h4|0,f=c;for(let h=0;h<5;h++){const y=4-h,A=Un[h],_=Kn[h],rt=Le[h],R=Fe[h],W=On[h],X=qn[h];for(let q=0;q<16;q++){const tt=K.rotl(o+be(h,i,u,w)+Tt[rt[q]]+A,W[q])+c|0;o=c,c=w,w=K.rotl(u,10)|0,u=i,i=tt}for(let q=0;q<16;q++){const tt=K.rotl(s+be(y,a,l,m)+Tt[R[q]]+_,X[q])+f|0;s=f,f=m,m=K.rotl(l,10)|0,l=a,a=tt}}this.set(this.h1+u+m|0,this.h2+w+f|0,this.h3+c+s|0,this.h4+o+a|0,this.h0+i+l|0)}roundClean(){K.clean(Tt)}destroy(){this.destroyed=!0,K.clean(this.buffer),this.set(0,0,0,0,0)}}const Ze=K.createHasher(()=>new Mn),gt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Lt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function re(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function lt(t,...e){if(!Lt(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function ze(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");re(t.outputLen),re(t.blockLen)}function Nt(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ln(t,e){lt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function kt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Y(t,e){return t<<32-e|t>>>e}const Xe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Fn=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function pt(t){if(lt(t),Xe)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Fn[t[r]];return e}const G={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ee(t){if(t>=G._0&&t<=G._9)return t-G._0;if(t>=G.A&&t<=G.F)return t-(G.A-10);if(t>=G.a&&t<=G.f)return t-(G.a-10)}function Ht(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Xe)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){const i=Ee(t.charCodeAt(s)),a=Ee(t.charCodeAt(s+1));if(i===void 0||a===void 0){const u=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+u+'" at index '+s)}n[o]=i*16+a}return n}function Ye(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function le(t){return typeof t=="string"&&(t=Ye(t)),lt(t),t}function j(...t){let e=0;for(let n=0;n<t.length;n++){const o=t[n];lt(o),e+=o.length}const r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){const s=t[n];r.set(s,o),o+=s.length}return r}class je{}function Dn(t){const e=n=>t().update(le(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ft(t=32){if(gt&&typeof gt.getRandomValues=="function")return gt.getRandomValues(new Uint8Array(t));if(gt&&typeof gt.randomBytes=="function")return Uint8Array.from(gt.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function Zn(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),u=n?4:0,l=n?0:4;t.setUint32(e+u,i,n),t.setUint32(e+l,a,n)}function zn(t,e,r){return t&e^~t&r}function Xn(t,e,r){return t&e^t&r^e&r}class Yn extends je{constructor(e,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=zt(this.buffer)}update(e){Nt(this),e=le(e),lt(e);const{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const u=zt(e);for(;o<=s-i;i+=o)this.process(u,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Nt(this),Ln(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:o,isLE:s}=this;let{pos:i}=this;r[i++]=128,kt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let m=i;m<o;m++)r[m]=0;Zn(n,o-8,BigInt(this.length*8),s),this.process(n,0);const a=zt(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=u/4,w=this.get();if(l>w.length)throw new Error("_sha2: outputLen bigger than state");for(let m=0;m<l;m++)a.setUint32(4*m,w[m],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const et=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),jn=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),nt=new Uint32Array(64);class Wn extends Yn{constructor(e=32){super(64,e,8,!1),this.A=et[0]|0,this.B=et[1]|0,this.C=et[2]|0,this.D=et[3]|0,this.E=et[4]|0,this.F=et[5]|0,this.G=et[6]|0,this.H=et[7]|0}get(){const{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:u}=this;return[e,r,n,o,s,i,a,u]}set(e,r,n,o,s,i,a,u){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=u|0}process(e,r){for(let m=0;m<16;m++,r+=4)nt[m]=e.getUint32(r,!1);for(let m=16;m<64;m++){const c=nt[m-15],f=nt[m-2],h=Y(c,7)^Y(c,18)^c>>>3,y=Y(f,17)^Y(f,19)^f>>>10;nt[m]=y+nt[m-7]+h+nt[m-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:u,G:l,H:w}=this;for(let m=0;m<64;m++){const c=Y(a,6)^Y(a,11)^Y(a,25),f=w+c+zn(a,u,l)+jn[m]+nt[m]|0,y=(Y(n,2)^Y(n,13)^Y(n,22))+Xn(n,o,s)|0;w=l,l=u,u=a,a=i+f|0,i=s,s=o,o=n,n=f+y|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,u=u+this.F|0,l=l+this.G|0,w=w+this.H|0,this.set(n,o,s,i,a,u,l,w)}roundClean(){kt(nt)}destroy(){this.set(0,0,0,0,0,0,0,0),kt(this.buffer)}}const oe=Dn(()=>new Wn);class We extends je{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,ze(e);const n=le(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),kt(s)}update(e){return Nt(this),this.iHash.update(e),this}digestInto(e){Nt(this),lt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ge=(t,e,r)=>new We(t,e).update(r).digest();Ge.create=(t,e)=>new We(t,e);const de=BigInt(0),se=BigInt(1);function Ot(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function ct(t,e,r=""){const n=Lt(t),o=t==null?void 0:t.length,s=e!==void 0;if(!n||s&&o!==e){const i=r&&`"${r}" `,a=s?` of length ${e}`:"",u=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+u)}return t}function Vt(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Qe(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?de:BigInt("0x"+t)}function bt(t){return Qe(pt(t))}function Je(t){return lt(t),Qe(pt(Uint8Array.from(t).reverse()))}function Dt(t,e){return Ht(t.toString(16).padStart(e*2,"0"))}function tn(t,e){return Dt(t,e).reverse()}function O(t,e,r){let n;if(typeof e=="string")try{n=Ht(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Lt(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=n.length;if(typeof r=="number"&&o!==r)throw new Error(t+" of length "+r+" expected, got "+o);return n}const Xt=t=>typeof t=="bigint"&&de<=t;function ie(t,e,r){return Xt(t)&&Xt(e)&&Xt(r)&&e<=t&&t<r}function Gn(t,e,r,n){if(!ie(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function en(t){let e;for(e=0;t>de;t>>=se,e+=1);return e}const It=t=>(se<<BigInt(t))-se;function Qn(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const n=f=>new Uint8Array(f),o=f=>Uint8Array.of(f);let s=n(t),i=n(t),a=0;const u=()=>{s.fill(1),i.fill(0),a=0},l=(...f)=>r(i,s,...f),w=(f=n(0))=>{i=l(o(0),f),s=l(),f.length!==0&&(i=l(o(1),f),s=l())},m=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const h=[];for(;f<e;){s=l();const y=s.slice();h.push(y),f+=s.length}return j(...h)};return(f,h)=>{u(),w(f);let y;for(;!(y=h(m()));)w();return u(),y}}function he(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(o,s,i){const a=t[o];if(i&&a===void 0)return;const u=typeof a;if(u!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${u}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}function Be(t){const e=new WeakMap;return(r,...n)=>{const o=e.get(r);if(o!==void 0)return o;const s=t(r,...n);return e.set(r,s),s}}const F=BigInt(0),M=BigInt(1),at=BigInt(2),nn=BigInt(3),rn=BigInt(4),on=BigInt(5),Jn=BigInt(7),sn=BigInt(8),tr=BigInt(9),cn=BigInt(16);function z(t,e){const r=t%e;return r>=F?r:e+r}function Z(t,e,r){let n=t;for(;e-- >F;)n*=n,n%=r;return n}function xe(t,e){if(t===F)throw new Error("invert: expected non-zero number");if(e<=F)throw new Error("invert: expected positive modulus, got "+e);let r=z(t,e),n=e,o=F,s=M;for(;r!==F;){const a=n/r,u=n%r,l=o-s*a;n=r,r=u,o=s,s=l}if(n!==M)throw new Error("invert: does not exist");return z(o,e)}function ge(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function an(t,e){const r=(t.ORDER+M)/rn,n=t.pow(e,r);return ge(t,n,e),n}function er(t,e){const r=(t.ORDER-on)/sn,n=t.mul(e,at),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,at),o),a=t.mul(s,t.sub(i,t.ONE));return ge(t,a,e),a}function nr(t){const e=At(t),r=un(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+Jn)/cn;return(a,u)=>{let l=a.pow(u,i),w=a.mul(l,n);const m=a.mul(l,o),c=a.mul(l,s),f=a.eql(a.sqr(w),u),h=a.eql(a.sqr(m),u);l=a.cmov(l,w,f),w=a.cmov(c,m,h);const y=a.eql(a.sqr(w),u),A=a.cmov(l,w,y);return ge(a,A,u),A}}function un(t){if(t<nn)throw new Error("sqrt is not defined for small field");let e=t-M,r=0;for(;e%at===F;)e/=at,r++;let n=at;const o=At(t);for(;ve(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return an;let s=o.pow(n,e);const i=(e+M)/at;return function(u,l){if(u.is0(l))return l;if(ve(u,l)!==1)throw new Error("Cannot find square root");let w=r,m=u.mul(u.ONE,s),c=u.pow(l,e),f=u.pow(l,i);for(;!u.eql(c,u.ONE);){if(u.is0(c))return u.ZERO;let h=1,y=u.sqr(c);for(;!u.eql(y,u.ONE);)if(h++,y=u.sqr(y),h===w)throw new Error("Cannot find square root");const A=M<<BigInt(w-h-1),_=u.pow(m,A);w=h,m=u.sqr(_),c=u.mul(c,m),f=u.mul(f,_)}return f}}function rr(t){return t%rn===nn?an:t%sn===on?er:t%cn===tr?nr(t):un(t)}const or=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function sr(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=or.reduce((n,o)=>(n[o]="function",n),e);return he(t,r),t}function ir(t,e,r){if(r<F)throw new Error("invalid exponent, negatives unsupported");if(r===F)return t.ONE;if(r===M)return e;let n=t.ONE,o=e;for(;r>F;)r&M&&(n=t.mul(n,o)),o=t.sqr(o),r>>=M;return n}function fn(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,u)=>t.is0(a)?i:(n[u]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,u)=>t.is0(a)?i:(n[u]=t.mul(i,n[u]),t.mul(i,a)),s),n}function ve(t,e){const r=(t.ORDER-M)/at,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function ln(t,e){e!==void 0&&re(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function At(t,e,r=!1,n={}){if(t<=F)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const c=e;c.BITS&&(o=c.BITS),c.sqrt&&(s=c.sqrt),typeof c.isLE=="boolean"&&(r=c.isLE),typeof c.modFromBytes=="boolean"&&(i=c.modFromBytes),a=c.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);const{nBitLength:u,nByteLength:l}=ln(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let w;const m=Object.freeze({ORDER:t,isLE:r,BITS:u,BYTES:l,MASK:It(u),ZERO:F,ONE:M,allowedLengths:a,create:c=>z(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return F<=c&&c<t},is0:c=>c===F,isValidNot0:c=>!m.is0(c)&&m.isValid(c),isOdd:c=>(c&M)===M,neg:c=>z(-c,t),eql:(c,f)=>c===f,sqr:c=>z(c*c,t),add:(c,f)=>z(c+f,t),sub:(c,f)=>z(c-f,t),mul:(c,f)=>z(c*f,t),pow:(c,f)=>ir(m,c,f),div:(c,f)=>z(c*xe(f,t),t),sqrN:c=>c*c,addN:(c,f)=>c+f,subN:(c,f)=>c-f,mulN:(c,f)=>c*f,inv:c=>xe(c,t),sqrt:s||(c=>(w||(w=rr(t)),w(m,c))),toBytes:c=>r?tn(c,l):Dt(c,l),fromBytes:(c,f=!0)=>{if(a){if(!a.includes(c.length)||c.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+c.length);const y=new Uint8Array(l);y.set(c,r?0:y.length-c.length),c=y}if(c.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+c.length);let h=r?Je(c):bt(c);if(i&&(h=z(h,t)),!f&&!m.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:c=>fn(m,c),cmov:(c,f,h)=>h?f:c});return Object.freeze(m)}function dn(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function hn(t){const e=dn(t);return e+Math.ceil(e/2)}function gn(t,e,r=!1){const n=t.length,o=dn(e),s=hn(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const i=r?Je(t):bt(t),a=z(i,e-M)+M;return r?tn(a,o):Dt(a,o)}const yt=BigInt(0),ut=BigInt(1);function qt(t,e){const r=e.negate();return t?r:e}function Yt(t,e){const r=fn(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function pn(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function jt(t,e){pn(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=It(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Pe(t,e,r){const{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r;let a=Number(t&o),u=t>>i;a>n&&(a-=s,u+=ut);const l=e*n,w=l+Math.abs(a)-1,m=a===0,c=a<0,f=e%2!==0;return{nextN:u,offset:w,isZero:m,isNeg:c,isNegF:f,offsetF:l}}function cr(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function ar(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const Wt=new WeakMap,wn=new WeakMap;function Gt(t){return wn.get(t)||1}function Ie(t){if(t!==yt)throw new Error("invalid wNAF")}class ur{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>yt;)r&ut&&(n=n.add(o)),o=o.double(),r>>=ut;return n}precomputeWindow(e,r){const{windows:n,windowSize:o}=jt(r,this.bits),s=[];let i=e,a=i;for(let u=0;u<n;u++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=jt(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:u,offset:l,isZero:w,isNeg:m,isNegF:c,offsetF:f}=Pe(n,a,i);n=u,w?s=s.add(qt(c,r[f])):o=o.add(qt(m,r[l]))}return Ie(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){const s=jt(e,this.bits);for(let i=0;i<s.windows&&n!==yt;i++){const{nextN:a,offset:u,isZero:l,isNeg:w}=Pe(n,i,s);if(n=a,!l){const m=r[u];o=o.add(w?m.negate():m)}}return Ie(n),o}getPrecomputes(e,r,n){let o=Wt.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),Wt.set(r,o))),o}cached(e,r,n){const o=Gt(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){const s=Gt(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){pn(r,this.bits),wn.set(e,r),Wt.delete(e)}hasCache(e){return Gt(e)!==1}}function fr(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>yt||n>yt;)r&ut&&(s=s.add(o)),n&ut&&(i=i.add(o)),o=o.double(),r>>=ut,n>>=ut;return{p1:s,p2:i}}function lr(t,e,r,n){cr(r,t),ar(n,e);const o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=en(BigInt(o));let u=1;a>12?u=a-3:a>4?u=a-2:a>0&&(u=2);const l=It(u),w=new Array(Number(l)+1).fill(i),m=Math.floor((e.BITS-1)/u)*u;let c=i;for(let f=m;f>=0;f-=u){w.fill(i);for(let y=0;y<s;y++){const A=n[y],_=Number(A>>BigInt(f)&l);w[_]=w[_].add(r[y])}let h=i;for(let y=w.length-1,A=i;y>0;y--)A=A.add(w[y]),h=h.add(A);if(c=c.add(h),f!==0)for(let y=0;y<u;y++)c=c.double()}return c}function Ae(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return sr(e),e}else return At(t,{isLE:r})}function dr(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const u of["p","n","h"]){const l=e[u];if(!(typeof l=="bigint"&&l>yt))throw new Error(`CURVE.${u} must be positive bigint`)}const o=Ae(e.p,r.Fp,n),s=Ae(e.n,r.Fn,n),a=["Gx","Gy","a","b"];for(const u of a)if(!o.isValid(e[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}const Se=(t,e)=>(t+(t>=0?e:-e)/yn)/e;function hr(t,e,r){const[[n,o],[s,i]]=e,a=Se(i*t,r),u=Se(-o*t,r);let l=t-a*n-u*s,w=-a*o-u*i;const m=l<J,c=w<J;m&&(l=-l),c&&(w=-w);const f=It(Math.ceil(en(r)/2))+wt;if(l<J||l>=f||w<J||w>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:m,k1:l,k2neg:c,k2:w}}function ce(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Qt(t,e){const r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Ot(r.lowS,"lowS"),Ot(r.prehash,"prehash"),r.format!==void 0&&ce(r.format),r}class gr extends Error{constructor(e=""){super(e)}}const Q={Err:gr,_tlv:{encode:(t,e)=>{const{Err:r}=Q;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,o=Vt(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Vt(o.length/2|128):"";return Vt(t)+s+o+e},decode(t,e){const{Err:r}=Q;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const o=e[n++],s=!!(o&128);let i=0;if(!s)i=o;else{const u=o&127;if(!u)throw new r("tlv.decode(long): indefinite length not supported");if(u>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+u);if(l.length!==u)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const w of l)i=i<<8|w;if(n+=u,i<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){const{Err:e}=Q;if(t<J)throw new e("integer: negative integers are not allowed");let r=Vt(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=Q;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return bt(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=Q,o=O("signature",t),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:u}=n.decode(2,s),{v:l,l:w}=n.decode(2,u);if(w.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=Q,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},J=BigInt(0),wt=BigInt(1),yn=BigInt(2),_t=BigInt(3),pr=BigInt(4);function ft(t,e){const{BYTES:r}=t;let n;if(typeof e=="bigint")n=e;else{let o=O("private key",e);try{n=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function wr(t,e={}){const r=dr("weierstrass",t,e),{Fp:n,Fn:o}=r;let s=r.CURVE;const{h:i,n:a}=s;he(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:u}=e;if(u&&(!n.is0(s.a)||typeof u.beta!="bigint"||!Array.isArray(u.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=bn(n,o);function w(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(T,p,g){const{x:d,y:b}=p.toAffine(),E=n.toBytes(d);if(Ot(g,"isCompressed"),g){w();const v=!n.isOdd(b);return j(mn(v),E)}else return j(Uint8Array.of(4),E,n.toBytes(b))}function c(T){ct(T,void 0,"Point");const{publicKey:p,publicKeyUncompressed:g}=l,d=T.length,b=T[0],E=T.subarray(1);if(d===p&&(b===2||b===3)){const v=n.fromBytes(E);if(!n.isValid(v))throw new Error("bad point: is not on curve, wrong x");const x=y(v);let B;try{B=n.sqrt(x)}catch(k){const V=k instanceof Error?": "+k.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}w();const P=n.isOdd(B);return(b&1)===1!==P&&(B=n.neg(B)),{x:v,y:B}}else if(d===g&&b===4){const v=n.BYTES,x=n.fromBytes(E.subarray(0,v)),B=n.fromBytes(E.subarray(v,v*2));if(!A(x,B))throw new Error("bad point: is not on curve");return{x,y:B}}else throw new Error(`bad point: got length ${d}, expected compressed=${p} or uncompressed=${g}`)}const f=e.toBytes||m,h=e.fromBytes||c;function y(T){const p=n.sqr(T),g=n.mul(p,T);return n.add(n.add(g,n.mul(T,s.a)),s.b)}function A(T,p){const g=n.sqr(p),d=y(T);return n.eql(g,d)}if(!A(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const _=n.mul(n.pow(s.a,_t),pr),rt=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(_,rt)))throw new Error("bad curve params: a or b");function R(T,p,g=!1){if(!n.isValid(p)||g&&n.is0(p))throw new Error(`bad point coordinate ${T}`);return p}function W(T){if(!(T instanceof S))throw new Error("ProjectivePoint expected")}function X(T){if(!u||!u.basises)throw new Error("no endo");return hr(T,u.basises,o.ORDER)}const q=Be((T,p)=>{const{X:g,Y:d,Z:b}=T;if(n.eql(b,n.ONE))return{x:g,y:d};const E=T.is0();p==null&&(p=E?n.ONE:n.inv(b));const v=n.mul(g,p),x=n.mul(d,p),B=n.mul(b,p);if(E)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:v,y:x}}),tt=Be(T=>{if(T.is0()){if(e.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}const{x:p,y:g}=T.toAffine();if(!n.isValid(p)||!n.isValid(g))throw new Error("bad point: x or y not field elements");if(!A(p,g))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function dt(T,p,g,d,b){return g=new S(n.mul(g.X,T),g.Y,g.Z),p=qt(d,p),g=qt(b,g),p.add(g)}class S{constructor(p,g,d){this.X=R("x",p),this.Y=R("y",g,!0),this.Z=R("z",d),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){const{x:g,y:d}=p||{};if(!p||!n.isValid(g)||!n.isValid(d))throw new Error("invalid affine point");if(p instanceof S)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(d)?S.ZERO:new S(g,d,n.ONE)}static fromBytes(p){const g=S.fromAffine(h(ct(p,void 0,"point")));return g.assertValidity(),g}static fromHex(p){return S.fromBytes(O("pointHex",p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,g=!0){return ot.createCache(this,p),g||this.multiply(_t),this}assertValidity(){tt(this)}hasEvenY(){const{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){W(p);const{X:g,Y:d,Z:b}=this,{X:E,Y:v,Z:x}=p,B=n.eql(n.mul(g,x),n.mul(E,b)),P=n.eql(n.mul(d,x),n.mul(v,b));return B&&P}negate(){return new S(this.X,n.neg(this.Y),this.Z)}double(){const{a:p,b:g}=s,d=n.mul(g,_t),{X:b,Y:E,Z:v}=this;let x=n.ZERO,B=n.ZERO,P=n.ZERO,I=n.mul(b,b),k=n.mul(E,E),V=n.mul(v,v),C=n.mul(b,E);return C=n.add(C,C),P=n.mul(b,v),P=n.add(P,P),x=n.mul(p,P),B=n.mul(d,V),B=n.add(x,B),x=n.sub(k,B),B=n.add(k,B),B=n.mul(x,B),x=n.mul(C,x),P=n.mul(d,P),V=n.mul(p,V),C=n.sub(I,V),C=n.mul(p,C),C=n.add(C,P),P=n.add(I,I),I=n.add(P,I),I=n.add(I,V),I=n.mul(I,C),B=n.add(B,I),V=n.mul(E,v),V=n.add(V,V),I=n.mul(V,C),x=n.sub(x,I),P=n.mul(V,k),P=n.add(P,P),P=n.add(P,P),new S(x,B,P)}add(p){W(p);const{X:g,Y:d,Z:b}=this,{X:E,Y:v,Z:x}=p;let B=n.ZERO,P=n.ZERO,I=n.ZERO;const k=s.a,V=n.mul(s.b,_t);let C=n.mul(g,E),$=n.mul(d,v),H=n.mul(b,x),L=n.add(g,d),N=n.add(E,v);L=n.mul(L,N),N=n.add(C,$),L=n.sub(L,N),N=n.add(g,b);let U=n.add(E,x);return N=n.mul(N,U),U=n.add(C,H),N=n.sub(N,U),U=n.add(d,b),B=n.add(v,x),U=n.mul(U,B),B=n.add($,H),U=n.sub(U,B),I=n.mul(k,N),B=n.mul(V,H),I=n.add(B,I),B=n.sub($,I),I=n.add($,I),P=n.mul(B,I),$=n.add(C,C),$=n.add($,C),H=n.mul(k,H),N=n.mul(V,N),$=n.add($,H),H=n.sub(C,H),H=n.mul(k,H),N=n.add(N,H),C=n.mul($,N),P=n.add(P,C),C=n.mul(U,N),B=n.mul(L,B),B=n.sub(B,C),C=n.mul(L,$),I=n.mul(U,I),I=n.add(I,C),new S(B,P,I)}subtract(p){return this.add(p.negate())}is0(){return this.equals(S.ZERO)}multiply(p){const{endo:g}=e;if(!o.isValidNot0(p))throw new Error("invalid scalar: out of range");let d,b;const E=v=>ot.cached(this,v,x=>Yt(S,x));if(g){const{k1neg:v,k1:x,k2neg:B,k2:P}=X(p),{p:I,f:k}=E(x),{p:V,f:C}=E(P);b=k.add(C),d=dt(g.beta,I,V,v,B)}else{const{p:v,f:x}=E(p);d=v,b=x}return Yt(S,[d,b])[0]}multiplyUnsafe(p){const{endo:g}=e,d=this;if(!o.isValid(p))throw new Error("invalid scalar: out of range");if(p===J||d.is0())return S.ZERO;if(p===wt)return d;if(ot.hasCache(this))return this.multiply(p);if(g){const{k1neg:b,k1:E,k2neg:v,k2:x}=X(p),{p1:B,p2:P}=fr(S,d,E,x);return dt(g.beta,B,P,b,v)}else return ot.unsafe(d,p)}multiplyAndAddUnsafe(p,g,d){const b=this.multiplyUnsafe(g).add(p.multiplyUnsafe(d));return b.is0()?void 0:b}toAffine(p){return q(this,p)}isTorsionFree(){const{isTorsionFree:p}=e;return i===wt?!0:p?p(S,this):ot.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:p}=e;return i===wt?this:p?p(S,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(p=!0){return Ot(p,"isCompressed"),this.assertValidity(),f(S,this,p)}toHex(p=!0){return pt(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(p=!0){return this.toBytes(p)}_setWindowSize(p){this.precompute(p)}static normalizeZ(p){return Yt(S,p)}static msm(p,g){return lr(S,o,p,g)}static fromPrivateKey(p){return S.BASE.multiply(ft(o,p))}}S.BASE=new S(s.Gx,s.Gy,n.ONE),S.ZERO=new S(n.ZERO,n.ONE,n.ZERO),S.Fp=n,S.Fn=o;const St=o.BITS,ot=new ur(S,e.endo?Math.ceil(St/2):St);return S.BASE.precompute(8),S}function mn(t){return Uint8Array.of(t?2:3)}function bn(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function yr(t,e={}){const{Fn:r}=t,n=e.randomBytes||Ft,o=Object.assign(bn(t.Fp,r),{seed:hn(r.ORDER)});function s(f){try{return!!ft(r,f)}catch{return!1}}function i(f,h){const{publicKey:y,publicKeyUncompressed:A}=o;try{const _=f.length;return h===!0&&_!==y||h===!1&&_!==A?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=n(o.seed)){return gn(ct(f,o.seed,"seed"),r.ORDER)}function u(f,h=!0){return t.BASE.multiply(ft(r,f)).toBytes(h)}function l(f){const h=a(f);return{secretKey:h,publicKey:u(h)}}function w(f){if(typeof f=="bigint")return!1;if(f instanceof t)return!0;const{secretKey:h,publicKey:y,publicKeyUncompressed:A}=o;if(r.allowedLengths||h===y)return;const _=O("key",f).length;return _===y||_===A}function m(f,h,y=!0){if(w(f)===!0)throw new Error("first arg must be private key");if(w(h)===!1)throw new Error("second arg must be public key");const A=ft(r,f);return t.fromHex(h).multiply(A).toBytes(y)}return Object.freeze({getPublicKey:u,getSharedSecret:m,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:f=>ft(r,f),precompute(f=8,h=t.BASE){return h.precompute(f,!1)}},lengths:o})}function mr(t,e,r={}){ze(e),he(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||Ft,o=r.hmac||((g,...d)=>Ge(e,g,j(...d))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:u}=i,{keygen:l,getPublicKey:w,getSharedSecret:m,utils:c,lengths:f}=yr(t,r),h={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},y="compact";function A(g){const d=a>>wt;return g>d}function _(g,d){if(!i.isValidNot0(d))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return d}function rt(g,d){ce(d);const b=f.signature,E=d==="compact"?b:d==="recovered"?b+1:void 0;return ct(g,E,`${d} signature`)}class R{constructor(d,b,E){this.r=_("r",d),this.s=_("s",b),E!=null&&(this.recovery=E),Object.freeze(this)}static fromBytes(d,b=y){rt(d,b);let E;if(b==="der"){const{r:P,s:I}=Q.toSig(ct(d));return new R(P,I)}b==="recovered"&&(E=d[0],b="compact",d=d.subarray(1));const v=i.BYTES,x=d.subarray(0,v),B=d.subarray(v,v*2);return new R(i.fromBytes(x),i.fromBytes(B),E)}static fromHex(d,b){return this.fromBytes(Ht(d),b)}addRecoveryBit(d){return new R(this.r,this.s,d)}recoverPublicKey(d){const b=s.ORDER,{r:E,s:v,recovery:x}=this;if(x==null||![0,1,2,3].includes(x))throw new Error("recovery id invalid");if(a*yn<b&&x>1)throw new Error("recovery id is ambiguous for h>1 curve");const P=x===2||x===3?E+a:E;if(!s.isValid(P))throw new Error("recovery id 2 or 3 invalid");const I=s.toBytes(P),k=t.fromBytes(j(mn((x&1)===0),I)),V=i.inv(P),C=X(O("msgHash",d)),$=i.create(-C*V),H=i.create(v*V),L=t.BASE.multiplyUnsafe($).add(k.multiplyUnsafe(H));if(L.is0())throw new Error("point at infinify");return L.assertValidity(),L}hasHighS(){return A(this.s)}toBytes(d=y){if(ce(d),d==="der")return Ht(Q.hexFromSig(this));const b=i.toBytes(this.r),E=i.toBytes(this.s);if(d==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return j(Uint8Array.of(this.recovery),b,E)}return j(b,E)}toHex(d){return pt(this.toBytes(d))}assertValidity(){}static fromCompact(d){return R.fromBytes(O("sig",d),"compact")}static fromDER(d){return R.fromBytes(O("sig",d),"der")}normalizeS(){return this.hasHighS()?new R(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return pt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return pt(this.toBytes("compact"))}}const W=r.bits2int||function(d){if(d.length>8192)throw new Error("input is too large");const b=bt(d),E=d.length*8-u;return E>0?b>>BigInt(E):b},X=r.bits2int_modN||function(d){return i.create(W(d))},q=It(u);function tt(g){return Gn("num < 2^"+u,g,J,q),i.toBytes(g)}function dt(g,d){return ct(g,void 0,"message"),d?ct(e(g),void 0,"prehashed message"):g}function S(g,d,b){if(["recovered","canonical"].some($=>$ in b))throw new Error("sign() legacy options not supported");const{lowS:E,prehash:v,extraEntropy:x}=Qt(b,h);g=dt(g,v);const B=X(g),P=ft(i,d),I=[tt(P),tt(B)];if(x!=null&&x!==!1){const $=x===!0?n(f.secretKey):x;I.push(O("extraEntropy",$))}const k=j(...I),V=B;function C($){const H=W($);if(!i.isValidNot0(H))return;const L=i.inv(H),N=t.BASE.multiply(H).toAffine(),U=i.create(N.x);if(U===J)return;const Ct=i.create(L*i.create(V+U*P));if(Ct===J)return;let ye=(N.x===U?0:2)|Number(N.y&wt),me=Ct;return E&&A(Ct)&&(me=i.neg(Ct),ye^=1),new R(U,me,ye)}return{seed:k,k2sig:C}}function St(g,d,b={}){g=O("message",g);const{seed:E,k2sig:v}=S(g,d,b);return Qn(e.outputLen,i.BYTES,o)(E,v)}function ot(g){let d;const b=typeof g=="string"||Lt(g),E=!b&&g!==null&&typeof g=="object"&&typeof g.r=="bigint"&&typeof g.s=="bigint";if(!b&&!E)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(E)d=new R(g.r,g.s);else if(b){try{d=R.fromBytes(O("sig",g),"der")}catch(v){if(!(v instanceof Q.Err))throw v}if(!d)try{d=R.fromBytes(O("sig",g),"compact")}catch{return!1}}return d||!1}function T(g,d,b,E={}){const{lowS:v,prehash:x,format:B}=Qt(E,h);if(b=O("publicKey",b),d=dt(O("message",d),x),"strict"in E)throw new Error("options.strict was renamed to lowS");const P=B===void 0?ot(g):R.fromBytes(O("sig",g),B);if(P===!1)return!1;try{const I=t.fromBytes(b);if(v&&P.hasHighS())return!1;const{r:k,s:V}=P,C=X(d),$=i.inv(V),H=i.create(C*$),L=i.create(k*$),N=t.BASE.multiplyUnsafe(H).add(I.multiplyUnsafe(L));return N.is0()?!1:i.create(N.x)===k}catch{return!1}}function p(g,d,b={}){const{prehash:E}=Qt(b,h);return d=dt(d,E),R.fromBytes(g,"recovered").recoverPublicKey(d).toBytes()}return Object.freeze({keygen:l,getPublicKey:w,getSharedSecret:m,utils:c,lengths:f,Point:t,sign:St,verify:T,recoverPublicKey:p,Signature:R,hash:e})}function br(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=At(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function Er(t){const{CURVE:e,curveOpts:r}=br(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function Br(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,ln(r.Fn.ORDER,r.Fn.BITS))})}function xr(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:o}=Er(t),s=wr(e,r),i=mr(s,n,o);return Br(t,i)}function vr(t,e){const r=n=>xr({...t,hash:n});return{...r(e),create:r}}const mt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Pr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ir=BigInt(0),Ce=BigInt(1),ae=BigInt(2);function Ar(t){const e=mt.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),u=BigInt(88),l=t*t*t%e,w=l*l*t%e,m=Z(w,r,e)*w%e,c=Z(m,r,e)*w%e,f=Z(c,ae,e)*l%e,h=Z(f,o,e)*f%e,y=Z(h,s,e)*h%e,A=Z(y,a,e)*y%e,_=Z(A,u,e)*A%e,rt=Z(_,a,e)*y%e,R=Z(rt,r,e)*w%e,W=Z(R,i,e)*h%e,X=Z(W,n,e)*l%e,q=Z(X,ae,e);if(!Ut.eql(Ut.sqr(q),t))throw new Error("Cannot find square root");return q}const Ut=At(mt.p,{sqrt:Ar}),Zt=vr({...mt,Fp:Ut,lowS:!0,endo:Pr},oe),Te={};function Kt(t,...e){let r=Te[t];if(r===void 0){const n=oe(Ye(t));r=j(n,n),Te[t]=r}return oe(j(r,...e))}const pe=t=>t.toBytes(!0).slice(1),Et=Zt.Point,we=t=>t%ae===Ir;function ue(t){const{Fn:e,BASE:r}=Et,n=ft(e,t),o=r.multiply(n);return{scalar:we(o.y)?n:e.neg(n),bytes:pe(o)}}function En(t){const e=Ut;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x ≥ p");const r=e.create(t*t),n=e.create(r*t+BigInt(7));let o=e.sqrt(n);we(o)||(o=e.neg(o));const s=Et.fromAffine({x:t,y:o});return s.assertValidity(),s}const vt=bt;function Bn(...t){return Et.Fn.create(vt(Kt("BIP0340/challenge",...t)))}function Ve(t){return ue(t).bytes}function Sr(t,e,r=Ft(32)){const{Fn:n}=Et,o=O("message",t),{bytes:s,scalar:i}=ue(e),a=O("auxRand",r,32),u=n.toBytes(i^vt(Kt("BIP0340/aux",a))),l=Kt("BIP0340/nonce",u,s,o),{bytes:w,scalar:m}=ue(l),c=Bn(w,s,o),f=new Uint8Array(64);if(f.set(w,0),f.set(n.toBytes(n.create(m+c*i)),32),!xn(f,o,s))throw new Error("sign: Invalid signature produced");return f}function xn(t,e,r){const{Fn:n,BASE:o}=Et,s=O("signature",t,64),i=O("message",e),a=O("publicKey",r,32);try{const u=En(vt(a)),l=vt(s.subarray(0,32));if(!ie(l,Ce,mt.p))return!1;const w=vt(s.subarray(32,64));if(!ie(w,Ce,mt.n))return!1;const m=Bn(n.toBytes(l),pe(u),i),c=o.multiplyUnsafe(w).add(u.multiplyUnsafe(n.neg(m))),{x:f,y:h}=c.toAffine();return!(c.is0()||!we(h)||f!==l)}catch{return!1}}const Bt=(()=>{const r=(o=Ft(48))=>gn(o,mt.n);Zt.utils.randomSecretKey;function n(o){const s=r(o);return{secretKey:s,publicKey:Ve(s)}}return{keygen:n,getPublicKey:Ve,sign:Sr,verify:xn,Point:Et,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:Kt,lift_x:En,pointToBytes:pe,numberToBytesBE:Dt,bytesToNumberBE:bt,mod:z},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),Cr="5120",fe="0014",Tr=20,_e=33,Vr=65,_r=2,Rr=3,$r=4;function vn(t,e){const r=t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t;if(!/^(?:[0-9a-fA-F]{2})+$/.test(r))throw new Error(`${e} must be non-empty, even-length hex`);return`0x${r.toLowerCase()}`}function Nr(t){const e=K.hexToBytes(t),r=Bt.utils.lift_x(BigInt(`0x${t}`)),n=Bt.utils.bytesToNumberBE(Bt.utils.taggedHash("TapTweak",e));if(n>=Zt.CURVE.n)throw new Error("Proof of possession BTC pubkey has an invalid TapTweak");const o=n===0n?r:r.add(Bt.Point.BASE.multiply(n));return`0x${Cr}${K.bytesToHex(Bt.utils.pointToBytes(o))}`}function kr(t){const e=vn(t,"depositorBtcPubkeyRaw"),r=K.hexToBytes(e.slice(2));if(r.length===32)return{xOnlyPubkey:Pt.assertOnChainBtcPubkey(e,"Payout BTC pubkey")};const n=r.length===_e&&(r[0]===_r||r[0]===Rr),o=r.length===Vr&&r[0]===$r;if(!n&&!o)throw new Error("depositorBtcPubkeyRaw must be x-only, compressed, or uncompressed");try{Zt.Point.fromBytes(r)}catch{throw new Error("depositorBtcPubkeyRaw is not a valid BTC pubkey")}return{xOnlyPubkey:K.bytesToHex(r.subarray(1,_e)),compressedPubkey:n?r:void 0}}function Hr(t){return`0x${fe}${K.bytesToHex(Ze(K.sha256(t)))}`}function Or(t,e,r){const n=vn(t,"depositorPayoutScriptPubKey");if((n.length-2)/2>Rt.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`depositorPayoutScriptPubKey exceeds ${Rt.MAX_PAYOUT_SCRIPT_LEN} bytes`);const o=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e,s=Pt.assertOnChainBtcPubkey(`0x${o}`,"Proof of possession BTC pubkey"),i=kr(r);if(i.xOnlyPubkey!==s)throw new Error("depositorBtcPubkeyRaw does not match the proof of possession BTC pubkey");if(n===Nr(s))return n;if(n.startsWith(`0x${fe}`)&&n.length===2+fe.length+Tr*2){if(!i.compressedPubkey)throw new Error("A P2WPKH payout requires a compressed BTC pubkey");if(n===Hr(i.compressedPubkey))return n}throw new Error("depositorPayoutScriptPubKey does not match the proof of possession BTC pubkey")}function qr(t,e){const r=t.startsWith("0x")?t.slice(2):t;if(r.length===0||r.length%2!==0)throw new Error(`${e} must be non-empty, even-length hex`);if(!/^[0-9a-fA-F]+$/.test(r))throw new Error(`${e} contains non-hex characters`);const n=new Uint8Array(r.length/2);for(let o=0;o<n.length;o++)n[o]=Number.parseInt(r.slice(o*2,o*2+2),16);return n}function Ur(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Kr(t){const e=new Uint8Array(t.reduce((n,o)=>n+o.length,0));let r=0;for(const n of t)e.set(n,r),r+=n.length;return e}function Mr(t){let e=0;const r=(c,f)=>{if(!Number.isSafeInteger(c)||c<0)throw new Error(`Invalid ${f} length ${c}`);if(e+c>t.length)throw new Error(`Truncated Bitcoin transaction while reading ${f}`);const h=t.slice(e,e+c);return e+=c,h},n=(c,f)=>{const h=r(c,f);let y=0n;for(let A=h.length-1;A>=0;A--)y=y<<8n|BigInt(h[A]);return y},o=c=>{const f=e,h=r(1,c)[0];let y;if(h<253)y=BigInt(h);else if(h===253){if(y=n(2,c),y<0xfdn)throw new Error(`Non-canonical ${c}`)}else if(h===254){if(y=n(4,c),y<=0xffffn)throw new Error(`Non-canonical ${c}`)}else if(y=n(8,c),y<=0xffffffffn)throw new Error(`Non-canonical ${c}`);if(y>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`${c} exceeds JavaScript's safe integer range`);return{encoded:t.slice(f,e),value:Number(y)}},s=r(4,"version"),i=t[e]===0&&t[e+1]===1;i&&(e+=2);const a=o("input count"),u=[];for(let c=0;c<a.value;c++){const f=e;r(32,`input ${c} previous transaction hash`),r(4,`input ${c} previous output index`);const h=o(`input ${c} script length`);r(h.value,`input ${c} script`),r(4,`input ${c} sequence`),u.push(t.slice(f,e))}const l=o("output count"),w=[];for(let c=0;c<l.value;c++){const f=e;r(8,`output ${c} value`);const h=o(`output ${c} script length`);r(h.value,`output ${c} script`),w.push(t.slice(f,e))}if(i){let c=!1;for(let f=0;f<a.value;f++){const h=o(`input ${f} witness item count`);c||(c=h.value>0);for(let y=0;y<h.value;y++){const A=o(`input ${f} witness item ${y} length`);r(A.value,`input ${f} witness item ${y}`)}}if(!c)throw new Error("Bitcoin transaction has superfluous witness marker")}const m=r(4,"locktime");if(e!==t.length)throw new Error(`Bitcoin transaction has ${t.length-e} trailing byte(s)`);return Kr([s,a.encoded,...u,l.encoded,...w,m])}function Pn(t){const e=Mr(qr(t,"transactionHex")),r=K.sha256(K.sha256(e));return r.reverse(),`0x${Ur(r)}`}function In(t,e){const r=t.startsWith("0x")?t:`0x${t}`;if(!/^0x[0-9a-fA-F]{64}$/.test(r))throw new Error("peginTxHash must be a 32-byte hex value");const n=e.startsWith("0x")?e:`0x${e}`;if(!it.isAddress(n,{strict:!0}))throw new Error(`Invalid depositor Ethereum address: ${e}`);return it.keccak256(it.encodeAbiParameters([{type:"bytes32"},{type:"address"}],[r,n])).slice(2)}const Jt=65535,Re=1e4,Mt=4294967295,$e=255;function An(t){if(!Number.isInteger(t)||t<0||t>Mt)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`)}function Sn(t){const e=[];if(t.timelockAssert<=0n&&e.push(`timelockAssert must be positive, got ${t.timelockAssert}`),t.timelockAssert>BigInt(Jt)&&e.push(`timelockAssert ${t.timelockAssert} exceeds uint16 max (${Jt})`),t.timelockChallengeAssert<=0n&&e.push(`timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`),t.tRefund<=0&&e.push(`tRefund must be positive, got ${t.tRefund}`),t.tStale<=0&&e.push(`tStale must be positive, got ${t.tStale}`),t.securityCouncilKeys.length===0&&e.push("securityCouncilKeys must not be empty"),t.councilQuorum<=0&&e.push(`councilQuorum must be positive, got ${t.councilQuorum}`),t.councilQuorum>t.securityCouncilKeys.length&&e.push(`councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`),t.feeRate<=0n&&e.push(`feeRate must be positive, got ${t.feeRate}`),t.minPeginFeeRate<=0n&&e.push(`minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`),(!Number.isInteger(t.proverCircuitVersion)||t.proverCircuitVersion<0||t.proverCircuitVersion>Jt)&&e.push(`proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`),(!Number.isInteger(t.minPrepeginDepth)||t.minPrepeginDepth<=0||t.minPrepeginDepth>Mt)&&e.push(`minPrepeginDepth must be a uint32 in [1, ${Mt}], got ${t.minPrepeginDepth}`),t.babeTotalInstances<=0&&e.push(`babeTotalInstances must be positive, got ${t.babeTotalInstances}`),t.babeInstancesToFinalize<=0&&e.push(`babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`),t.babeInstancesToFinalize>t.babeTotalInstances&&e.push(`babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`),(t.minVpCommissionBps<0||t.minVpCommissionBps>Re)&&e.push(`minVpCommissionBps must be in [0, ${Re}], got ${t.minVpCommissionBps}`),e.length>0)throw new Error(`Invalid offchain protocol parameters: ${e.join("; ")}`)}function Cn(t){const e=[];if(t.minimumPegInAmount<=0n&&e.push(`minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`),t.maxPegInAmount<t.minimumPegInAmount&&e.push(`maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`),t.pegInAckTimeout<=0n&&e.push(`pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`),t.pegInActivationTimeout<=0n&&e.push(`pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`),(!Number.isInteger(t.maxHtlcOutputCount)||t.maxHtlcOutputCount<=0||t.maxHtlcOutputCount>$e)&&e.push(`maxHtlcOutputCount must be an integer in [1, ${$e}], got ${t.maxHtlcOutputCount}`),(typeof t.expiredPegInGraceBlocks!="bigint"||t.expiredPegInGraceBlocks<=0n)&&e.push(`expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`),e.length>0)throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`)}function Lr(t){if(Cn(t),Sn(t.offchainParams),!Number.isInteger(t.offchainParamsVersion)||t.offchainParamsVersion<0||t.offchainParamsVersion>Mt)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`);Nn.assertValidVaultCoreVersion(t.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const Ne=9999;function ke(t){return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}function te(t){const e=Number(t.offchainParamsVersion);return An(e),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:e,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,vaultCoreVersion:t.vaultCoreVersion}}const Fr=1n<<64n,He=0n;function ee(t,e,r){if(t<0n||t>=Fr)throw new Error(`getBtcVaultProtocolInfo returned ${e}=${t} for vault ${r}, outside the uint64 range — the registry may predate RFC-006`);return t}function Oe(t,e){return{vpKeyEpoch:ee(t.vpKeyEpoch,"vpKeyEpoch",e),appKeeperKeyEpoch:ee(t.appKeeperKeyEpoch,"appKeeperKeyEpoch",e),ucKeyEpoch:ee(t.ucKeyEpoch,"ucKeyEpoch",e)}}class Tn{constructor(e,r){this.publicClient=e,this.contractAddress=r}async getVaultProviderGenesisBtcPubKey(e,r){const n=await this.publicClient.readContract({address:this.contractAddress,abi:D.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e,He],blockNumber:r});return Pt.assertOnChainBtcPubkey(n,`getOperationBtcKeyAtEpoch (vp=${e}, epoch=${He})`)}async getCurrentVaultProviderOperationBtcKey(e){const r=await this.publicClient.readContract({address:this.contractAddress,abi:D.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e]});return Pt.assertOnChainBtcPubkey(r,`getCurrentOperationBtcKey (vp=${e})`)}async getVaultKeyEpochs(e){const r=await this.publicClient.readContract({address:this.contractAddress,abi:xt.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return Oe(r,e)}async getVaultKeyEpochsBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(n=>({address:this.contractAddress,abi:xt.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[n]})),allowFailure:!1})).map((n,o)=>Oe(n,e[o]))}async getVaultBasicInfo(e){const r=await this.publicClient.readContract({address:this.contractAddress,abi:D.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return ke(r)}async getVaultProtocolInfo(e){const r=await this.publicClient.readContract({address:this.contractAddress,abi:D.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return te(r)}async getProtocolInfoBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(n=>({address:this.contractAddress,abi:D.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[n]})),allowFailure:!1})).map((n,o)=>{const s=n;if(!s.depositorSignedPeginTx||s.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e[o]} not found on-chain or has no pegin transaction`);return te(s)})}async getPegInFee(e){return await this.publicClient.readContract({address:this.contractAddress,abi:D.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}async getVaultProviderCommission(e){const r=await this.publicClient.readContract({address:this.contractAddress,abi:D.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[e]});if(!Number.isInteger(r)||r<0||r>Ne)throw new Error(`getVaultProviderCommission returned ${r} bps for ${e}, outside the protocol range [0, ${Ne}]`);return r}async getVaultData(e){const[r,n]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:D.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]},{address:this.contractAddress,abi:D.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]}],allowFailure:!1}),o=ke(r),s=te(n);if(!s.depositorSignedPeginTx||s.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:o,protocol:s}}}const Vn=0,Dr=255,Zr=12e4;function st(t,e){const r=t.startsWith("0x")?t:t.startsWith("0X")?`0x${t.slice(2)}`:`0x${t}`;if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(r))throw new Error(`${e} must be non-empty, even-length hex`);return r}function qe(t,e){if(!/^0x[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be a 32-byte hex value`)}function zr(t){if(!Number.isInteger(t)||t<0||t>Dr)throw new Error(`htlcVout must be a uint8, got ${t}`)}class Xr{constructor(e){this.config=e}async registerPeginOnChain(e){const r={...e,popSignature:{...e.popSignature}};this.assertQuotedCommissionPresentWhenRequired(r.quotedCommissionBps);const n=this.assertPopMatchesEthAccount(r.popSignature),o=this.normalizeBtcPubkey(r.popSignature),s=st(r.popSignature.btcPopSignature,"btcPopSignature"),i=this.normalizeRequest(r,n,o);await this.assertVaultDoesNotExist(i.vaultId,i.peginTxHash);const a=await this.readPeginFee(r.vaultProvider),u=await this.resolveMaxAcceptableCommissionBps(r.vaultProvider,r.quotedCommissionBps),l=it.encodeFunctionData({abi:D.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[n,o,s,i.unsignedPrePeginTx,i.depositorSignedPeginTx,r.vaultProvider,u,r.hashlock,r.htlcVout,i.payoutScript,r.depositorWotsPkHash]});return{ethTxHash:await this.sendAndWait(l,a,!1,n),vaultId:i.vaultId,peginTxHash:i.peginTxHash}}async registerPeginBatchOnChain(e){const r={...e,popSignature:{...e.popSignature},requests:e.requests.map(h=>({...h}))};if(r.requests.length===0)throw new Error("Batch pegin requires at least one request");this.assertQuotedCommissionPresentWhenRequired(r.quotedCommissionBps);const n=this.assertPopMatchesEthAccount(r.popSignature),o=st(r.unsignedPrePeginTx,"unsignedPrePeginTx"),s=this.normalizeBtcPubkey(r.popSignature),i=st(r.popSignature.btcPopSignature,"btcPopSignature"),a=[],u=[],l=new Set;for(const h of r.requests){const y=this.normalizeRequest({...h,unsignedPrePeginTx:r.unsignedPrePeginTx,vaultProvider:r.vaultProvider,depositorBtcPubkeyRaw:r.depositorBtcPubkeyRaw},n,s);if(l.has(y.vaultId))throw new Error(`Duplicate vault in batch: ${y.vaultId}`);l.add(y.vaultId),a.push({vaultId:y.vaultId,peginTxHash:y.peginTxHash}),u.push({depositorBtcPubKey:s,btcPopSignature:i,unsignedPrePeginTx:o,depositorSignedPeginTx:y.depositorSignedPeginTx,hashlock:h.hashlock,htlcVout:h.htlcVout,referralCode:Vn,depositorPayoutBtcAddress:y.payoutScript,depositorWotsPkHash:h.depositorWotsPkHash})}for(const h of a)await this.assertVaultDoesNotExist(h.vaultId,h.peginTxHash);const w=await this.readPeginFee(r.vaultProvider),m=await this.resolveMaxAcceptableCommissionBps(r.vaultProvider,r.quotedCommissionBps),c=it.encodeFunctionData({abi:D.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[n,r.vaultProvider,m,u]});return{ethTxHash:await this.sendAndWait(c,w*BigInt(r.requests.length),!0,n),vaults:a}}assertQuotedCommissionPresentWhenRequired(e){if(e===void 0&&this.config.requireQuotedCommissionBps)throw new Error("quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote.")}assertPopMatchesEthAccount(e){return this.assertEthAccount(e.depositorEthAddress)}assertEthAccount(e){const r=this.config.ethWallet.account;if(!r)throw new Error("Ethereum wallet account not found");if(!it.isAddressEqual(e,r.address))throw new Error(`Proof of possession was signed for ${e} but the Ethereum wallet is currently connected to ${r.address}. Reconnect the original account or sign a new proof of possession.`);return r.address}normalizeBtcPubkey(e){return`0x${Pt.assertOnChainBtcPubkey(st(e.depositorBtcPubkey,"Proof of possession BTC pubkey"),"Proof of possession BTC pubkey")}`}normalizeRequest(e,r,n){qe(e.hashlock,"hashlock"),qe(e.depositorWotsPkHash,"depositorWotsPkHash"),zr(e.htlcVout);const o=st(e.unsignedPrePeginTx,"unsignedPrePeginTx"),s=st(e.depositorSignedPeginTx,"depositorSignedPeginTx"),i=Pn(s);return{unsignedPrePeginTx:o,depositorSignedPeginTx:s,payoutScript:Or(e.depositorPayoutScriptPubKey,n,e.depositorBtcPubkeyRaw),peginTxHash:i,vaultId:st(In(i,r),"vaultId")}}async assertVaultDoesNotExist(e,r){if((await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:D.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]})).depositor!==it.zeroAddress)throw new Error(`Vault already exists (ID: ${e}, peginTxHash: ${r}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`)}async readPeginFee(e){try{return await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:D.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}catch(r){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and contract address.",{cause:r})}}async resolveMaxAcceptableCommissionBps(e,r){let n;try{n=await new Tn(this.config.publicClient,this.config.btcVaultRegistry).getVaultProviderCommission(e)}catch(o){throw new Error("Failed to query vault provider commission from the contract. Please check your network connection and contract address.",{cause:o})}if(r!==void 0){if(n>r+$t)throw new Error(`Vault provider commission changed since quote: quoted ${r} bps, chain currently reports ${n} bps (allowed drift ${$t} bps). Please refresh and try again.`);return ne(r)}return ne(n)}async sendAndWait(e,r,n,o){let s=this.assertEthAccount(o),i;try{i=await this.config.publicClient.estimateGas({to:this.config.btcVaultRegistry,data:e,value:r,account:s})}catch(l){xt.handleContractError(l)}s=this.assertEthAccount(o);let a;try{a=await this.config.ethWallet.sendTransaction({to:this.config.btcVaultRegistry,data:e,value:r,gas:i,account:s,chain:this.config.ethChain})}catch(l){xt.handleContractError(l)}const u=await $n.waitForTransactionReceiptSmartAware({publicClient:this.config.publicClient,walletAddress:o,hash:a,timeout:this.config.receiptTimeoutMs??Zr});return u.status==="reverted"&&xt.handleContractError(new Error(`${n?"Batch transaction":"Transaction"} reverted. Hash: ${u.transactionHash}. Check a block explorer for details.`)),u.transactionHash}}exports.COMMISSION_BPS_HEADROOM=$t;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=Ue;exports.NO_REFERRAL_CODE=Vn;exports.ViemPeginRegistrationClient=Xr;exports.ViemVaultRegistryReader=Tn;exports.assertValidOffchainParamsVersion=An;exports.calculateBtcTxHash=Pn;exports.capMaxAcceptableCommissionBps=ne;exports.derivePeginVaultId=In;exports.ripemd160=Ze;exports.validateOffchainParams=Sn;exports.validatePegInConfiguration=Lr;exports.validateTBVProtocolParams=Cn;
2
- //# sourceMappingURL=pegin-registration-client-6vLk2itL.cjs.map