@babylonlabs-io/ts-sdk 3.2.1 → 3.3.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 (70) hide show
  1. package/dist/{PeginManager-sizm3dlw.js → PeginManager-CQ9bVPR3.js} +116 -105
  2. package/dist/{PeginManager-sizm3dlw.js.map → PeginManager-CQ9bVPR3.js.map} +1 -1
  3. package/dist/PeginManager-D2R4Q1bN.cjs +2 -0
  4. package/dist/{PeginManager-BCRtUqyX.cjs.map → PeginManager-D2R4Q1bN.cjs.map} +1 -1
  5. package/dist/ProtocolParams.abi-BgEZaQ2I.cjs +2 -0
  6. package/dist/ProtocolParams.abi-BgEZaQ2I.cjs.map +1 -0
  7. package/dist/{ProtocolParams.abi-CKOVqFJP.js → ProtocolParams.abi-Cv77fsUe.js} +15 -9
  8. package/dist/ProtocolParams.abi-Cv77fsUe.js.map +1 -0
  9. package/dist/{buildAndBroadcastReclaim-rQyAiAUS.js → buildAndBroadcastReclaim-CQANDXVJ.js} +3 -3
  10. package/dist/{buildAndBroadcastReclaim-rQyAiAUS.js.map → buildAndBroadcastReclaim-CQANDXVJ.js.map} +1 -1
  11. package/dist/{buildAndBroadcastReclaim-CE77jzTp.cjs → buildAndBroadcastReclaim-DPk36Uhp.cjs} +2 -2
  12. package/dist/{buildAndBroadcastReclaim-CE77jzTp.cjs.map → buildAndBroadcastReclaim-DPk36Uhp.cjs.map} +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +8 -8
  15. package/dist/{pegin-registration-client-Bmkh1OZ9.cjs → pegin-registration-client-CdRyXP3j.cjs} +2 -2
  16. package/dist/{pegin-registration-client-Bmkh1OZ9.cjs.map → pegin-registration-client-CdRyXP3j.cjs.map} +1 -1
  17. package/dist/{pegin-registration-client-8tzSRDaq.js → pegin-registration-client-Cvjk4ILq.js} +2 -2
  18. package/dist/{pegin-registration-client-8tzSRDaq.js.map → pegin-registration-client-Cvjk4ILq.js.map} +1 -1
  19. package/dist/{registration-records-BBOz21Dm.js → registration-records-DJJC2NiO.js} +81 -79
  20. package/dist/{registration-records-BBOz21Dm.js.map → registration-records-DJJC2NiO.js.map} +1 -1
  21. package/dist/{registration-records-DaBufozs.cjs → registration-records-XQMIKjGV.cjs} +2 -2
  22. package/dist/{registration-records-DaBufozs.cjs.map → registration-records-XQMIKjGV.cjs.map} +1 -1
  23. package/dist/shared/index.cjs.map +1 -1
  24. package/dist/shared/index.js.map +1 -1
  25. package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts +5 -0
  26. package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts.map +1 -1
  27. package/dist/{signer-set-reader-DFF9MgQN.js → signer-set-reader-CSUe92zE.js} +2 -2
  28. package/dist/{signer-set-reader-DFF9MgQN.js.map → signer-set-reader-CSUe92zE.js.map} +1 -1
  29. package/dist/{signer-set-reader-D-CyIYR5.cjs → signer-set-reader-GrFe_rsW.cjs} +2 -2
  30. package/dist/{signer-set-reader-D-CyIYR5.cjs.map → signer-set-reader-GrFe_rsW.cjs.map} +1 -1
  31. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  32. package/dist/tbv/core/clients/eth/index.js +4 -4
  33. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +1 -0
  34. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
  35. package/dist/tbv/core/clients/eth/protocol-params-validation.d.ts.map +1 -1
  36. package/dist/tbv/core/clients/eth/types.d.ts +12 -6
  37. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  38. package/dist/tbv/core/clients/index.cjs +1 -1
  39. package/dist/tbv/core/clients/index.js +4 -4
  40. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +8 -0
  41. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts.map +1 -1
  42. package/dist/tbv/core/contracts/index.cjs +1 -1
  43. package/dist/tbv/core/contracts/index.js +1 -1
  44. package/dist/tbv/core/index.cjs +1 -1
  45. package/dist/tbv/core/index.js +8 -8
  46. package/dist/tbv/core/managers/PeginManager.d.ts +2 -1
  47. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  48. package/dist/tbv/core/managers/index.cjs +1 -1
  49. package/dist/tbv/core/managers/index.js +1 -1
  50. package/dist/tbv/core/services/index.cjs +1 -1
  51. package/dist/tbv/core/services/index.js +1 -1
  52. package/dist/tbv/index.cjs +1 -1
  53. package/dist/tbv/index.js +8 -8
  54. package/dist/{toRefundInputs-Dso_QEr-.js → toRefundInputs-DH-1bRNY.js} +3 -3
  55. package/dist/{toRefundInputs-Dso_QEr-.js.map → toRefundInputs-DH-1bRNY.js.map} +1 -1
  56. package/dist/{toRefundInputs-DOCLxqC1.cjs → toRefundInputs-DRmK83fv.cjs} +2 -2
  57. package/dist/{toRefundInputs-DOCLxqC1.cjs.map → toRefundInputs-DRmK83fv.cjs.map} +1 -1
  58. package/dist/types-24A9Qoxb.js +274 -0
  59. package/dist/types-24A9Qoxb.js.map +1 -0
  60. package/dist/types-BC2TGzcp.cjs +2 -0
  61. package/dist/types-BC2TGzcp.cjs.map +1 -0
  62. package/package.json +2 -2
  63. package/dist/PeginManager-BCRtUqyX.cjs +0 -2
  64. package/dist/ProtocolParams.abi-CKOVqFJP.js.map +0 -1
  65. package/dist/ProtocolParams.abi-CjrT0545.cjs +0 -2
  66. package/dist/ProtocolParams.abi-CjrT0545.cjs.map +0 -1
  67. package/dist/types-DGr5HWwD.cjs +0 -2
  68. package/dist/types-DGr5HWwD.cjs.map +0 -1
  69. package/dist/types-Dbs--c2M.js +0 -198
  70. package/dist/types-Dbs--c2M.js.map +0 -1
@@ -1,2 +1,2 @@
1
- "use strict";var Pe=Object.defineProperty;var fe=(e,t,r)=>t in e?Pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var j=(e,t,r)=>fe(e,typeof t!="symbol"?t+"":t,r);const M=require("./registration-records-DaBufozs.cjs"),p=require("./bitcoin-D-O2GjbC.cjs"),N=require("./btcTxHash-CGb5BqFL.cjs"),O=require("bitcoinjs-lib"),ve=require("buffer"),be=require("./tbv/core/clients/mempool/index.cjs"),X=require("./validation-C6XTfZak.cjs"),C=require("viem"),Ee=require("./sha2-Ce6KewYx.cjs"),D=require("./PayoutManager-B1Ev0r7o.cjs"),ee=require("./PeginManager-BCRtUqyX.cjs"),v=require("./tbv/core/wasm/index.cjs"),xe=require("./deriveVaultRoot-C3uqnJto.cjs"),we=require("./parseFundingOutpoints-C_-PT9BT.cjs"),K=require("./verifyScriptPathSchnorrSignature-CahYx5Td.cjs"),Q=require("./fundPeginTransaction-54-Rwb2k.cjs"),ye=["vaultCoreVersion","offchainParamsVersion","appVaultKeepersVersion","universalChallengersVersion"],Ce=["applicationEntryPoint","vaultProvider"];function te(e,t){const r=t.depositor.toLowerCase(),n=M.registrationPrePeginTxHash(t).toLowerCase();return e.filter(o=>o.vaultId!==t.vaultId&&o.depositor.toLowerCase()===r&&M.registrationPrePeginTxHash(o).toLowerCase()===n)}function re(e,t){for(const r of t){for(const n of ye)if(r.vault.protocol[n]!==e.vault.protocol[n])throw new Error(`Sibling vaults of this Pre-PegIn disagree on ${n} (${r.vault.protocol[n]} vs ${e.vault.protocol[n]}); the batch cannot be described by one set of deposit terms.`);if(r.maxAcceptableCommissionBps!==e.maxAcceptableCommissionBps)throw new Error(`Sibling vaults of this Pre-PegIn disagree on maxAcceptableCommissionBps (${r.maxAcceptableCommissionBps} vs ${e.maxAcceptableCommissionBps}); the batch cannot be described by one set of deposit terms.`);for(const n of Ce)if(r.vault.basic[n].toLowerCase()!==e.vault.basic[n].toLowerCase())throw new Error(`Sibling vaults of this Pre-PegIn disagree on ${n} (${r.vault.basic[n]} vs ${e.vault.basic[n]}); the batch cannot be described by one set of deposit terms.`)}}function ne(e){const t=[...e].sort((r,n)=>r.vault.protocol.htlcVout-n.vault.protocol.htlcVout);return t.forEach((r,n)=>{if(r.vault.protocol.htlcVout!==n)throw new Error(`Sibling discovery produced a non-contiguous HTLC vector (${t.map(o=>o.vault.protocol.htlcVout).join(", ")}).`)}),t.map(r=>({hashlock:r.vault.protocol.hashlock,amount:r.vault.basic.amount}))}const L="DepositTermsRejectedError";class oe extends Error{constructor(r,n="device-envelope"){super(r);j(this,"reason");this.name=L,this.reason=n}}function Re(e){if(e instanceof oe)return!0;if(typeof e!="object"||e===null)return!1;const t=e;return t.name===L&&t.reason==="device-envelope"}async function se(e,t){const r=O.Transaction.fromHex(p.stripHexPrefix(e)),o=(await Promise.all(r.ins.map(i=>be.getUtxoInfo(ve.Buffer.from(i.hash).reverse().toString("hex"),i.index,t)))).reduce((i,a)=>i+BigInt(a.value),0n),u=r.outs.reduce((i,a)=>i+BigInt(a.value),0n),s=o-u;if(s<=0n)throw new Error(`The funded Pre-PegIn transaction's inputs do not cover its outputs plus a fee (computed fee: ${s} sats).`);if(s>X.MAX_REASONABLE_FEE_SATS)throw new Error(`The funded Pre-PegIn transaction's computed fee (${s} sats) exceeds the maximum reasonable fee (${X.MAX_REASONABLE_FEE_SATS} sats); the mempool API may have returned manipulated prevout data.`);return s}async function z(e){const t=e.siblings.length;if(t===0)throw new Error("rebuildDepositTermsCore: at least one sibling is required");for(const[l,E]of e.siblings.entries())if(E.amount<=0n)throw new Error(`rebuildDepositTermsCore: sibling[${l}] has non-positive on-chain pegin amount ${E.amount}; the chain-read vault record is invalid. Resume refused.`);if(e.prepeginMaxFee<=0n)throw new Error(`rebuildDepositTermsCore: prepeginMaxFee must be > 0, got ${e.prepeginMaxFee}`);const r=p.stripHexPrefix(e.prepeginTxid).toLowerCase(),n=p.stripHexPrefix(N.calculateBtcTxHash(e.fundedPrePeginTxHex)).toLowerCase();if(n!==r)throw new Error(`Funded Pre-PegIn tx hashes to ${n}, expected ${r} (on-chain prepeginTxid). Resume refused.`);const o=D.findAuthAnchorOpReturn(p.stripHexPrefix(e.fundedPrePeginTxHex));if(o===void 0)throw new Error("Funded Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN commitment — it either predates auth anchoring or is malformed. The intent resume path requires the anchor to prove sibling completeness. Resume refused.");if(o.vout!==t)throw new Error(`Auth-anchor OP_RETURN at vout ${o.vout} does not match the discovered sibling count ${t}; the discovered sibling set does not cover this transaction's HTLC outputs (a lagging index can cause this — retry later). Resume refused.`);const u=e.vaultKeeperBtcPubkeys.length,s=e.universalChallengerBtcPubkeys.length,i=await v.computeMinClaimValue(e.vaultCoreVersion,u,s,e.councilQuorum,e.councilSize,e.protocolFeeRate),a=await v.computeMinPeginFee(e.vaultCoreVersion,u,s,e.minPeginFeeRate),d=await v.peginP2aAnchorOutput(e.vaultCoreVersion),c=(d==null?void 0:d.value)??0n;if(i<=0n)throw new Error(`WASM returned non-positive depositorClaimValue ${i}; expected > 0. Resume refused.`);if(a<=0n)throw new Error(`WASM returned non-positive peginMaxFee ${a}; expected > 0. Resume refused.`);if(c<0n)throw new Error(`WASM returned negative P2A anchor value ${c}. Resume refused.`);const h=a+c,b=e.minPeginFeeRate*Q.MAX_REASONABLE_PEGIN_VBYTES;if(h<=0n||h>b)throw new Error(`WASM implied PegIn reserve ${h} sat is outside (0, ${b}] (minPeginFeeRate=${e.minPeginFeeRate} × ${Q.MAX_REASONABLE_PEGIN_VBYTES} vbytes). Resume refused.`);const w=e.siblings.map(l=>l.amount+i+a+c),R=await Promise.all(e.siblings.map(async l=>(await v.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorBtcPubkey,vaultProviderPubkey:e.vaultProviderBtcPubkey,vaultKeeperPubkeys:[...e.vaultKeeperBtcPubkeys],universalChallengerPubkeys:[...e.universalChallengerBtcPubkeys],hashlock:p.stripHexPrefix(l.hashlock),timelockRefund:e.timelockRefund,network:e.network})).scriptPubKey)),y=O.Transaction.fromHex(p.stripHexPrefix(e.fundedPrePeginTxHex)).outs.map(l=>({value:l.value,script:l.script}));return K.assertEncodedHtlcOutputsMatch(y,w,R),ee.buildDepositTerms({vaultCoreVersion:e.vaultCoreVersion,protocolFeeRate:e.protocolFeeRate,timelockPegin:e.timelockPegin,timelockAssert:e.timelockAssert,timelockRefund:e.timelockRefund,prepeginTxid:e.prepeginTxid,prepeginMaxFee:e.prepeginMaxFee,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:e.universalChallengerBtcPubkeys,maxAcceptableCommissionBps:e.maxAcceptableCommissionBps,peginAmounts:e.siblings.map(l=>l.amount),depositorClaimValue:i,peginMaxFee:a})}async function ke(e){const{read:t}=e,r=p.canonicalizeBtcPubkey(e.depositorBtcPubkey);if(r!==t.context.depositorBtcPubkey)throw new Error("Connected wallet key is not the vault's depositor key; select the account that made the deposit.");const n=p.stripHexPrefix(t.prePeginTxHash).toLowerCase(),o=p.stripHexPrefix(N.calculateBtcTxHash(e.fundedPrePeginTxHex)).toLowerCase();if(o!==n)throw new Error(`Funded Pre-PegIn tx hashes to ${o}, expected ${n} (on-chain prePeginTxHash).`);const u=await Promise.all(te(t.registrationRecords,t.registrationRecord).map(async d=>{const c=await e.siblingReader.getVaultData(d.vaultId);if(c.protocol.prePeginTxHash.toLowerCase()!==M.registrationPrePeginTxHash(d).toLowerCase())throw new Error(`Sibling ${d.vaultId} is registered against a different Pre-PegIn on chain than its registration log records; refusing an inconsistent node.`);return{vault:c,maxAcceptableCommissionBps:d.maxAcceptableCommissionBps}})),s={vault:t.vault,maxAcceptableCommissionBps:t.registrationRecord.maxAcceptableCommissionBps};re(s,u);const i=ne([s,...u]),a=await se(e.fundedPrePeginTxHex,e.mempoolApiUrl);return z({vaultCoreVersion:t.vault.protocol.vaultCoreVersion,siblings:i,fundedPrePeginTxHex:e.fundedPrePeginTxHex,depositorBtcPubkey:r,vaultProviderBtcPubkey:t.participantKeys.vaultProvider.operationBtcPubkey,vaultKeeperBtcPubkeys:t.participantKeys.vaultKeeperOperationKeysSorted,universalChallengerBtcPubkeys:t.participantKeys.universalChallengerOperationKeysSorted,protocolFeeRate:t.offchainParams.feeRate,minPeginFeeRate:t.offchainParams.minPeginFeeRate,councilQuorum:t.offchainParams.councilQuorum,councilSize:t.offchainParams.securityCouncilKeys.length,timelockPegin:t.context.timelockPegin,timelockAssert:t.context.timelockAssert,timelockRefund:t.offchainParams.tRefund,prepeginTxid:n,prepeginMaxFee:a,maxAcceptableCommissionBps:t.registrationRecord.maxAcceptableCommissionBps,network:e.network})}function Te(e){const t=(e instanceof Error?e.message:typeof e=="string"?e:"").toLowerCase();return t.includes("wots")&&t.includes("hash")&&t.includes("does not match")}const ie="TBV.PeginFingerprint.v1",ae=C.keccak256(C.toHex(ie)),W=65535,J=2n**64n-1n,Ae=2n**256n-1n,Ve=/^0x[0-9a-fA-F]{64}$/,Y=1;class P extends Error{constructor(t){super(t),this.name="PeginFingerprintInputError"}}function Ie(e){return e instanceof P||e instanceof Error&&e.name==="PeginFingerprintInputError"}function _(e,t,r,n){if(typeof t!="bigint")throw new P(`${e} must be a bigint (Solidity ${n}), got ${typeof t}`);if(t<0n||t>r)throw new P(`${e} must fit Solidity ${n} (0..${r}), got ${t}`)}function $(e,t){if(!Number.isInteger(t)||t<0||t>W)throw new P(`${e} must be an integer fitting Solidity uint16 (0..${W}), got ${t}`)}function $e(e,t){if(!Ve.test(t))throw new P(`${e} must be 32 bytes as 0x-prefixed hex (66 characters), got "${t}"`);return t.toLowerCase()}function Be(e){if(!C.isAddress(e,{strict:!1}))throw new P(`registryAddress must be a 20-byte 0x-prefixed address, got "${e}"`);const t=e.toLowerCase();if(t===C.zeroAddress)throw new P("registryAddress must not be the zero address; a zero here means the registry address was never resolved");return t}const Fe=[{name:"domain",type:"bytes32"},{name:"chainId",type:"uint256"},{name:"registry",type:"address"},{name:"vaultProviderBtcKey",type:"bytes32"},{name:"appKeeperKeyEpoch",type:"uint64"},{name:"ucKeyEpoch",type:"uint64"},{name:"appVaultKeepersVersion",type:"uint16"},{name:"universalChallengersVersion",type:"uint16"},{name:"offchainParamsVersion",type:"uint16"},{name:"vaultCoreVersion",type:"uint16"}];function ce(e){if(_("chainId",e.chainId,Ae,"uint256"),e.chainId===0n)throw new P("chainId must not be 0; a zero here means the chain id was never resolved");const t=Be(e.registryAddress),r=$e("vaultProviderBtcKey",e.vaultProviderBtcKey);if(_("appKeeperKeyEpoch",e.appKeeperKeyEpoch,J,"uint64"),_("ucKeyEpoch",e.ucKeyEpoch,J,"uint64"),$("appVaultKeepersVersion",e.appVaultKeepersVersion),$("universalChallengersVersion",e.universalChallengersVersion),$("offchainParamsVersion",e.offchainParamsVersion),$("vaultCoreVersion",e.vaultCoreVersion),e.vaultCoreVersion<Y)throw new P(`vaultCoreVersion must be at least ${Y}; ${e.vaultCoreVersion} means the version was never resolved`);return C.encodeAbiParameters(Fe,[ae,e.chainId,t,r,e.appKeeperKeyEpoch,e.ucKeyEpoch,e.appVaultKeepersVersion,e.universalChallengersVersion,e.offchainParamsVersion,e.vaultCoreVersion])}function Se(e){return C.keccak256(ce(e))}class ue extends Error{constructor(t,r){super(`Re-derived vault root does not match this Pre-PegIn: derived auth-anchor hash ${t}, transaction commits to ${r}. Connect the same wallet, on the same account and the same network, that created the deposit.`),this.derivedAuthAnchorHash=t,this.onChainAuthAnchorHash=r,this.name="VaultRootMismatchError"}}class F extends Error{constructor(t){super(t),this.name="UnanchoredPrePeginError"}}class le extends Error{constructor(t,r,n=[]){super(`No candidate parameter set reproduces this Pre-PegIn's HTLC outputs (${t} candidate(s) tried). `+(n.length>0?`${n.length} version(s) could not be resolved and may hold the answer: ${n.join(" | ")}. `:"")+`Sample rejections: ${r.join(" | ")}`),this.candidatesTried=t,this.sampleRejections=r,this.unresolvedLabels=n,this.name="PeginParamsNotFoundError"}}class he extends Error{constructor(t){super(`${t.length} candidate parameter sets reproduce this Pre-PegIn's HTLC outputs, so the vault's stamped versions cannot be determined: ${t.join(" | ")}. Reconstruction refused.`),this.survivorLabels=t,this.name="PeginParamsAmbiguousError"}}class de extends Error{constructor(t,r){super(`A candidate matched this Pre-PegIn (${t}), but ${r.length} version(s) could not be resolved, so the search space did not provably contain the true parameters: ${r.join(" | ")}. A version sharing the matched timelockRefund and participants is indistinguishable from the true one, so the match cannot be trusted. Reconstruction refused.`),this.matchedLabel=t,this.unresolvedLabels=r,this.name="PeginParamsIncompleteSpaceError"}}class V extends Error{constructor(t){super(`${t}. Reconstruction refused.`),this.name="PeginSizingIntegrityError"}}async function He(e){const{wallet:t,depositorBtcPubkey:r,fundedPrePeginTxHex:n}=e,o=p.stripHexPrefix(n),u=D.findAuthAnchorOpReturn(o);if(u===void 0)throw new F("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN, so the number of HTLC outputs it funds cannot be determined. Legacy pre-anchor deposits are not recoverable by this path.");const s=u.vout;if(s===0)throw new F("Pre-PegIn's auth-anchor OP_RETURN is at vout 0, implying zero HTLC outputs; there is nothing to recover.");const i=we.parseFundingOutpointsFromTx(o),a=await xe.deriveVaultRoot(t,{depositorBtcPubkey:p.hexToUint8Array(p.processPublicKeyToXOnly(r)),fundingOutpoints:i});try{const c=await v.expandAuthAnchor(a);let h;try{h=p.uint8ArrayToHex(Ee.sha256(c))}finally{c.fill(0)}if(h!==u.hash)throw new ue(h,u.hash)}catch(c){throw a.fill(0),c}const{hashlocks:d}=await ee.expandPerVaultSecrets(a,s);return{vaultCount:s,hashlocks:d,authAnchorHash:u.hash}}function _e(e){const{vaultCoreVersion:t,offchainParams:r,participantKeySets:n}=e;if(!Number.isInteger(t)||t<1)throw new Error(`buildPeginParamsCandidates: vaultCoreVersion must be a positive integer, got ${t}`);if(r.length===0)throw new Error("buildPeginParamsCandidates: at least one offchain-params version is required");if(n.length===0)throw new Error("buildPeginParamsCandidates: at least one participant key set is required");const o=[];for(const u of r)for(const s of n)o.push({vaultCoreVersion:t,offchainParams:u,participants:s});return o}function pe(e){return`${e.axis} v${e.version} (${e.reason})`}function B(e){const{participants:t}=e;return`core=${e.vaultCoreVersion} offchain=${e.offchainParams.version} keepers=${t.appVaultKeepersVersion} challengers=${t.universalChallengersVersion} vp=${t.vaultProvider}`}const Z=5;function Me(e,t){return JSON.stringify({terms:e,peginAmounts:t},(r,n)=>typeof n=="bigint"?`${n}`:n)}function Ke(e){const{offchainParams:t,participants:r}=e;return[e.vaultCoreVersion,r.vaultKeeperBtcPubkeys.length,r.universalChallengerBtcPubkeys.length,t.councilQuorum,t.councilSize,t.protocolFeeRate,t.minPeginFeeRate].join("|")}async function Ne(e){const{offchainParams:t,participants:r}=e,n=r.vaultKeeperBtcPubkeys.length,o=r.universalChallengerBtcPubkeys.length,[u,s,i]=await Promise.all([v.computeMinClaimValue(e.vaultCoreVersion,n,o,t.councilQuorum,t.councilSize,t.protocolFeeRate),v.computeMinPeginFee(e.vaultCoreVersion,n,o,t.minPeginFeeRate),v.peginP2aAnchorOutput(e.vaultCoreVersion)]),a=(i==null?void 0:i.value)??0n;if(u<=0n)throw new V(`WASM returned non-positive depositorClaimValue ${u} for graph version ${e.vaultCoreVersion}`);if(s<=0n)throw new V(`WASM returned non-positive peginMaxFee ${s} for graph version ${e.vaultCoreVersion}`);if(a<0n)throw new V(`WASM returned negative P2A anchor value ${a} for graph version ${e.vaultCoreVersion}`);return{depositorClaimValue:u,peginMaxFee:s,p2aAnchorValue:a}}async function Oe(e){const{hashlocks:t,fundedPrePeginTxHex:r,depositorBtcPubkey:n,prepeginMaxFee:o,maxAcceptableCommissionBps:u,network:s,candidates:i,unresolvedVersions:a}=e;if(t.length===0)throw new Error("reconstructPeginParams: at least one hashlock is required");if(i.length===0)throw new Error("reconstructPeginParams: candidate space is empty");const d=p.processPublicKeyToXOnly(n),c=p.stripHexPrefix(r),h=D.findAuthAnchorOpReturn(c);if(h===void 0)throw new F("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN; the sibling set cannot be proven complete. Reconstruction refused.");if(h.vout!==t.length)throw new Error(`reconstructPeginParams: ${t.length} hashlock(s) supplied but the auth-anchor OP_RETURN sits at vout ${h.vout}, so the transaction funds ${h.vout} HTLC output(s). Reconstruction refused.`);const b=O.Transaction.fromHex(c).outs,w=t.map((m,g)=>BigInt(b[g].value)),R=p.stripHexPrefix(N.calculateBtcTxHash(c)).toLowerCase(),y=new Map,l=[],E=[],S=[];let U=0;for(const m of i)try{const g=Ke(m);let f=y.get(g);f===void 0&&(f=await Ne(m),y.set(g,f));const k=f.depositorClaimValue+f.peginMaxFee+f.p2aAnchorValue,T=w.map(A=>A-k),I=T.findIndex(A=>A<=0n);if(I!==-1)throw new K.HtlcOutputMismatchError(`HTLC output[${I}] value ${w[I]} is not above this candidate's reserve ${k}, so it implies a non-positive pegin amount ${T[I]}.`);const{offchainParams:x,participants:H}=m,G=await z({vaultCoreVersion:m.vaultCoreVersion,siblings:t.map((A,ge)=>({hashlock:A,amount:T[ge]})),fundedPrePeginTxHex:c,depositorBtcPubkey:d,vaultProviderBtcPubkey:H.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:H.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:H.universalChallengerBtcPubkeys,protocolFeeRate:x.protocolFeeRate,minPeginFeeRate:x.minPeginFeeRate,councilQuorum:x.councilQuorum,councilSize:x.councilSize,timelockPegin:x.timelockPegin,timelockAssert:x.timelockAssert,timelockRefund:x.timelockRefund,prepeginTxid:R,prepeginMaxFee:o,maxAcceptableCommissionBps:u,network:s});l.push({candidate:m,terms:G,peginAmounts:T,fingerprint:Me(G,T)})}catch(g){if(g instanceof V)throw g;const f=B(m),k=g instanceof Error?g.message:String(g);g instanceof K.HtlcOutputMismatchError?E.length<Z&&E.push(`[${f}] ${k}`):(U++,S.length<Z&&S.push(`${f} (${k})`))}const me=a.length+U,q=[...a.map(pe),...S];if(l.length===0)throw new le(i.length,E,q);if(new Set(l.map(m=>m.fingerprint)).size>1)throw new he(l.map(m=>B(m.candidate)));if(me>0)throw new de(B(l[0].candidate),q);return{candidate:l[0].candidate,terms:l[0].terms,peginAmounts:l[0].peginAmounts,authAnchorHash:h.hash,candidatesTried:i.length,matchedCandidates:l.map(m=>m.candidate)}}function De(e,t){const{htlcVout:r,depositorBtcPubkey:n,applicationEntryPoint:o,fundedPrePeginTxHex:u,hashlocks:s,network:i}=t,{candidate:a,peginAmounts:d}=e,{offchainParams:c,participants:h}=a;if(s.length!==d.length)throw new Error(`toRefundInputs: ${s.length} hashlock(s) but ${d.length} reconstructed amount(s); the reconstruction and the hashlock vector describe different transactions.`);if(!Number.isInteger(r)||r<0||r>=d.length)throw new Error(`toRefundInputs: htlcVout ${r} is outside the reconstructed batch of ${d.length} vault(s).`);const b=d.map((y,l)=>({hashlock:p.ensureHexPrefix(s[l]),amount:y,htlcVout:l})),w={vaultCoreVersion:a.vaultCoreVersion,hashlock:b[r].hashlock,htlcVout:r,offchainParamsVersion:c.version,appVaultKeepersVersion:h.appVaultKeepersVersion,universalChallengersVersion:h.universalChallengersVersion,vaultProvider:h.vaultProvider,applicationEntryPoint:o,amount:d[r],unsignedPrePeginTxHex:u,depositorBtcPubkey:n,batch:b},R={vaultProviderPubkey:h.vaultProviderBtcPubkey,vaultKeeperPubkeys:h.vaultKeeperBtcPubkeys,universalChallengerPubkeys:h.universalChallengerBtcPubkeys,timelockRefund:c.timelockRefund,feeRate:c.protocolFeeRate,minPeginFeeRate:c.minPeginFeeRate,numLocalChallengers:h.vaultKeeperBtcPubkeys.length,councilQuorum:c.councilQuorum,councilSize:c.councilSize,network:i};return{vault:w,context:R}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=L;exports.DepositTermsRejectedError=oe;exports.PEGIN_FINGERPRINT_DOMAIN=ae;exports.PEGIN_FINGERPRINT_DOMAIN_PREIMAGE=ie;exports.PeginFingerprintInputError=P;exports.PeginParamsAmbiguousError=he;exports.PeginParamsIncompleteSpaceError=de;exports.PeginParamsNotFoundError=le;exports.PeginSizingIntegrityError=V;exports.UnanchoredPrePeginError=F;exports.VaultRootMismatchError=ue;exports.assertClaimBatchHomogeneous=re;exports.buildPeginParamsCandidates=_e;exports.computeFundedPrePeginFee=se;exports.computePeginFingerprint=Se;exports.deriveHashlocksFromPrePegin=He;exports.describePeginParamsCandidate=B;exports.describeUnresolvedVersion=pe;exports.encodePeginFingerprintPreimage=ce;exports.isDepositTermsRejectedError=Re;exports.isPeginFingerprintInputError=Ie;exports.isWotsMismatchError=Te;exports.orderClaimBatchByHtlcVout=ne;exports.rebuildDepositTermsCore=z;exports.rebuildDepositTermsForClaim=ke;exports.reconstructPeginParams=Oe;exports.selectSiblingRegistrations=te;exports.toRefundInputs=De;
2
- //# sourceMappingURL=toRefundInputs-DOCLxqC1.cjs.map
1
+ "use strict";var Pe=Object.defineProperty;var fe=(e,t,r)=>t in e?Pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var j=(e,t,r)=>fe(e,typeof t!="symbol"?t+"":t,r);const M=require("./registration-records-XQMIKjGV.cjs"),p=require("./bitcoin-D-O2GjbC.cjs"),N=require("./btcTxHash-CGb5BqFL.cjs"),O=require("bitcoinjs-lib"),ve=require("buffer"),be=require("./tbv/core/clients/mempool/index.cjs"),X=require("./validation-C6XTfZak.cjs"),C=require("viem"),Ee=require("./sha2-Ce6KewYx.cjs"),D=require("./PayoutManager-B1Ev0r7o.cjs"),ee=require("./PeginManager-D2R4Q1bN.cjs"),v=require("./tbv/core/wasm/index.cjs"),xe=require("./deriveVaultRoot-C3uqnJto.cjs"),we=require("./parseFundingOutpoints-C_-PT9BT.cjs"),K=require("./verifyScriptPathSchnorrSignature-CahYx5Td.cjs"),Q=require("./fundPeginTransaction-54-Rwb2k.cjs"),ye=["vaultCoreVersion","offchainParamsVersion","appVaultKeepersVersion","universalChallengersVersion"],Ce=["applicationEntryPoint","vaultProvider"];function te(e,t){const r=t.depositor.toLowerCase(),n=M.registrationPrePeginTxHash(t).toLowerCase();return e.filter(o=>o.vaultId!==t.vaultId&&o.depositor.toLowerCase()===r&&M.registrationPrePeginTxHash(o).toLowerCase()===n)}function re(e,t){for(const r of t){for(const n of ye)if(r.vault.protocol[n]!==e.vault.protocol[n])throw new Error(`Sibling vaults of this Pre-PegIn disagree on ${n} (${r.vault.protocol[n]} vs ${e.vault.protocol[n]}); the batch cannot be described by one set of deposit terms.`);if(r.maxAcceptableCommissionBps!==e.maxAcceptableCommissionBps)throw new Error(`Sibling vaults of this Pre-PegIn disagree on maxAcceptableCommissionBps (${r.maxAcceptableCommissionBps} vs ${e.maxAcceptableCommissionBps}); the batch cannot be described by one set of deposit terms.`);for(const n of Ce)if(r.vault.basic[n].toLowerCase()!==e.vault.basic[n].toLowerCase())throw new Error(`Sibling vaults of this Pre-PegIn disagree on ${n} (${r.vault.basic[n]} vs ${e.vault.basic[n]}); the batch cannot be described by one set of deposit terms.`)}}function ne(e){const t=[...e].sort((r,n)=>r.vault.protocol.htlcVout-n.vault.protocol.htlcVout);return t.forEach((r,n)=>{if(r.vault.protocol.htlcVout!==n)throw new Error(`Sibling discovery produced a non-contiguous HTLC vector (${t.map(o=>o.vault.protocol.htlcVout).join(", ")}).`)}),t.map(r=>({hashlock:r.vault.protocol.hashlock,amount:r.vault.basic.amount}))}const L="DepositTermsRejectedError";class oe extends Error{constructor(r,n="device-envelope"){super(r);j(this,"reason");this.name=L,this.reason=n}}function Re(e){if(e instanceof oe)return!0;if(typeof e!="object"||e===null)return!1;const t=e;return t.name===L&&t.reason==="device-envelope"}async function se(e,t){const r=O.Transaction.fromHex(p.stripHexPrefix(e)),o=(await Promise.all(r.ins.map(i=>be.getUtxoInfo(ve.Buffer.from(i.hash).reverse().toString("hex"),i.index,t)))).reduce((i,a)=>i+BigInt(a.value),0n),u=r.outs.reduce((i,a)=>i+BigInt(a.value),0n),s=o-u;if(s<=0n)throw new Error(`The funded Pre-PegIn transaction's inputs do not cover its outputs plus a fee (computed fee: ${s} sats).`);if(s>X.MAX_REASONABLE_FEE_SATS)throw new Error(`The funded Pre-PegIn transaction's computed fee (${s} sats) exceeds the maximum reasonable fee (${X.MAX_REASONABLE_FEE_SATS} sats); the mempool API may have returned manipulated prevout data.`);return s}async function z(e){const t=e.siblings.length;if(t===0)throw new Error("rebuildDepositTermsCore: at least one sibling is required");for(const[l,E]of e.siblings.entries())if(E.amount<=0n)throw new Error(`rebuildDepositTermsCore: sibling[${l}] has non-positive on-chain pegin amount ${E.amount}; the chain-read vault record is invalid. Resume refused.`);if(e.prepeginMaxFee<=0n)throw new Error(`rebuildDepositTermsCore: prepeginMaxFee must be > 0, got ${e.prepeginMaxFee}`);const r=p.stripHexPrefix(e.prepeginTxid).toLowerCase(),n=p.stripHexPrefix(N.calculateBtcTxHash(e.fundedPrePeginTxHex)).toLowerCase();if(n!==r)throw new Error(`Funded Pre-PegIn tx hashes to ${n}, expected ${r} (on-chain prepeginTxid). Resume refused.`);const o=D.findAuthAnchorOpReturn(p.stripHexPrefix(e.fundedPrePeginTxHex));if(o===void 0)throw new Error("Funded Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN commitment — it either predates auth anchoring or is malformed. The intent resume path requires the anchor to prove sibling completeness. Resume refused.");if(o.vout!==t)throw new Error(`Auth-anchor OP_RETURN at vout ${o.vout} does not match the discovered sibling count ${t}; the discovered sibling set does not cover this transaction's HTLC outputs (a lagging index can cause this — retry later). Resume refused.`);const u=e.vaultKeeperBtcPubkeys.length,s=e.universalChallengerBtcPubkeys.length,i=await v.computeMinClaimValue(e.vaultCoreVersion,u,s,e.councilQuorum,e.councilSize,e.protocolFeeRate),a=await v.computeMinPeginFee(e.vaultCoreVersion,u,s,e.minPeginFeeRate),d=await v.peginP2aAnchorOutput(e.vaultCoreVersion),c=(d==null?void 0:d.value)??0n;if(i<=0n)throw new Error(`WASM returned non-positive depositorClaimValue ${i}; expected > 0. Resume refused.`);if(a<=0n)throw new Error(`WASM returned non-positive peginMaxFee ${a}; expected > 0. Resume refused.`);if(c<0n)throw new Error(`WASM returned negative P2A anchor value ${c}. Resume refused.`);const h=a+c,b=e.minPeginFeeRate*Q.MAX_REASONABLE_PEGIN_VBYTES;if(h<=0n||h>b)throw new Error(`WASM implied PegIn reserve ${h} sat is outside (0, ${b}] (minPeginFeeRate=${e.minPeginFeeRate} × ${Q.MAX_REASONABLE_PEGIN_VBYTES} vbytes). Resume refused.`);const w=e.siblings.map(l=>l.amount+i+a+c),R=await Promise.all(e.siblings.map(async l=>(await v.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorBtcPubkey,vaultProviderPubkey:e.vaultProviderBtcPubkey,vaultKeeperPubkeys:[...e.vaultKeeperBtcPubkeys],universalChallengerPubkeys:[...e.universalChallengerBtcPubkeys],hashlock:p.stripHexPrefix(l.hashlock),timelockRefund:e.timelockRefund,network:e.network})).scriptPubKey)),y=O.Transaction.fromHex(p.stripHexPrefix(e.fundedPrePeginTxHex)).outs.map(l=>({value:l.value,script:l.script}));return K.assertEncodedHtlcOutputsMatch(y,w,R),ee.buildDepositTerms({vaultCoreVersion:e.vaultCoreVersion,protocolFeeRate:e.protocolFeeRate,timelockPegin:e.timelockPegin,timelockAssert:e.timelockAssert,timelockRefund:e.timelockRefund,prepeginTxid:e.prepeginTxid,prepeginMaxFee:e.prepeginMaxFee,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:e.universalChallengerBtcPubkeys,maxAcceptableCommissionBps:e.maxAcceptableCommissionBps,peginAmounts:e.siblings.map(l=>l.amount),depositorClaimValue:i,peginMaxFee:a})}async function ke(e){const{read:t}=e,r=p.canonicalizeBtcPubkey(e.depositorBtcPubkey);if(r!==t.context.depositorBtcPubkey)throw new Error("Connected wallet key is not the vault's depositor key; select the account that made the deposit.");const n=p.stripHexPrefix(t.prePeginTxHash).toLowerCase(),o=p.stripHexPrefix(N.calculateBtcTxHash(e.fundedPrePeginTxHex)).toLowerCase();if(o!==n)throw new Error(`Funded Pre-PegIn tx hashes to ${o}, expected ${n} (on-chain prePeginTxHash).`);const u=await Promise.all(te(t.registrationRecords,t.registrationRecord).map(async d=>{const c=await e.siblingReader.getVaultData(d.vaultId);if(c.protocol.prePeginTxHash.toLowerCase()!==M.registrationPrePeginTxHash(d).toLowerCase())throw new Error(`Sibling ${d.vaultId} is registered against a different Pre-PegIn on chain than its registration log records; refusing an inconsistent node.`);return{vault:c,maxAcceptableCommissionBps:d.maxAcceptableCommissionBps}})),s={vault:t.vault,maxAcceptableCommissionBps:t.registrationRecord.maxAcceptableCommissionBps};re(s,u);const i=ne([s,...u]),a=await se(e.fundedPrePeginTxHex,e.mempoolApiUrl);return z({vaultCoreVersion:t.vault.protocol.vaultCoreVersion,siblings:i,fundedPrePeginTxHex:e.fundedPrePeginTxHex,depositorBtcPubkey:r,vaultProviderBtcPubkey:t.participantKeys.vaultProvider.operationBtcPubkey,vaultKeeperBtcPubkeys:t.participantKeys.vaultKeeperOperationKeysSorted,universalChallengerBtcPubkeys:t.participantKeys.universalChallengerOperationKeysSorted,protocolFeeRate:t.offchainParams.feeRate,minPeginFeeRate:t.offchainParams.minPeginFeeRate,councilQuorum:t.offchainParams.councilQuorum,councilSize:t.offchainParams.securityCouncilKeys.length,timelockPegin:t.context.timelockPegin,timelockAssert:t.context.timelockAssert,timelockRefund:t.offchainParams.tRefund,prepeginTxid:n,prepeginMaxFee:a,maxAcceptableCommissionBps:t.registrationRecord.maxAcceptableCommissionBps,network:e.network})}function Te(e){const t=(e instanceof Error?e.message:typeof e=="string"?e:"").toLowerCase();return t.includes("wots")&&t.includes("hash")&&t.includes("does not match")}const ie="TBV.PeginFingerprint.v1",ae=C.keccak256(C.toHex(ie)),W=65535,J=2n**64n-1n,Ae=2n**256n-1n,Ve=/^0x[0-9a-fA-F]{64}$/,Y=1;class P extends Error{constructor(t){super(t),this.name="PeginFingerprintInputError"}}function Ie(e){return e instanceof P||e instanceof Error&&e.name==="PeginFingerprintInputError"}function _(e,t,r,n){if(typeof t!="bigint")throw new P(`${e} must be a bigint (Solidity ${n}), got ${typeof t}`);if(t<0n||t>r)throw new P(`${e} must fit Solidity ${n} (0..${r}), got ${t}`)}function $(e,t){if(!Number.isInteger(t)||t<0||t>W)throw new P(`${e} must be an integer fitting Solidity uint16 (0..${W}), got ${t}`)}function $e(e,t){if(!Ve.test(t))throw new P(`${e} must be 32 bytes as 0x-prefixed hex (66 characters), got "${t}"`);return t.toLowerCase()}function Be(e){if(!C.isAddress(e,{strict:!1}))throw new P(`registryAddress must be a 20-byte 0x-prefixed address, got "${e}"`);const t=e.toLowerCase();if(t===C.zeroAddress)throw new P("registryAddress must not be the zero address; a zero here means the registry address was never resolved");return t}const Fe=[{name:"domain",type:"bytes32"},{name:"chainId",type:"uint256"},{name:"registry",type:"address"},{name:"vaultProviderBtcKey",type:"bytes32"},{name:"appKeeperKeyEpoch",type:"uint64"},{name:"ucKeyEpoch",type:"uint64"},{name:"appVaultKeepersVersion",type:"uint16"},{name:"universalChallengersVersion",type:"uint16"},{name:"offchainParamsVersion",type:"uint16"},{name:"vaultCoreVersion",type:"uint16"}];function ce(e){if(_("chainId",e.chainId,Ae,"uint256"),e.chainId===0n)throw new P("chainId must not be 0; a zero here means the chain id was never resolved");const t=Be(e.registryAddress),r=$e("vaultProviderBtcKey",e.vaultProviderBtcKey);if(_("appKeeperKeyEpoch",e.appKeeperKeyEpoch,J,"uint64"),_("ucKeyEpoch",e.ucKeyEpoch,J,"uint64"),$("appVaultKeepersVersion",e.appVaultKeepersVersion),$("universalChallengersVersion",e.universalChallengersVersion),$("offchainParamsVersion",e.offchainParamsVersion),$("vaultCoreVersion",e.vaultCoreVersion),e.vaultCoreVersion<Y)throw new P(`vaultCoreVersion must be at least ${Y}; ${e.vaultCoreVersion} means the version was never resolved`);return C.encodeAbiParameters(Fe,[ae,e.chainId,t,r,e.appKeeperKeyEpoch,e.ucKeyEpoch,e.appVaultKeepersVersion,e.universalChallengersVersion,e.offchainParamsVersion,e.vaultCoreVersion])}function Se(e){return C.keccak256(ce(e))}class ue extends Error{constructor(t,r){super(`Re-derived vault root does not match this Pre-PegIn: derived auth-anchor hash ${t}, transaction commits to ${r}. Connect the same wallet, on the same account and the same network, that created the deposit.`),this.derivedAuthAnchorHash=t,this.onChainAuthAnchorHash=r,this.name="VaultRootMismatchError"}}class F extends Error{constructor(t){super(t),this.name="UnanchoredPrePeginError"}}class le extends Error{constructor(t,r,n=[]){super(`No candidate parameter set reproduces this Pre-PegIn's HTLC outputs (${t} candidate(s) tried). `+(n.length>0?`${n.length} version(s) could not be resolved and may hold the answer: ${n.join(" | ")}. `:"")+`Sample rejections: ${r.join(" | ")}`),this.candidatesTried=t,this.sampleRejections=r,this.unresolvedLabels=n,this.name="PeginParamsNotFoundError"}}class he extends Error{constructor(t){super(`${t.length} candidate parameter sets reproduce this Pre-PegIn's HTLC outputs, so the vault's stamped versions cannot be determined: ${t.join(" | ")}. Reconstruction refused.`),this.survivorLabels=t,this.name="PeginParamsAmbiguousError"}}class de extends Error{constructor(t,r){super(`A candidate matched this Pre-PegIn (${t}), but ${r.length} version(s) could not be resolved, so the search space did not provably contain the true parameters: ${r.join(" | ")}. A version sharing the matched timelockRefund and participants is indistinguishable from the true one, so the match cannot be trusted. Reconstruction refused.`),this.matchedLabel=t,this.unresolvedLabels=r,this.name="PeginParamsIncompleteSpaceError"}}class V extends Error{constructor(t){super(`${t}. Reconstruction refused.`),this.name="PeginSizingIntegrityError"}}async function He(e){const{wallet:t,depositorBtcPubkey:r,fundedPrePeginTxHex:n}=e,o=p.stripHexPrefix(n),u=D.findAuthAnchorOpReturn(o);if(u===void 0)throw new F("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN, so the number of HTLC outputs it funds cannot be determined. Legacy pre-anchor deposits are not recoverable by this path.");const s=u.vout;if(s===0)throw new F("Pre-PegIn's auth-anchor OP_RETURN is at vout 0, implying zero HTLC outputs; there is nothing to recover.");const i=we.parseFundingOutpointsFromTx(o),a=await xe.deriveVaultRoot(t,{depositorBtcPubkey:p.hexToUint8Array(p.processPublicKeyToXOnly(r)),fundingOutpoints:i});try{const c=await v.expandAuthAnchor(a);let h;try{h=p.uint8ArrayToHex(Ee.sha256(c))}finally{c.fill(0)}if(h!==u.hash)throw new ue(h,u.hash)}catch(c){throw a.fill(0),c}const{hashlocks:d}=await ee.expandPerVaultSecrets(a,s);return{vaultCount:s,hashlocks:d,authAnchorHash:u.hash}}function _e(e){const{vaultCoreVersion:t,offchainParams:r,participantKeySets:n}=e;if(!Number.isInteger(t)||t<1)throw new Error(`buildPeginParamsCandidates: vaultCoreVersion must be a positive integer, got ${t}`);if(r.length===0)throw new Error("buildPeginParamsCandidates: at least one offchain-params version is required");if(n.length===0)throw new Error("buildPeginParamsCandidates: at least one participant key set is required");const o=[];for(const u of r)for(const s of n)o.push({vaultCoreVersion:t,offchainParams:u,participants:s});return o}function pe(e){return`${e.axis} v${e.version} (${e.reason})`}function B(e){const{participants:t}=e;return`core=${e.vaultCoreVersion} offchain=${e.offchainParams.version} keepers=${t.appVaultKeepersVersion} challengers=${t.universalChallengersVersion} vp=${t.vaultProvider}`}const Z=5;function Me(e,t){return JSON.stringify({terms:e,peginAmounts:t},(r,n)=>typeof n=="bigint"?`${n}`:n)}function Ke(e){const{offchainParams:t,participants:r}=e;return[e.vaultCoreVersion,r.vaultKeeperBtcPubkeys.length,r.universalChallengerBtcPubkeys.length,t.councilQuorum,t.councilSize,t.protocolFeeRate,t.minPeginFeeRate].join("|")}async function Ne(e){const{offchainParams:t,participants:r}=e,n=r.vaultKeeperBtcPubkeys.length,o=r.universalChallengerBtcPubkeys.length,[u,s,i]=await Promise.all([v.computeMinClaimValue(e.vaultCoreVersion,n,o,t.councilQuorum,t.councilSize,t.protocolFeeRate),v.computeMinPeginFee(e.vaultCoreVersion,n,o,t.minPeginFeeRate),v.peginP2aAnchorOutput(e.vaultCoreVersion)]),a=(i==null?void 0:i.value)??0n;if(u<=0n)throw new V(`WASM returned non-positive depositorClaimValue ${u} for graph version ${e.vaultCoreVersion}`);if(s<=0n)throw new V(`WASM returned non-positive peginMaxFee ${s} for graph version ${e.vaultCoreVersion}`);if(a<0n)throw new V(`WASM returned negative P2A anchor value ${a} for graph version ${e.vaultCoreVersion}`);return{depositorClaimValue:u,peginMaxFee:s,p2aAnchorValue:a}}async function Oe(e){const{hashlocks:t,fundedPrePeginTxHex:r,depositorBtcPubkey:n,prepeginMaxFee:o,maxAcceptableCommissionBps:u,network:s,candidates:i,unresolvedVersions:a}=e;if(t.length===0)throw new Error("reconstructPeginParams: at least one hashlock is required");if(i.length===0)throw new Error("reconstructPeginParams: candidate space is empty");const d=p.processPublicKeyToXOnly(n),c=p.stripHexPrefix(r),h=D.findAuthAnchorOpReturn(c);if(h===void 0)throw new F("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN; the sibling set cannot be proven complete. Reconstruction refused.");if(h.vout!==t.length)throw new Error(`reconstructPeginParams: ${t.length} hashlock(s) supplied but the auth-anchor OP_RETURN sits at vout ${h.vout}, so the transaction funds ${h.vout} HTLC output(s). Reconstruction refused.`);const b=O.Transaction.fromHex(c).outs,w=t.map((m,g)=>BigInt(b[g].value)),R=p.stripHexPrefix(N.calculateBtcTxHash(c)).toLowerCase(),y=new Map,l=[],E=[],S=[];let U=0;for(const m of i)try{const g=Ke(m);let f=y.get(g);f===void 0&&(f=await Ne(m),y.set(g,f));const k=f.depositorClaimValue+f.peginMaxFee+f.p2aAnchorValue,T=w.map(A=>A-k),I=T.findIndex(A=>A<=0n);if(I!==-1)throw new K.HtlcOutputMismatchError(`HTLC output[${I}] value ${w[I]} is not above this candidate's reserve ${k}, so it implies a non-positive pegin amount ${T[I]}.`);const{offchainParams:x,participants:H}=m,G=await z({vaultCoreVersion:m.vaultCoreVersion,siblings:t.map((A,ge)=>({hashlock:A,amount:T[ge]})),fundedPrePeginTxHex:c,depositorBtcPubkey:d,vaultProviderBtcPubkey:H.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:H.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:H.universalChallengerBtcPubkeys,protocolFeeRate:x.protocolFeeRate,minPeginFeeRate:x.minPeginFeeRate,councilQuorum:x.councilQuorum,councilSize:x.councilSize,timelockPegin:x.timelockPegin,timelockAssert:x.timelockAssert,timelockRefund:x.timelockRefund,prepeginTxid:R,prepeginMaxFee:o,maxAcceptableCommissionBps:u,network:s});l.push({candidate:m,terms:G,peginAmounts:T,fingerprint:Me(G,T)})}catch(g){if(g instanceof V)throw g;const f=B(m),k=g instanceof Error?g.message:String(g);g instanceof K.HtlcOutputMismatchError?E.length<Z&&E.push(`[${f}] ${k}`):(U++,S.length<Z&&S.push(`${f} (${k})`))}const me=a.length+U,q=[...a.map(pe),...S];if(l.length===0)throw new le(i.length,E,q);if(new Set(l.map(m=>m.fingerprint)).size>1)throw new he(l.map(m=>B(m.candidate)));if(me>0)throw new de(B(l[0].candidate),q);return{candidate:l[0].candidate,terms:l[0].terms,peginAmounts:l[0].peginAmounts,authAnchorHash:h.hash,candidatesTried:i.length,matchedCandidates:l.map(m=>m.candidate)}}function De(e,t){const{htlcVout:r,depositorBtcPubkey:n,applicationEntryPoint:o,fundedPrePeginTxHex:u,hashlocks:s,network:i}=t,{candidate:a,peginAmounts:d}=e,{offchainParams:c,participants:h}=a;if(s.length!==d.length)throw new Error(`toRefundInputs: ${s.length} hashlock(s) but ${d.length} reconstructed amount(s); the reconstruction and the hashlock vector describe different transactions.`);if(!Number.isInteger(r)||r<0||r>=d.length)throw new Error(`toRefundInputs: htlcVout ${r} is outside the reconstructed batch of ${d.length} vault(s).`);const b=d.map((y,l)=>({hashlock:p.ensureHexPrefix(s[l]),amount:y,htlcVout:l})),w={vaultCoreVersion:a.vaultCoreVersion,hashlock:b[r].hashlock,htlcVout:r,offchainParamsVersion:c.version,appVaultKeepersVersion:h.appVaultKeepersVersion,universalChallengersVersion:h.universalChallengersVersion,vaultProvider:h.vaultProvider,applicationEntryPoint:o,amount:d[r],unsignedPrePeginTxHex:u,depositorBtcPubkey:n,batch:b},R={vaultProviderPubkey:h.vaultProviderBtcPubkey,vaultKeeperPubkeys:h.vaultKeeperBtcPubkeys,universalChallengerPubkeys:h.universalChallengerBtcPubkeys,timelockRefund:c.timelockRefund,feeRate:c.protocolFeeRate,minPeginFeeRate:c.minPeginFeeRate,numLocalChallengers:h.vaultKeeperBtcPubkeys.length,councilQuorum:c.councilQuorum,councilSize:c.councilSize,network:i};return{vault:w,context:R}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=L;exports.DepositTermsRejectedError=oe;exports.PEGIN_FINGERPRINT_DOMAIN=ae;exports.PEGIN_FINGERPRINT_DOMAIN_PREIMAGE=ie;exports.PeginFingerprintInputError=P;exports.PeginParamsAmbiguousError=he;exports.PeginParamsIncompleteSpaceError=de;exports.PeginParamsNotFoundError=le;exports.PeginSizingIntegrityError=V;exports.UnanchoredPrePeginError=F;exports.VaultRootMismatchError=ue;exports.assertClaimBatchHomogeneous=re;exports.buildPeginParamsCandidates=_e;exports.computeFundedPrePeginFee=se;exports.computePeginFingerprint=Se;exports.deriveHashlocksFromPrePegin=He;exports.describePeginParamsCandidate=B;exports.describeUnresolvedVersion=pe;exports.encodePeginFingerprintPreimage=ce;exports.isDepositTermsRejectedError=Re;exports.isPeginFingerprintInputError=Ie;exports.isWotsMismatchError=Te;exports.orderClaimBatchByHtlcVout=ne;exports.rebuildDepositTermsCore=z;exports.rebuildDepositTermsForClaim=ke;exports.reconstructPeginParams=Oe;exports.selectSiblingRegistrations=te;exports.toRefundInputs=De;
2
+ //# sourceMappingURL=toRefundInputs-DRmK83fv.cjs.map