@babylonlabs-io/ts-sdk 0.26.0 → 0.26.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 (38) hide show
  1. package/dist/{buildAndBroadcastRefund-Ce5jAu-C.js → buildAndBroadcastRefund-Ccp-2GWW.js} +2 -2
  2. package/dist/{buildAndBroadcastRefund-Ce5jAu-C.js.map → buildAndBroadcastRefund-Ccp-2GWW.js.map} +1 -1
  3. package/dist/{buildAndBroadcastRefund-IQ_2SCic.cjs → buildAndBroadcastRefund-Mr3ck5ek.cjs} +2 -2
  4. package/dist/{buildAndBroadcastRefund-IQ_2SCic.cjs.map → buildAndBroadcastRefund-Mr3ck5ek.cjs.map} +1 -1
  5. package/dist/{errors-B3DbZYLe.cjs → errors-BqKsTgDW.cjs} +2 -2
  6. package/dist/{errors-B3DbZYLe.cjs.map → errors-BqKsTgDW.cjs.map} +1 -1
  7. package/dist/{errors-Ul7fTCjl.js → errors-b6sBSfA6.js} +4 -4
  8. package/dist/{errors-Ul7fTCjl.js.map → errors-b6sBSfA6.js.map} +1 -1
  9. package/dist/{index-BAECy2oz.cjs → index-CIuXb72l.cjs} +2 -2
  10. package/dist/{index-BAECy2oz.cjs.map → index-CIuXb72l.cjs.map} +1 -1
  11. package/dist/{index-DLtpqdlu.js → index-D7s2ilf8.js} +2 -2
  12. package/dist/{index-DLtpqdlu.js.map → index-D7s2ilf8.js.map} +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +4 -4
  15. package/dist/tbv/core/clients/index.cjs +1 -1
  16. package/dist/tbv/core/clients/index.js +2 -2
  17. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +6 -6
  18. package/dist/tbv/core/index.cjs +1 -1
  19. package/dist/tbv/core/index.js +4 -4
  20. package/dist/tbv/core/services/index.cjs +1 -1
  21. package/dist/tbv/core/services/index.js +1 -1
  22. package/dist/tbv/index.cjs +1 -1
  23. package/dist/tbv/index.js +4 -4
  24. package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
  25. package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
  26. package/dist/tbv/integrations/aave/clients/query.d.ts +0 -9
  27. package/dist/tbv/integrations/aave/clients/query.d.ts.map +1 -1
  28. package/dist/tbv/integrations/aave/index.cjs +1 -1
  29. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  30. package/dist/tbv/integrations/aave/index.d.ts +1 -1
  31. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  32. package/dist/tbv/integrations/aave/index.js +69 -78
  33. package/dist/tbv/integrations/aave/index.js.map +1 -1
  34. package/dist/{types-DWjaqVfP.js → types-WrGfwlJd.js} +7 -7
  35. package/dist/{types-DWjaqVfP.js.map → types-WrGfwlJd.js.map} +1 -1
  36. package/dist/{types-B-p4dhEH.cjs → types-xU3SBcpH.cjs} +2 -2
  37. package/dist/{types-B-p4dhEH.cjs.map → types-xU3SBcpH.cjs.map} +1 -1
  38. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- "use strict";var Vt=Object.defineProperty;var Ft=(e,t,n)=>t in e?Vt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var P=(e,t,n)=>Ft(e,typeof t!="symbol"?t+"":t,n);const M=require("bitcoinjs-lib"),ot=require("buffer"),B=require("viem"),Kt=require("./signing-DHSXjhLM.cjs"),ut=require("@babylonlabs-io/babylon-tbv-rust-wasm"),R=require("./challengeAssert-X7V3Ik_Q.cjs"),k=require("./bitcoin-CNnPFU6Y.cjs"),ht=require("./validation-u8W7Lp2x.cjs"),$=require("./psbtInputFields-tnAR8tG5.cjs"),ft=require("./fundPeginTransaction-DxNOeyNI.cjs"),wt=require("./index-BAECy2oz.cjs"),O=require("./types-B-p4dhEH.cjs"),u=require("./buildAndBroadcastRefund-IQ_2SCic.cjs");function Dt(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Mt=Dt(M),C={"0x04aabf33":"Vault already exists: This Bitcoin transaction has already been registered. Please select different UTXOs or use a different amount to create a unique transaction.","0x4fec082d":"Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. This may be caused by incorrect vault participants or key configuration.","0x6cc363a5":"Invalid BTC proof of possession: The signature could not be verified. Please ensure you're signing with the correct Bitcoin wallet.","0x6c3f2bf6":"Invalid BTC public key: The Bitcoin public key format is invalid.","0x2c5211c6":"Invalid amount: The deposit amount is invalid or below the minimum required.","0x0405f772":"Application not registered: The application controller is not registered in the system.","0x24e165cc":"Invalid provider status: The vault provider is not in a valid state to accept deposits.","0xd92e233d":"Zero address: One of the required addresses is the zero address.","0x65aa7007":"BTC key mismatch: The Bitcoin public key does not match the expected key.","0x82b42900":"Unauthorized: You must be the depositor or vault provider to submit this transaction.","0x8baa579f":"Invalid signature: The BTC proof of possession signature could not be verified.","0x2f9d01e9":"Invalid BTC transaction: The Bitcoin transaction format is invalid.","0x5a3c6b3e":"Vault provider not registered: The selected vault provider is not registered.","0x979f4518":"Invalid pegin fee: The ETH fee sent does not match the required amount. This may indicate a fee rate change during the transaction.","0x5fad9694":"This pre-pegin output has already been used to activate another vault.","0x7ed061c9":"This pegin transaction has already been used to activate another vault."};function N(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.data=="string"&&t.data.startsWith("0x"))return t.data;if(typeof t.details=="string"&&t.details.startsWith("0x"))return t.details;let n=t.cause,s=0;const o=5;for(;n&&typeof n=="object"&&s<o;){const a=n;if(typeof a.data=="string"&&a.data.startsWith("0x"))return a.data;n=a.cause,s++}const i=(typeof t.message=="string"?t.message:"").match(/\b(0x[a-fA-F0-9]{8})\b/);if(i)return i[1]}function Nt(e){const t=N(e);if(t){const n=t.substring(0,10);return C[t]??C[n]}}function Xt(e){const t=N(e);if(t===void 0)return!1;const n=t.substring(0,10);return t in C||n in C}function S(e){console.error("[Contract Error] Raw error:",e);const t=N(e);if(console.error("[Contract Error] Extracted error data:",t),t){const s=t.substring(0,10),o=C[t]??C[s];if(o)throw console.error("[Contract Error] Known error:",o),new Error(o)}const n=(e==null?void 0:e.message)||"";if(n.includes("gas limit too high")||n.includes("21000000")||n.includes("Internal JSON-RPC error")){const s=t?` (error code: ${t})`:"";throw console.error("[Contract Error] Transaction rejected. Error code:",t,"Message:",n),new Error(`Transaction failed: The contract rejected this transaction${s}. Possible causes: (1) Vault already exists for this transaction, (2) Invalid signature, (3) Unauthorized caller. Please check your transaction parameters and try again.`)}throw e instanceof Error?(console.error("[Contract Error] Unhandled error:",e.message),e):new Error(`Contract call failed: ${String(e)}`)}const qt=0,jt=/^0x[0-9a-f]+$/i,Gt=/^[0-9a-f]+$/i,zt=/^[A-Za-z0-9+/]+={0,2}$/;function W(e){if(typeof e!="string"||e.length===0)throw new Error("BTC wallet returned empty public key");return k.processPublicKeyToXOnly(e).toLowerCase()}function Zt(e){if(typeof e!="string"||e.length===0)throw new Error("BTC wallet returned empty BIP-322 signature");if(e.startsWith("0x")||e.startsWith("0X")){if(!jt.test(e)||e.length<4||e.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return e.toLowerCase()}if(Gt.test(e)){if(e.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return`0x${e.toLowerCase()}`}if(!zt.test(e)||e.length%4!==0)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");const t=ot.Buffer.from(e,"base64");if(t.length===0||t.toString("base64")!==e)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");return`0x${t.toString("hex")}`}function Yt(e,t,n,s){const o=n==null?void 0:n[`${e}:${t}`];return o?Promise.resolve({txid:e,vout:t,value:o.value,scriptPubKey:o.scriptPubKey}):wt.getUtxoInfo(e,t,s)}const dt=12e4;class Jt{constructor(t){P(this,"config");this.config=t}async preparePegin(t){const n=await this.config.btcWallet.getPublicKeyHex(),s=W(n),o=k.stripHexPrefix(t.vaultProviderBtcPubkey),r=t.vaultKeeperBtcPubkeys.map(k.stripHexPrefix),i=t.universalChallengerBtcPubkeys.map(k.stripHexPrefix);if(t.hashlocks.length!==t.amounts.length)throw new Error(`hashlocks.length (${t.hashlocks.length}) must equal amounts.length (${t.amounts.length})`);if(t.hashlocks.length===0)throw new Error("hashlocks must contain at least one entry");const a=r.length,p={depositorPubkey:s,vaultProviderPubkey:o,vaultKeeperPubkeys:r,universalChallengerPubkeys:i,hashlocks:t.hashlocks,timelockRefund:t.timelockRefund,pegInAmounts:t.amounts,feeRate:t.protocolFeeRate,numLocalChallengers:a,councilQuorum:t.councilQuorum,councilSize:t.councilSize,network:this.config.btcNetwork},h=await R.buildPrePeginPsbt(p),c=$.selectUtxosForPegin([...t.availableUTXOs],h.totalOutputValue,t.mempoolFeeRate,ft.peginOutputCount(h.htlcValues.length)),y=k.getNetwork(this.config.btcNetwork),l=ft.fundPeginTransaction({unfundedTxHex:h.psbtHex,selectedUTXOs:c.selectedUTXOs,changeAddress:t.changeAddress,changeAmount:c.changeAmount,network:y}),x=k.stripHexPrefix($.calculateBtcTxHash(l)),g=[],w=[],T=[];for(let m=0;m<t.hashlocks.length;m++){const b=await R.buildPeginTxFromFundedPrePegin({prePeginParams:p,timelockPegin:t.timelockPegin,fundedPrePeginTxHex:l,htlcVout:m}),I=await R.buildPeginInputPsbt({peginTxHex:b.txHex,fundedPrePeginTxHex:l,depositorPubkey:s,vaultProviderPubkey:o,vaultKeeperPubkeys:r,universalChallengerPubkeys:i,hashlock:t.hashlocks[m],timelockRefund:t.timelockRefund,network:this.config.btcNetwork});g.push(b),w.push(I.psbtHex),T.push(Kt.createTaprootScriptPathSignOptions(n,1))}const d=await this.signPsbtsWithFallback(w,T),f=[];for(let m=0;m<d.length;m++){const b=R.extractPeginInputSignature(d[m],s),I=R.finalizePeginInputPsbt(d[m]);f.push({htlcVout:m,htlcValue:h.htlcValues[m],peginTxHex:I,peginTxid:g[m].txid,peginInputSignature:b,vaultScriptPubKey:g[m].vaultScriptPubKey})}return{fundedPrePeginTxHex:l,prePeginTxid:x,perVault:f,selectedUTXOs:c.selectedUTXOs,fee:c.fee,changeAmount:c.changeAmount}}async signPsbtsWithFallback(t,n){if(typeof this.config.btcWallet.signPsbts=="function"){const o=await this.config.btcWallet.signPsbts(t,n);if(o.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${o.length}`);return o}const s=[];for(let o=0;o<t.length;o++){const r=await this.config.btcWallet.signPsbt(t[o],n[o]);s.push(r)}return s}async signAndBroadcast(t){const{fundedPrePeginTxHex:n,depositorBtcPubkey:s}=t,o=n.startsWith("0x")?n.slice(2):n,r=M.Transaction.fromHex(o);if(r.ins.length===0)throw new Error("Transaction has no inputs");const i=new M.Psbt;i.setVersion(r.version),i.setLocktime(r.locktime);const a=ot.Buffer.from(W(s),"hex"),p=this.config.mempoolApiUrl,h=r.ins.map(f=>{const m=ot.Buffer.from(f.hash).reverse().toString("hex"),b=f.index;return Yt(m,b,t.localPrevouts,p).then(I=>({input:f,utxoData:I,txid:m,vout:b}))}),c=await Promise.all(h),y=c.reduce((f,m)=>f+BigInt(m.utxoData.value),0n),l=r.outs.reduce((f,m)=>f+BigInt(m.value),0n);if(y<l)throw new Error(`UTXO value mismatch: total input value (${y} sat) is less than total output value (${l} sat). This may indicate the mempool API returned manipulated UTXO data.`);const x=y-l;if(x>ht.MAX_REASONABLE_FEE_SATS)throw new Error(`Implied transaction fee (${x} sat) exceeds maximum reasonable fee (${ht.MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`);for(const{input:f,utxoData:m,txid:b,vout:I}of c){const E=$.getPsbtInputFields({value:m.value,scriptPubKey:m.scriptPubKey},a);i.addInput({hash:f.hash,index:f.index,sequence:f.sequence,...E})}for(const f of r.outs)i.addOutput({script:f.script,value:f.value});const g=await this.config.btcWallet.signPsbt(i.toHex()),w=M.Psbt.fromHex(g);try{w.finalizeAllInputs()}catch(f){if(!w.data.inputs.every(b=>b.finalScriptWitness||b.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${f}`)}const T=w.extractTransaction().toHex();return await wt.pushTx(T,p)}async registerPeginOnChain(t){const{unsignedPrePeginTx:n,depositorSignedPeginTx:s,vaultProvider:o,hashlock:r,htlcVout:i,depositorPayoutBtcAddress:a,depositorWotsPkHash:p,popSignature:h}=t;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const c=this.config.ethWallet.account.address;if(!B.isAddressEqual(h.depositorEthAddress,c))throw new Error(`Proof of possession was signed for ${h.depositorEthAddress} but the Ethereum wallet is currently connected to ${c}. Reconnect the original account or call signProofOfPossession() again.`);await this.assertPopMatchesBtcWallet(h);const y=h.btcPopSignature,l=k.ensureHexPrefix(h.depositorBtcPubkey),x=k.ensureHexPrefix(n),g=k.ensureHexPrefix(s),w=await this.resolvePayoutScriptPubKey(a),T=$.calculateBtcTxHash(g),d=await ut.deriveVaultId(k.stripHexPrefix(T),k.stripHexPrefix(c)),f=k.ensureHexPrefix(d);if(await this.checkVaultExists(f))throw new Error(`Vault already exists (ID: ${f}, peginTxHash: ${T}). 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.`);const b=B.createPublicClient({chain:this.config.ethChain,transport:B.http()});let I;try{I=await b.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})}catch{throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.")}const E=B.encodeFunctionData({abi:O.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[c,l,y,x,g,o,r,i,w,p]});let v;try{v=await b.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:E,value:I,account:this.config.ethWallet.account.address})}catch(q){S(q)}let _;try{_=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:E,value:I,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:v})}catch(q){S(q)}const A=await b.waitForTransactionReceipt({hash:_,timeout:dt});return A.status==="reverted"&&S(new Error(`Transaction reverted. Hash: ${_}. Check the transaction on block explorer for details.`)),{ethTxHash:A.transactionHash,vaultId:f,peginTxHash:T}}async registerPeginBatchOnChain(t){const{vaultProvider:n,unsignedPrePeginTx:s,requests:o,popSignature:r}=t;if(o.length===0)throw new Error("Batch pegin requires at least one request");if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const i=this.config.ethWallet.account.address;if(!B.isAddressEqual(r.depositorEthAddress,i))throw new Error(`Proof of possession was signed for ${r.depositorEthAddress} but the Ethereum wallet is currently connected to ${i}. Reconnect the original account or call signProofOfPossession() again.`);await this.assertPopMatchesBtcWallet(r);const a=r.btcPopSignature,p=[];for(const b of o)p.push(await this.resolvePayoutScriptPubKey(b.depositorPayoutBtcAddress));const h=[];for(const b of o){const I=k.ensureHexPrefix(b.depositorSignedPeginTx),E=$.calculateBtcTxHash(I),v=await ut.deriveVaultId(k.stripHexPrefix(E),k.stripHexPrefix(i)),_=k.ensureHexPrefix(v);if(await this.checkVaultExists(_))throw new Error(`Vault already exists (ID: ${_}, peginTxHash: ${E}). To create a new vault, use different UTXOs or a different amount.`);h.push({vaultId:_,peginTxHash:E})}const c=B.createPublicClient({chain:this.config.ethChain,transport:B.http()});let y;try{y=await c.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getPegInFee",args:[n]})}catch{throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.")}const l=y*BigInt(o.length),x=k.ensureHexPrefix(r.depositorBtcPubkey),g=k.ensureHexPrefix(s),w=o.map((b,I)=>({depositorBtcPubKey:x,btcPopSignature:a,unsignedPrePeginTx:g,depositorSignedPeginTx:k.ensureHexPrefix(b.depositorSignedPeginTx),hashlock:b.hashlock,htlcVout:b.htlcVout,referralCode:qt,depositorPayoutBtcAddress:p[I],depositorWotsPkHash:b.depositorWotsPkHash})),T=B.encodeFunctionData({abi:O.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[i,n,w]});let d;try{d=await c.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:T,value:l,account:this.config.ethWallet.account.address})}catch(b){S(b)}let f;try{f=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:T,value:l,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:d})}catch(b){S(b)}const m=await c.waitForTransactionReceipt({hash:f,timeout:dt});return m.status==="reverted"&&S(new Error(`Batch transaction reverted. Hash: ${f}. Check the transaction on block explorer for details.`)),{ethTxHash:m.transactionHash,vaults:h}}async checkVaultExists(t){try{return(await B.createPublicClient({chain:this.config.ethChain,transport:B.http()}).readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]}))[0]!==B.zeroAddress}catch{return!1}}async resolvePayoutScriptPubKey(t){let n;if(t)n=t;else{n=await this.config.btcWallet.getAddress();const o=await this.config.btcWallet.getPublicKeyHex();if(!k.isAddressFromPublicKey(n,o,this.config.btcNetwork))throw new Error("The BTC address from your wallet does not match the wallet's public key. Please ensure your wallet is using a supported address type (Taproot or Native SegWit).")}const s=k.getNetwork(this.config.btcNetwork);try{return`0x${Mt.address.toOutputScript(n,s).toString("hex")}`}catch{throw new Error(`Invalid BTC payout address: "${n}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`)}}async signProofOfPossession(){if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const t=this.config.ethWallet.account.address,n=W(await this.config.btcWallet.getPublicKeyHex()),s=this.config.vaultContracts.btcVaultRegistry,o=`${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${s.toLowerCase()}`,r=await this.config.btcWallet.signMessage(o,"bip322-simple");return{btcPopSignature:Zt(r),depositorEthAddress:t,depositorBtcPubkey:n}}async assertPopMatchesBtcWallet(t){const n=W(await this.config.btcWallet.getPublicKeyHex()),s=W(t.depositorBtcPubkey);if(n!==s)throw new Error(`Proof of possession was signed with BTC pubkey ${s} but the BTC wallet is currently connected to ${n}. Reconnect the original wallet or call signProofOfPossession() again.`)}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}class Pt{constructor(t,n){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(u.ahash(t),u.abytes(n,void 0,"key"),this.iHash=t.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 s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?t.create().update(n).digest():n);for(let r=0;r<o.length;r++)o[r]^=54;this.iHash.update(o),this.oHash=t.create();for(let r=0;r<o.length;r++)o[r]^=106;this.oHash.update(o),u.clean(o)}update(t){return u.aexists(this),this.iHash.update(t),this}digestInto(t){u.aexists(this),u.abytes(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:s,finished:o,destroyed:r,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=r,t.blockLen=i,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=s._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const X=(e,t,n)=>new Pt(e,t).update(n).digest();X.create=(e,t)=>new Pt(e,t);const Qt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),kt=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),te=kt.map(e=>(9*e+5)%16),Tt=(()=>{const n=[[kt],[te]];for(let s=0;s<4;s++)for(let o of n)o.push(o[s].map(r=>Qt[r]));return n})(),Et=Tt[0],It=Tt[1],Ht=[[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(e=>Uint8Array.from(e)),ee=Et.map((e,t)=>e.map(n=>Ht[t][n])),ne=It.map((e,t)=>e.map(n=>Ht[t][n])),se=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),oe=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function gt(e,t,n,s){return e===0?t^n^s:e===1?t&n|~t&s:e===2?(t|~n)^s:e===3?t&s|n&~s:t^(n|~s)}const V=new Uint32Array(16);class re extends u.HashMD{constructor(){super(64,20,8,!0);P(this,"h0",1732584193);P(this,"h1",-271733879);P(this,"h2",-1732584194);P(this,"h3",271733878);P(this,"h4",-1009589776)}get(){const{h0:n,h1:s,h2:o,h3:r,h4:i}=this;return[n,s,o,r,i]}set(n,s,o,r,i){this.h0=n|0,this.h1=s|0,this.h2=o|0,this.h3=r|0,this.h4=i|0}process(n,s){for(let g=0;g<16;g++,s+=4)V[g]=n.getUint32(s,!0);let o=this.h0|0,r=o,i=this.h1|0,a=i,p=this.h2|0,h=p,c=this.h3|0,y=c,l=this.h4|0,x=l;for(let g=0;g<5;g++){const w=4-g,T=se[g],d=oe[g],f=Et[g],m=It[g],b=ee[g],I=ne[g];for(let E=0;E<16;E++){const v=u.rotl(o+gt(g,i,p,c)+V[f[E]]+T,b[E])+l|0;o=l,l=c,c=u.rotl(p,10)|0,p=i,i=v}for(let E=0;E<16;E++){const v=u.rotl(r+gt(w,a,h,y)+V[m[E]]+d,I[E])+x|0;r=x,x=y,y=u.rotl(h,10)|0,h=a,a=v}}this.set(this.h1+p+y|0,this.h2+c+x|0,this.h3+l+r|0,this.h4+o+a|0,this.h0+i+h|0)}roundClean(){u.clean(V)}destroy(){this.destroyed=!0,u.clean(this.buffer),this.set(0,0,0,0,0)}}const vt=u.createHasher(()=>new re),ie=BigInt(0),U=BigInt(1),ae=BigInt(2),ce=BigInt(7),le=BigInt(256),ue=BigInt(113),Bt=[],_t=[],St=[];for(let e=0,t=U,n=1,s=0;e<24;e++){[n,s]=[s,(2*n+3*s)%5],Bt.push(2*(5*s+n)),_t.push((e+1)*(e+2)/2%64);let o=ie;for(let r=0;r<7;r++)t=(t<<U^(t>>ce)*ue)%le,t&ae&&(o^=U<<(U<<BigInt(r))-U);St.push(o)}const Ct=u.split(St,!0),he=Ct[0],fe=Ct[1],pt=(e,t,n)=>n>32?u.rotlBH(e,t,n):u.rotlSH(e,t,n),mt=(e,t,n)=>n>32?u.rotlBL(e,t,n):u.rotlSL(e,t,n);function de(e,t=24){const n=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,p=(i+2)%10,h=n[p],c=n[p+1],y=pt(h,c,1)^n[a],l=mt(h,c,1)^n[a+1];for(let x=0;x<50;x+=10)e[i+x]^=y,e[i+x+1]^=l}let o=e[2],r=e[3];for(let i=0;i<24;i++){const a=_t[i],p=pt(o,r,a),h=mt(o,r,a),c=Bt[i];o=e[c],r=e[c+1],e[c]=p,e[c+1]=h}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)n[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~n[(a+2)%10]&n[(a+4)%10]}e[0]^=he[s],e[1]^=fe[s]}u.clean(n)}class ct{constructor(t,n,s,o=!1,r=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=t,this.suffix=n,this.outputLen=s,this.enableXOF=o,this.rounds=r,u.anumber(s,"outputLen"),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=u.u32(this.state)}clone(){return this._cloneInto()}keccak(){u.swap32IfBE(this.state32),de(this.state32,this.rounds),u.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(t){u.aexists(this),u.abytes(t);const{blockLen:n,state:s}=this,o=t.length;for(let r=0;r<o;){const i=Math.min(n-this.pos,o-r);for(let a=0;a<i;a++)s[this.pos++]^=t[r++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:n,pos:s,blockLen:o}=this;t[s]^=n,(n&128)!==0&&s===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){u.aexists(this,!1),u.abytes(t),this.finish();const n=this.state,{blockLen:s}=this;for(let o=0,r=t.length;o<r;){this.posOut>=s&&this.keccak();const i=Math.min(s-this.posOut,r-o);t.set(n.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return u.anumber(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(u.aoutput(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,u.clean(this.state)}_cloneInto(t){const{blockLen:n,suffix:s,outputLen:o,rounds:r,enableXOF:i}=this;return t||(t=new ct(n,s,o,i,r)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=r,t.suffix=s,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}}const ge=(e,t,n,s={})=>u.createHasher(()=>new ct(t,e,n),s),At=ge(1,136,32);function pe(e,t,n,s){u.ahash(e);const o=u.checkOpts({dkLen:32,asyncTick:10},s),{c:r,dkLen:i,asyncTick:a}=o;if(u.anumber(r,"c"),u.anumber(i,"dkLen"),u.anumber(a,"asyncTick"),r<1)throw new Error("iterations (c) must be >= 1");const p=u.kdfInputToBytes(t,"password"),h=u.kdfInputToBytes(n,"salt"),c=new Uint8Array(i),y=X.create(e,p),l=y._cloneInto().update(h);return{c:r,dkLen:i,asyncTick:a,DK:c,PRF:y,PRFSalt:l}}function me(e,t,n,s,o){return e.destroy(),t.destroy(),s&&s.destroy(),u.clean(o),n}function ye(e,t,n,s){const{c:o,dkLen:r,DK:i,PRF:a,PRFSalt:p}=pe(e,t,n,s);let h;const c=new Uint8Array(4),y=u.createView(c),l=new Uint8Array(a.outputLen);for(let x=1,g=0;g<r;x++,g+=a.outputLen){const w=i.subarray(g,g+a.outputLen);y.setInt32(0,x,!1),(h=p._cloneInto(h)).update(c).digestInto(l),w.set(l.subarray(0,w.length));for(let T=1;T<o;T++){a._cloneInto(h).update(l).digestInto(l);for(let d=0;d<w.length;d++)w[d]^=l[d]}}return me(a,p,i,h,l)}function Rt(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function be(e){const t=Rt(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}const xe=e=>Rt("mnemonic"+e);function we(e,t=""){return ye(u.sha512,be(e).nfkd,xe(t),{c:2048,dkLen:64})}const Pe=508,yt=16,F=32,K=64,bt=5,ke=4;function L(...e){const t=e.reduce((o,r)=>o+r.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;return n}function j(e){return new TextEncoder().encode(e)}function G(e){const t=new Uint8Array(ke);return new DataView(t.buffer).setUint32(0,e.length,!1),L(t,e)}function z(e,t){return X(u.sha512,e,t)}function xt(e){return vt(u.sha256(e))}const rt=e=>Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");function $t(e){const t=we(e),n=new Uint8Array(t);return t.fill(0),n}async function Ot(e,t,n,s){if(e.length!==K)throw new Error(`WOTS seed must be ${K} bytes, got ${e.length}`);t=k.stripHexPrefix(t),n=k.stripHexPrefix(n);const o=e.slice(F,K),r=e.slice(0,F),i=[o,r];try{const a=L(G(j(t)),G(j(n)),G(j(s))),p=L(r,a);i.push(p);const h=z(o,p);i.push(h);const c=h.slice(0,F),y=h.slice(F,K);i.push(c,y);const l=[],x=[],g=[],w=[];let T=!1;try{for(let d=0;d<Pe;d++){const f=new Uint8Array(bt);f[0]=0,new DataView(f.buffer).setUint32(1,d,!1);const m=new Uint8Array(bt);m[0]=1,new DataView(m.buffer).setUint32(1,d,!1);const b=L(c,f),I=L(c,m),E=z(y,b),v=z(y,I);try{const _=E.slice(0,yt),A=v.slice(0,yt);l.push(_),x.push(A),g.push(xt(_)),w.push(xt(A))}finally{b.fill(0),I.fill(0),E.fill(0),v.fill(0)}}return T=!0,{falsePreimages:l,truePreimages:x,falseHashes:g,trueHashes:w}}finally{if(!T){for(const d of l)d.fill(0);for(const d of x)d.fill(0)}}}finally{for(const a of i)a.fill(0)}}function Te(e){return{false_list:e.falseHashes.map(rt),true_list:e.trueHashes.map(rt)}}function Wt(e){if(e.falseHashes.length===0||e.trueHashes.length===0)throw new Error("computeWotsPkHash: keypair hash arrays must not be empty");const t=e.falseHashes[0].length,n=(e.falseHashes.length+e.trueHashes.length)*t,s=new Uint8Array(n);let o=0;for(const i of e.falseHashes)s.set(i,o),o+=t;for(const i of e.trueHashes)s.set(i,o),o+=t;const r=At(s);return`0x${rt(r)}`}const Z=32,Y=64,Ee=4,H=20,it=4,Ut=2,Ie=0,He=1,D=[64,64];function at(...e){const t=e.reduce((o,r)=>o+r.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;return n}function J(e){return new TextEncoder().encode(e)}function Q(e){const t=new Uint8Array(Ee);return new DataView(t.buffer).setUint32(0,e.length,!1),at(t,e)}function tt(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}const ve=e=>Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");function Be(e,t){return X(u.sha512,e,t)}function lt(e){return vt(u.sha256(e))}function Lt(e){return(1<<e)-1}function _e(e){let t=1;for(;t*t<e+1;)t++;return Math.max(t,2)}function Se(e){const t=it,n=Lt(t),s=e*n;return{d:t,n:e,checksum_radix:_e(s)}}function et(e,t){const n=[];let s=t;for(;s>0;)n.push(s&255),s>>>=8;const o=new Uint8Array(e.length+n.length);o.set(e);for(let r=0;r<n.length;r++)o[e.length+r]=n[r];return lt(o)}function nt(e,t){let n=e;for(let s=0;s<t;s++)n=lt(n);return n}function Ce(e,t){const n=Lt(t.d),s=t.checksum_radix-1,o=Math.floor(t.n*n/t.checksum_radix),r=[];for(let c=0;c<t.n;c++){const y=et(e,c+Ut),l=nt(y,n);r.push(Array.from(l))}const i=et(e,Ie),a=nt(i,s),p=et(e,He),h=nt(p,o);return{config:t,message_terminals:r,checksum_major_terminal:Array.from(h),checksum_minor_terminal:Array.from(a)}}async function Ae(e,t,n,s){if(e.length!==Y)throw new Error(`WOTS seed must be exactly ${Y} bytes, got ${e.length}`);const o=tt(t),r=tt(n),i=e.slice(Z,Y),a=e.slice(0,Z),p=at(a,at(Q(J(o)),Q(J(r)),Q(J(tt(s))))),h=Be(i,p),c=h.slice(0,Z);try{const y=[];for(let l=0;l<D.length;l++){const x=D[l],g=Se(x),w=new Uint8Array(c.length+1);w.set(c),w[c.length]=l;const T=lt(w);try{const d=Ce(T,g);if(d.config.d!==it)throw new Error(`Block ${l}: expected d=${it}, got d=${d.config.d}`);if(d.config.n!==x)throw new Error(`Block ${l}: expected n=${x}, got n=${d.config.n}`);if(d.message_terminals.length!==x)throw new Error(`Block ${l}: expected ${x} message terminals, got ${d.message_terminals.length}`);for(let f=0;f<d.message_terminals.length;f++)if(d.message_terminals[f].length!==H)throw new Error(`Block ${l} terminal ${f}: expected ${H} bytes, got ${d.message_terminals[f].length}`);if(d.checksum_minor_terminal.length!==H)throw new Error(`Block ${l} checksum_minor: expected ${H} bytes`);if(d.checksum_major_terminal.length!==H)throw new Error(`Block ${l} checksum_major: expected ${H} bytes`);y.push(d)}finally{w.fill(0),T.fill(0)}}if(y.length!==D.length)throw new Error(`Expected ${D.length} blocks, got ${y.length}`);return y}finally{p.fill(0),i.fill(0),a.fill(0),h.fill(0),c.fill(0),e.fill(0)}}function st(e,t,n){if(e.length!==H)throw new Error(`Block ${t} ${n}: expected ${H} bytes, got ${e.length}`);for(let s=0;s<e.length;s++){const o=e[s];if(!Number.isInteger(o)||o<0||o>255)throw new Error(`Block ${t} ${n}[${s}]: invalid byte value ${o}`)}}function Re(e){if(e.length===0)throw new Error("Public keys array must not be empty");for(let r=0;r<e.length;r++){const i=e[r];st(i.checksum_minor_terminal,r,"checksum_minor_terminal"),st(i.checksum_major_terminal,r,"checksum_major_terminal");for(let a=0;a<i.message_terminals.length;a++)st(i.message_terminals[a],r,`message_terminal[${a}]`)}let t=0;for(const r of e)t+=Ut+r.message_terminals.length;const n=new Uint8Array(t*H);let s=0;for(const r of e){n.set(r.checksum_minor_terminal,s),s+=H,n.set(r.checksum_major_terminal,s),s+=H;for(const i of r.message_terminals)n.set(i,s),s+=H}const o=At(n);return`0x${ve(o)}`}async function $e(e,t,n,s){const o=$t(e);try{const r=await Ot(o,t,n,s);try{return Wt(r)}finally{for(const i of r.falsePreimages)i.fill(0);for(const i of r.truePreimages)i.fill(0)}}finally{o.fill(0)}}function Oe(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")}exports.CONTRACT_ERRORS=C;exports.PeginManager=Jt;exports.computeWotsBlockPublicKeysHash=Re;exports.computeWotsPkHash=Wt;exports.deriveWotsBlockPublicKeys=Ae;exports.deriveWotsKeypair=Ot;exports.deriveWotsPkHash=$e;exports.extractErrorData=N;exports.getContractErrorMessage=Nt;exports.handleContractError=S;exports.isKnownContractError=Xt;exports.isWotsMismatchError=Oe;exports.keypairToPublicKey=Te;exports.mnemonicToWotsSeed=$t;
2
- //# sourceMappingURL=errors-B3DbZYLe.cjs.map
1
+ "use strict";var Vt=Object.defineProperty;var Ft=(e,t,n)=>t in e?Vt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var P=(e,t,n)=>Ft(e,typeof t!="symbol"?t+"":t,n);const M=require("bitcoinjs-lib"),ot=require("buffer"),B=require("viem"),Kt=require("./signing-DHSXjhLM.cjs"),ut=require("@babylonlabs-io/babylon-tbv-rust-wasm"),R=require("./challengeAssert-X7V3Ik_Q.cjs"),k=require("./bitcoin-CNnPFU6Y.cjs"),ht=require("./validation-u8W7Lp2x.cjs"),$=require("./psbtInputFields-tnAR8tG5.cjs"),ft=require("./fundPeginTransaction-DxNOeyNI.cjs"),wt=require("./index-CIuXb72l.cjs"),O=require("./types-xU3SBcpH.cjs"),u=require("./buildAndBroadcastRefund-Mr3ck5ek.cjs");function Dt(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Mt=Dt(M),C={"0x04aabf33":"Vault already exists: This Bitcoin transaction has already been registered. Please select different UTXOs or use a different amount to create a unique transaction.","0x4fec082d":"Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. This may be caused by incorrect vault participants or key configuration.","0x6cc363a5":"Invalid BTC proof of possession: The signature could not be verified. Please ensure you're signing with the correct Bitcoin wallet.","0x6c3f2bf6":"Invalid BTC public key: The Bitcoin public key format is invalid.","0x2c5211c6":"Invalid amount: The deposit amount is invalid or below the minimum required.","0x0405f772":"Application not registered: The application controller is not registered in the system.","0x24e165cc":"Invalid provider status: The vault provider is not in a valid state to accept deposits.","0xd92e233d":"Zero address: One of the required addresses is the zero address.","0x65aa7007":"BTC key mismatch: The Bitcoin public key does not match the expected key.","0x82b42900":"Unauthorized: You must be the depositor or vault provider to submit this transaction.","0x8baa579f":"Invalid signature: The BTC proof of possession signature could not be verified.","0x2f9d01e9":"Invalid BTC transaction: The Bitcoin transaction format is invalid.","0x5a3c6b3e":"Vault provider not registered: The selected vault provider is not registered.","0x979f4518":"Invalid pegin fee: The ETH fee sent does not match the required amount. This may indicate a fee rate change during the transaction.","0x5fad9694":"This pre-pegin output has already been used to activate another vault.","0x7ed061c9":"This pegin transaction has already been used to activate another vault."};function N(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.data=="string"&&t.data.startsWith("0x"))return t.data;if(typeof t.details=="string"&&t.details.startsWith("0x"))return t.details;let n=t.cause,s=0;const o=5;for(;n&&typeof n=="object"&&s<o;){const a=n;if(typeof a.data=="string"&&a.data.startsWith("0x"))return a.data;n=a.cause,s++}const i=(typeof t.message=="string"?t.message:"").match(/\b(0x[a-fA-F0-9]{8})\b/);if(i)return i[1]}function Nt(e){const t=N(e);if(t){const n=t.substring(0,10);return C[t]??C[n]}}function Xt(e){const t=N(e);if(t===void 0)return!1;const n=t.substring(0,10);return t in C||n in C}function S(e){console.error("[Contract Error] Raw error:",e);const t=N(e);if(console.error("[Contract Error] Extracted error data:",t),t){const s=t.substring(0,10),o=C[t]??C[s];if(o)throw console.error("[Contract Error] Known error:",o),new Error(o)}const n=(e==null?void 0:e.message)||"";if(n.includes("gas limit too high")||n.includes("21000000")||n.includes("Internal JSON-RPC error")){const s=t?` (error code: ${t})`:"";throw console.error("[Contract Error] Transaction rejected. Error code:",t,"Message:",n),new Error(`Transaction failed: The contract rejected this transaction${s}. Possible causes: (1) Vault already exists for this transaction, (2) Invalid signature, (3) Unauthorized caller. Please check your transaction parameters and try again.`)}throw e instanceof Error?(console.error("[Contract Error] Unhandled error:",e.message),e):new Error(`Contract call failed: ${String(e)}`)}const qt=0,jt=/^0x[0-9a-f]+$/i,Gt=/^[0-9a-f]+$/i,zt=/^[A-Za-z0-9+/]+={0,2}$/;function W(e){if(typeof e!="string"||e.length===0)throw new Error("BTC wallet returned empty public key");return k.processPublicKeyToXOnly(e).toLowerCase()}function Zt(e){if(typeof e!="string"||e.length===0)throw new Error("BTC wallet returned empty BIP-322 signature");if(e.startsWith("0x")||e.startsWith("0X")){if(!jt.test(e)||e.length<4||e.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return e.toLowerCase()}if(Gt.test(e)){if(e.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return`0x${e.toLowerCase()}`}if(!zt.test(e)||e.length%4!==0)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");const t=ot.Buffer.from(e,"base64");if(t.length===0||t.toString("base64")!==e)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");return`0x${t.toString("hex")}`}function Yt(e,t,n,s){const o=n==null?void 0:n[`${e}:${t}`];return o?Promise.resolve({txid:e,vout:t,value:o.value,scriptPubKey:o.scriptPubKey}):wt.getUtxoInfo(e,t,s)}const dt=12e4;class Jt{constructor(t){P(this,"config");this.config=t}async preparePegin(t){const n=await this.config.btcWallet.getPublicKeyHex(),s=W(n),o=k.stripHexPrefix(t.vaultProviderBtcPubkey),r=t.vaultKeeperBtcPubkeys.map(k.stripHexPrefix),i=t.universalChallengerBtcPubkeys.map(k.stripHexPrefix);if(t.hashlocks.length!==t.amounts.length)throw new Error(`hashlocks.length (${t.hashlocks.length}) must equal amounts.length (${t.amounts.length})`);if(t.hashlocks.length===0)throw new Error("hashlocks must contain at least one entry");const a=r.length,p={depositorPubkey:s,vaultProviderPubkey:o,vaultKeeperPubkeys:r,universalChallengerPubkeys:i,hashlocks:t.hashlocks,timelockRefund:t.timelockRefund,pegInAmounts:t.amounts,feeRate:t.protocolFeeRate,numLocalChallengers:a,councilQuorum:t.councilQuorum,councilSize:t.councilSize,network:this.config.btcNetwork},h=await R.buildPrePeginPsbt(p),c=$.selectUtxosForPegin([...t.availableUTXOs],h.totalOutputValue,t.mempoolFeeRate,ft.peginOutputCount(h.htlcValues.length)),y=k.getNetwork(this.config.btcNetwork),l=ft.fundPeginTransaction({unfundedTxHex:h.psbtHex,selectedUTXOs:c.selectedUTXOs,changeAddress:t.changeAddress,changeAmount:c.changeAmount,network:y}),x=k.stripHexPrefix($.calculateBtcTxHash(l)),g=[],w=[],T=[];for(let m=0;m<t.hashlocks.length;m++){const b=await R.buildPeginTxFromFundedPrePegin({prePeginParams:p,timelockPegin:t.timelockPegin,fundedPrePeginTxHex:l,htlcVout:m}),I=await R.buildPeginInputPsbt({peginTxHex:b.txHex,fundedPrePeginTxHex:l,depositorPubkey:s,vaultProviderPubkey:o,vaultKeeperPubkeys:r,universalChallengerPubkeys:i,hashlock:t.hashlocks[m],timelockRefund:t.timelockRefund,network:this.config.btcNetwork});g.push(b),w.push(I.psbtHex),T.push(Kt.createTaprootScriptPathSignOptions(n,1))}const d=await this.signPsbtsWithFallback(w,T),f=[];for(let m=0;m<d.length;m++){const b=R.extractPeginInputSignature(d[m],s),I=R.finalizePeginInputPsbt(d[m]);f.push({htlcVout:m,htlcValue:h.htlcValues[m],peginTxHex:I,peginTxid:g[m].txid,peginInputSignature:b,vaultScriptPubKey:g[m].vaultScriptPubKey})}return{fundedPrePeginTxHex:l,prePeginTxid:x,perVault:f,selectedUTXOs:c.selectedUTXOs,fee:c.fee,changeAmount:c.changeAmount}}async signPsbtsWithFallback(t,n){if(typeof this.config.btcWallet.signPsbts=="function"){const o=await this.config.btcWallet.signPsbts(t,n);if(o.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${o.length}`);return o}const s=[];for(let o=0;o<t.length;o++){const r=await this.config.btcWallet.signPsbt(t[o],n[o]);s.push(r)}return s}async signAndBroadcast(t){const{fundedPrePeginTxHex:n,depositorBtcPubkey:s}=t,o=n.startsWith("0x")?n.slice(2):n,r=M.Transaction.fromHex(o);if(r.ins.length===0)throw new Error("Transaction has no inputs");const i=new M.Psbt;i.setVersion(r.version),i.setLocktime(r.locktime);const a=ot.Buffer.from(W(s),"hex"),p=this.config.mempoolApiUrl,h=r.ins.map(f=>{const m=ot.Buffer.from(f.hash).reverse().toString("hex"),b=f.index;return Yt(m,b,t.localPrevouts,p).then(I=>({input:f,utxoData:I,txid:m,vout:b}))}),c=await Promise.all(h),y=c.reduce((f,m)=>f+BigInt(m.utxoData.value),0n),l=r.outs.reduce((f,m)=>f+BigInt(m.value),0n);if(y<l)throw new Error(`UTXO value mismatch: total input value (${y} sat) is less than total output value (${l} sat). This may indicate the mempool API returned manipulated UTXO data.`);const x=y-l;if(x>ht.MAX_REASONABLE_FEE_SATS)throw new Error(`Implied transaction fee (${x} sat) exceeds maximum reasonable fee (${ht.MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`);for(const{input:f,utxoData:m,txid:b,vout:I}of c){const E=$.getPsbtInputFields({value:m.value,scriptPubKey:m.scriptPubKey},a);i.addInput({hash:f.hash,index:f.index,sequence:f.sequence,...E})}for(const f of r.outs)i.addOutput({script:f.script,value:f.value});const g=await this.config.btcWallet.signPsbt(i.toHex()),w=M.Psbt.fromHex(g);try{w.finalizeAllInputs()}catch(f){if(!w.data.inputs.every(b=>b.finalScriptWitness||b.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${f}`)}const T=w.extractTransaction().toHex();return await wt.pushTx(T,p)}async registerPeginOnChain(t){const{unsignedPrePeginTx:n,depositorSignedPeginTx:s,vaultProvider:o,hashlock:r,htlcVout:i,depositorPayoutBtcAddress:a,depositorWotsPkHash:p,popSignature:h}=t;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const c=this.config.ethWallet.account.address;if(!B.isAddressEqual(h.depositorEthAddress,c))throw new Error(`Proof of possession was signed for ${h.depositorEthAddress} but the Ethereum wallet is currently connected to ${c}. Reconnect the original account or call signProofOfPossession() again.`);await this.assertPopMatchesBtcWallet(h);const y=h.btcPopSignature,l=k.ensureHexPrefix(h.depositorBtcPubkey),x=k.ensureHexPrefix(n),g=k.ensureHexPrefix(s),w=await this.resolvePayoutScriptPubKey(a),T=$.calculateBtcTxHash(g),d=await ut.deriveVaultId(k.stripHexPrefix(T),k.stripHexPrefix(c)),f=k.ensureHexPrefix(d);if(await this.checkVaultExists(f))throw new Error(`Vault already exists (ID: ${f}, peginTxHash: ${T}). 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.`);const b=B.createPublicClient({chain:this.config.ethChain,transport:B.http()});let I;try{I=await b.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})}catch{throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.")}const E=B.encodeFunctionData({abi:O.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[c,l,y,x,g,o,r,i,w,p]});let v;try{v=await b.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:E,value:I,account:this.config.ethWallet.account.address})}catch(q){S(q)}let _;try{_=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:E,value:I,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:v})}catch(q){S(q)}const A=await b.waitForTransactionReceipt({hash:_,timeout:dt});return A.status==="reverted"&&S(new Error(`Transaction reverted. Hash: ${_}. Check the transaction on block explorer for details.`)),{ethTxHash:A.transactionHash,vaultId:f,peginTxHash:T}}async registerPeginBatchOnChain(t){const{vaultProvider:n,unsignedPrePeginTx:s,requests:o,popSignature:r}=t;if(o.length===0)throw new Error("Batch pegin requires at least one request");if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const i=this.config.ethWallet.account.address;if(!B.isAddressEqual(r.depositorEthAddress,i))throw new Error(`Proof of possession was signed for ${r.depositorEthAddress} but the Ethereum wallet is currently connected to ${i}. Reconnect the original account or call signProofOfPossession() again.`);await this.assertPopMatchesBtcWallet(r);const a=r.btcPopSignature,p=[];for(const b of o)p.push(await this.resolvePayoutScriptPubKey(b.depositorPayoutBtcAddress));const h=[];for(const b of o){const I=k.ensureHexPrefix(b.depositorSignedPeginTx),E=$.calculateBtcTxHash(I),v=await ut.deriveVaultId(k.stripHexPrefix(E),k.stripHexPrefix(i)),_=k.ensureHexPrefix(v);if(await this.checkVaultExists(_))throw new Error(`Vault already exists (ID: ${_}, peginTxHash: ${E}). To create a new vault, use different UTXOs or a different amount.`);h.push({vaultId:_,peginTxHash:E})}const c=B.createPublicClient({chain:this.config.ethChain,transport:B.http()});let y;try{y=await c.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getPegInFee",args:[n]})}catch{throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.")}const l=y*BigInt(o.length),x=k.ensureHexPrefix(r.depositorBtcPubkey),g=k.ensureHexPrefix(s),w=o.map((b,I)=>({depositorBtcPubKey:x,btcPopSignature:a,unsignedPrePeginTx:g,depositorSignedPeginTx:k.ensureHexPrefix(b.depositorSignedPeginTx),hashlock:b.hashlock,htlcVout:b.htlcVout,referralCode:qt,depositorPayoutBtcAddress:p[I],depositorWotsPkHash:b.depositorWotsPkHash})),T=B.encodeFunctionData({abi:O.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[i,n,w]});let d;try{d=await c.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:T,value:l,account:this.config.ethWallet.account.address})}catch(b){S(b)}let f;try{f=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:T,value:l,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:d})}catch(b){S(b)}const m=await c.waitForTransactionReceipt({hash:f,timeout:dt});return m.status==="reverted"&&S(new Error(`Batch transaction reverted. Hash: ${f}. Check the transaction on block explorer for details.`)),{ethTxHash:m.transactionHash,vaults:h}}async checkVaultExists(t){try{return(await B.createPublicClient({chain:this.config.ethChain,transport:B.http()}).readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]}))[0]!==B.zeroAddress}catch{return!1}}async resolvePayoutScriptPubKey(t){let n;if(t)n=t;else{n=await this.config.btcWallet.getAddress();const o=await this.config.btcWallet.getPublicKeyHex();if(!k.isAddressFromPublicKey(n,o,this.config.btcNetwork))throw new Error("The BTC address from your wallet does not match the wallet's public key. Please ensure your wallet is using a supported address type (Taproot or Native SegWit).")}const s=k.getNetwork(this.config.btcNetwork);try{return`0x${Mt.address.toOutputScript(n,s).toString("hex")}`}catch{throw new Error(`Invalid BTC payout address: "${n}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`)}}async signProofOfPossession(){if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const t=this.config.ethWallet.account.address,n=W(await this.config.btcWallet.getPublicKeyHex()),s=this.config.vaultContracts.btcVaultRegistry,o=`${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${s.toLowerCase()}`,r=await this.config.btcWallet.signMessage(o,"bip322-simple");return{btcPopSignature:Zt(r),depositorEthAddress:t,depositorBtcPubkey:n}}async assertPopMatchesBtcWallet(t){const n=W(await this.config.btcWallet.getPublicKeyHex()),s=W(t.depositorBtcPubkey);if(n!==s)throw new Error(`Proof of possession was signed with BTC pubkey ${s} but the BTC wallet is currently connected to ${n}. Reconnect the original wallet or call signProofOfPossession() again.`)}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}class Pt{constructor(t,n){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(u.ahash(t),u.abytes(n,void 0,"key"),this.iHash=t.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 s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?t.create().update(n).digest():n);for(let r=0;r<o.length;r++)o[r]^=54;this.iHash.update(o),this.oHash=t.create();for(let r=0;r<o.length;r++)o[r]^=106;this.oHash.update(o),u.clean(o)}update(t){return u.aexists(this),this.iHash.update(t),this}digestInto(t){u.aexists(this),u.abytes(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:s,finished:o,destroyed:r,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=r,t.blockLen=i,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=s._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const X=(e,t,n)=>new Pt(e,t).update(n).digest();X.create=(e,t)=>new Pt(e,t);const Qt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),kt=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),te=kt.map(e=>(9*e+5)%16),Tt=(()=>{const n=[[kt],[te]];for(let s=0;s<4;s++)for(let o of n)o.push(o[s].map(r=>Qt[r]));return n})(),Et=Tt[0],It=Tt[1],Ht=[[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(e=>Uint8Array.from(e)),ee=Et.map((e,t)=>e.map(n=>Ht[t][n])),ne=It.map((e,t)=>e.map(n=>Ht[t][n])),se=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),oe=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function gt(e,t,n,s){return e===0?t^n^s:e===1?t&n|~t&s:e===2?(t|~n)^s:e===3?t&s|n&~s:t^(n|~s)}const V=new Uint32Array(16);class re extends u.HashMD{constructor(){super(64,20,8,!0);P(this,"h0",1732584193);P(this,"h1",-271733879);P(this,"h2",-1732584194);P(this,"h3",271733878);P(this,"h4",-1009589776)}get(){const{h0:n,h1:s,h2:o,h3:r,h4:i}=this;return[n,s,o,r,i]}set(n,s,o,r,i){this.h0=n|0,this.h1=s|0,this.h2=o|0,this.h3=r|0,this.h4=i|0}process(n,s){for(let g=0;g<16;g++,s+=4)V[g]=n.getUint32(s,!0);let o=this.h0|0,r=o,i=this.h1|0,a=i,p=this.h2|0,h=p,c=this.h3|0,y=c,l=this.h4|0,x=l;for(let g=0;g<5;g++){const w=4-g,T=se[g],d=oe[g],f=Et[g],m=It[g],b=ee[g],I=ne[g];for(let E=0;E<16;E++){const v=u.rotl(o+gt(g,i,p,c)+V[f[E]]+T,b[E])+l|0;o=l,l=c,c=u.rotl(p,10)|0,p=i,i=v}for(let E=0;E<16;E++){const v=u.rotl(r+gt(w,a,h,y)+V[m[E]]+d,I[E])+x|0;r=x,x=y,y=u.rotl(h,10)|0,h=a,a=v}}this.set(this.h1+p+y|0,this.h2+c+x|0,this.h3+l+r|0,this.h4+o+a|0,this.h0+i+h|0)}roundClean(){u.clean(V)}destroy(){this.destroyed=!0,u.clean(this.buffer),this.set(0,0,0,0,0)}}const vt=u.createHasher(()=>new re),ie=BigInt(0),U=BigInt(1),ae=BigInt(2),ce=BigInt(7),le=BigInt(256),ue=BigInt(113),Bt=[],_t=[],St=[];for(let e=0,t=U,n=1,s=0;e<24;e++){[n,s]=[s,(2*n+3*s)%5],Bt.push(2*(5*s+n)),_t.push((e+1)*(e+2)/2%64);let o=ie;for(let r=0;r<7;r++)t=(t<<U^(t>>ce)*ue)%le,t&ae&&(o^=U<<(U<<BigInt(r))-U);St.push(o)}const Ct=u.split(St,!0),he=Ct[0],fe=Ct[1],pt=(e,t,n)=>n>32?u.rotlBH(e,t,n):u.rotlSH(e,t,n),mt=(e,t,n)=>n>32?u.rotlBL(e,t,n):u.rotlSL(e,t,n);function de(e,t=24){const n=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,p=(i+2)%10,h=n[p],c=n[p+1],y=pt(h,c,1)^n[a],l=mt(h,c,1)^n[a+1];for(let x=0;x<50;x+=10)e[i+x]^=y,e[i+x+1]^=l}let o=e[2],r=e[3];for(let i=0;i<24;i++){const a=_t[i],p=pt(o,r,a),h=mt(o,r,a),c=Bt[i];o=e[c],r=e[c+1],e[c]=p,e[c+1]=h}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)n[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~n[(a+2)%10]&n[(a+4)%10]}e[0]^=he[s],e[1]^=fe[s]}u.clean(n)}class ct{constructor(t,n,s,o=!1,r=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=t,this.suffix=n,this.outputLen=s,this.enableXOF=o,this.rounds=r,u.anumber(s,"outputLen"),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=u.u32(this.state)}clone(){return this._cloneInto()}keccak(){u.swap32IfBE(this.state32),de(this.state32,this.rounds),u.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(t){u.aexists(this),u.abytes(t);const{blockLen:n,state:s}=this,o=t.length;for(let r=0;r<o;){const i=Math.min(n-this.pos,o-r);for(let a=0;a<i;a++)s[this.pos++]^=t[r++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:n,pos:s,blockLen:o}=this;t[s]^=n,(n&128)!==0&&s===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){u.aexists(this,!1),u.abytes(t),this.finish();const n=this.state,{blockLen:s}=this;for(let o=0,r=t.length;o<r;){this.posOut>=s&&this.keccak();const i=Math.min(s-this.posOut,r-o);t.set(n.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return u.anumber(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(u.aoutput(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,u.clean(this.state)}_cloneInto(t){const{blockLen:n,suffix:s,outputLen:o,rounds:r,enableXOF:i}=this;return t||(t=new ct(n,s,o,i,r)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=r,t.suffix=s,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}}const ge=(e,t,n,s={})=>u.createHasher(()=>new ct(t,e,n),s),At=ge(1,136,32);function pe(e,t,n,s){u.ahash(e);const o=u.checkOpts({dkLen:32,asyncTick:10},s),{c:r,dkLen:i,asyncTick:a}=o;if(u.anumber(r,"c"),u.anumber(i,"dkLen"),u.anumber(a,"asyncTick"),r<1)throw new Error("iterations (c) must be >= 1");const p=u.kdfInputToBytes(t,"password"),h=u.kdfInputToBytes(n,"salt"),c=new Uint8Array(i),y=X.create(e,p),l=y._cloneInto().update(h);return{c:r,dkLen:i,asyncTick:a,DK:c,PRF:y,PRFSalt:l}}function me(e,t,n,s,o){return e.destroy(),t.destroy(),s&&s.destroy(),u.clean(o),n}function ye(e,t,n,s){const{c:o,dkLen:r,DK:i,PRF:a,PRFSalt:p}=pe(e,t,n,s);let h;const c=new Uint8Array(4),y=u.createView(c),l=new Uint8Array(a.outputLen);for(let x=1,g=0;g<r;x++,g+=a.outputLen){const w=i.subarray(g,g+a.outputLen);y.setInt32(0,x,!1),(h=p._cloneInto(h)).update(c).digestInto(l),w.set(l.subarray(0,w.length));for(let T=1;T<o;T++){a._cloneInto(h).update(l).digestInto(l);for(let d=0;d<w.length;d++)w[d]^=l[d]}}return me(a,p,i,h,l)}function Rt(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function be(e){const t=Rt(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}const xe=e=>Rt("mnemonic"+e);function we(e,t=""){return ye(u.sha512,be(e).nfkd,xe(t),{c:2048,dkLen:64})}const Pe=508,yt=16,F=32,K=64,bt=5,ke=4;function L(...e){const t=e.reduce((o,r)=>o+r.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;return n}function j(e){return new TextEncoder().encode(e)}function G(e){const t=new Uint8Array(ke);return new DataView(t.buffer).setUint32(0,e.length,!1),L(t,e)}function z(e,t){return X(u.sha512,e,t)}function xt(e){return vt(u.sha256(e))}const rt=e=>Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");function $t(e){const t=we(e),n=new Uint8Array(t);return t.fill(0),n}async function Ot(e,t,n,s){if(e.length!==K)throw new Error(`WOTS seed must be ${K} bytes, got ${e.length}`);t=k.stripHexPrefix(t),n=k.stripHexPrefix(n);const o=e.slice(F,K),r=e.slice(0,F),i=[o,r];try{const a=L(G(j(t)),G(j(n)),G(j(s))),p=L(r,a);i.push(p);const h=z(o,p);i.push(h);const c=h.slice(0,F),y=h.slice(F,K);i.push(c,y);const l=[],x=[],g=[],w=[];let T=!1;try{for(let d=0;d<Pe;d++){const f=new Uint8Array(bt);f[0]=0,new DataView(f.buffer).setUint32(1,d,!1);const m=new Uint8Array(bt);m[0]=1,new DataView(m.buffer).setUint32(1,d,!1);const b=L(c,f),I=L(c,m),E=z(y,b),v=z(y,I);try{const _=E.slice(0,yt),A=v.slice(0,yt);l.push(_),x.push(A),g.push(xt(_)),w.push(xt(A))}finally{b.fill(0),I.fill(0),E.fill(0),v.fill(0)}}return T=!0,{falsePreimages:l,truePreimages:x,falseHashes:g,trueHashes:w}}finally{if(!T){for(const d of l)d.fill(0);for(const d of x)d.fill(0)}}}finally{for(const a of i)a.fill(0)}}function Te(e){return{false_list:e.falseHashes.map(rt),true_list:e.trueHashes.map(rt)}}function Wt(e){if(e.falseHashes.length===0||e.trueHashes.length===0)throw new Error("computeWotsPkHash: keypair hash arrays must not be empty");const t=e.falseHashes[0].length,n=(e.falseHashes.length+e.trueHashes.length)*t,s=new Uint8Array(n);let o=0;for(const i of e.falseHashes)s.set(i,o),o+=t;for(const i of e.trueHashes)s.set(i,o),o+=t;const r=At(s);return`0x${rt(r)}`}const Z=32,Y=64,Ee=4,H=20,it=4,Ut=2,Ie=0,He=1,D=[64,64];function at(...e){const t=e.reduce((o,r)=>o+r.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;return n}function J(e){return new TextEncoder().encode(e)}function Q(e){const t=new Uint8Array(Ee);return new DataView(t.buffer).setUint32(0,e.length,!1),at(t,e)}function tt(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}const ve=e=>Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");function Be(e,t){return X(u.sha512,e,t)}function lt(e){return vt(u.sha256(e))}function Lt(e){return(1<<e)-1}function _e(e){let t=1;for(;t*t<e+1;)t++;return Math.max(t,2)}function Se(e){const t=it,n=Lt(t),s=e*n;return{d:t,n:e,checksum_radix:_e(s)}}function et(e,t){const n=[];let s=t;for(;s>0;)n.push(s&255),s>>>=8;const o=new Uint8Array(e.length+n.length);o.set(e);for(let r=0;r<n.length;r++)o[e.length+r]=n[r];return lt(o)}function nt(e,t){let n=e;for(let s=0;s<t;s++)n=lt(n);return n}function Ce(e,t){const n=Lt(t.d),s=t.checksum_radix-1,o=Math.floor(t.n*n/t.checksum_radix),r=[];for(let c=0;c<t.n;c++){const y=et(e,c+Ut),l=nt(y,n);r.push(Array.from(l))}const i=et(e,Ie),a=nt(i,s),p=et(e,He),h=nt(p,o);return{config:t,message_terminals:r,checksum_major_terminal:Array.from(h),checksum_minor_terminal:Array.from(a)}}async function Ae(e,t,n,s){if(e.length!==Y)throw new Error(`WOTS seed must be exactly ${Y} bytes, got ${e.length}`);const o=tt(t),r=tt(n),i=e.slice(Z,Y),a=e.slice(0,Z),p=at(a,at(Q(J(o)),Q(J(r)),Q(J(tt(s))))),h=Be(i,p),c=h.slice(0,Z);try{const y=[];for(let l=0;l<D.length;l++){const x=D[l],g=Se(x),w=new Uint8Array(c.length+1);w.set(c),w[c.length]=l;const T=lt(w);try{const d=Ce(T,g);if(d.config.d!==it)throw new Error(`Block ${l}: expected d=${it}, got d=${d.config.d}`);if(d.config.n!==x)throw new Error(`Block ${l}: expected n=${x}, got n=${d.config.n}`);if(d.message_terminals.length!==x)throw new Error(`Block ${l}: expected ${x} message terminals, got ${d.message_terminals.length}`);for(let f=0;f<d.message_terminals.length;f++)if(d.message_terminals[f].length!==H)throw new Error(`Block ${l} terminal ${f}: expected ${H} bytes, got ${d.message_terminals[f].length}`);if(d.checksum_minor_terminal.length!==H)throw new Error(`Block ${l} checksum_minor: expected ${H} bytes`);if(d.checksum_major_terminal.length!==H)throw new Error(`Block ${l} checksum_major: expected ${H} bytes`);y.push(d)}finally{w.fill(0),T.fill(0)}}if(y.length!==D.length)throw new Error(`Expected ${D.length} blocks, got ${y.length}`);return y}finally{p.fill(0),i.fill(0),a.fill(0),h.fill(0),c.fill(0),e.fill(0)}}function st(e,t,n){if(e.length!==H)throw new Error(`Block ${t} ${n}: expected ${H} bytes, got ${e.length}`);for(let s=0;s<e.length;s++){const o=e[s];if(!Number.isInteger(o)||o<0||o>255)throw new Error(`Block ${t} ${n}[${s}]: invalid byte value ${o}`)}}function Re(e){if(e.length===0)throw new Error("Public keys array must not be empty");for(let r=0;r<e.length;r++){const i=e[r];st(i.checksum_minor_terminal,r,"checksum_minor_terminal"),st(i.checksum_major_terminal,r,"checksum_major_terminal");for(let a=0;a<i.message_terminals.length;a++)st(i.message_terminals[a],r,`message_terminal[${a}]`)}let t=0;for(const r of e)t+=Ut+r.message_terminals.length;const n=new Uint8Array(t*H);let s=0;for(const r of e){n.set(r.checksum_minor_terminal,s),s+=H,n.set(r.checksum_major_terminal,s),s+=H;for(const i of r.message_terminals)n.set(i,s),s+=H}const o=At(n);return`0x${ve(o)}`}async function $e(e,t,n,s){const o=$t(e);try{const r=await Ot(o,t,n,s);try{return Wt(r)}finally{for(const i of r.falsePreimages)i.fill(0);for(const i of r.truePreimages)i.fill(0)}}finally{o.fill(0)}}function Oe(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")}exports.CONTRACT_ERRORS=C;exports.PeginManager=Jt;exports.computeWotsBlockPublicKeysHash=Re;exports.computeWotsPkHash=Wt;exports.deriveWotsBlockPublicKeys=Ae;exports.deriveWotsKeypair=Ot;exports.deriveWotsPkHash=$e;exports.extractErrorData=N;exports.getContractErrorMessage=Nt;exports.handleContractError=S;exports.isKnownContractError=Xt;exports.isWotsMismatchError=Oe;exports.keypairToPublicKey=Te;exports.mnemonicToWotsSeed=$t;
2
+ //# sourceMappingURL=errors-BqKsTgDW.cjs.map