@babylonlabs-io/ts-sdk 0.16.0 → 0.16.2

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 (31) hide show
  1. package/README.md +17 -3
  2. package/dist/challengeAssert-CTajvPAY.cjs +2 -0
  3. package/dist/challengeAssert-CTajvPAY.cjs.map +1 -0
  4. package/dist/{challengeAssert-C5DQSUnp.js → challengeAssert-DtrQLG0c.js} +164 -161
  5. package/dist/challengeAssert-DtrQLG0c.js.map +1 -0
  6. package/dist/{errors-BEUjAw2k.js → errors-BeFfs5_J.js} +370 -369
  7. package/dist/errors-BeFfs5_J.js.map +1 -0
  8. package/dist/errors-CAFiRPYI.cjs +2 -0
  9. package/dist/errors-CAFiRPYI.cjs.map +1 -0
  10. package/dist/index.cjs +1 -1
  11. package/dist/index.js +2 -2
  12. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts.map +1 -1
  13. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +29 -74
  14. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  15. package/dist/tbv/core/index.cjs +1 -1
  16. package/dist/tbv/core/index.js +2 -2
  17. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  18. package/dist/tbv/core/primitives/index.cjs +1 -1
  19. package/dist/tbv/core/primitives/index.js +1 -1
  20. package/dist/tbv/core/primitives/utils/bitcoin.d.ts +0 -11
  21. package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
  22. package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts.map +1 -1
  23. package/dist/tbv/index.cjs +1 -1
  24. package/dist/tbv/index.js +2 -2
  25. package/package.json +3 -3
  26. package/dist/challengeAssert-C5DQSUnp.js.map +0 -1
  27. package/dist/challengeAssert-D7SqsNpQ.cjs +0 -2
  28. package/dist/challengeAssert-D7SqsNpQ.cjs.map +0 -1
  29. package/dist/errors-BEUjAw2k.js.map +0 -1
  30. package/dist/errors-DnMc1lLU.cjs +0 -2
  31. package/dist/errors-DnMc1lLU.cjs.map +0 -1
@@ -1,2 +0,0 @@
1
- "use strict";var he=Object.defineProperty;var fe=(e,t,n)=>t in e?he(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var p=(e,t,n)=>fe(e,typeof t!="symbol"?t+"":t,n);const V=require("bitcoinjs-lib"),D=require("buffer"),C=require("viem"),y=require("./challengeAssert-D7SqsNpQ.cjs"),mt=require("@babylonlabs-io/babylon-tbv-rust-wasm");function de(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 pe=de(V);function Ot(e,t,n,s){if(!Number.isInteger(s)||s<1)throw new Error(`Invalid numOutputs: expected a positive integer, got ${s}`);if(e.length===0)throw new Error("Insufficient funds: no UTXOs available");const r=e.filter(l=>{const h=D.Buffer.from(l.scriptPubKey,"hex");return!!V.script.decompile(h)});if(r.length===0)throw new Error("Insufficient funds: no valid UTXOs available (all have invalid scripts)");const o=[...r].sort((l,h)=>h.value-l.value),i=[];let a=0n,c=0n;for(const l of o){i.push(l),a+=BigInt(l.value);const h=i.length*y.P2TR_INPUT_SIZE,u=s*y.MAX_NON_LEGACY_OUTPUT_SIZE,f=h+u+y.TX_BUFFER_SIZE_OVERHEAD;if(c=BigInt(Math.ceil(f*n))+BigInt(y.rateBasedTxBufferFee(n)),a-t-c>y.DUST_THRESHOLD){const g=BigInt(Math.ceil(y.MAX_NON_LEGACY_OUTPUT_SIZE*n));c+=g}if(a>=t+c){const g=a-t-c;return{selectedUTXOs:i,totalValue:a,fee:c,changeAmount:g}}}throw new Error(`Insufficient funds: need ${t+c} sats (${t} pegin + ${c} fee), have ${a} sats`)}function ge(e){return e>y.DUST_THRESHOLD}function be(){return y.BTC_DUST_SAT}function it(e){const t=e.startsWith("0x")?e.slice(2):e;return`0x${V.Transaction.fromHex(t).getId()}`}var Y=(e=>(e.P2PKH="P2PKH",e.P2SH="P2SH",e.P2WPKH="P2WPKH",e.P2WSH="P2WSH",e.P2TR="P2TR",e.UNKNOWN="UNKNOWN",e))(Y||{});function _t(e){const t=e.length;return t===25&&e[0]===118&&e[1]===169&&e[2]===20&&e[23]===136&&e[24]===172?"P2PKH":t===23&&e[0]===169&&e[1]===20&&e[22]===135?"P2SH":t===22&&e[0]===0&&e[1]===20?"P2WPKH":t===34&&e[0]===0&&e[1]===32?"P2WSH":t===34&&e[0]===81&&e[1]===32?"P2TR":"UNKNOWN"}function $t(e,t){const n=D.Buffer.from(e.scriptPubKey,"hex"),s=_t(n);switch(s){case Y.P2WPKH:return{witnessUtxo:{script:n,value:e.value}};case Y.P2WSH:{if(!e.witnessScript)throw new Error("Missing witnessScript for P2WSH input");return{witnessUtxo:{script:n,value:e.value},witnessScript:D.Buffer.from(e.witnessScript,"hex")}}case Y.P2TR:{if(t&&t.length!==32)throw new Error(`Invalid tapInternalKey length: expected 32 bytes, got ${t.length}`);return{witnessUtxo:{script:n,value:e.value},...t&&{tapInternalKey:t}}}default:throw new Error(`Unsupported script type: ${s}`)}}function ct(e,t){if(!Number.isInteger(t)||t<1)throw new Error(`inputCount must be a positive integer, got ${t}`);return{autoFinalized:!1,signInputs:Array.from({length:t},(n,s)=>({index:s,publicKey:e,disableTweakSigner:!0}))}}const ye=21e6*1e8,Lt=1e4;function Rt(e){return Number.isInteger(e)&&e>0&&e<=ye}function xe(e){return Number.isInteger(e)&&e>0&&e<=Lt}function Wt(e,t){return!Number.isInteger(e)||e<0?!1:t===void 0||e<t}const Vt={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function ut(e,t){try{const n=await fetch(e,t);if(!n.ok){const r=await n.text();throw new Error(`Mempool API error (${n.status}): ${r||n.statusText}`)}const s=n.headers.get("content-type");return s!=null&&s.includes("application/json")?await n.json():await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to fetch from mempool API: ${n.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function Dt(e,t){try{const n=await fetch(`${t}/tx`,{method:"POST",body:e,headers:{"Content-Type":"text/plain"}});if(!n.ok){const r=await n.text();let o;try{o=JSON.parse(r).message}catch{o=r}throw new Error(o||`Failed to broadcast transaction: ${n.statusText}`)}return await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to broadcast BTC transaction: ${n.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function Kt(e,t){return ut(`${t}/tx/${e}`)}async function we(e,t){try{const n=await fetch(`${t}/tx/${e}/hex`);if(!n.ok){const s=await n.text();throw new Error(`Mempool API error (${n.status}): ${s||n.statusText}`)}return await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to get transaction hex for ${e}: ${n.message}`):new Error(`Failed to get transaction hex for ${e}: Unknown error`)}}async function Mt(e,t,n){const s=await Kt(e,n);if(!Wt(t,s.vout.length))throw new Error(`Invalid vout ${t} for transaction ${e} (has ${s.vout.length} outputs)`);const r=s.vout[t];if(!Rt(r.value))throw new Error(`Invalid UTXO value ${r.value} for ${e}:${t}`);return{txid:e,vout:t,value:r.value,scriptPubKey:r.scriptpubkey}}async function Pe(e,t){try{const n=await ut(`${t}/address/${e}/utxo`),s=await ut(`${t}/v1/validate-address/${e}`);if(!s.isvalid)throw new Error(`Invalid Bitcoin address: ${e}. Mempool API validation failed.`);for(const o of n){if(!Wt(o.vout))throw new Error(`Invalid vout ${o.vout} for ${o.txid}`);if(!Rt(o.value))throw new Error(`Invalid UTXO value ${o.value} for ${o.txid}:${o.vout}`)}return n.sort((o,i)=>i.value-o.value).map(o=>({txid:o.txid,vout:o.vout,value:o.value,scriptPubKey:s.scriptPubKey,confirmed:o.status.confirmed}))}catch(n){throw n instanceof Error?new Error(`Failed to get UTXOs for address ${e}: ${n.message}`):new Error(`Failed to get UTXOs for address ${e}: Unknown error`)}}function me(e){return Vt[e]}async function Te(e,t){return ut(`${t}/address/${e}/txs`)}async function ve(e){const t=await fetch(`${e}/v1/fees/recommended`);if(!t.ok)throw new Error(`Failed to fetch network fees: ${t.status} ${t.statusText}`);const n=await t.json(),s=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const r of s)if(!xe(n[r]))throw new Error(`Invalid fee rate ${r}=${n[r]} from mempool API: expected a positive number ≤ ${Lt}`);if(n.minimumFee>n.economyFee||n.economyFee>n.hourFee||n.hourFee>n.halfHourFee||n.halfHourFee>n.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${n.minimumFee}) <= economyFee (${n.economyFee}) <= hourFee (${n.hourFee}) <= halfHourFee (${n.halfHourFee}) <= fastestFee (${n.fastestFee}).`);return n}const G=[{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequestBatch",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"requests",type:"tuple[]",internalType:"struct IBTCVaultRegistry.BatchPeginRequest[]",components:[{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}]}],outputs:[{name:"vaultIds",type:"bytes32[]",internalType:"bytes32[]"}],stateMutability:"payable"},{type:"function",name:"activateVaultWithSecret",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"},{name:"s",type:"bytes32",internalType:"bytes32"},{name:"activationMetadata",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"getPegInFee",inputs:[{name:"vaultProvider",type:"address",internalType:"address"}],outputs:[{name:"totalFee",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getBTCVault",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"vault",type:"tuple",internalType:"struct IBTCVaultRegistry.BTCVault",components:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"status",type:"uint8",internalType:"enum IBTCVaultRegistry.BTCVaultStatus"},{name:"applicationEntryPoint",type:"address",internalType:"address"},{name:"universalChallengersVersion",type:"uint16",internalType:"uint16"},{name:"appVaultKeepersVersion",type:"uint16",internalType:"uint16"},{name:"offchainParamsVersion",type:"uint16",internalType:"uint16"},{name:"createdAt",type:"uint256",internalType:"uint256"},{name:"verifiedAt",type:"uint256",internalType:"uint256"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPopSignature",type:"bytes",internalType:"bytes"},{name:"prePeginTxHash",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"error",name:"InvalidPeginFee",inputs:[{name:"provided",type:"uint256",internalType:"uint256"},{name:"required",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidSecret",inputs:[]},{type:"error",name:"ActivationDeadlineExpired",inputs:[]},{type:"error",name:"InvalidHashlock",inputs:[]},{type:"error",name:"DuplicateHashlock",inputs:[]},{type:"error",name:"CapExceeded",inputs:[]},{type:"error",name:"InvalidOutputIndex",inputs:[]},{type:"error",name:"PeginSignaturesIncomplete",inputs:[]}],M={"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."};function lt(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 r=5;for(;n&&typeof n=="object"&&s<r;){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 He(e){const t=lt(e);if(t){const n=t.substring(0,10);return M[t]??M[n]}}function ke(e){const t=lt(e);if(t===void 0)return!1;const n=t.substring(0,10);return t in M||n in M}function W(e){console.error("[Contract Error] Raw error:",e);const t=lt(e);if(console.error("[Contract Error] Extracted error data:",t),t){const s=t.substring(0,10),r=M[t]??M[s];if(r)throw console.error("[Contract Error] Known error:",r),new Error(r)}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 Ee=0;function Ie(e,t,n,s){const r=n==null?void 0:n[`${e}:${t}`];return r?Promise.resolve({txid:e,vout:t,value:r.value,scriptPubKey:r.scriptPubKey}):Mt(e,t,s)}const Tt=12e4;class Se{constructor(t){p(this,"config");this.config=t}async preparePegin(t){const n=await this.config.btcWallet.getPublicKeyHex(),s=n.length===66?n.slice(2):n,r=y.stripHexPrefix(t.vaultProviderBtcPubkey),o=t.vaultKeeperBtcPubkeys.map(y.stripHexPrefix),i=t.universalChallengerBtcPubkeys.map(y.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=o.length,c={depositorPubkey:s,vaultProviderPubkey:r,vaultKeeperPubkeys:o,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},l=await y.buildPrePeginPsbt(c),h=Ot([...t.availableUTXOs],l.totalOutputValue,t.mempoolFeeRate,y.peginOutputCount(l.htlcValues.length)),u=y.getNetwork(this.config.btcNetwork),f=y.fundPeginTransaction({unfundedTxHex:l.psbtHex,selectedUTXOs:h.selectedUTXOs,changeAddress:t.changeAddress,changeAmount:h.changeAmount,network:u}),x=y.stripHexPrefix(it(f)),g=[],w=[],T=[];for(let d=0;d<t.hashlocks.length;d++){const P=await y.buildPeginTxFromFundedPrePegin({prePeginParams:c,timelockPegin:t.timelockPegin,fundedPrePeginTxHex:f,htlcVout:d}),H=await y.buildPeginInputPsbt({peginTxHex:P.txHex,fundedPrePeginTxHex:f,depositorPubkey:s,vaultProviderPubkey:r,vaultKeeperPubkeys:o,universalChallengerPubkeys:i,hashlock:t.hashlocks[d],timelockRefund:t.timelockRefund,network:this.config.btcNetwork});g.push(P),w.push(H.psbtHex),T.push(ct(n,1))}const m=await this.signPsbtsWithFallback(w,T),b=[];for(let d=0;d<m.length;d++){const P=y.extractPeginInputSignature(m[d],s),H=y.finalizePeginInputPsbt(m[d]);b.push({htlcVout:d,htlcValue:l.htlcValues[d],peginTxHex:H,peginTxid:g[d].txid,peginInputSignature:P,vaultScriptPubKey:g[d].vaultScriptPubKey})}return{fundedPrePeginTxHex:f,prePeginTxid:x,unsignedPrePeginTxHex:l.psbtHex,perVault:b,selectedUTXOs:h.selectedUTXOs,fee:h.fee,changeAmount:h.changeAmount}}async signPsbtsWithFallback(t,n){if(typeof this.config.btcWallet.signPsbts=="function"){const r=await this.config.btcWallet.signPsbts(t,n);if(r.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${r.length}`);return r}const s=[];for(let r=0;r<t.length;r++){const o=await this.config.btcWallet.signPsbt(t[r],n[r]);s.push(o)}return s}async signAndBroadcast(t){const{fundedPrePeginTxHex:n,depositorBtcPubkey:s}=t,r=n.startsWith("0x")?n.slice(2):n,o=V.Transaction.fromHex(r);if(o.ins.length===0)throw new Error("Transaction has no inputs");const i=new V.Psbt;i.setVersion(o.version),i.setLocktime(o.locktime);const a=s.startsWith("0x")?s.slice(2):s;if(a.length!==64||!/^[0-9a-fA-F]+$/.test(a))throw new Error("Invalid depositorBtcPubkey: expected 64 hex characters (x-only pubkey)");const c=D.Buffer.from(a,"hex");if(c.length!==32)throw new Error(`Invalid depositorBtcPubkey length: expected 32 bytes, got ${c.length}`);const l=this.config.mempoolApiUrl,h=o.ins.map(b=>{const d=D.Buffer.from(b.hash).reverse().toString("hex"),P=b.index;return Ie(d,P,t.localPrevouts,l).then(H=>({input:b,utxoData:H,txid:d,vout:P}))}),u=await Promise.all(h),f=u.reduce((b,d)=>b+BigInt(d.utxoData.value),0n),x=o.outs.reduce((b,d)=>b+BigInt(d.value),0n);if(f<x)throw new Error(`UTXO value mismatch: total input value (${f} sat) is less than total output value (${x} sat). This may indicate the mempool API returned manipulated UTXO data.`);for(const{input:b,utxoData:d,txid:P,vout:H}of u){const v=$t({value:d.value,scriptPubKey:d.scriptPubKey},c);i.addInput({hash:b.hash,index:b.index,sequence:b.sequence,...v})}for(const b of o.outs)i.addOutput({script:b.script,value:b.value});const g=await this.config.btcWallet.signPsbt(i.toHex()),w=V.Psbt.fromHex(g);try{w.finalizeAllInputs()}catch(b){if(!w.data.inputs.every(P=>P.finalScriptWitness||P.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${b}`)}const T=w.extractTransaction().toHex();return await Dt(T,l)}async registerPeginOnChain(t){const{depositorBtcPubkey:n,unsignedPrePeginTx:s,depositorSignedPeginTx:r,vaultProvider:o,hashlock:i,htlcVout:a,onPopSigned:c,depositorPayoutBtcAddress:l,depositorWotsPkHash:h,preSignedBtcPopSignature:u}=t;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const f=this.config.ethWallet.account.address,x=await this.resolvePopSignature(f,u);c&&await c();const g=y.ensureHexPrefix(n),w=y.ensureHexPrefix(s),T=y.ensureHexPrefix(r),m=await this.resolvePayoutScriptPubKey(l),b=it(T),d=await mt.deriveVaultId(y.stripHexPrefix(b),y.stripHexPrefix(f)),P=y.ensureHexPrefix(d);if(await this.checkVaultExists(P))throw new Error(`Vault already exists (ID: ${P}, peginTxHash: ${b}). 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 v=C.createPublicClient({chain:this.config.ethChain,transport:C.http()});let E;try{E=await v.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:G,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 I=C.encodeFunctionData({abi:G,functionName:"submitPeginRequest",args:[f,g,x,w,T,o,i,a,m,h]});let S;try{S=await v.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:I,value:E,account:this.config.ethWallet.account.address})}catch(O){W(O)}let F;try{F=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:I,value:E,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:S})}catch(O){W(O)}const X=await v.waitForTransactionReceipt({hash:F,timeout:Tt});return X.status==="reverted"&&W(new Error(`Transaction reverted. Hash: ${F}. Check the transaction on block explorer for details.`)),{ethTxHash:X.transactionHash,vaultId:P,peginTxHash:b,btcPopSignature:x}}async registerPeginBatchOnChain(t){const{vaultProvider:n,requests:s,preSignedBtcPopSignature:r,onPopSigned:o}=t;if(s.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,a=await this.resolvePopSignature(i,r);o&&await o();const c=[];for(const b of s)c.push(await this.resolvePayoutScriptPubKey(b.depositorPayoutBtcAddress));const l=[];for(const b of s){const d=y.ensureHexPrefix(b.depositorSignedPeginTx),P=it(d),H=await mt.deriveVaultId(y.stripHexPrefix(P),y.stripHexPrefix(i)),v=y.ensureHexPrefix(H);if(await this.checkVaultExists(v))throw new Error(`Vault already exists (ID: ${v}, peginTxHash: ${P}). To create a new vault, use different UTXOs or a different amount.`);l.push({vaultId:v,peginTxHash:P})}const h=C.createPublicClient({chain:this.config.ethChain,transport:C.http()});let u;try{u=await h.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:G,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 f=u*BigInt(s.length),x=s.map((b,d)=>({depositorBtcPubKey:y.ensureHexPrefix(b.depositorBtcPubkey),btcPopSignature:a,unsignedPrePeginTx:y.ensureHexPrefix(b.unsignedPrePeginTx),depositorSignedPeginTx:y.ensureHexPrefix(b.depositorSignedPeginTx),hashlock:b.hashlock,htlcVout:b.htlcVout,referralCode:Ee,depositorPayoutBtcAddress:c[d],depositorWotsPkHash:b.depositorWotsPkHash})),g=C.encodeFunctionData({abi:G,functionName:"submitPeginRequestBatch",args:[i,n,x]});let w;try{w=await h.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:g,value:f,account:this.config.ethWallet.account.address})}catch(b){W(b)}let T;try{T=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:g,value:f,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:w})}catch(b){W(b)}const m=await h.waitForTransactionReceipt({hash:T,timeout:Tt});return m.status==="reverted"&&W(new Error(`Batch transaction reverted. Hash: ${T}. Check the transaction on block explorer for details.`)),{ethTxHash:m.transactionHash,vaults:l,btcPopSignature:a}}async checkVaultExists(t){try{return(await C.createPublicClient({chain:this.config.ethChain,transport:C.http()}).readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:G,functionName:"getBTCVault",args:[t]})).depositor!==C.zeroAddress}catch{return!1}}async resolvePayoutScriptPubKey(t){y.ensureEcc();let n;if(t)n=t;else{n=await this.config.btcWallet.getAddress();const r=await this.config.btcWallet.getPublicKeyHex();if(!y.isAddressFromPublicKey(n,r,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=y.getNetwork(this.config.btcNetwork);try{return`0x${pe.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 resolvePopSignature(t,n){if(n)return n;const s=this.config.vaultContracts.btcVaultRegistry,r=`${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${s.toLowerCase()}`,o=await this.config.btcWallet.signMessage(r,"bip322-simple");return o.startsWith("0x")?o:`0x${D.Buffer.from(o,"base64").toString("hex")}`}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}class Be{constructor(t){p(this,"config");this.config=t}async signPayoutTransaction(t){this.validatePayoutOutputs(t.payoutTxHex,t.registeredPayoutScriptPubKey);const n=await this.config.btcWallet.getPublicKeyHex(),{depositorPubkey:s}=y.validateWalletPubkey(n,t.depositorBtcPubkey),r=await y.buildPayoutPsbt({payoutTxHex:t.payoutTxHex,peginTxHex:t.peginTxHex,assertTxHex:t.assertTxHex,depositorBtcPubkey:s,vaultProviderBtcPubkey:t.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys,timelockPegin:t.timelockPegin,network:this.config.network}),o=await this.config.btcWallet.signPsbt(r.psbtHex,ct(n,1));return{signature:y.extractPayoutSignature(o,s),depositorBtcPubkey:s}}getNetwork(){return this.config.network}supportsBatchSigning(){return typeof this.config.btcWallet.signPsbts=="function"}async signPayoutTransactionsBatch(t){if(!this.supportsBatchSigning())throw new Error("Wallet does not support batch signing (signPsbts method not available)");const n=await this.config.btcWallet.getPublicKeyHex(),s=[],r=[],o=[];for(const c of t){this.validatePayoutOutputs(c.payoutTxHex,c.registeredPayoutScriptPubKey);const{depositorPubkey:l}=y.validateWalletPubkey(n,c.depositorBtcPubkey);o.push(l);const h=await y.buildPayoutPsbt({payoutTxHex:c.payoutTxHex,peginTxHex:c.peginTxHex,assertTxHex:c.assertTxHex,depositorBtcPubkey:l,vaultProviderBtcPubkey:c.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:c.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:c.universalChallengerBtcPubkeys,timelockPegin:c.timelockPegin,network:this.config.network});s.push(h.psbtHex),r.push(ct(n,1))}const i=await this.config.btcWallet.signPsbts(s,r);if(i.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${i.length}`);const a=[];for(let c=0;c<t.length;c++){const l=o[c],h=y.extractPayoutSignature(i[c],l);a.push({payoutSignature:h,depositorBtcPubkey:l})}return a}validatePayoutOutputs(t,n){if(!y.isValidHex(n))throw new Error("Invalid registeredPayoutScriptPubKey: not valid hex");const s=D.Buffer.from(y.stripHexPrefix(n),"hex"),r=V.Transaction.fromHex(y.stripHexPrefix(t));if(r.outs.length===0)throw new Error("Payout transaction has no outputs");if(!r.outs.reduce((i,a)=>a.value>i.value?a:i).script.equals(s))throw new Error("Payout transaction does not pay to the registered depositor payout address")}}function Ae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function K(e,t=""){if(!Number.isSafeInteger(e)||e<0){const n=t&&`"${t}" `;throw new Error(`${n}expected integer >= 0, got ${e}`)}}function N(e,t,n=""){const s=Ae(e),r=e==null?void 0:e.length,o=t!==void 0;if(!s||o&&r!==t){const i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=s?`length=${r}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function Nt(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");K(e.outputLen),K(e.blockLen)}function z(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Xt(e,t){N(e,void 0,"digestInto() output");const n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function Ce(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function B(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function at(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function A(e,t){return e<<32-t|e>>>t}function Q(e,t){return e<<t|e>>>32-t>>>0}const Ue=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Fe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Oe(e){for(let t=0;t<e.length;t++)e[t]=Fe(e[t]);return e}const vt=Ue?e=>e:Oe;function _e(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Ht(e,t=""){return typeof e=="string"?_e(e):N(e,void 0,t)}function $e(e,t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error("options must be object or undefined");return Object.assign(e,t)}function ht(e,t={}){const n=(r,o)=>e(o).update(r).digest(),s=e(void 0);return n.outputLen=s.outputLen,n.blockLen=s.blockLen,n.create=r=>e(r),Object.assign(n,t),Object.freeze(n)}const qt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});class jt{constructor(t,n){p(this,"oHash");p(this,"iHash");p(this,"blockLen");p(this,"outputLen");p(this,"finished",!1);p(this,"destroyed",!1);if(Nt(t),N(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,r=new Uint8Array(s);r.set(n.length>s?t.create().update(n).digest():n);for(let o=0;o<r.length;o++)r[o]^=54;this.iHash.update(r),this.oHash=t.create();for(let o=0;o<r.length;o++)r[o]^=106;this.oHash.update(r),B(r)}update(t){return z(this),this.iHash.update(t),this}digestInto(t){z(this),N(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:r,destroyed:o,blockLen:i,outputLen:a}=this;return t=t,t.finished=r,t.destroyed=o,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 yt=(e,t,n)=>new jt(e,t).update(n).digest();yt.create=(e,t)=>new jt(e,t);function Le(e,t,n){return e&t^~e&n}function Re(e,t,n){return e&t^e&n^t&n}class xt{constructor(t,n,s,r){p(this,"blockLen");p(this,"outputLen");p(this,"padOffset");p(this,"isLE");p(this,"buffer");p(this,"view");p(this,"finished",!1);p(this,"length",0);p(this,"pos",0);p(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=s,this.isLE=r,this.buffer=new Uint8Array(t),this.view=at(this.buffer)}update(t){z(this),N(t);const{view:n,buffer:s,blockLen:r}=this,o=t.length;for(let i=0;i<o;){const a=Math.min(r-this.pos,o-i);if(a===r){const c=at(t);for(;r<=o-i;i+=r)this.process(c,i);continue}s.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){z(this),Xt(t,this),this.finished=!0;const{buffer:n,view:s,blockLen:r,isLE:o}=this;let{pos:i}=this;n[i++]=128,B(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(s,0),i=0);for(let u=i;u<r;u++)n[u]=0;s.setBigUint64(r-8,BigInt(this.length*8),o),this.process(s,0);const a=at(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,h[u],o)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const s=t.slice(0,n);return this.destroy(),s}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:s,length:r,finished:o,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=o,t.length=r,t.pos=a,r%n&&t.buffer.set(s),t}clone(){return this._cloneInto()}}const _=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),k=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),We=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Gt=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Ve=Gt.map(e=>(9*e+5)%16),zt=(()=>{const n=[[Gt],[Ve]];for(let s=0;s<4;s++)for(let r of n)r.push(r[s].map(o=>We[o]));return n})(),Zt=zt[0],Jt=zt[1],Yt=[[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)),De=Zt.map((e,t)=>e.map(n=>Yt[t][n])),Ke=Jt.map((e,t)=>e.map(n=>Yt[t][n])),Me=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Ne=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function kt(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 tt=new Uint32Array(16);class Xe extends xt{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:r,h3:o,h4:i}=this;return[n,s,r,o,i]}set(n,s,r,o,i){this.h0=n|0,this.h1=s|0,this.h2=r|0,this.h3=o|0,this.h4=i|0}process(n,s){for(let g=0;g<16;g++,s+=4)tt[g]=n.getUint32(s,!0);let r=this.h0|0,o=r,i=this.h1|0,a=i,c=this.h2|0,l=c,h=this.h3|0,u=h,f=this.h4|0,x=f;for(let g=0;g<5;g++){const w=4-g,T=Me[g],m=Ne[g],b=Zt[g],d=Jt[g],P=De[g],H=Ke[g];for(let v=0;v<16;v++){const E=Q(r+kt(g,i,c,h)+tt[b[v]]+T,P[v])+f|0;r=f,f=h,h=Q(c,10)|0,c=i,i=E}for(let v=0;v<16;v++){const E=Q(o+kt(w,a,l,u)+tt[d[v]]+m,H[v])+x|0;o=x,x=u,u=Q(l,10)|0,l=a,a=E}}this.set(this.h1+c+u|0,this.h2+h+x|0,this.h3+f+o|0,this.h4+r+a|0,this.h0+i+l|0)}roundClean(){B(tt)}destroy(){this.destroyed=!0,B(this.buffer),this.set(0,0,0,0,0)}}const qe=ht(()=>new Xe),et=BigInt(2**32-1),Et=BigInt(32);function je(e,t=!1){return t?{h:Number(e&et),l:Number(e>>Et&et)}:{h:Number(e>>Et&et)|0,l:Number(e&et)|0}}function Qt(e,t=!1){const n=e.length;let s=new Uint32Array(n),r=new Uint32Array(n);for(let o=0;o<n;o++){const{h:i,l:a}=je(e[o],t);[s[o],r[o]]=[i,a]}return[s,r]}const It=(e,t,n)=>e>>>n,St=(e,t,n)=>e<<32-n|t>>>n,q=(e,t,n)=>e>>>n|t<<32-n,j=(e,t,n)=>e<<32-n|t>>>n,nt=(e,t,n)=>e<<64-n|t>>>n-32,st=(e,t,n)=>e>>>n-32|t<<64-n,Ge=(e,t,n)=>e<<n|t>>>32-n,ze=(e,t,n)=>t<<n|e>>>32-n,Ze=(e,t,n)=>t<<n-32|e>>>64-n,Je=(e,t,n)=>e<<n-32|t>>>64-n;function U(e,t,n,s){const r=(t>>>0)+(s>>>0);return{h:e+n+(r/2**32|0)|0,l:r|0}}const Ye=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Qe=(e,t,n,s)=>t+n+s+(e/2**32|0)|0,tn=(e,t,n,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),en=(e,t,n,s,r)=>t+n+s+r+(e/2**32|0)|0,nn=(e,t,n,s,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0)+(r>>>0),sn=(e,t,n,s,r,o)=>t+n+s+r+o+(e/2**32|0)|0,rn=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$=new Uint32Array(64);class on extends xt{constructor(t){super(64,t,8,!1)}get(){const{A:t,B:n,C:s,D:r,E:o,F:i,G:a,H:c}=this;return[t,n,s,r,o,i,a,c]}set(t,n,s,r,o,i,a,c){this.A=t|0,this.B=n|0,this.C=s|0,this.D=r|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)$[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const f=$[u-15],x=$[u-2],g=A(f,7)^A(f,18)^f>>>3,w=A(x,17)^A(x,19)^x>>>10;$[u]=w+$[u-7]+g+$[u-16]|0}let{A:s,B:r,C:o,D:i,E:a,F:c,G:l,H:h}=this;for(let u=0;u<64;u++){const f=A(a,6)^A(a,11)^A(a,25),x=h+f+Le(a,c,l)+rn[u]+$[u]|0,w=(A(s,2)^A(s,13)^A(s,22))+Re(s,r,o)|0;h=l,l=c,c=a,a=i+x|0,i=o,o=r,r=s,s=x+w|0}s=s+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(s,r,o,i,a,c,l,h)}roundClean(){B($)}destroy(){this.set(0,0,0,0,0,0,0,0),B(this.buffer)}}class an extends on{constructor(){super(32);p(this,"A",_[0]|0);p(this,"B",_[1]|0);p(this,"C",_[2]|0);p(this,"D",_[3]|0);p(this,"E",_[4]|0);p(this,"F",_[5]|0);p(this,"G",_[6]|0);p(this,"H",_[7]|0)}}const te=Qt(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),cn=te[0],un=te[1],L=new Uint32Array(80),R=new Uint32Array(80);class ln extends xt{constructor(t){super(128,t,16,!1)}get(){const{Ah:t,Al:n,Bh:s,Bl:r,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:h,Fh:u,Fl:f,Gh:x,Gl:g,Hh:w,Hl:T}=this;return[t,n,s,r,o,i,a,c,l,h,u,f,x,g,w,T]}set(t,n,s,r,o,i,a,c,l,h,u,f,x,g,w,T){this.Ah=t|0,this.Al=n|0,this.Bh=s|0,this.Bl=r|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=h|0,this.Fh=u|0,this.Fl=f|0,this.Gh=x|0,this.Gl=g|0,this.Hh=w|0,this.Hl=T|0}process(t,n){for(let d=0;d<16;d++,n+=4)L[d]=t.getUint32(n),R[d]=t.getUint32(n+=4);for(let d=16;d<80;d++){const P=L[d-15]|0,H=R[d-15]|0,v=q(P,H,1)^q(P,H,8)^It(P,H,7),E=j(P,H,1)^j(P,H,8)^St(P,H,7),I=L[d-2]|0,S=R[d-2]|0,F=q(I,S,19)^nt(I,S,61)^It(I,S,6),X=j(I,S,19)^st(I,S,61)^St(I,S,6),O=tn(E,X,R[d-7],R[d-16]),ft=en(O,v,F,L[d-7],L[d-16]);L[d]=ft|0,R[d]=O|0}let{Ah:s,Al:r,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:h,Eh:u,El:f,Fh:x,Fl:g,Gh:w,Gl:T,Hh:m,Hl:b}=this;for(let d=0;d<80;d++){const P=q(u,f,14)^q(u,f,18)^nt(u,f,41),H=j(u,f,14)^j(u,f,18)^st(u,f,41),v=u&x^~u&w,E=f&g^~f&T,I=nn(b,H,E,un[d],R[d]),S=sn(I,m,P,v,cn[d],L[d]),F=I|0,X=q(s,r,28)^nt(s,r,34)^nt(s,r,39),O=j(s,r,28)^st(s,r,34)^st(s,r,39),ft=s&o^s&a^o&a,le=r&i^r&c^i&c;m=w|0,b=T|0,w=x|0,T=g|0,x=u|0,g=f|0,{h:u,l:f}=U(l|0,h|0,S|0,F|0),l=a|0,h=c|0,a=o|0,c=i|0,o=s|0,i=r|0;const Pt=Ye(F,O,le);s=Qe(Pt,S,X,ft),r=Pt|0}({h:s,l:r}=U(this.Ah|0,this.Al|0,s|0,r|0)),{h:o,l:i}=U(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=U(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:h}=U(this.Dh|0,this.Dl|0,l|0,h|0),{h:u,l:f}=U(this.Eh|0,this.El|0,u|0,f|0),{h:x,l:g}=U(this.Fh|0,this.Fl|0,x|0,g|0),{h:w,l:T}=U(this.Gh|0,this.Gl|0,w|0,T|0),{h:m,l:b}=U(this.Hh|0,this.Hl|0,m|0,b|0),this.set(s,r,o,i,a,c,l,h,u,f,x,g,w,T,m,b)}roundClean(){B(L,R)}destroy(){B(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class hn extends ln{constructor(){super(64);p(this,"Ah",k[0]|0);p(this,"Al",k[1]|0);p(this,"Bh",k[2]|0);p(this,"Bl",k[3]|0);p(this,"Ch",k[4]|0);p(this,"Cl",k[5]|0);p(this,"Dh",k[6]|0);p(this,"Dl",k[7]|0);p(this,"Eh",k[8]|0);p(this,"El",k[9]|0);p(this,"Fh",k[10]|0);p(this,"Fl",k[11]|0);p(this,"Gh",k[12]|0);p(this,"Gl",k[13]|0);p(this,"Hh",k[14]|0);p(this,"Hl",k[15]|0)}}const fn=ht(()=>new an,qt(1)),ee=ht(()=>new hn,qt(3)),dn=BigInt(0),Z=BigInt(1),pn=BigInt(2),gn=BigInt(7),bn=BigInt(256),yn=BigInt(113),ne=[],se=[],re=[];for(let e=0,t=Z,n=1,s=0;e<24;e++){[n,s]=[s,(2*n+3*s)%5],ne.push(2*(5*s+n)),se.push((e+1)*(e+2)/2%64);let r=dn;for(let o=0;o<7;o++)t=(t<<Z^(t>>gn)*yn)%bn,t&pn&&(r^=Z<<(Z<<BigInt(o))-Z);re.push(r)}const oe=Qt(re,!0),xn=oe[0],wn=oe[1],Bt=(e,t,n)=>n>32?Ze(e,t,n):Ge(e,t,n),At=(e,t,n)=>n>32?Je(e,t,n):ze(e,t,n);function Pn(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,c=(i+2)%10,l=n[c],h=n[c+1],u=Bt(l,h,1)^n[a],f=At(l,h,1)^n[a+1];for(let x=0;x<50;x+=10)e[i+x]^=u,e[i+x+1]^=f}let r=e[2],o=e[3];for(let i=0;i<24;i++){const a=se[i],c=Bt(r,o,a),l=At(r,o,a),h=ne[i];r=e[h],o=e[h+1],e[h]=c,e[h+1]=l}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]^=xn[s],e[1]^=wn[s]}B(n)}class wt{constructor(t,n,s,r=!1,o=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=r,this.rounds=o,K(s,"outputLen"),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ce(this.state)}clone(){return this._cloneInto()}keccak(){vt(this.state32),Pn(this.state32,this.rounds),vt(this.state32),this.posOut=0,this.pos=0}update(t){z(this),N(t);const{blockLen:n,state:s}=this,r=t.length;for(let o=0;o<r;){const i=Math.min(n-this.pos,r-o);for(let a=0;a<i;a++)s[this.pos++]^=t[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:n,pos:s,blockLen:r}=this;t[s]^=n,(n&128)!==0&&s===r-1&&this.keccak(),t[r-1]^=128,this.keccak()}writeInto(t){z(this,!1),N(t),this.finish();const n=this.state,{blockLen:s}=this;for(let r=0,o=t.length;r<o;){this.posOut>=s&&this.keccak();const i=Math.min(s-this.posOut,o-r);t.set(n.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=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 K(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Xt(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,B(this.state)}_cloneInto(t){const{blockLen:n,suffix:s,outputLen:r,rounds:o,enableXOF:i}=this;return t||(t=new wt(n,s,r,i,o)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=o,t.suffix=s,t.outputLen=r,t.enableXOF=i,t.destroyed=this.destroyed,t}}const mn=(e,t,n,s={})=>ht(()=>new wt(t,e,n),s),Tn=mn(1,136,32);function vn(e,t,n,s){Nt(e);const r=$e({dkLen:32,asyncTick:10},s),{c:o,dkLen:i,asyncTick:a}=r;if(K(o,"c"),K(i,"dkLen"),K(a,"asyncTick"),o<1)throw new Error("iterations (c) must be >= 1");const c=Ht(t,"password"),l=Ht(n,"salt"),h=new Uint8Array(i),u=yt.create(e,c),f=u._cloneInto().update(l);return{c:o,dkLen:i,asyncTick:a,DK:h,PRF:u,PRFSalt:f}}function Hn(e,t,n,s,r){return e.destroy(),t.destroy(),s&&s.destroy(),B(r),n}function kn(e,t,n,s){const{c:r,dkLen:o,DK:i,PRF:a,PRFSalt:c}=vn(e,t,n,s);let l;const h=new Uint8Array(4),u=at(h),f=new Uint8Array(a.outputLen);for(let x=1,g=0;g<o;x++,g+=a.outputLen){const w=i.subarray(g,g+a.outputLen);u.setInt32(0,x,!1),(l=c._cloneInto(l)).update(h).digestInto(f),w.set(f.subarray(0,w.length));for(let T=1;T<r;T++){a._cloneInto(l).update(f).digestInto(f);for(let m=0;m<w.length;m++)w[m]^=f[m]}}return Hn(a,c,i,l,f)}function ie(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function En(e){const t=ie(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}const In=e=>ie("mnemonic"+e);function Sn(e,t=""){return kn(ee,En(e).nfkd,In(t),{c:2048,dkLen:64})}const Bn=508,Ct=16,rt=32,ot=64,Ut=5,An=4;function J(...e){const t=e.reduce((r,o)=>r+o.length,0),n=new Uint8Array(t);let s=0;for(const r of e)n.set(r,s),s+=r.length;return n}function dt(e){return new TextEncoder().encode(e)}function pt(e){const t=new Uint8Array(An);return new DataView(t.buffer).setUint32(0,e.length,!1),J(t,e)}function gt(e,t){return yt(ee,e,t)}function Ft(e){return qe(fn(e))}const bt=e=>Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");function ae(e){const t=Sn(e),n=new Uint8Array(t);return t.fill(0),n}async function ce(e,t,n,s){if(e.length!==ot)throw new Error(`WOTS seed must be ${ot} bytes, got ${e.length}`);t=y.stripHexPrefix(t),n=y.stripHexPrefix(n);const r=e.slice(rt,ot),o=e.slice(0,rt),i=[r,o];try{const a=J(pt(dt(t)),pt(dt(n)),pt(dt(s))),c=J(o,a);i.push(c);const l=gt(r,c);i.push(l);const h=l.slice(0,rt),u=l.slice(rt,ot);i.push(h,u);const f=[],x=[],g=[],w=[];let T=!1;try{for(let m=0;m<Bn;m++){const b=new Uint8Array(Ut);b[0]=0,new DataView(b.buffer).setUint32(1,m,!1);const d=new Uint8Array(Ut);d[0]=1,new DataView(d.buffer).setUint32(1,m,!1);const P=J(h,b),H=J(h,d),v=gt(u,P),E=gt(u,H);try{const I=v.slice(0,Ct),S=E.slice(0,Ct);f.push(I),x.push(S),g.push(Ft(I)),w.push(Ft(S))}finally{P.fill(0),H.fill(0),v.fill(0),E.fill(0)}}return T=!0,{falsePreimages:f,truePreimages:x,falseHashes:g,trueHashes:w}}finally{if(!T){for(const m of f)m.fill(0);for(const m of x)m.fill(0)}}}finally{for(const a of i)a.fill(0)}}function Cn(e){return{false_list:e.falseHashes.map(bt),true_list:e.trueHashes.map(bt)}}function ue(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 r=0;for(const i of e.falseHashes)s.set(i,r),r+=t;for(const i of e.trueHashes)s.set(i,r),r+=t;const o=Tn(s);return`0x${bt(o)}`}async function Un(e,t,n,s){const r=ae(e);try{const o=await ce(r,t,n,s);try{return ue(o)}finally{for(const i of o.falsePreimages)i.fill(0);for(const i of o.truePreimages)i.fill(0)}}finally{r.fill(0)}}function Fn(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.BTCVaultRegistryABI=G;exports.BitcoinScriptType=Y;exports.CONTRACT_ERRORS=M;exports.MEMPOOL_API_URLS=Vt;exports.PayoutManager=Be;exports.PeginManager=Se;exports.calculateBtcTxHash=it;exports.computeWotsPkHash=ue;exports.createTaprootScriptPathSignOptions=ct;exports.deriveWotsKeypair=ce;exports.deriveWotsPkHash=Un;exports.extractErrorData=lt;exports.getAddressTxs=Te;exports.getAddressUtxos=Pe;exports.getContractErrorMessage=He;exports.getDustThreshold=be;exports.getMempoolApiUrl=me;exports.getNetworkFees=ve;exports.getPsbtInputFields=$t;exports.getScriptType=_t;exports.getTxHex=we;exports.getTxInfo=Kt;exports.getUtxoInfo=Mt;exports.handleContractError=W;exports.isKnownContractError=ke;exports.isWotsMismatchError=Fn;exports.keypairToPublicKey=Cn;exports.mnemonicToWotsSeed=ae;exports.pushTx=Dt;exports.selectUtxosForPegin=Ot;exports.shouldAddChangeOutput=ge;
2
- //# sourceMappingURL=errors-DnMc1lLU.cjs.map