droplinked-web3-kit 1.0.8 → 1.0.9
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.
package/index.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
data.chainLinkRoundId: ${n.chainLinkRoundId}
|
|
15
15
|
data.memo: ${n.memo}
|
|
16
16
|
data.totalPrice: ${Number(n.totalPrice)}
|
|
17
|
-
`),ae===Chains.SKALE)return await skalePayment(n,le,ye,Ee,me,xe,ie);he?await handleCustomTokenApproval(n,xe,ye,me,ie):n.tbdValues=n.tbdValues.map(Ue=>parseInt(Ue.toString(),10));try{await Ee.callStatic.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{value:he?BigNumber.from(0):n.totalPrice})}catch(Ue){throw new Error("Transaction will fail: "+Ue.message)}let Se;try{Se=await getGasPrice(fe)}catch(Ue){throw new Error("Failed to get gas price: "+Ue.message)}let Me;try{Me=await Ee.estimateGas.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{value:he?BigNumber.from(0):n.totalPrice})}catch(Ue){throw new Error(`Gas estimation failed: ${Ue.message}. Please check the transaction parameters.`)}const Be=Me.mul(105).div(100),$e=he?BigNumber.from(0):BigNumber.from(n.totalPrice);let Ce;try{Ce=await fe.getBalance(me)}catch(Ue){throw new Error("Failed to get user balance: "+Ue.message)}const ke=$e.add(Be.mul(Se));if(Ce.lt(ke))throw new InsufficientBalanceException;ie.changeStep("Sending Payment Transaction");const Pe=await Ee.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{gasLimit:Be,value:he?BigNumber.from(0):n.totalPrice});return ie.changeStep("Awaiting transaction"),await Pe.wait(),ie.success("Payment Successful"),{transactionHash:Pe.hash,cryptoAmount:n.totalPrice}}catch(Se){handleError(Se,ie)}},skalePayment=async function(c,t,n,ie,fe,ae,le){try{const he=t===Network.TESTNET?SkaleUsdcAddressForTestnet:SkaleUsdcAddressForMainnet;return c.tokenAddress=he,await handleCustomTokenApproval(c,ae,n,fe,le),{transactionHash:(await ie.droplinkedPurchase(c.tbdValues,c.tbdReceivers,he,"0",c.memo)).hash,cryptoAmount:c.totalPrice}}catch(he){handleError(he,le)}};function handleError(c,t){var n;throw c instanceof Error?((n=c.code)==null?void 0:n.toString())==="ACTION_REJECTED"||c.message.includes("User denied")||c.message.includes("User cancelled transaction")?(t.error("Transaction rejected by user","User Denied"),new UserDeniedException("Metamask*")):c.message.includes("insufficient funds")||c.message.includes("gas * price + value")||c.code==="INSUFFICIENT_FUNDS"?(t.error("Insufficient balance to complete the transaction","Insufficient Balance"),new InsufficientBalanceException):c:(t.error("An unknown error occurred","Unknown Error"),new Error("An unknown error occurred"))}async function payment({chain:c,orderID:t,paymentToken:n,axiosInstance:ie,shopId:fe,network:ae,provider:le,stepizer:he}){const ye=new Web3Provider(le,"any");if(await ensureWalletOnChainFromConfig(ye,getChainByName(c),ae),!fe)throw new InvalidParametersException(c,"shopId not found");const me=await startPayment(t,n,c,fe,ie),xe=await getCartData(t,n,c,ie),Ee=xe.paymentData,Be=await droplinkedPayment({chain:c,network:ae,provider:ye},{modalInterface:he},Ee);if(await updateHash("payment",me,Be.transactionHash,ie),!await web3Callback(Be.transactionHash,c,Network[ae],`${getBaseUrl(ae)}/web3/payment/callback/${me}/${Be.transactionHash}`))throw new Web3CallbackFailedException(Actions.Payment);return{...Be,orderID:xe.orderID,transactionId:me}}const DROPLINKED_MANAGER="0x2F86E1B1A69D259b9609b40E3cbEBEa29946f979";async function doClaimNFT(c,t,n){const{modalInterface:ie}=n,fe=t.provider.getSigner();ie.changeStep("Claiming NFTs");const ae=new Contract(n.shopContractAddress,shopABI,fe);try{console.log(DROPLINKED_MANAGER,c.signature.signature,{cart:c.signature.purchaseData.map(ye=>({amount:ye.amount,productId:ye.productId,nullifier:ye.nullifier})),shop:n.shopContractAddress});const le=c.signature.purchaseData.map(ye=>({amount:ye.amount,productId:BigNumber.from(ye.productId),nullifier:BigNumber.from(ye.nullifier)}));ie.changeStep("Sending Transaction");const he=await ae.claimPurchase(DROPLINKED_MANAGER,c.signature.signature,{cart:le,shop:n.shopContractAddress});return ie.changeStep("Waiting for confirmation"),await he.wait(),ie.changeStep("NFT Claimed!"),{transactionHash:he.hash}}catch(le){if(console.error(le),le.code&&le.code.toString()==="ACTION_REJECTED")throw n.modalInterface.error("Transaction Rejected","Transaction Rejected by the user"),new UserDeniedException("Transaction Rejected");try{const he=ae.interface.parseError(le.data);throw he.name==="OwnableUnauthorizedAccount"&&n.modalInterface.error("Ownable Error",he.name),n.modalInterface.error(le,le),le}catch(he){throw console.log("Could not parse error with ABI, showing generic error",he),ie.error("Unexpected error occurred","An unexpected error occurred, please try again. If the issue persists, contact support."),he}}}async function claimNFT({provider:c,axiosInstance:t,stepizer:n,orderId:ie,skuId:fe,network:ae}){const le=new Web3Provider(c,"any"),{shopContractAddress:he,signature:ye,networkName:me,nftId:xe,claimed:Ee}=await getPurchaseSignature(ie,fe,t);if(Ee)throw n.error("Already Claimed","This NFT has already been claimed for this order."),new Error("NFT already claimed");await ensureWalletOnChainFromConfig(le,getChainByName(me),ae);const $e=await doClaimNFT({signature:ye},{provider:le},{axiosInstance:t,modalInterface:n,nftContract:"",shopContractAddress:he});return await sendClaim(xe,$e.transactionHash,t),$e}class EVMBaseWallet extends Web3Wallet{constructor(t,n){super(t.wallet,t.group,n),this.provider=null,this.cfg=t}async initializeProvider(){this.provider=await getEvmProviderByWalletName(this.cfg.wallet),console.log(`Initialized ${this.name} EVM Provider.`)}async login({chain:t,network:n}){if(!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);try{this.stepizer.changeStep("Connecting to wallet..."),console.log(`Login on ${t} ${n}`);const ie=await this.provider.request({method:"eth_requestAccounts"});if(!Array.isArray(ie)||ie.length===0)throw new ProviderException("Evm Wallet");return this.stepizer.success("Wallet connected"),{address:ie[0]}}catch(ie){throw console.error(ie),ie instanceof UserDeniedException?(this.stepizer.error("User denied the request",""),ie):(this.stepizer.error("An error occurred while connecting to the wallet",""),ie)}}async isWalletConnected(){if(!this.provider)return!1;try{const t=await this.provider.request({method:"eth_accounts"});return Array.isArray(t)&&t.length>0}catch{return!1}}async getConnectedAccounts(){if(!this.provider)return[];const t=await this.provider.request({method:"eth_accounts"});return Array.isArray(t)?t:[]}async recordProduct({productId:t,chain:n,axiosInstance:ie,shopId:fe,network:ae}){if(console.log(`Recording for ${t} on ${n}`),!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);return recordProduct({axiosInstance:ie,chain:n,network:ae,productId:t,provider:this.provider,shopId:fe,stepizer:this.stepizer})}async auth({chain:t,network:n,axiosInstance:ie}){if(console.log(`Authentication process ${t}`),!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);const fe=this.provider,ae=this.stepizer,le=new Web3Provider(this.provider,"any");try{if(ae.changeStep("Connecting to wallet..."),!await this.isWalletConnected())try{return await fe.request({method:"eth_requestAccounts"})}catch(Me){throw console.error(Me),new UserDeniedException(this.name)}const he=(await this.login({chain:t,network:n})).address;ae.changeStep("Signing message...");const ye=await getNonce(he,ie),me=new Date().toLocaleString(),xe=`Welcome to Droplinked! Please sign this message to verify your ownership over your wallet and log in. - Nonce: ${ye} - Date: ${me}`,Se=await le.getSigner().signMessage(xe);return ae.success("Authentication successful!"),{address:he,signature:Se,nonce:ye,date:me}}catch(he){throw console.error(he),he instanceof UserDeniedException?(ae.error("User denied the request",""),he):(ae.error("An error occurred while connecting to the wallet",""),he)}}async claimNFT({orderId:t,skuId:n,axiosInstance:ie,network:fe}){if(console.log(`ClaimNFT process for order: ${t} - sku: ${n}`),!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);return claimNFT({axiosInstance:ie,network:fe,orderId:t,provider:this.provider,skuId:n,stepizer:this.stepizer})}async payment({chain:t,network:n,orderID:ie,paymentToken:fe,shopId:ae,axiosInstance:le}){if(!this.supportsToken(t,fe))throw new TokenNotSupportedException(this.name,fe);if(this.stepizer.changeStep("Starting payment process"),!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);return await payment({axiosInstance:le,chain:t,network:n,orderID:ie,paymentToken:fe,provider:this.provider,shopId:ae,stepizer:this.stepizer})}async isWalletInstalled(){let t=!1;const n=this.name;function ie(fe){var le,he;const ae=fe.detail;((he=(le=ae==null?void 0:ae.info)==null?void 0:le.name)==null?void 0:he.toLowerCase())===n.toLowerCase()&&(t=!0)}return window.addEventListener("eip6963:announceProvider",ie),window.dispatchEvent(new Event("eip6963:requestProvider")),await new Promise(fe=>setTimeout(fe,700)),window.removeEventListener("eip6963:announceProvider",ie),t}getInstallationLink(){return this.cfg.installationLink}}var Wallets=(c=>(c.Metamask="Metamask",c.Phantom="Phantom",c.TrustWallet="Trust Wallet",c.UnstoppableDomains="Unstoppable Domains",c.XION="Xion",c))(Wallets||{});class MetamaskEVMWallet extends EVMBaseWallet{constructor(t){super({group:Groups.EVM,installationLink:{website:"https://metamask.io/download",chrome:"https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn",firefox:"https://addons.mozilla.org/en-US/firefox/addon/ether-metamask/"},wallet:Wallets.Metamask},t)}supportsToken(t,n){return console.log(`Checking support for ${n} on ${t}`),!!this.supportsChain(t)}supportsChain(t){return isChainInGroup(t,Groups.EVM)}}var __classPrivateFieldGet=function(c,t,n,ie){if(n==="a"&&!ie)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?c!==t||!ie:!t.has(c))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?ie:n==="a"?ie.call(c):ie?ie.value:t.get(c)},__classPrivateFieldSet=function(c,t,n,ie,fe){if(ie==="m")throw new TypeError("Private method is not writable");if(ie==="a"&&!fe)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?c!==t||!fe:!t.has(c))throw new TypeError("Cannot write private member to an object whose class did not declare it");return ie==="a"?fe.call(c,n):fe?fe.value=n:t.set(c,n),n},_AppReadyEvent_detail;let wallets;const registeredWalletsSet=new Set;function addRegisteredWallet(c){cachedWalletsArray=void 0,registeredWalletsSet.add(c)}function removeRegisteredWallet(c){cachedWalletsArray=void 0,registeredWalletsSet.delete(c)}const listeners={};function getWallets(){if(wallets||(wallets=Object.freeze({register,get:get$1,on}),typeof window>"u"))return wallets;const c=Object.freeze({register});try{window.addEventListener("wallet-standard:register-wallet",({detail:t})=>t(c))}catch(t){console.error(`wallet-standard:register-wallet event listener could not be added
|
|
17
|
+
`),ae===Chains.SKALE)return await skalePayment(n,le,ye,Ee,me,xe,ie);he?await handleCustomTokenApproval(n,xe,ye,me,ie):n.tbdValues=n.tbdValues.map(Ue=>parseInt(Ue.toString(),10));try{await Ee.callStatic.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{value:he?BigNumber.from(0):n.totalPrice})}catch(Ue){throw new Error("Transaction will fail: "+Ue.message)}let Se;try{Se=await getGasPrice(fe)}catch(Ue){throw new Error("Failed to get gas price: "+Ue.message)}let Me;try{Me=await Ee.estimateGas.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{value:he?BigNumber.from(0):n.totalPrice})}catch(Ue){throw new Error(`Gas estimation failed: ${Ue.message}. Please check the transaction parameters.`)}const Be=Me.mul(105).div(100),$e=he?BigNumber.from(0):BigNumber.from(n.totalPrice);let Ce;try{Ce=await fe.getBalance(me)}catch(Ue){throw new Error("Failed to get user balance: "+Ue.message)}const ke=$e.add(Be.mul(Se));if(Ce.lt(ke))throw new InsufficientBalanceException;ie.changeStep("Sending Payment Transaction");const Pe=await Ee.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{gasLimit:Be,value:he?BigNumber.from(0):n.totalPrice});return ie.changeStep("Awaiting transaction"),await Pe.wait(),ie.success("Payment Successful"),{transactionHash:Pe.hash,cryptoAmount:n.totalPrice}}catch(Se){handleError(Se,ie)}},skalePayment=async function(c,t,n,ie,fe,ae,le){try{const he=t===Network.TESTNET?SkaleUsdcAddressForTestnet:SkaleUsdcAddressForMainnet;return c.tokenAddress=he,await handleCustomTokenApproval(c,ae,n,fe,le),{transactionHash:(await ie.droplinkedPurchase(c.tbdValues,c.tbdReceivers,he,"0",c.memo)).hash,cryptoAmount:c.totalPrice}}catch(he){handleError(he,le)}};function handleError(c,t){var n;throw c instanceof Error?((n=c.code)==null?void 0:n.toString())==="ACTION_REJECTED"||c.message.includes("User denied")||c.message.includes("User cancelled transaction")?(t.error("Transaction rejected by user","User Denied"),new UserDeniedException("Metamask*")):c.message.includes("insufficient funds")||c.message.includes("gas * price + value")||c.code==="INSUFFICIENT_FUNDS"?(t.error("Insufficient balance to complete the transaction","Insufficient Balance"),new InsufficientBalanceException):c:(t.error("An unknown error occurred","Unknown Error"),new Error("An unknown error occurred"))}async function payment({chain:c,orderID:t,paymentToken:n,axiosInstance:ie,shopId:fe,network:ae,provider:le,stepizer:he}){const ye=new Web3Provider(le,"any");if(await ensureWalletOnChainFromConfig(ye,getChainByName(c),ae),!fe)throw new InvalidParametersException(c,"shopId not found");const me=await startPayment(t,n,c,fe,ie),xe=await getCartData(t,n,c,ie),Ee=xe.paymentData,Be=await droplinkedPayment({chain:c,network:ae,provider:ye},{modalInterface:he},Ee);if(await updateHash("payment",me,Be.transactionHash,ie),!await web3Callback(Be.transactionHash,c,Network[ae],`${getBaseUrl(ae)}/web3/payment/callback/${me}/${Be.transactionHash}`))throw new Web3CallbackFailedException(Actions.Payment);return{...Be,orderID:xe.orderID,transactionId:me}}const DROPLINKED_MANAGER="0x2F86E1B1A69D259b9609b40E3cbEBEa29946f979";async function doClaimNFT(c,t,n){const{modalInterface:ie}=n,fe=t.provider.getSigner();ie.changeStep("Claiming NFTs");const ae=new Contract(n.shopContractAddress,shopABI,fe);try{console.log(DROPLINKED_MANAGER,c.signature.signature,{cart:c.signature.purchaseData.map(ye=>({amount:ye.amount,productId:ye.productId,nullifier:ye.nullifier})),shop:n.shopContractAddress});const le=c.signature.purchaseData.map(ye=>({amount:ye.amount,productId:BigNumber.from(ye.productId),nullifier:BigNumber.from(ye.nullifier)}));ie.changeStep("Sending Transaction");const he=await ae.claimPurchase(DROPLINKED_MANAGER,c.signature.signature,{cart:le,shop:n.shopContractAddress});return ie.changeStep("Waiting for confirmation"),await he.wait(),ie.changeStep("NFT Claimed!"),{transactionHash:he.hash}}catch(le){if(console.error(le),le.code&&le.code.toString()==="ACTION_REJECTED")throw n.modalInterface.error("Transaction Rejected","Transaction Rejected by the user"),new UserDeniedException("Transaction Rejected");try{const he=ae.interface.parseError(le.data);throw he.name==="OwnableUnauthorizedAccount"&&n.modalInterface.error("Ownable Error",he.name),n.modalInterface.error(le,le),le}catch(he){throw console.log("Could not parse error with ABI, showing generic error",he),ie.error("Unexpected error occurred","An unexpected error occurred, please try again. If the issue persists, contact support."),he}}}async function claimNFT({provider:c,axiosInstance:t,stepizer:n,orderId:ie,skuId:fe,network:ae}){const le=new Web3Provider(c,"any"),{shopContractAddress:he,signature:ye,networkName:me,nftId:xe,claimed:Ee}=await getPurchaseSignature(ie,fe,t);if(Ee)throw n.error("Already Claimed","This NFT has already been claimed for this order."),new Error("NFT already claimed");const Se=me;await ensureWalletOnChainFromConfig(le,getChainByName(Se),ae);const $e=await doClaimNFT({signature:ye},{provider:le},{axiosInstance:t,modalInterface:n,nftContract:"",shopContractAddress:he});await sendClaim(xe,$e.transactionHash,t);const Ce=getTransactionLink({blockchain:Se,transactionHash:$e.transactionHash,isTestnet:ae===Network.TESTNET});return{...$e,transactionUrl:Ce}}class EVMBaseWallet extends Web3Wallet{constructor(t,n){super(t.wallet,t.group,n),this.provider=null,this.cfg=t}async initializeProvider(){this.provider=await getEvmProviderByWalletName(this.cfg.wallet),console.log(`Initialized ${this.name} EVM Provider.`)}async login({chain:t,network:n}){if(!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);try{this.stepizer.changeStep("Connecting to wallet..."),console.log(`Login on ${t} ${n}`);const ie=await this.provider.request({method:"eth_requestAccounts"});if(!Array.isArray(ie)||ie.length===0)throw new ProviderException("Evm Wallet");return this.stepizer.success("Wallet connected"),{address:ie[0]}}catch(ie){throw console.error(ie),ie instanceof UserDeniedException?(this.stepizer.error("User denied the request",""),ie):(this.stepizer.error("An error occurred while connecting to the wallet",""),ie)}}async isWalletConnected(){if(!this.provider)return!1;try{const t=await this.provider.request({method:"eth_accounts"});return Array.isArray(t)&&t.length>0}catch{return!1}}async getConnectedAccounts(){if(!this.provider)return[];const t=await this.provider.request({method:"eth_accounts"});return Array.isArray(t)?t:[]}async recordProduct({productId:t,chain:n,axiosInstance:ie,shopId:fe,network:ae}){if(console.log(`Recording for ${t} on ${n}`),!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);return recordProduct({axiosInstance:ie,chain:n,network:ae,productId:t,provider:this.provider,shopId:fe,stepizer:this.stepizer})}async auth({chain:t,network:n,axiosInstance:ie}){if(console.log(`Authentication process ${t}`),!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);const fe=this.provider,ae=this.stepizer,le=new Web3Provider(this.provider,"any");try{if(ae.changeStep("Connecting to wallet..."),!await this.isWalletConnected())try{return await fe.request({method:"eth_requestAccounts"})}catch(Me){throw console.error(Me),new UserDeniedException(this.name)}const he=(await this.login({chain:t,network:n})).address;ae.changeStep("Signing message...");const ye=await getNonce(he,ie),me=new Date().toLocaleString(),xe=`Welcome to Droplinked! Please sign this message to verify your ownership over your wallet and log in. - Nonce: ${ye} - Date: ${me}`,Se=await le.getSigner().signMessage(xe);return ae.success("Authentication successful!"),{address:he,signature:Se,nonce:ye,date:me}}catch(he){throw console.error(he),he instanceof UserDeniedException?(ae.error("User denied the request",""),he):(ae.error("An error occurred while connecting to the wallet",""),he)}}async claimNFT({orderId:t,skuId:n,axiosInstance:ie,network:fe}){if(console.log(`ClaimNFT process for order: ${t} - sku: ${n}`),!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);return claimNFT({axiosInstance:ie,network:fe,orderId:t,provider:this.provider,skuId:n,stepizer:this.stepizer})}async payment({chain:t,network:n,orderID:ie,paymentToken:fe,shopId:ae,axiosInstance:le}){if(!this.supportsToken(t,fe))throw new TokenNotSupportedException(this.name,fe);if(this.stepizer.changeStep("Starting payment process"),!this.provider)throw this.stepizer.error("Provider Error","Provider not initialized"),new ProviderException(this.name);return await payment({axiosInstance:le,chain:t,network:n,orderID:ie,paymentToken:fe,provider:this.provider,shopId:ae,stepizer:this.stepizer})}async isWalletInstalled(){let t=!1;const n=this.name;function ie(fe){var le,he;const ae=fe.detail;((he=(le=ae==null?void 0:ae.info)==null?void 0:le.name)==null?void 0:he.toLowerCase())===n.toLowerCase()&&(t=!0)}return window.addEventListener("eip6963:announceProvider",ie),window.dispatchEvent(new Event("eip6963:requestProvider")),await new Promise(fe=>setTimeout(fe,700)),window.removeEventListener("eip6963:announceProvider",ie),t}getInstallationLink(){return this.cfg.installationLink}}var Wallets=(c=>(c.Metamask="Metamask",c.Phantom="Phantom",c.TrustWallet="Trust Wallet",c.UnstoppableDomains="Unstoppable Domains",c.XION="Xion",c))(Wallets||{});class MetamaskEVMWallet extends EVMBaseWallet{constructor(t){super({group:Groups.EVM,installationLink:{website:"https://metamask.io/download",chrome:"https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn",firefox:"https://addons.mozilla.org/en-US/firefox/addon/ether-metamask/"},wallet:Wallets.Metamask},t)}supportsToken(t,n){return console.log(`Checking support for ${n} on ${t}`),!!this.supportsChain(t)}supportsChain(t){return isChainInGroup(t,Groups.EVM)}}var __classPrivateFieldGet=function(c,t,n,ie){if(n==="a"&&!ie)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?c!==t||!ie:!t.has(c))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?ie:n==="a"?ie.call(c):ie?ie.value:t.get(c)},__classPrivateFieldSet=function(c,t,n,ie,fe){if(ie==="m")throw new TypeError("Private method is not writable");if(ie==="a"&&!fe)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?c!==t||!fe:!t.has(c))throw new TypeError("Cannot write private member to an object whose class did not declare it");return ie==="a"?fe.call(c,n):fe?fe.value=n:t.set(c,n),n},_AppReadyEvent_detail;let wallets;const registeredWalletsSet=new Set;function addRegisteredWallet(c){cachedWalletsArray=void 0,registeredWalletsSet.add(c)}function removeRegisteredWallet(c){cachedWalletsArray=void 0,registeredWalletsSet.delete(c)}const listeners={};function getWallets(){if(wallets||(wallets=Object.freeze({register,get:get$1,on}),typeof window>"u"))return wallets;const c=Object.freeze({register});try{window.addEventListener("wallet-standard:register-wallet",({detail:t})=>t(c))}catch(t){console.error(`wallet-standard:register-wallet event listener could not be added
|
|
18
18
|
`,t)}try{window.dispatchEvent(new AppReadyEvent(c))}catch(t){console.error(`wallet-standard:app-ready event could not be dispatched
|
|
19
19
|
`,t)}return wallets}function register(...c){var t;return c=c.filter(n=>!registeredWalletsSet.has(n)),c.length?(c.forEach(n=>addRegisteredWallet(n)),(t=listeners.register)==null||t.forEach(n=>guard(()=>n(...c))),function(){var ie;c.forEach(fe=>removeRegisteredWallet(fe)),(ie=listeners.unregister)==null||ie.forEach(fe=>guard(()=>fe(...c)))}):()=>{}}let cachedWalletsArray;function get$1(){return cachedWalletsArray||(cachedWalletsArray=[...registeredWalletsSet]),cachedWalletsArray}function on(c,t){var n;return(n=listeners[c])!=null&&n.push(t)||(listeners[c]=[t]),function(){var fe;listeners[c]=(fe=listeners[c])==null?void 0:fe.filter(ae=>t!==ae)}}function guard(c){try{c()}catch(t){console.error(t)}}class AppReadyEvent extends Event{get detail(){return __classPrivateFieldGet(this,_AppReadyEvent_detail,"f")}get type(){return"wallet-standard:app-ready"}constructor(t){super("wallet-standard:app-ready",{bubbles:!1,cancelable:!1,composed:!1}),_AppReadyEvent_detail.set(this,void 0),__classPrivateFieldSet(this,_AppReadyEvent_detail,t,"f")}preventDefault(){throw new Error("preventDefault cannot be called")}stopImmediatePropagation(){throw new Error("stopImmediatePropagation cannot be called")}stopPropagation(){throw new Error("stopPropagation cannot be called")}}_AppReadyEvent_detail=new WeakMap;const crypto$2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function isBytes(c){return c instanceof Uint8Array||ArrayBuffer.isView(c)&&c.constructor.name==="Uint8Array"}function anumber(c){if(!Number.isSafeInteger(c)||c<0)throw new Error("positive integer expected, got "+c)}function abytes(c,...t){if(!isBytes(c))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(c.length))throw new Error("Uint8Array expected of length "+t+", got length="+c.length)}function ahash(c){if(typeof c!="function"||typeof c.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");anumber(c.outputLen),anumber(c.blockLen)}function aexists(c,t=!0){if(c.destroyed)throw new Error("Hash instance has been destroyed");if(t&&c.finished)throw new Error("Hash#digest() has already been called")}function aoutput(c,t){abytes(c);const n=t.outputLen;if(c.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function clean(...c){for(let t=0;t<c.length;t++)c[t].fill(0)}function createView(c){return new DataView(c.buffer,c.byteOffset,c.byteLength)}function rotr(c,t){return c<<32-t|c>>>t}const hasHexBuiltin=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hexes=Array.from({length:256},(c,t)=>t.toString(16).padStart(2,"0"));function bytesToHex(c){if(abytes(c),hasHexBuiltin)return c.toHex();let t="";for(let n=0;n<c.length;n++)t+=hexes[c[n]];return t}const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(c){if(c>=asciis._0&&c<=asciis._9)return c-asciis._0;if(c>=asciis.A&&c<=asciis.F)return c-(asciis.A-10);if(c>=asciis.a&&c<=asciis.f)return c-(asciis.a-10)}function hexToBytes(c){if(typeof c!="string")throw new Error("hex string expected, got "+typeof c);if(hasHexBuiltin)return Uint8Array.fromHex(c);const t=c.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const ie=new Uint8Array(n);for(let fe=0,ae=0;fe<n;fe++,ae+=2){const le=asciiToBase16(c.charCodeAt(ae)),he=asciiToBase16(c.charCodeAt(ae+1));if(le===void 0||he===void 0){const ye=c[ae]+c[ae+1];throw new Error('hex string expected, got non-hex character "'+ye+'" at index '+ae)}ie[fe]=le*16+he}return ie}function utf8ToBytes(c){if(typeof c!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(c))}function toBytes(c){return typeof c=="string"&&(c=utf8ToBytes(c)),abytes(c),c}function concatBytes(...c){let t=0;for(let ie=0;ie<c.length;ie++){const fe=c[ie];abytes(fe),t+=fe.length}const n=new Uint8Array(t);for(let ie=0,fe=0;ie<c.length;ie++){const ae=c[ie];n.set(ae,fe),fe+=ae.length}return n}class Hash{}function createHasher(c){const t=ie=>c().update(toBytes(ie)).digest(),n=c();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>c(),t}function randomBytes(c=32){if(crypto$2&&typeof crypto$2.getRandomValues=="function")return crypto$2.getRandomValues(new Uint8Array(c));if(crypto$2&&typeof crypto$2.randomBytes=="function")return Uint8Array.from(crypto$2.randomBytes(c));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64(c,t,n,ie){if(typeof c.setBigUint64=="function")return c.setBigUint64(t,n,ie);const fe=BigInt(32),ae=BigInt(4294967295),le=Number(n>>fe&ae),he=Number(n&ae),ye=ie?4:0,me=ie?0:4;c.setUint32(t+ye,le,ie),c.setUint32(t+me,he,ie)}function Chi(c,t,n){return c&t^~c&n}function Maj(c,t,n){return c&t^c&n^t&n}class HashMD extends Hash{constructor(t,n,ie,fe){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=ie,this.isLE=fe,this.buffer=new Uint8Array(t),this.view=createView(this.buffer)}update(t){aexists(this),t=toBytes(t),abytes(t);const{view:n,buffer:ie,blockLen:fe}=this,ae=t.length;for(let le=0;le<ae;){const he=Math.min(fe-this.pos,ae-le);if(he===fe){const ye=createView(t);for(;fe<=ae-le;le+=fe)this.process(ye,le);continue}ie.set(t.subarray(le,le+he),this.pos),this.pos+=he,le+=he,this.pos===fe&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){aexists(this),aoutput(t,this),this.finished=!0;const{buffer:n,view:ie,blockLen:fe,isLE:ae}=this;let{pos:le}=this;n[le++]=128,clean(this.buffer.subarray(le)),this.padOffset>fe-le&&(this.process(ie,0),le=0);for(let Ee=le;Ee<fe;Ee++)n[Ee]=0;setBigUint64(ie,fe-8,BigInt(this.length*8),ae),this.process(ie,0);const he=createView(t),ye=this.outputLen;if(ye%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const me=ye/4,xe=this.get();if(me>xe.length)throw new Error("_sha2: outputLen bigger than state");for(let Ee=0;Ee<me;Ee++)he.setUint32(4*Ee,xe[Ee],ae)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const ie=t.slice(0,n);return this.destroy(),ie}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:ie,length:fe,finished:ae,destroyed:le,pos:he}=this;return t.destroyed=le,t.finished=ae,t.length=fe,t.pos=he,fe%n&&t.buffer.set(ie),t}clone(){return this._cloneInto()}}const SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(c,t=!1){return t?{h:Number(c&U32_MASK64),l:Number(c>>_32n&U32_MASK64)}:{h:Number(c>>_32n&U32_MASK64)|0,l:Number(c&U32_MASK64)|0}}function split(c,t=!1){const n=c.length;let ie=new Uint32Array(n),fe=new Uint32Array(n);for(let ae=0;ae<n;ae++){const{h:le,l:he}=fromBig(c[ae],t);[ie[ae],fe[ae]]=[le,he]}return[ie,fe]}const shrSH=(c,t,n)=>c>>>n,shrSL=(c,t,n)=>c<<32-n|t>>>n,rotrSH=(c,t,n)=>c>>>n|t<<32-n,rotrSL=(c,t,n)=>c<<32-n|t>>>n,rotrBH=(c,t,n)=>c<<64-n|t>>>n-32,rotrBL=(c,t,n)=>c>>>n-32|t<<64-n;function add(c,t,n,ie){const fe=(t>>>0)+(ie>>>0);return{h:c+n+(fe/2**32|0)|0,l:fe|0}}const add3L=(c,t,n)=>(c>>>0)+(t>>>0)+(n>>>0),add3H=(c,t,n,ie)=>t+n+ie+(c/2**32|0)|0,add4L=(c,t,n,ie)=>(c>>>0)+(t>>>0)+(n>>>0)+(ie>>>0),add4H=(c,t,n,ie,fe)=>t+n+ie+fe+(c/2**32|0)|0,add5L=(c,t,n,ie,fe)=>(c>>>0)+(t>>>0)+(n>>>0)+(ie>>>0)+(fe>>>0),add5H=(c,t,n,ie,fe,ae)=>t+n+ie+fe+ae+(c/2**32|0)|0,SHA256_K=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]),SHA256_W=new Uint32Array(64);class SHA256 extends HashMD{constructor(t=32){super(64,t,8,!1),this.A=SHA256_IV[0]|0,this.B=SHA256_IV[1]|0,this.C=SHA256_IV[2]|0,this.D=SHA256_IV[3]|0,this.E=SHA256_IV[4]|0,this.F=SHA256_IV[5]|0,this.G=SHA256_IV[6]|0,this.H=SHA256_IV[7]|0}get(){const{A:t,B:n,C:ie,D:fe,E:ae,F:le,G:he,H:ye}=this;return[t,n,ie,fe,ae,le,he,ye]}set(t,n,ie,fe,ae,le,he,ye){this.A=t|0,this.B=n|0,this.C=ie|0,this.D=fe|0,this.E=ae|0,this.F=le|0,this.G=he|0,this.H=ye|0}process(t,n){for(let Ee=0;Ee<16;Ee++,n+=4)SHA256_W[Ee]=t.getUint32(n,!1);for(let Ee=16;Ee<64;Ee++){const Se=SHA256_W[Ee-15],Me=SHA256_W[Ee-2],Be=rotr(Se,7)^rotr(Se,18)^Se>>>3,$e=rotr(Me,17)^rotr(Me,19)^Me>>>10;SHA256_W[Ee]=$e+SHA256_W[Ee-7]+Be+SHA256_W[Ee-16]|0}let{A:ie,B:fe,C:ae,D:le,E:he,F:ye,G:me,H:xe}=this;for(let Ee=0;Ee<64;Ee++){const Se=rotr(he,6)^rotr(he,11)^rotr(he,25),Me=xe+Se+Chi(he,ye,me)+SHA256_K[Ee]+SHA256_W[Ee]|0,$e=(rotr(ie,2)^rotr(ie,13)^rotr(ie,22))+Maj(ie,fe,ae)|0;xe=me,me=ye,ye=he,he=le+Me|0,le=ae,ae=fe,fe=ie,ie=Me+$e|0}ie=ie+this.A|0,fe=fe+this.B|0,ae=ae+this.C|0,le=le+this.D|0,he=he+this.E|0,ye=ye+this.F|0,me=me+this.G|0,xe=xe+this.H|0,this.set(ie,fe,ae,le,he,ye,me,xe)}roundClean(){clean(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0),clean(this.buffer)}}const K512=split(["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(c=>BigInt(c))),SHA512_Kh=K512[0],SHA512_Kl=K512[1],SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends HashMD{constructor(t=64){super(128,t,16,!1),this.Ah=SHA512_IV[0]|0,this.Al=SHA512_IV[1]|0,this.Bh=SHA512_IV[2]|0,this.Bl=SHA512_IV[3]|0,this.Ch=SHA512_IV[4]|0,this.Cl=SHA512_IV[5]|0,this.Dh=SHA512_IV[6]|0,this.Dl=SHA512_IV[7]|0,this.Eh=SHA512_IV[8]|0,this.El=SHA512_IV[9]|0,this.Fh=SHA512_IV[10]|0,this.Fl=SHA512_IV[11]|0,this.Gh=SHA512_IV[12]|0,this.Gl=SHA512_IV[13]|0,this.Hh=SHA512_IV[14]|0,this.Hl=SHA512_IV[15]|0}get(){const{Ah:t,Al:n,Bh:ie,Bl:fe,Ch:ae,Cl:le,Dh:he,Dl:ye,Eh:me,El:xe,Fh:Ee,Fl:Se,Gh:Me,Gl:Be,Hh:$e,Hl:Ce}=this;return[t,n,ie,fe,ae,le,he,ye,me,xe,Ee,Se,Me,Be,$e,Ce]}set(t,n,ie,fe,ae,le,he,ye,me,xe,Ee,Se,Me,Be,$e,Ce){this.Ah=t|0,this.Al=n|0,this.Bh=ie|0,this.Bl=fe|0,this.Ch=ae|0,this.Cl=le|0,this.Dh=he|0,this.Dl=ye|0,this.Eh=me|0,this.El=xe|0,this.Fh=Ee|0,this.Fl=Se|0,this.Gh=Me|0,this.Gl=Be|0,this.Hh=$e|0,this.Hl=Ce|0}process(t,n){for(let Ue=0;Ue<16;Ue++,n+=4)SHA512_W_H[Ue]=t.getUint32(n),SHA512_W_L[Ue]=t.getUint32(n+=4);for(let Ue=16;Ue<80;Ue++){const qe=SHA512_W_H[Ue-15]|0,He=SHA512_W_L[Ue-15]|0,Ve=rotrSH(qe,He,1)^rotrSH(qe,He,8)^shrSH(qe,He,7),Ye=rotrSL(qe,He,1)^rotrSL(qe,He,8)^shrSL(qe,He,7),Qe=SHA512_W_H[Ue-2]|0,Ke=SHA512_W_L[Ue-2]|0,Pt=rotrSH(Qe,Ke,19)^rotrBH(Qe,Ke,61)^shrSH(Qe,Ke,6),_e=rotrSL(Qe,Ke,19)^rotrBL(Qe,Ke,61)^shrSL(Qe,Ke,6),se=add4L(Ye,_e,SHA512_W_L[Ue-7],SHA512_W_L[Ue-16]),ce=add4H(se,Ve,Pt,SHA512_W_H[Ue-7],SHA512_W_H[Ue-16]);SHA512_W_H[Ue]=ce|0,SHA512_W_L[Ue]=se|0}let{Ah:ie,Al:fe,Bh:ae,Bl:le,Ch:he,Cl:ye,Dh:me,Dl:xe,Eh:Ee,El:Se,Fh:Me,Fl:Be,Gh:$e,Gl:Ce,Hh:ke,Hl:Pe}=this;for(let Ue=0;Ue<80;Ue++){const qe=rotrSH(Ee,Se,14)^rotrSH(Ee,Se,18)^rotrBH(Ee,Se,41),He=rotrSL(Ee,Se,14)^rotrSL(Ee,Se,18)^rotrBL(Ee,Se,41),Ve=Ee&Me^~Ee&$e,Ye=Se&Be^~Se&Ce,Qe=add5L(Pe,He,Ye,SHA512_Kl[Ue],SHA512_W_L[Ue]),Ke=add5H(Qe,ke,qe,Ve,SHA512_Kh[Ue],SHA512_W_H[Ue]),Pt=Qe|0,_e=rotrSH(ie,fe,28)^rotrBH(ie,fe,34)^rotrBH(ie,fe,39),se=rotrSL(ie,fe,28)^rotrBL(ie,fe,34)^rotrBL(ie,fe,39),ce=ie&ae^ie&he^ae&he,de=fe&le^fe&ye^le&ye;ke=$e|0,Pe=Ce|0,$e=Me|0,Ce=Be|0,Me=Ee|0,Be=Se|0,{h:Ee,l:Se}=add(me|0,xe|0,Ke|0,Pt|0),me=he|0,xe=ye|0,he=ae|0,ye=le|0,ae=ie|0,le=fe|0;const pe=add3L(Pt,se,de);ie=add3H(pe,Ke,_e,ce),fe=pe|0}({h:ie,l:fe}=add(this.Ah|0,this.Al|0,ie|0,fe|0)),{h:ae,l:le}=add(this.Bh|0,this.Bl|0,ae|0,le|0),{h:he,l:ye}=add(this.Ch|0,this.Cl|0,he|0,ye|0),{h:me,l:xe}=add(this.Dh|0,this.Dl|0,me|0,xe|0),{h:Ee,l:Se}=add(this.Eh|0,this.El|0,Ee|0,Se|0),{h:Me,l:Be}=add(this.Fh|0,this.Fl|0,Me|0,Be|0),{h:$e,l:Ce}=add(this.Gh|0,this.Gl|0,$e|0,Ce|0),{h:ke,l:Pe}=add(this.Hh|0,this.Hl|0,ke|0,Pe|0),this.set(ie,fe,ae,le,he,ye,me,xe,Ee,Se,Me,Be,$e,Ce,ke,Pe)}roundClean(){clean(SHA512_W_H,SHA512_W_L)}destroy(){clean(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha256$5=createHasher(()=>new SHA256),sha512$3=createHasher(()=>new SHA512);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$5=BigInt(1);function _abool2(c,t=""){if(typeof c!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof c)}return c}function _abytes2(c,t,n=""){const ie=isBytes(c),fe=c==null?void 0:c.length,ae=t!==void 0;if(!ie||ae&&fe!==t){const le=n&&`"${n}" `,he=ae?` of length ${t}`:"",ye=ie?`length=${fe}`:`type=${typeof c}`;throw new Error(le+"expected Uint8Array"+he+", got "+ye)}return c}function numberToHexUnpadded(c){const t=c.toString(16);return t.length&1?"0"+t:t}function hexToNumber(c){if(typeof c!="string")throw new Error("hex string expected, got "+typeof c);return c===""?_0n$4:BigInt("0x"+c)}function bytesToNumberBE(c){return hexToNumber(bytesToHex(c))}function bytesToNumberLE(c){return abytes(c),hexToNumber(bytesToHex(Uint8Array.from(c).reverse()))}function numberToBytesBE(c,t){return hexToBytes(c.toString(16).padStart(t*2,"0"))}function numberToBytesLE(c,t){return numberToBytesBE(c,t).reverse()}function ensureBytes(c,t,n){let ie;if(typeof t=="string")try{ie=hexToBytes(t)}catch(ae){throw new Error(c+" must be hex string or Uint8Array, cause: "+ae)}else if(isBytes(t))ie=Uint8Array.from(t);else throw new Error(c+" must be hex string or Uint8Array");const fe=ie.length;if(typeof n=="number"&&fe!==n)throw new Error(c+" of length "+n+" expected, got "+fe);return ie}function copyBytes(c){return Uint8Array.from(c)}const isPosBig=c=>typeof c=="bigint"&&_0n$4<=c;function inRange$1(c,t,n){return isPosBig(c)&&isPosBig(t)&&isPosBig(n)&&t<=c&&c<n}function aInRange(c,t,n,ie){if(!inRange$1(t,n,ie))throw new Error("expected valid "+c+": "+n+" <= n < "+ie+", got "+t)}function bitLen(c){let t;for(t=0;c>_0n$4;c>>=_1n$5,t+=1);return t}const bitMask=c=>(_1n$5<<BigInt(c))-_1n$5;function createHmacDrbg(c,t,n){if(typeof c!="number"||c<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const ie=Me=>new Uint8Array(Me),fe=Me=>Uint8Array.of(Me);let ae=ie(c),le=ie(c),he=0;const ye=()=>{ae.fill(1),le.fill(0),he=0},me=(...Me)=>n(le,ae,...Me),xe=(Me=ie(0))=>{le=me(fe(0),Me),ae=me(),Me.length!==0&&(le=me(fe(1),Me),ae=me())},Ee=()=>{if(he++>=1e3)throw new Error("drbg: tried 1000 values");let Me=0;const Be=[];for(;Me<t;){ae=me();const $e=ae.slice();Be.push($e),Me+=ae.length}return concatBytes(...Be)};return(Me,Be)=>{ye(),xe(Me);let $e;for(;!($e=Be(Ee()));)xe();return ye(),$e}}function _validateObject(c,t,n={}){if(!c||typeof c!="object")throw new Error("expected valid options object");function ie(fe,ae,le){const he=c[fe];if(le&&he===void 0)return;const ye=typeof he;if(ye!==ae||he===null)throw new Error(`param "${fe}" is invalid: expected ${ae}, got ${ye}`)}Object.entries(t).forEach(([fe,ae])=>ie(fe,ae,!1)),Object.entries(n).forEach(([fe,ae])=>ie(fe,ae,!0))}function memoized(c){const t=new WeakMap;return(n,...ie)=>{const fe=t.get(n);if(fe!==void 0)return fe;const ae=c(n,...ie);return t.set(n,ae),ae}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$4=BigInt(1),_2n$4=BigInt(2),_3n$1=BigInt(3),_4n$1=BigInt(4),_5n$1=BigInt(5),_7n=BigInt(7),_8n$2=BigInt(8),_9n=BigInt(9),_16n=BigInt(16);function mod(c,t){const n=c%t;return n>=_0n$3?n:t+n}function pow2(c,t,n){let ie=c;for(;t-- >_0n$3;)ie*=ie,ie%=n;return ie}function invert(c,t){if(c===_0n$3)throw new Error("invert: expected non-zero number");if(t<=_0n$3)throw new Error("invert: expected positive modulus, got "+t);let n=mod(c,t),ie=t,fe=_0n$3,ae=_1n$4;for(;n!==_0n$3;){const he=ie/n,ye=ie%n,me=fe-ae*he;ie=n,n=ye,fe=ae,ae=me}if(ie!==_1n$4)throw new Error("invert: does not exist");return mod(fe,t)}function assertIsSquare(c,t,n){if(!c.eql(c.sqr(t),n))throw new Error("Cannot find square root")}function sqrt3mod4(c,t){const n=(c.ORDER+_1n$4)/_4n$1,ie=c.pow(t,n);return assertIsSquare(c,ie,t),ie}function sqrt5mod8(c,t){const n=(c.ORDER-_5n$1)/_8n$2,ie=c.mul(t,_2n$4),fe=c.pow(ie,n),ae=c.mul(t,fe),le=c.mul(c.mul(ae,_2n$4),fe),he=c.mul(ae,c.sub(le,c.ONE));return assertIsSquare(c,he,t),he}function sqrt9mod16(c){const t=Field(c),n=tonelliShanks(c),ie=n(t,t.neg(t.ONE)),fe=n(t,ie),ae=n(t,t.neg(ie)),le=(c+_7n)/_16n;return(he,ye)=>{let me=he.pow(ye,le),xe=he.mul(me,ie);const Ee=he.mul(me,fe),Se=he.mul(me,ae),Me=he.eql(he.sqr(xe),ye),Be=he.eql(he.sqr(Ee),ye);me=he.cmov(me,xe,Me),xe=he.cmov(Se,Ee,Be);const $e=he.eql(he.sqr(xe),ye),Ce=he.cmov(me,xe,$e);return assertIsSquare(he,Ce,ye),Ce}}function tonelliShanks(c){if(c<_3n$1)throw new Error("sqrt is not defined for small field");let t=c-_1n$4,n=0;for(;t%_2n$4===_0n$3;)t/=_2n$4,n++;let ie=_2n$4;const fe=Field(c);for(;FpLegendre(fe,ie)===1;)if(ie++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return sqrt3mod4;let ae=fe.pow(ie,t);const le=(t+_1n$4)/_2n$4;return function(ye,me){if(ye.is0(me))return me;if(FpLegendre(ye,me)!==1)throw new Error("Cannot find square root");let xe=n,Ee=ye.mul(ye.ONE,ae),Se=ye.pow(me,t),Me=ye.pow(me,le);for(;!ye.eql(Se,ye.ONE);){if(ye.is0(Se))return ye.ZERO;let Be=1,$e=ye.sqr(Se);for(;!ye.eql($e,ye.ONE);)if(Be++,$e=ye.sqr($e),Be===xe)throw new Error("Cannot find square root");const Ce=_1n$4<<BigInt(xe-Be-1),ke=ye.pow(Ee,Ce);xe=Be,Ee=ye.sqr(ke),Se=ye.mul(Se,Ee),Me=ye.mul(Me,ke)}return Me}}function FpSqrt(c){return c%_4n$1===_3n$1?sqrt3mod4:c%_8n$2===_5n$1?sqrt5mod8:c%_16n===_9n?sqrt9mod16(c):tonelliShanks(c)}const isNegativeLE=(c,t)=>(mod(c,t)&_1n$4)===_1n$4,FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(c){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=FIELD_FIELDS.reduce((ie,fe)=>(ie[fe]="function",ie),t);return _validateObject(c,n),c}function FpPow(c,t,n){if(n<_0n$3)throw new Error("invalid exponent, negatives unsupported");if(n===_0n$3)return c.ONE;if(n===_1n$4)return t;let ie=c.ONE,fe=t;for(;n>_0n$3;)n&_1n$4&&(ie=c.mul(ie,fe)),fe=c.sqr(fe),n>>=_1n$4;return ie}function FpInvertBatch(c,t,n=!1){const ie=new Array(t.length).fill(n?c.ZERO:void 0),fe=t.reduce((le,he,ye)=>c.is0(he)?le:(ie[ye]=le,c.mul(le,he)),c.ONE),ae=c.inv(fe);return t.reduceRight((le,he,ye)=>c.is0(he)?le:(ie[ye]=c.mul(le,ie[ye]),c.mul(le,he)),ae),ie}function FpLegendre(c,t){const n=(c.ORDER-_1n$4)/_2n$4,ie=c.pow(t,n),fe=c.eql(ie,c.ONE),ae=c.eql(ie,c.ZERO),le=c.eql(ie,c.neg(c.ONE));if(!fe&&!ae&&!le)throw new Error("invalid Legendre symbol result");return fe?1:ae?0:-1}function nLength(c,t){t!==void 0&&anumber(t);const n=t!==void 0?t:c.toString(2).length,ie=Math.ceil(n/8);return{nBitLength:n,nByteLength:ie}}function Field(c,t,n=!1,ie={}){if(c<=_0n$3)throw new Error("invalid field: expected ORDER > 0, got "+c);let fe,ae,le=!1,he;if(typeof t=="object"&&t!=null){if(ie.sqrt||n)throw new Error("cannot specify opts in two arguments");const Se=t;Se.BITS&&(fe=Se.BITS),Se.sqrt&&(ae=Se.sqrt),typeof Se.isLE=="boolean"&&(n=Se.isLE),typeof Se.modFromBytes=="boolean"&&(le=Se.modFromBytes),he=Se.allowedLengths}else typeof t=="number"&&(fe=t),ie.sqrt&&(ae=ie.sqrt);const{nBitLength:ye,nByteLength:me}=nLength(c,fe);if(me>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let xe;const Ee=Object.freeze({ORDER:c,isLE:n,BITS:ye,BYTES:me,MASK:bitMask(ye),ZERO:_0n$3,ONE:_1n$4,allowedLengths:he,create:Se=>mod(Se,c),isValid:Se=>{if(typeof Se!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof Se);return _0n$3<=Se&&Se<c},is0:Se=>Se===_0n$3,isValidNot0:Se=>!Ee.is0(Se)&&Ee.isValid(Se),isOdd:Se=>(Se&_1n$4)===_1n$4,neg:Se=>mod(-Se,c),eql:(Se,Me)=>Se===Me,sqr:Se=>mod(Se*Se,c),add:(Se,Me)=>mod(Se+Me,c),sub:(Se,Me)=>mod(Se-Me,c),mul:(Se,Me)=>mod(Se*Me,c),pow:(Se,Me)=>FpPow(Ee,Se,Me),div:(Se,Me)=>mod(Se*invert(Me,c),c),sqrN:Se=>Se*Se,addN:(Se,Me)=>Se+Me,subN:(Se,Me)=>Se-Me,mulN:(Se,Me)=>Se*Me,inv:Se=>invert(Se,c),sqrt:ae||(Se=>(xe||(xe=FpSqrt(c)),xe(Ee,Se))),toBytes:Se=>n?numberToBytesLE(Se,me):numberToBytesBE(Se,me),fromBytes:(Se,Me=!0)=>{if(he){if(!he.includes(Se.length)||Se.length>me)throw new Error("Field.fromBytes: expected "+he+" bytes, got "+Se.length);const $e=new Uint8Array(me);$e.set(Se,n?0:$e.length-Se.length),Se=$e}if(Se.length!==me)throw new Error("Field.fromBytes: expected "+me+" bytes, got "+Se.length);let Be=n?bytesToNumberLE(Se):bytesToNumberBE(Se);if(le&&(Be=mod(Be,c)),!Me&&!Ee.isValid(Be))throw new Error("invalid field element: outside of range 0..ORDER");return Be},invertBatch:Se=>FpInvertBatch(Ee,Se),cmov:(Se,Me,Be)=>Be?Me:Se});return Object.freeze(Ee)}function getFieldBytesLength(c){if(typeof c!="bigint")throw new Error("field order must be bigint");const t=c.toString(2).length;return Math.ceil(t/8)}function getMinHashLength(c){const t=getFieldBytesLength(c);return t+Math.ceil(t/2)}function mapHashToField(c,t,n=!1){const ie=c.length,fe=getFieldBytesLength(t),ae=getMinHashLength(t);if(ie<16||ie<ae||ie>1024)throw new Error("expected "+ae+"-1024 bytes of input, got "+ie);const le=n?bytesToNumberLE(c):bytesToNumberBE(c),he=mod(le,t-_1n$4)+_1n$4;return n?numberToBytesLE(he,fe):numberToBytesBE(he,fe)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$3=BigInt(1);function negateCt(c,t){const n=t.negate();return c?n:t}function normalizeZ(c,t){const n=FpInvertBatch(c.Fp,t.map(ie=>ie.Z));return t.map((ie,fe)=>c.fromAffine(ie.toAffine(n[fe])))}function validateW(c,t){if(!Number.isSafeInteger(c)||c<=0||c>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+c)}function calcWOpts(c,t){validateW(c,t);const n=Math.ceil(t/c)+1,ie=2**(c-1),fe=2**c,ae=bitMask(c),le=BigInt(c);return{windows:n,windowSize:ie,mask:ae,maxNumber:fe,shiftBy:le}}function calcOffsets(c,t,n){const{windowSize:ie,mask:fe,maxNumber:ae,shiftBy:le}=n;let he=Number(c&fe),ye=c>>le;he>ie&&(he-=ae,ye+=_1n$3);const me=t*ie,xe=me+Math.abs(he)-1,Ee=he===0,Se=he<0,Me=t%2!==0;return{nextN:ye,offset:xe,isZero:Ee,isNeg:Se,isNegF:Me,offsetF:me}}function validateMSMPoints(c,t){if(!Array.isArray(c))throw new Error("array expected");c.forEach((n,ie)=>{if(!(n instanceof t))throw new Error("invalid point at index "+ie)})}function validateMSMScalars(c,t){if(!Array.isArray(c))throw new Error("array of scalars expected");c.forEach((n,ie)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+ie)})}const pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(c){return pointWindowSizes.get(c)||1}function assert0(c){if(c!==_0n$2)throw new Error("invalid wNAF")}class wNAF{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,ie=this.ZERO){let fe=t;for(;n>_0n$2;)n&_1n$3&&(ie=ie.add(fe)),fe=fe.double(),n>>=_1n$3;return ie}precomputeWindow(t,n){const{windows:ie,windowSize:fe}=calcWOpts(n,this.bits),ae=[];let le=t,he=le;for(let ye=0;ye<ie;ye++){he=le,ae.push(he);for(let me=1;me<fe;me++)he=he.add(le),ae.push(he);le=he.double()}return ae}wNAF(t,n,ie){if(!this.Fn.isValid(ie))throw new Error("invalid scalar");let fe=this.ZERO,ae=this.BASE;const le=calcWOpts(t,this.bits);for(let he=0;he<le.windows;he++){const{nextN:ye,offset:me,isZero:xe,isNeg:Ee,isNegF:Se,offsetF:Me}=calcOffsets(ie,he,le);ie=ye,xe?ae=ae.add(negateCt(Se,n[Me])):fe=fe.add(negateCt(Ee,n[me]))}return assert0(ie),{p:fe,f:ae}}wNAFUnsafe(t,n,ie,fe=this.ZERO){const ae=calcWOpts(t,this.bits);for(let le=0;le<ae.windows&&ie!==_0n$2;le++){const{nextN:he,offset:ye,isZero:me,isNeg:xe}=calcOffsets(ie,le,ae);if(ie=he,!me){const Ee=n[ye];fe=fe.add(xe?Ee.negate():Ee)}}return assert0(ie),fe}getPrecomputes(t,n,ie){let fe=pointPrecomputes.get(n);return fe||(fe=this.precomputeWindow(n,t),t!==1&&(typeof ie=="function"&&(fe=ie(fe)),pointPrecomputes.set(n,fe))),fe}cached(t,n,ie){const fe=getW(t);return this.wNAF(fe,this.getPrecomputes(fe,t,ie),n)}unsafe(t,n,ie,fe){const ae=getW(t);return ae===1?this._unsafeLadder(t,n,fe):this.wNAFUnsafe(ae,this.getPrecomputes(ae,t,ie),n,fe)}createCache(t,n){validateW(n,this.bits),pointWindowSizes.set(t,n),pointPrecomputes.delete(t)}hasCache(t){return getW(t)!==1}}function mulEndoUnsafe(c,t,n,ie){let fe=t,ae=c.ZERO,le=c.ZERO;for(;n>_0n$2||ie>_0n$2;)n&_1n$3&&(ae=ae.add(fe)),ie&_1n$3&&(le=le.add(fe)),fe=fe.double(),n>>=_1n$3,ie>>=_1n$3;return{p1:ae,p2:le}}function pippenger(c,t,n,ie){validateMSMPoints(n,c),validateMSMScalars(ie,t);const fe=n.length,ae=ie.length;if(fe!==ae)throw new Error("arrays of points and scalars must have equal length");const le=c.ZERO,he=bitLen(BigInt(fe));let ye=1;he>12?ye=he-3:he>4?ye=he-2:he>0&&(ye=2);const me=bitMask(ye),xe=new Array(Number(me)+1).fill(le),Ee=Math.floor((t.BITS-1)/ye)*ye;let Se=le;for(let Me=Ee;Me>=0;Me-=ye){xe.fill(le);for(let $e=0;$e<ae;$e++){const Ce=ie[$e],ke=Number(Ce>>BigInt(Me)&me);xe[ke]=xe[ke].add(n[$e])}let Be=le;for(let $e=xe.length-1,Ce=le;$e>0;$e--)Ce=Ce.add(xe[$e]),Be=Be.add(Ce);if(Se=Se.add(Be),Me!==0)for(let $e=0;$e<ye;$e++)Se=Se.double()}return Se}function createField(c,t,n){if(t){if(t.ORDER!==c)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField(t),t}else return Field(c,{isLE:n})}function _createCurveFields(c,t,n={},ie){if(ie===void 0&&(ie=c==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${c} CURVE object`);for(const ye of["p","n","h"]){const me=t[ye];if(!(typeof me=="bigint"&&me>_0n$2))throw new Error(`CURVE.${ye} must be positive bigint`)}const fe=createField(t.p,n.Fp,ie),ae=createField(t.n,n.Fn,ie),he=["Gx","Gy","a",c==="weierstrass"?"b":"d"];for(const ye of he)if(!fe.isValid(t[ye]))throw new Error(`CURVE.${ye} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:fe,Fn:ae}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$1=BigInt(0),_1n$2=BigInt(1),_2n$3=BigInt(2),_8n$1=BigInt(8);function isEdValidXY(c,t,n,ie){const fe=c.sqr(n),ae=c.sqr(ie),le=c.add(c.mul(t.a,fe),ae),he=c.add(c.ONE,c.mul(t.d,c.mul(fe,ae)));return c.eql(le,he)}function edwards$1(c,t={}){const n=_createCurveFields("edwards",c,t,t.FpFnLE),{Fp:ie,Fn:fe}=n;let ae=n.CURVE;const{h:le}=ae;_validateObject(t,{},{uvRatio:"function"});const he=_2n$3<<BigInt(fe.BYTES*8)-_1n$2,ye=Ce=>ie.create(Ce),me=t.uvRatio||((Ce,ke)=>{try{return{isValid:!0,value:ie.sqrt(ie.div(Ce,ke))}}catch{return{isValid:!1,value:_0n$1}}});if(!isEdValidXY(ie,ae,ae.Gx,ae.Gy))throw new Error("bad curve params: generator point");function xe(Ce,ke,Pe=!1){const Ue=Pe?_1n$2:_0n$1;return aInRange("coordinate "+Ce,ke,Ue,he),ke}function Ee(Ce){if(!(Ce instanceof Be))throw new Error("ExtendedPoint expected")}const Se=memoized((Ce,ke)=>{const{X:Pe,Y:Ue,Z:qe}=Ce,He=Ce.is0();ke==null&&(ke=He?_8n$1:ie.inv(qe));const Ve=ye(Pe*ke),Ye=ye(Ue*ke),Qe=ie.mul(qe,ke);if(He)return{x:_0n$1,y:_1n$2};if(Qe!==_1n$2)throw new Error("invZ was invalid");return{x:Ve,y:Ye}}),Me=memoized(Ce=>{const{a:ke,d:Pe}=ae;if(Ce.is0())throw new Error("bad point: ZERO");const{X:Ue,Y:qe,Z:He,T:Ve}=Ce,Ye=ye(Ue*Ue),Qe=ye(qe*qe),Ke=ye(He*He),Pt=ye(Ke*Ke),_e=ye(Ye*ke),se=ye(Ke*ye(_e+Qe)),ce=ye(Pt+ye(Pe*ye(Ye*Qe)));if(se!==ce)throw new Error("bad point: equation left != right (1)");const de=ye(Ue*qe),pe=ye(He*Ve);if(de!==pe)throw new Error("bad point: equation left != right (2)");return!0});class Be{constructor(ke,Pe,Ue,qe){this.X=xe("x",ke),this.Y=xe("y",Pe),this.Z=xe("z",Ue,!0),this.T=xe("t",qe),Object.freeze(this)}static CURVE(){return ae}static fromAffine(ke){if(ke instanceof Be)throw new Error("extended point not allowed");const{x:Pe,y:Ue}=ke||{};return xe("x",Pe),xe("y",Ue),new Be(Pe,Ue,_1n$2,ye(Pe*Ue))}static fromBytes(ke,Pe=!1){const Ue=ie.BYTES,{a:qe,d:He}=ae;ke=copyBytes(_abytes2(ke,Ue,"point")),_abool2(Pe,"zip215");const Ve=copyBytes(ke),Ye=ke[Ue-1];Ve[Ue-1]=Ye&-129;const Qe=bytesToNumberLE(Ve),Ke=Pe?he:ie.ORDER;aInRange("point.y",Qe,_0n$1,Ke);const Pt=ye(Qe*Qe),_e=ye(Pt-_1n$2),se=ye(He*Pt-qe);let{isValid:ce,value:de}=me(_e,se);if(!ce)throw new Error("bad point: invalid y coordinate");const pe=(de&_1n$2)===_1n$2,ve=(Ye&128)!==0;if(!Pe&&de===_0n$1&&ve)throw new Error("bad point: x=0 and x_0=1");return ve!==pe&&(de=ye(-de)),Be.fromAffine({x:de,y:Qe})}static fromHex(ke,Pe=!1){return Be.fromBytes(ensureBytes("point",ke),Pe)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(ke=8,Pe=!0){return $e.createCache(this,ke),Pe||this.multiply(_2n$3),this}assertValidity(){Me(this)}equals(ke){Ee(ke);const{X:Pe,Y:Ue,Z:qe}=this,{X:He,Y:Ve,Z:Ye}=ke,Qe=ye(Pe*Ye),Ke=ye(He*qe),Pt=ye(Ue*Ye),_e=ye(Ve*qe);return Qe===Ke&&Pt===_e}is0(){return this.equals(Be.ZERO)}negate(){return new Be(ye(-this.X),this.Y,this.Z,ye(-this.T))}double(){const{a:ke}=ae,{X:Pe,Y:Ue,Z:qe}=this,He=ye(Pe*Pe),Ve=ye(Ue*Ue),Ye=ye(_2n$3*ye(qe*qe)),Qe=ye(ke*He),Ke=Pe+Ue,Pt=ye(ye(Ke*Ke)-He-Ve),_e=Qe+Ve,se=_e-Ye,ce=Qe-Ve,de=ye(Pt*se),pe=ye(_e*ce),ve=ye(Pt*ce),we=ye(se*_e);return new Be(de,pe,we,ve)}add(ke){Ee(ke);const{a:Pe,d:Ue}=ae,{X:qe,Y:He,Z:Ve,T:Ye}=this,{X:Qe,Y:Ke,Z:Pt,T:_e}=ke,se=ye(qe*Qe),ce=ye(He*Ke),de=ye(Ye*Ue*_e),pe=ye(Ve*Pt),ve=ye((qe+He)*(Qe+Ke)-se-ce),we=pe-de,Ae=pe+de,ge=ye(ce-Pe*se),ue=ye(ve*we),be=ye(Ae*ge),Re=ye(ve*ge),Ne=ye(we*Ae);return new Be(ue,be,Ne,Re)}subtract(ke){return this.add(ke.negate())}multiply(ke){if(!fe.isValidNot0(ke))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:Pe,f:Ue}=$e.cached(this,ke,qe=>normalizeZ(Be,qe));return normalizeZ(Be,[Pe,Ue])[0]}multiplyUnsafe(ke,Pe=Be.ZERO){if(!fe.isValid(ke))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return ke===_0n$1?Be.ZERO:this.is0()||ke===_1n$2?this:$e.unsafe(this,ke,Ue=>normalizeZ(Be,Ue),Pe)}isSmallOrder(){return this.multiplyUnsafe(le).is0()}isTorsionFree(){return $e.unsafe(this,ae.n).is0()}toAffine(ke){return Se(this,ke)}clearCofactor(){return le===_1n$2?this:this.multiplyUnsafe(le)}toBytes(){const{x:ke,y:Pe}=this.toAffine(),Ue=ie.toBytes(Pe);return Ue[Ue.length-1]|=ke&_1n$2?128:0,Ue}toHex(){return bytesToHex(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(ke){return normalizeZ(Be,ke)}static msm(ke,Pe){return pippenger(Be,fe,ke,Pe)}_setWindowSize(ke){this.precompute(ke)}toRawBytes(){return this.toBytes()}}Be.BASE=new Be(ae.Gx,ae.Gy,_1n$2,ye(ae.Gx*ae.Gy)),Be.ZERO=new Be(_0n$1,_1n$2,_1n$2,_0n$1),Be.Fp=ie,Be.Fn=fe;const $e=new wNAF(Be,fe.BITS);return Be.BASE.precompute(8),Be}function eddsa$1(c,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');_validateObject(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:ie}=n,{BASE:fe,Fp:ae,Fn:le}=c,he=n.randomBytes||randomBytes,ye=n.adjustScalarBytes||(Ke=>Ke),me=n.domain||((Ke,Pt,_e)=>{if(_abool2(_e,"phflag"),Pt.length||_e)throw new Error("Contexts/pre-hash are not supported");return Ke});function xe(Ke){return le.create(bytesToNumberLE(Ke))}function Ee(Ke){const Pt=Ue.secretKey;Ke=ensureBytes("private key",Ke,Pt);const _e=ensureBytes("hashed private key",t(Ke),2*Pt),se=ye(_e.slice(0,Pt)),ce=_e.slice(Pt,2*Pt),de=xe(se);return{head:se,prefix:ce,scalar:de}}function Se(Ke){const{head:Pt,prefix:_e,scalar:se}=Ee(Ke),ce=fe.multiply(se),de=ce.toBytes();return{head:Pt,prefix:_e,scalar:se,point:ce,pointBytes:de}}function Me(Ke){return Se(Ke).pointBytes}function Be(Ke=Uint8Array.of(),...Pt){const _e=concatBytes(...Pt);return xe(t(me(_e,ensureBytes("context",Ke),!!ie)))}function $e(Ke,Pt,_e={}){Ke=ensureBytes("message",Ke),ie&&(Ke=ie(Ke));const{prefix:se,scalar:ce,pointBytes:de}=Se(Pt),pe=Be(_e.context,se,Ke),ve=fe.multiply(pe).toBytes(),we=Be(_e.context,ve,de,Ke),Ae=le.create(pe+we*ce);if(!le.isValid(Ae))throw new Error("sign failed: invalid s");const ge=concatBytes(ve,le.toBytes(Ae));return _abytes2(ge,Ue.signature,"result")}const Ce={zip215:!0};function ke(Ke,Pt,_e,se=Ce){const{context:ce,zip215:de}=se,pe=Ue.signature;Ke=ensureBytes("signature",Ke,pe),Pt=ensureBytes("message",Pt),_e=ensureBytes("publicKey",_e,Ue.publicKey),de!==void 0&&_abool2(de,"zip215"),ie&&(Pt=ie(Pt));const ve=pe/2,we=Ke.subarray(0,ve),Ae=bytesToNumberLE(Ke.subarray(ve,pe));let ge,ue,be;try{ge=c.fromBytes(_e,de),ue=c.fromBytes(we,de),be=fe.multiplyUnsafe(Ae)}catch{return!1}if(!de&&ge.isSmallOrder())return!1;const Re=Be(ce,ue.toBytes(),ge.toBytes(),Pt);return ue.add(ge.multiplyUnsafe(Re)).subtract(be).clearCofactor().is0()}const Pe=ae.BYTES,Ue={secretKey:Pe,publicKey:Pe,signature:2*Pe,seed:Pe};function qe(Ke=he(Ue.seed)){return _abytes2(Ke,Ue.seed,"seed")}function He(Ke){const Pt=Qe.randomSecretKey(Ke);return{secretKey:Pt,publicKey:Me(Pt)}}function Ve(Ke){return isBytes(Ke)&&Ke.length===le.BYTES}function Ye(Ke,Pt){try{return!!c.fromBytes(Ke,Pt)}catch{return!1}}const Qe={getExtendedPublicKey:Se,randomSecretKey:qe,isValidSecretKey:Ve,isValidPublicKey:Ye,toMontgomery(Ke){const{y:Pt}=c.fromBytes(Ke),_e=Ue.publicKey,se=_e===32;if(!se&&_e!==57)throw new Error("only defined for 25519 and 448");const ce=se?ae.div(_1n$2+Pt,_1n$2-Pt):ae.div(Pt-_1n$2,Pt+_1n$2);return ae.toBytes(ce)},toMontgomerySecret(Ke){const Pt=Ue.secretKey;_abytes2(Ke,Pt);const _e=t(Ke.subarray(0,Pt));return ye(_e).subarray(0,Pt)},randomPrivateKey:qe,precompute(Ke=8,Pt=c.BASE){return Pt.precompute(Ke,!1)}};return Object.freeze({keygen:He,getPublicKey:Me,sign:$e,verify:ke,utils:Qe,Point:c,lengths:Ue})}function _eddsa_legacy_opts_to_new(c){const t={a:c.a,d:c.d,p:c.Fp.ORDER,n:c.n,h:c.h,Gx:c.Gx,Gy:c.Gy},n=c.Fp,ie=Field(t.n,c.nBitLength,!0),fe={Fp:n,Fn:ie,uvRatio:c.uvRatio},ae={randomBytes:c.randomBytes,adjustScalarBytes:c.adjustScalarBytes,domain:c.domain,prehash:c.prehash,mapToCurve:c.mapToCurve};return{CURVE:t,curveOpts:fe,hash:c.hash,eddsaOpts:ae}}function _eddsa_new_output_to_legacy(c,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:c,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function twistedEdwards(c){const{CURVE:t,curveOpts:n,hash:ie,eddsaOpts:fe}=_eddsa_legacy_opts_to_new(c),ae=edwards$1(t,n),le=eddsa$1(ae,ie,fe);return _eddsa_new_output_to_legacy(c,le)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _1n$1=BigInt(1),_2n$2=BigInt(2);BigInt(3);const _5n=BigInt(5),_8n=BigInt(8),ed25519_CURVE_p=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ed25519_CURVE={p:ed25519_CURVE_p,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:_8n,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ed25519_pow_2_252_3(c){const t=BigInt(10),n=BigInt(20),ie=BigInt(40),fe=BigInt(80),ae=ed25519_CURVE_p,he=c*c%ae*c%ae,ye=pow2(he,_2n$2,ae)*he%ae,me=pow2(ye,_1n$1,ae)*c%ae,xe=pow2(me,_5n,ae)*me%ae,Ee=pow2(xe,t,ae)*xe%ae,Se=pow2(Ee,n,ae)*Ee%ae,Me=pow2(Se,ie,ae)*Se%ae,Be=pow2(Me,fe,ae)*Me%ae,$e=pow2(Be,fe,ae)*Me%ae,Ce=pow2($e,t,ae)*xe%ae;return{pow_p_5_8:pow2(Ce,_2n$2,ae)*c%ae,b2:he}}function adjustScalarBytes(c){return c[0]&=248,c[31]&=127,c[31]|=64,c}const ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function uvRatio(c,t){const n=ed25519_CURVE_p,ie=mod(t*t*t,n),fe=mod(ie*ie*t,n),ae=ed25519_pow_2_252_3(c*fe).pow_p_5_8;let le=mod(c*ie*ae,n);const he=mod(t*le*le,n),ye=le,me=mod(le*ED25519_SQRT_M1,n),xe=he===c,Ee=he===mod(-c,n),Se=he===mod(-c*ED25519_SQRT_M1,n);return xe&&(le=ye),(Ee||Se)&&(le=me),isNegativeLE(le,n)&&(le=mod(-le,n)),{isValid:xe||Ee,value:le}}const Fp=Field(ed25519_CURVE.p,{isLE:!0}),ed25519Defaults={...ed25519_CURVE,Fp,hash:sha512$3,adjustScalarBytes,uvRatio},ed25519=twistedEdwards(ed25519Defaults);var safeBuffer$2={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(c,t){var n=require$$0$4,ie=n.Buffer;function fe(le,he){for(var ye in le)he[ye]=le[ye]}ie.from&&ie.alloc&&ie.allocUnsafe&&ie.allocUnsafeSlow?c.exports=n:(fe(n,t),t.Buffer=ae);function ae(le,he,ye){return ie(le,he,ye)}ae.prototype=Object.create(ie.prototype),fe(ie,ae),ae.from=function(le,he,ye){if(typeof le=="number")throw new TypeError("Argument must not be a number");return ie(le,he,ye)},ae.alloc=function(le,he,ye){if(typeof le!="number")throw new TypeError("Argument must be a number");var me=ie(le);return he!==void 0?typeof ye=="string"?me.fill(he,ye):me.fill(he):me.fill(0),me},ae.allocUnsafe=function(le){if(typeof le!="number")throw new TypeError("Argument must be a number");return ie(le)},ae.allocUnsafeSlow=function(le){if(typeof le!="number")throw new TypeError("Argument must be a number");return n.SlowBuffer(le)}})(safeBuffer$2,safeBuffer$2.exports);var safeBufferExports=safeBuffer$2.exports,_Buffer=safeBufferExports.Buffer;function base$4(c){if(c.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var ie=0;ie<c.length;ie++){var fe=c.charAt(ie),ae=fe.charCodeAt(0);if(t[ae]!==255)throw new TypeError(fe+" is ambiguous");t[ae]=ie}var le=c.length,he=c.charAt(0),ye=Math.log(le)/Math.log(256),me=Math.log(256)/Math.log(le);function xe(Me){if((Array.isArray(Me)||Me instanceof Uint8Array)&&(Me=_Buffer.from(Me)),!_Buffer.isBuffer(Me))throw new TypeError("Expected Buffer");if(Me.length===0)return"";for(var Be=0,$e=0,Ce=0,ke=Me.length;Ce!==ke&&Me[Ce]===0;)Ce++,Be++;for(var Pe=(ke-Ce)*me+1>>>0,Ue=new Uint8Array(Pe);Ce!==ke;){for(var qe=Me[Ce],He=0,Ve=Pe-1;(qe!==0||He<$e)&&Ve!==-1;Ve--,He++)qe+=256*Ue[Ve]>>>0,Ue[Ve]=qe%le>>>0,qe=qe/le>>>0;if(qe!==0)throw new Error("Non-zero carry");$e=He,Ce++}for(var Ye=Pe-$e;Ye!==Pe&&Ue[Ye]===0;)Ye++;for(var Qe=he.repeat(Be);Ye<Pe;++Ye)Qe+=c.charAt(Ue[Ye]);return Qe}function Ee(Me){if(typeof Me!="string")throw new TypeError("Expected String");if(Me.length===0)return _Buffer.alloc(0);for(var Be=0,$e=0,Ce=0;Me[Be]===he;)$e++,Be++;for(var ke=(Me.length-Be)*ye+1>>>0,Pe=new Uint8Array(ke);Be<Me.length;){var Ue=Me.charCodeAt(Be);if(Ue>255)return;var qe=t[Ue];if(qe===255)return;for(var He=0,Ve=ke-1;(qe!==0||He<Ce)&&Ve!==-1;Ve--,He++)qe+=le*Pe[Ve]>>>0,Pe[Ve]=qe%256>>>0,qe=qe/256>>>0;if(qe!==0)throw new Error("Non-zero carry");Ce=He,Be++}for(var Ye=ke-Ce;Ye!==ke&&Pe[Ye]===0;)Ye++;var Qe=_Buffer.allocUnsafe($e+(ke-Ye));Qe.fill(0,0,$e);for(var Ke=$e;Ye!==ke;)Qe[Ke++]=Pe[Ye++];return Qe}function Se(Me){var Be=Ee(Me);if(Be)return Be;throw new Error("Non-base"+le+" character")}return{encode:xe,decodeUnsafe:Ee,decode:Se}}var src$7=base$4;const e$1=getDefaultExportFromCjs$2(src$7);var basex=src$7,ALPHABET$1="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",bs58=basex(ALPHABET$1);const o$1=getDefaultExportFromCjs$2(bs58),sha256$4=sha256$5;var lib={};function inRange(c,t,n){return t<=c&&c<=n}function ToDictionary(c){if(c===void 0)return{};if(c===Object(c))return c;throw TypeError("Could not convert argument to dictionary")}function stringToCodePoints(c){for(var t=String(c),n=t.length,ie=0,fe=[];ie<n;){var ae=t.charCodeAt(ie);if(ae<55296||ae>57343)fe.push(ae);else if(56320<=ae&&ae<=57343)fe.push(65533);else if(55296<=ae&&ae<=56319)if(ie===n-1)fe.push(65533);else{var le=c.charCodeAt(ie+1);if(56320<=le&&le<=57343){var he=ae&1023,ye=le&1023;fe.push(65536+(he<<10)+ye),ie+=1}else fe.push(65533)}ie+=1}return fe}function codePointsToString(c){for(var t="",n=0;n<c.length;++n){var ie=c[n];ie<=65535?t+=String.fromCharCode(ie):(ie-=65536,t+=String.fromCharCode((ie>>10)+55296,(ie&1023)+56320))}return t}var end_of_stream=-1;function Stream(c){this.tokens=[].slice.call(c)}Stream.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():end_of_stream},prepend:function(c){if(Array.isArray(c))for(var t=c;t.length;)this.tokens.unshift(t.pop());else this.tokens.unshift(c)},push:function(c){if(Array.isArray(c))for(var t=c;t.length;)this.tokens.push(t.shift());else this.tokens.push(c)}};var finished=-1;function decoderError(c,t){if(c)throw TypeError("Decoder error");return t||65533}var DEFAULT_ENCODING="utf-8";function TextDecoder$1(c,t){if(!(this instanceof TextDecoder$1))return new TextDecoder$1(c,t);if(c=c!==void 0?String(c).toLowerCase():DEFAULT_ENCODING,c!==DEFAULT_ENCODING)throw new Error("Encoding not supported. Only utf-8 is supported");t=ToDictionary(t),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=!!t.fatal,this._ignoreBOM=!!t.ignoreBOM,Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}TextDecoder$1.prototype={decode:function(t,n){var ie;typeof t=="object"&&t instanceof ArrayBuffer?ie=new Uint8Array(t):typeof t=="object"&&"buffer"in t&&t.buffer instanceof ArrayBuffer?ie=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):ie=new Uint8Array(0),n=ToDictionary(n),this._streaming||(this._decoder=new UTF8Decoder({fatal:this._fatal}),this._BOMseen=!1),this._streaming=!!n.stream;for(var fe=new Stream(ie),ae=[],le;!fe.endOfStream()&&(le=this._decoder.handler(fe,fe.read()),le!==finished);)le!==null&&(Array.isArray(le)?ae.push.apply(ae,le):ae.push(le));if(!this._streaming){do{if(le=this._decoder.handler(fe,fe.read()),le===finished)break;le!==null&&(Array.isArray(le)?ae.push.apply(ae,le):ae.push(le))}while(!fe.endOfStream());this._decoder=null}return ae.length&&["utf-8"].indexOf(this.encoding)!==-1&&!this._ignoreBOM&&!this._BOMseen&&(ae[0]===65279?(this._BOMseen=!0,ae.shift()):this._BOMseen=!0),codePointsToString(ae)}};function TextEncoder$1(c,t){if(!(this instanceof TextEncoder$1))return new TextEncoder$1(c,t);if(c=c!==void 0?String(c).toLowerCase():DEFAULT_ENCODING,c!==DEFAULT_ENCODING)throw new Error("Encoding not supported. Only utf-8 is supported");t=ToDictionary(t),this._streaming=!1,this._encoder=null,this._options={fatal:!!t.fatal},Object.defineProperty(this,"encoding",{value:"utf-8"})}TextEncoder$1.prototype={encode:function(t,n){t=t?String(t):"",n=ToDictionary(n),this._streaming||(this._encoder=new UTF8Encoder(this._options)),this._streaming=!!n.stream;for(var ie=[],fe=new Stream(stringToCodePoints(t)),ae;!fe.endOfStream()&&(ae=this._encoder.handler(fe,fe.read()),ae!==finished);)Array.isArray(ae)?ie.push.apply(ie,ae):ie.push(ae);if(!this._streaming){for(;ae=this._encoder.handler(fe,fe.read()),ae!==finished;)Array.isArray(ae)?ie.push.apply(ie,ae):ie.push(ae);this._encoder=null}return new Uint8Array(ie)}};function UTF8Decoder(c){var t=c.fatal,n=0,ie=0,fe=0,ae=128,le=191;this.handler=function(he,ye){if(ye===end_of_stream&&fe!==0)return fe=0,decoderError(t);if(ye===end_of_stream)return finished;if(fe===0){if(inRange(ye,0,127))return ye;if(inRange(ye,194,223))fe=1,n=ye-192;else if(inRange(ye,224,239))ye===224&&(ae=160),ye===237&&(le=159),fe=2,n=ye-224;else if(inRange(ye,240,244))ye===240&&(ae=144),ye===244&&(le=143),fe=3,n=ye-240;else return decoderError(t);return n=n<<6*fe,null}if(!inRange(ye,ae,le))return n=fe=ie=0,ae=128,le=191,he.prepend(ye),decoderError(t);if(ae=128,le=191,ie+=1,n+=ye-128<<6*(fe-ie),ie!==fe)return null;var me=n;return n=fe=ie=0,me}}function UTF8Encoder(c){c.fatal,this.handler=function(t,n){if(n===end_of_stream)return finished;if(inRange(n,0,127))return n;var ie,fe;inRange(n,128,2047)?(ie=1,fe=192):inRange(n,2048,65535)?(ie=2,fe=224):inRange(n,65536,1114111)&&(ie=3,fe=240);for(var ae=[(n>>6*ie)+fe];ie>0;){var le=n>>6*(ie-1);ae.push(128|le&63),ie-=1}return ae}}const encoding$1=Object.freeze(Object.defineProperty({__proto__:null,TextDecoder:TextDecoder$1,TextEncoder:TextEncoder$1},Symbol.toStringTag,{value:"Module"})),require$$2$2=getAugmentedNamespace(encoding$1);var __createBinding$9=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(c,t,n,ie){ie===void 0&&(ie=n),Object.defineProperty(c,ie,{enumerable:!0,get:function(){return t[n]}})}:function(c,t,n,ie){ie===void 0&&(ie=n),c[ie]=t[n]}),__setModuleDefault$9=commonjsGlobal&&commonjsGlobal.__setModuleDefault||(Object.create?function(c,t){Object.defineProperty(c,"default",{enumerable:!0,value:t})}:function(c,t){c.default=t}),__decorate=commonjsGlobal&&commonjsGlobal.__decorate||function(c,t,n,ie){var fe=arguments.length,ae=fe<3?t:ie===null?ie=Object.getOwnPropertyDescriptor(t,n):ie,le;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")ae=Reflect.decorate(c,t,n,ie);else for(var he=c.length-1;he>=0;he--)(le=c[he])&&(ae=(fe<3?le(ae):fe>3?le(t,n,ae):le(t,n))||ae);return fe>3&&ae&&Object.defineProperty(t,n,ae),ae},__importStar$9=commonjsGlobal&&commonjsGlobal.__importStar||function(c){if(c&&c.__esModule)return c;var t={};if(c!=null)for(var n in c)n!=="default"&&Object.hasOwnProperty.call(c,n)&&__createBinding$9(t,c,n);return __setModuleDefault$9(t,c),t},__importDefault$9=commonjsGlobal&&commonjsGlobal.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(lib,"__esModule",{value:!0});var deserializeUnchecked_1=lib.deserializeUnchecked=deserialize_1=lib.deserialize=serialize_1=lib.serialize=lib.BinaryReader=lib.BinaryWriter=lib.BorshError=lib.baseDecode=lib.baseEncode=void 0;const bn_js_1$1=__importDefault$9(bnExports$3),bs58_1=__importDefault$9(bs58),encoding=__importStar$9(require$$2$2),ResolvedTextDecoder=typeof TextDecoder!="function"?encoding.TextDecoder:TextDecoder,textDecoder=new ResolvedTextDecoder("utf-8",{fatal:!0});function baseEncode(c){return typeof c=="string"&&(c=Buffer$7.from(c,"utf8")),bs58_1.default.encode(Buffer$7.from(c))}lib.baseEncode=baseEncode;function baseDecode(c){return Buffer$7.from(bs58_1.default.decode(c))}lib.baseDecode=baseDecode;const INITIAL_LENGTH=1024;class BorshError extends Error{constructor(t){super(t),this.fieldPath=[],this.originalMessage=t}addToFieldPath(t){this.fieldPath.splice(0,0,t),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}lib.BorshError=BorshError;class BinaryWriter{constructor(){this.buf=Buffer$7.alloc(INITIAL_LENGTH),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer$7.concat([this.buf,Buffer$7.alloc(INITIAL_LENGTH)]))}writeU8(t){this.maybeResize(),this.buf.writeUInt8(t,this.length),this.length+=1}writeU16(t){this.maybeResize(),this.buf.writeUInt16LE(t,this.length),this.length+=2}writeU32(t){this.maybeResize(),this.buf.writeUInt32LE(t,this.length),this.length+=4}writeU64(t){this.maybeResize(),this.writeBuffer(Buffer$7.from(new bn_js_1$1.default(t).toArray("le",8)))}writeU128(t){this.maybeResize(),this.writeBuffer(Buffer$7.from(new bn_js_1$1.default(t).toArray("le",16)))}writeU256(t){this.maybeResize(),this.writeBuffer(Buffer$7.from(new bn_js_1$1.default(t).toArray("le",32)))}writeU512(t){this.maybeResize(),this.writeBuffer(Buffer$7.from(new bn_js_1$1.default(t).toArray("le",64)))}writeBuffer(t){this.buf=Buffer$7.concat([Buffer$7.from(this.buf.subarray(0,this.length)),t,Buffer$7.alloc(INITIAL_LENGTH)]),this.length+=t.length}writeString(t){this.maybeResize();const n=Buffer$7.from(t,"utf8");this.writeU32(n.length),this.writeBuffer(n)}writeFixedArray(t){this.writeBuffer(Buffer$7.from(t))}writeArray(t,n){this.maybeResize(),this.writeU32(t.length);for(const ie of t)this.maybeResize(),n(ie)}toArray(){return this.buf.subarray(0,this.length)}}lib.BinaryWriter=BinaryWriter;function handlingRangeError(c,t,n){const ie=n.value;n.value=function(...fe){try{return ie.apply(this,fe)}catch(ae){if(ae instanceof RangeError){const le=ae.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(le)>=0)throw new BorshError("Reached the end of buffer when deserializing")}throw ae}}}class BinaryReader{constructor(t){this.buf=t,this.offset=0}readU8(){const t=this.buf.readUInt8(this.offset);return this.offset+=1,t}readU16(){const t=this.buf.readUInt16LE(this.offset);return this.offset+=2,t}readU32(){const t=this.buf.readUInt32LE(this.offset);return this.offset+=4,t}readU64(){const t=this.readBuffer(8);return new bn_js_1$1.default(t,"le")}readU128(){const t=this.readBuffer(16);return new bn_js_1$1.default(t,"le")}readU256(){const t=this.readBuffer(32);return new bn_js_1$1.default(t,"le")}readU512(){const t=this.readBuffer(64);return new bn_js_1$1.default(t,"le")}readBuffer(t){if(this.offset+t>this.buf.length)throw new BorshError(`Expected buffer length ${t} isn't within bounds`);const n=this.buf.slice(this.offset,this.offset+t);return this.offset+=t,n}readString(){const t=this.readU32(),n=this.readBuffer(t);try{return textDecoder.decode(n)}catch(ie){throw new BorshError(`Error decoding UTF-8 string: ${ie}`)}}readFixedArray(t){return new Uint8Array(this.readBuffer(t))}readArray(t){const n=this.readU32(),ie=Array();for(let fe=0;fe<n;++fe)ie.push(t());return ie}}__decorate([handlingRangeError],BinaryReader.prototype,"readU8",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU16",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU32",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU64",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU128",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU256",null);__decorate([handlingRangeError],BinaryReader.prototype,"readU512",null);__decorate([handlingRangeError],BinaryReader.prototype,"readString",null);__decorate([handlingRangeError],BinaryReader.prototype,"readFixedArray",null);__decorate([handlingRangeError],BinaryReader.prototype,"readArray",null);lib.BinaryReader=BinaryReader;function capitalizeFirstLetter(c){return c.charAt(0).toUpperCase()+c.slice(1)}function serializeField(c,t,n,ie,fe){try{if(typeof ie=="string")fe[`write${capitalizeFirstLetter(ie)}`](n);else if(ie instanceof Array)if(typeof ie[0]=="number"){if(n.length!==ie[0])throw new BorshError(`Expecting byte array of length ${ie[0]}, but got ${n.length} bytes`);fe.writeFixedArray(n)}else if(ie.length===2&&typeof ie[1]=="number"){if(n.length!==ie[1])throw new BorshError(`Expecting byte array of length ${ie[1]}, but got ${n.length} bytes`);for(let ae=0;ae<ie[1];ae++)serializeField(c,null,n[ae],ie[0],fe)}else fe.writeArray(n,ae=>{serializeField(c,t,ae,ie[0],fe)});else if(ie.kind!==void 0)switch(ie.kind){case"option":{n==null?fe.writeU8(0):(fe.writeU8(1),serializeField(c,t,n,ie.type,fe));break}case"map":{fe.writeU32(n.size),n.forEach((ae,le)=>{serializeField(c,t,le,ie.key,fe),serializeField(c,t,ae,ie.value,fe)});break}default:throw new BorshError(`FieldType ${ie} unrecognized`)}else serializeStruct(c,n,fe)}catch(ae){throw ae instanceof BorshError&&ae.addToFieldPath(t),ae}}function serializeStruct(c,t,n){if(typeof t.borshSerialize=="function"){t.borshSerialize(n);return}const ie=c.get(t.constructor);if(!ie)throw new BorshError(`Class ${t.constructor.name} is missing in schema`);if(ie.kind==="struct")ie.fields.map(([fe,ae])=>{serializeField(c,fe,t[fe],ae,n)});else if(ie.kind==="enum"){const fe=t[ie.field];for(let ae=0;ae<ie.values.length;++ae){const[le,he]=ie.values[ae];if(le===fe){n.writeU8(ae),serializeField(c,le,t[le],he,n);break}}}else throw new BorshError(`Unexpected schema kind: ${ie.kind} for ${t.constructor.name}`)}function serialize(c,t,n=BinaryWriter){const ie=new n;return serializeStruct(c,t,ie),ie.toArray()}var serialize_1=lib.serialize=serialize;function deserializeField(c,t,n,ie){try{if(typeof n=="string")return ie[`read${capitalizeFirstLetter(n)}`]();if(n instanceof Array){if(typeof n[0]=="number")return ie.readFixedArray(n[0]);if(typeof n[1]=="number"){const fe=[];for(let ae=0;ae<n[1];ae++)fe.push(deserializeField(c,null,n[0],ie));return fe}else return ie.readArray(()=>deserializeField(c,t,n[0],ie))}if(n.kind==="option")return ie.readU8()?deserializeField(c,t,n.type,ie):void 0;if(n.kind==="map"){let fe=new Map;const ae=ie.readU32();for(let le=0;le<ae;le++){const he=deserializeField(c,t,n.key,ie),ye=deserializeField(c,t,n.value,ie);fe.set(he,ye)}return fe}return deserializeStruct(c,n,ie)}catch(fe){throw fe instanceof BorshError&&fe.addToFieldPath(t),fe}}function deserializeStruct(c,t,n){if(typeof t.borshDeserialize=="function")return t.borshDeserialize(n);const ie=c.get(t);if(!ie)throw new BorshError(`Class ${t.name} is missing in schema`);if(ie.kind==="struct"){const fe={};for(const[ae,le]of c.get(t).fields)fe[ae]=deserializeField(c,ae,le,n);return new t(fe)}if(ie.kind==="enum"){const fe=n.readU8();if(fe>=ie.values.length)throw new BorshError(`Enum index: ${fe} is out of range`);const[ae,le]=ie.values[fe],he=deserializeField(c,ae,le,n);return new t({[ae]:he})}throw new BorshError(`Unexpected schema kind: ${ie.kind} for ${t.constructor.name}`)}function deserialize(c,t,n,ie=BinaryReader){const fe=new ie(n),ae=deserializeStruct(c,t,fe);if(fe.offset<n.length)throw new BorshError(`Unexpected ${n.length-fe.offset} bytes after deserialized data`);return ae}var deserialize_1=lib.deserialize=deserialize;function deserializeUnchecked(c,t,n,ie=BinaryReader){const fe=new ie(n);return deserializeStruct(c,t,fe)}deserializeUnchecked_1=lib.deserializeUnchecked=deserializeUnchecked;var Layout$1={};Object.defineProperty(Layout$1,"__esModule",{value:!0});Layout$1.s16=Layout$1.s8=Layout$1.nu64be=Layout$1.u48be=Layout$1.u40be=Layout$1.u32be=Layout$1.u24be=Layout$1.u16be=nu64=Layout$1.nu64=Layout$1.u48=Layout$1.u40=u32=Layout$1.u32=Layout$1.u24=u16=Layout$1.u16=u8=Layout$1.u8=offset=Layout$1.offset=Layout$1.greedy=Layout$1.Constant=Layout$1.UTF8=Layout$1.CString=Layout$1.Blob=Layout$1.Boolean=Layout$1.BitField=Layout$1.BitStructure=Layout$1.VariantLayout=Layout$1.Union=Layout$1.UnionLayoutDiscriminator=Layout$1.UnionDiscriminator=Layout$1.Structure=Layout$1.Sequence=Layout$1.DoubleBE=Layout$1.Double=Layout$1.FloatBE=Layout$1.Float=Layout$1.NearInt64BE=Layout$1.NearInt64=Layout$1.NearUInt64BE=Layout$1.NearUInt64=Layout$1.IntBE=Layout$1.Int=Layout$1.UIntBE=Layout$1.UInt=Layout$1.OffsetLayout=Layout$1.GreedyCount=Layout$1.ExternalLayout=Layout$1.bindConstructorLayout=Layout$1.nameWithProperty=Layout$1.Layout=Layout$1.uint8ArrayToBuffer=Layout$1.checkUint8Array=void 0;Layout$1.constant=Layout$1.utf8=Layout$1.cstr=blob=Layout$1.blob=Layout$1.unionLayoutDiscriminator=Layout$1.union=seq=Layout$1.seq=Layout$1.bits=struct=Layout$1.struct=Layout$1.f64be=Layout$1.f64=Layout$1.f32be=Layout$1.f32=Layout$1.ns64be=Layout$1.s48be=Layout$1.s40be=Layout$1.s32be=Layout$1.s24be=Layout$1.s16be=ns64=Layout$1.ns64=Layout$1.s48=Layout$1.s40=Layout$1.s32=Layout$1.s24=void 0;const buffer_1=require$$0$4;function checkUint8Array(c){if(!(c instanceof Uint8Array))throw new TypeError("b must be a Uint8Array")}Layout$1.checkUint8Array=checkUint8Array;function uint8ArrayToBuffer(c){return checkUint8Array(c),buffer_1.Buffer.from(c.buffer,c.byteOffset,c.length)}Layout$1.uint8ArrayToBuffer=uint8ArrayToBuffer;class Layout{constructor(t,n){if(!Number.isInteger(t))throw new TypeError("span must be an integer");this.span=t,this.property=n}makeDestinationObject(){return{}}getSpan(t,n){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(t){const n=Object.create(this.constructor.prototype);return Object.assign(n,this),n.property=t,n}fromArray(t){}}Layout$1.Layout=Layout;function nameWithProperty(c,t){return t.property?c+"["+t.property+"]":c}Layout$1.nameWithProperty=nameWithProperty;function bindConstructorLayout(c,t){if(typeof c!="function")throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(c,"layout_"))throw new Error("Class is already bound to a layout");if(!(t&&t instanceof Layout))throw new TypeError("layout must be a Layout");if(Object.prototype.hasOwnProperty.call(t,"boundConstructor_"))throw new Error("layout is already bound to a constructor");c.layout_=t,t.boundConstructor_=c,t.makeDestinationObject=()=>new c,Object.defineProperty(c.prototype,"encode",{value(n,ie){return t.encode(this,n,ie)},writable:!0}),Object.defineProperty(c,"decode",{value(n,ie){return t.decode(n,ie)},writable:!0})}Layout$1.bindConstructorLayout=bindConstructorLayout;class ExternalLayout extends Layout{isCount(){throw new Error("ExternalLayout is abstract")}}Layout$1.ExternalLayout=ExternalLayout;class GreedyCount extends ExternalLayout{constructor(t=1,n){if(!Number.isInteger(t)||0>=t)throw new TypeError("elementSpan must be a (positive) integer");super(-1,n),this.elementSpan=t}isCount(){return!0}decode(t,n=0){checkUint8Array(t);const ie=t.length-n;return Math.floor(ie/this.elementSpan)}encode(t,n,ie){return 0}}Layout$1.GreedyCount=GreedyCount;class OffsetLayout extends ExternalLayout{constructor(t,n=0,ie){if(!(t instanceof Layout))throw new TypeError("layout must be a Layout");if(!Number.isInteger(n))throw new TypeError("offset must be integer or undefined");super(t.span,ie||t.property),this.layout=t,this.offset=n}isCount(){return this.layout instanceof UInt||this.layout instanceof UIntBE}decode(t,n=0){return this.layout.decode(t,n+this.offset)}encode(t,n,ie=0){return this.layout.encode(t,n,ie+this.offset)}}Layout$1.OffsetLayout=OffsetLayout;class UInt extends Layout{constructor(t,n){if(super(t,n),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(t,n=0){return uint8ArrayToBuffer(t).readUIntLE(n,this.span)}encode(t,n,ie=0){return uint8ArrayToBuffer(n).writeUIntLE(t,ie,this.span),this.span}}Layout$1.UInt=UInt;class UIntBE extends Layout{constructor(t,n){if(super(t,n),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(t,n=0){return uint8ArrayToBuffer(t).readUIntBE(n,this.span)}encode(t,n,ie=0){return uint8ArrayToBuffer(n).writeUIntBE(t,ie,this.span),this.span}}Layout$1.UIntBE=UIntBE;class Int extends Layout{constructor(t,n){if(super(t,n),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(t,n=0){return uint8ArrayToBuffer(t).readIntLE(n,this.span)}encode(t,n,ie=0){return uint8ArrayToBuffer(n).writeIntLE(t,ie,this.span),this.span}}Layout$1.Int=Int;class IntBE extends Layout{constructor(t,n){if(super(t,n),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(t,n=0){return uint8ArrayToBuffer(t).readIntBE(n,this.span)}encode(t,n,ie=0){return uint8ArrayToBuffer(n).writeIntBE(t,ie,this.span),this.span}}Layout$1.IntBE=IntBE;const V2E32=Math.pow(2,32);function divmodInt64(c){const t=Math.floor(c/V2E32),n=c-t*V2E32;return{hi32:t,lo32:n}}function roundedInt64(c,t){return c*V2E32+t}class NearUInt64 extends Layout{constructor(t){super(8,t)}decode(t,n=0){const ie=uint8ArrayToBuffer(t),fe=ie.readUInt32LE(n),ae=ie.readUInt32LE(n+4);return roundedInt64(ae,fe)}encode(t,n,ie=0){const fe=divmodInt64(t),ae=uint8ArrayToBuffer(n);return ae.writeUInt32LE(fe.lo32,ie),ae.writeUInt32LE(fe.hi32,ie+4),8}}Layout$1.NearUInt64=NearUInt64;class NearUInt64BE extends Layout{constructor(t){super(8,t)}decode(t,n=0){const ie=uint8ArrayToBuffer(t),fe=ie.readUInt32BE(n),ae=ie.readUInt32BE(n+4);return roundedInt64(fe,ae)}encode(t,n,ie=0){const fe=divmodInt64(t),ae=uint8ArrayToBuffer(n);return ae.writeUInt32BE(fe.hi32,ie),ae.writeUInt32BE(fe.lo32,ie+4),8}}Layout$1.NearUInt64BE=NearUInt64BE;class NearInt64 extends Layout{constructor(t){super(8,t)}decode(t,n=0){const ie=uint8ArrayToBuffer(t),fe=ie.readUInt32LE(n),ae=ie.readInt32LE(n+4);return roundedInt64(ae,fe)}encode(t,n,ie=0){const fe=divmodInt64(t),ae=uint8ArrayToBuffer(n);return ae.writeUInt32LE(fe.lo32,ie),ae.writeInt32LE(fe.hi32,ie+4),8}}Layout$1.NearInt64=NearInt64;class NearInt64BE extends Layout{constructor(t){super(8,t)}decode(t,n=0){const ie=uint8ArrayToBuffer(t),fe=ie.readInt32BE(n),ae=ie.readUInt32BE(n+4);return roundedInt64(fe,ae)}encode(t,n,ie=0){const fe=divmodInt64(t),ae=uint8ArrayToBuffer(n);return ae.writeInt32BE(fe.hi32,ie),ae.writeUInt32BE(fe.lo32,ie+4),8}}Layout$1.NearInt64BE=NearInt64BE;class Float extends Layout{constructor(t){super(4,t)}decode(t,n=0){return uint8ArrayToBuffer(t).readFloatLE(n)}encode(t,n,ie=0){return uint8ArrayToBuffer(n).writeFloatLE(t,ie),4}}Layout$1.Float=Float;class FloatBE extends Layout{constructor(t){super(4,t)}decode(t,n=0){return uint8ArrayToBuffer(t).readFloatBE(n)}encode(t,n,ie=0){return uint8ArrayToBuffer(n).writeFloatBE(t,ie),4}}Layout$1.FloatBE=FloatBE;class Double extends Layout{constructor(t){super(8,t)}decode(t,n=0){return uint8ArrayToBuffer(t).readDoubleLE(n)}encode(t,n,ie=0){return uint8ArrayToBuffer(n).writeDoubleLE(t,ie),8}}Layout$1.Double=Double;class DoubleBE extends Layout{constructor(t){super(8,t)}decode(t,n=0){return uint8ArrayToBuffer(t).readDoubleBE(n)}encode(t,n,ie=0){return uint8ArrayToBuffer(n).writeDoubleBE(t,ie),8}}Layout$1.DoubleBE=DoubleBE;class Sequence extends Layout{constructor(t,n,ie){if(!(t instanceof Layout))throw new TypeError("elementLayout must be a Layout");if(!(n instanceof ExternalLayout&&n.isCount()||Number.isInteger(n)&&0<=n))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let fe=-1;!(n instanceof ExternalLayout)&&0<t.span&&(fe=n*t.span),super(fe,ie),this.elementLayout=t,this.count=n}getSpan(t,n=0){if(0<=this.span)return this.span;let ie=0,fe=this.count;if(fe instanceof ExternalLayout&&(fe=fe.decode(t,n)),0<this.elementLayout.span)ie=fe*this.elementLayout.span;else{let ae=0;for(;ae<fe;)ie+=this.elementLayout.getSpan(t,n+ie),++ae}return ie}decode(t,n=0){const ie=[];let fe=0,ae=this.count;for(ae instanceof ExternalLayout&&(ae=ae.decode(t,n));fe<ae;)ie.push(this.elementLayout.decode(t,n)),n+=this.elementLayout.getSpan(t,n),fe+=1;return ie}encode(t,n,ie=0){const fe=this.elementLayout,ae=t.reduce((le,he)=>le+fe.encode(he,n,ie+le),0);return this.count instanceof ExternalLayout&&this.count.encode(t.length,n,ie),ae}}Layout$1.Sequence=Sequence;class Structure extends Layout{constructor(t,n,ie){if(!(Array.isArray(t)&&t.reduce((ae,le)=>ae&&le instanceof Layout,!0)))throw new TypeError("fields must be array of Layout instances");typeof n=="boolean"&&ie===void 0&&(ie=n,n=void 0);for(const ae of t)if(0>ae.span&&ae.property===void 0)throw new Error("fields cannot contain unnamed variable-length layout");let fe=-1;try{fe=t.reduce((ae,le)=>ae+le.getSpan(),0)}catch{}super(fe,n),this.fields=t,this.decodePrefixes=!!ie}getSpan(t,n=0){if(0<=this.span)return this.span;let ie=0;try{ie=this.fields.reduce((fe,ae)=>{const le=ae.getSpan(t,n);return n+=le,fe+le},0)}catch{throw new RangeError("indeterminate span")}return ie}decode(t,n=0){checkUint8Array(t);const ie=this.makeDestinationObject();for(const fe of this.fields)if(fe.property!==void 0&&(ie[fe.property]=fe.decode(t,n)),n+=fe.getSpan(t,n),this.decodePrefixes&&t.length===n)break;return ie}encode(t,n,ie=0){const fe=ie;let ae=0,le=0;for(const he of this.fields){let ye=he.span;if(le=0<ye?ye:0,he.property!==void 0){const me=t[he.property];me!==void 0&&(le=he.encode(me,n,ie),0>ye&&(ye=he.getSpan(n,ie)))}ae=ie,ie+=ye}return ae+le-fe}fromArray(t){const n=this.makeDestinationObject();for(const ie of this.fields)ie.property!==void 0&&0<t.length&&(n[ie.property]=t.shift());return n}layoutFor(t){if(typeof t!="string")throw new TypeError("property must be string");for(const n of this.fields)if(n.property===t)return n}offsetOf(t){if(typeof t!="string")throw new TypeError("property must be string");let n=0;for(const ie of this.fields){if(ie.property===t)return n;0>ie.span?n=-1:0<=n&&(n+=ie.span)}}}Layout$1.Structure=Structure;class UnionDiscriminator{constructor(t){this.property=t}decode(t,n){throw new Error("UnionDiscriminator is abstract")}encode(t,n,ie){throw new Error("UnionDiscriminator is abstract")}}Layout$1.UnionDiscriminator=UnionDiscriminator;class UnionLayoutDiscriminator extends UnionDiscriminator{constructor(t,n){if(!(t instanceof ExternalLayout&&t.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(n||t.property||"variant"),this.layout=t}decode(t,n){return this.layout.decode(t,n)}encode(t,n,ie){return this.layout.encode(t,n,ie)}}Layout$1.UnionLayoutDiscriminator=UnionLayoutDiscriminator;class Union extends Layout{constructor(t,n,ie){let fe;if(t instanceof UInt||t instanceof UIntBE)fe=new UnionLayoutDiscriminator(new OffsetLayout(t));else if(t instanceof ExternalLayout&&t.isCount())fe=new UnionLayoutDiscriminator(t);else if(t instanceof UnionDiscriminator)fe=t;else throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");if(n===void 0&&(n=null),!(n===null||n instanceof Layout))throw new TypeError("defaultLayout must be null or a Layout");if(n!==null){if(0>n.span)throw new Error("defaultLayout must have constant span");n.property===void 0&&(n=n.replicate("content"))}let ae=-1;n&&(ae=n.span,0<=ae&&(t instanceof UInt||t instanceof UIntBE)&&(ae+=fe.layout.span)),super(ae,ie),this.discriminator=fe,this.usesPrefixDiscriminator=t instanceof UInt||t instanceof UIntBE,this.defaultLayout=n,this.registry={};let le=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(he){return le(he)},this.configGetSourceVariant=function(he){le=he.bind(this)}}getSpan(t,n=0){if(0<=this.span)return this.span;const ie=this.getVariant(t,n);if(!ie)throw new Error("unable to determine span for unrecognized variant");return ie.getSpan(t,n)}defaultGetSourceVariant(t){if(Object.prototype.hasOwnProperty.call(t,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(t,this.defaultLayout.property))return;const n=this.registry[t[this.discriminator.property]];if(n&&(!n.layout||n.property&&Object.prototype.hasOwnProperty.call(t,n.property)))return n}else for(const n in this.registry){const ie=this.registry[n];if(ie.property&&Object.prototype.hasOwnProperty.call(t,ie.property))return ie}throw new Error("unable to infer src variant")}decode(t,n=0){let ie;const fe=this.discriminator,ae=fe.decode(t,n),le=this.registry[ae];if(le===void 0){const he=this.defaultLayout;let ye=0;this.usesPrefixDiscriminator&&(ye=fe.layout.span),ie=this.makeDestinationObject(),ie[fe.property]=ae,ie[he.property]=he.decode(t,n+ye)}else ie=le.decode(t,n);return ie}encode(t,n,ie=0){const fe=this.getSourceVariant(t);if(fe===void 0){const ae=this.discriminator,le=this.defaultLayout;let he=0;return this.usesPrefixDiscriminator&&(he=ae.layout.span),ae.encode(t[ae.property],n,ie),he+le.encode(t[le.property],n,ie+he)}return fe.encode(t,n,ie)}addVariant(t,n,ie){const fe=new VariantLayout(this,t,n,ie);return this.registry[t]=fe,fe}getVariant(t,n=0){let ie;return t instanceof Uint8Array?ie=this.discriminator.decode(t,n):ie=t,this.registry[ie]}}Layout$1.Union=Union;class VariantLayout extends Layout{constructor(t,n,ie,fe){if(!(t instanceof Union))throw new TypeError("union must be a Union");if(!Number.isInteger(n)||0>n)throw new TypeError("variant must be a (non-negative) integer");if(typeof ie=="string"&&fe===void 0&&(fe=ie,ie=null),ie){if(!(ie instanceof Layout))throw new TypeError("layout must be a Layout");if(t.defaultLayout!==null&&0<=ie.span&&ie.span>t.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if(typeof fe!="string")throw new TypeError("variant must have a String property")}let ae=t.span;0>t.span&&(ae=ie?ie.span:0,0<=ae&&t.usesPrefixDiscriminator&&(ae+=t.discriminator.layout.span)),super(ae,fe),this.union=t,this.variant=n,this.layout=ie||null}getSpan(t,n=0){if(0<=this.span)return this.span;let ie=0;this.union.usesPrefixDiscriminator&&(ie=this.union.discriminator.layout.span);let fe=0;return this.layout&&(fe=this.layout.getSpan(t,n+ie)),ie+fe}decode(t,n=0){const ie=this.makeDestinationObject();if(this!==this.union.getVariant(t,n))throw new Error("variant mismatch");let fe=0;return this.union.usesPrefixDiscriminator&&(fe=this.union.discriminator.layout.span),this.layout?ie[this.property]=this.layout.decode(t,n+fe):this.property?ie[this.property]=!0:this.union.usesPrefixDiscriminator&&(ie[this.union.discriminator.property]=this.variant),ie}encode(t,n,ie=0){let fe=0;if(this.union.usesPrefixDiscriminator&&(fe=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(t,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,n,ie);let ae=fe;if(this.layout&&(this.layout.encode(t[this.property],n,ie+fe),ae+=this.layout.getSpan(n,ie+fe),0<=this.union.span&&ae>this.union.span))throw new Error("encoded variant overruns containing union");return ae}fromArray(t){if(this.layout)return this.layout.fromArray(t)}}Layout$1.VariantLayout=VariantLayout;function fixBitwiseResult(c){return 0>c&&(c+=4294967296),c}class BitStructure extends Layout{constructor(t,n,ie){if(!(t instanceof UInt||t instanceof UIntBE))throw new TypeError("word must be a UInt or UIntBE layout");if(typeof n=="string"&&ie===void 0&&(ie=n,n=!1),4<t.span)throw new RangeError("word cannot exceed 32 bits");super(t.span,ie),this.word=t,this.msb=!!n,this.fields=[];let fe=0;this._packedSetValue=function(ae){return fe=fixBitwiseResult(ae),this},this._packedGetValue=function(){return fe}}decode(t,n=0){const ie=this.makeDestinationObject(),fe=this.word.decode(t,n);this._packedSetValue(fe);for(const ae of this.fields)ae.property!==void 0&&(ie[ae.property]=ae.decode(t));return ie}encode(t,n,ie=0){const fe=this.word.decode(n,ie);this._packedSetValue(fe);for(const ae of this.fields)if(ae.property!==void 0){const le=t[ae.property];le!==void 0&&ae.encode(le)}return this.word.encode(this._packedGetValue(),n,ie)}addField(t,n){const ie=new BitField(this,t,n);return this.fields.push(ie),ie}addBoolean(t){const n=new Boolean$1(this,t);return this.fields.push(n),n}fieldFor(t){if(typeof t!="string")throw new TypeError("property must be string");for(const n of this.fields)if(n.property===t)return n}}Layout$1.BitStructure=BitStructure;class BitField{constructor(t,n,ie){if(!(t instanceof BitStructure))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(n)||0>=n)throw new TypeError("bits must be positive integer");const fe=8*t.span,ae=t.fields.reduce((le,he)=>le+he.bits,0);if(n+ae>fe)throw new Error("bits too long for span remainder ("+(fe-ae)+" of "+fe+" remain)");this.container=t,this.bits=n,this.valueMask=(1<<n)-1,n===32&&(this.valueMask=4294967295),this.start=ae,this.container.msb&&(this.start=fe-ae-n),this.wordMask=fixBitwiseResult(this.valueMask<<this.start),this.property=ie}decode(t,n){const ie=this.container._packedGetValue();return fixBitwiseResult(ie&this.wordMask)>>>this.start}encode(t){if(typeof t!="number"||!Number.isInteger(t)||t!==fixBitwiseResult(t&this.valueMask))throw new TypeError(nameWithProperty("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const n=this.container._packedGetValue(),ie=fixBitwiseResult(t<<this.start);this.container._packedSetValue(fixBitwiseResult(n&~this.wordMask)|ie)}}Layout$1.BitField=BitField;let Boolean$1=class extends BitField{constructor(t,n){super(t,1,n)}decode(t,n){return!!super.decode(t,n)}encode(t){typeof t=="boolean"&&(t=+t),super.encode(t)}};Layout$1.Boolean=Boolean$1;let Blob$1=class extends Layout{constructor(t,n){if(!(t instanceof ExternalLayout&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let ie=-1;t instanceof ExternalLayout||(ie=t),super(ie,n),this.length=t}getSpan(t,n){let ie=this.span;return 0>ie&&(ie=this.length.decode(t,n)),ie}decode(t,n=0){let ie=this.span;return 0>ie&&(ie=this.length.decode(t,n)),uint8ArrayToBuffer(t).slice(n,n+ie)}encode(t,n,ie){let fe=this.length;if(this.length instanceof ExternalLayout&&(fe=t.length),!(t instanceof Uint8Array&&fe===t.length))throw new TypeError(nameWithProperty("Blob.encode",this)+" requires (length "+fe+") Uint8Array as src");if(ie+fe>n.length)throw new RangeError("encoding overruns Uint8Array");const ae=uint8ArrayToBuffer(t);return uint8ArrayToBuffer(n).write(ae.toString("hex"),ie,fe,"hex"),this.length instanceof ExternalLayout&&this.length.encode(fe,n,ie),fe}};Layout$1.Blob=Blob$1;class CString extends Layout{constructor(t){super(-1,t)}getSpan(t,n=0){checkUint8Array(t);let ie=n;for(;ie<t.length&&t[ie]!==0;)ie+=1;return 1+ie-n}decode(t,n=0){const ie=this.getSpan(t,n);return uint8ArrayToBuffer(t).slice(n,n+ie-1).toString("utf-8")}encode(t,n,ie=0){typeof t!="string"&&(t=String(t));const fe=buffer_1.Buffer.from(t,"utf8"),ae=fe.length;if(ie+ae>n.length)throw new RangeError("encoding overruns Buffer");const le=uint8ArrayToBuffer(n);return fe.copy(le,ie),le[ie+ae]=0,ae+1}}Layout$1.CString=CString;class UTF8 extends Layout{constructor(t,n){if(typeof t=="string"&&n===void 0&&(n=t,t=void 0),t===void 0)t=-1;else if(!Number.isInteger(t))throw new TypeError("maxSpan must be an integer");super(-1,n),this.maxSpan=t}getSpan(t,n=0){return checkUint8Array(t),t.length-n}decode(t,n=0){const ie=this.getSpan(t,n);if(0<=this.maxSpan&&this.maxSpan<ie)throw new RangeError("text length exceeds maxSpan");return uint8ArrayToBuffer(t).slice(n,n+ie).toString("utf-8")}encode(t,n,ie=0){typeof t!="string"&&(t=String(t));const fe=buffer_1.Buffer.from(t,"utf8"),ae=fe.length;if(0<=this.maxSpan&&this.maxSpan<ae)throw new RangeError("text length exceeds maxSpan");if(ie+ae>n.length)throw new RangeError("encoding overruns Buffer");return fe.copy(uint8ArrayToBuffer(n),ie),ae}}Layout$1.UTF8=UTF8;class Constant extends Layout{constructor(t,n){super(0,n),this.value=t}decode(t,n){return this.value}encode(t,n,ie){return 0}}Layout$1.Constant=Constant;Layout$1.greedy=(c,t)=>new GreedyCount(c,t);var offset=Layout$1.offset=(c,t,n)=>new OffsetLayout(c,t,n),u8=Layout$1.u8=c=>new UInt(1,c),u16=Layout$1.u16=c=>new UInt(2,c);Layout$1.u24=c=>new UInt(3,c);var u32=Layout$1.u32=c=>new UInt(4,c);Layout$1.u40=c=>new UInt(5,c);Layout$1.u48=c=>new UInt(6,c);var nu64=Layout$1.nu64=c=>new NearUInt64(c);Layout$1.u16be=c=>new UIntBE(2,c);Layout$1.u24be=c=>new UIntBE(3,c);Layout$1.u32be=c=>new UIntBE(4,c);Layout$1.u40be=c=>new UIntBE(5,c);Layout$1.u48be=c=>new UIntBE(6,c);Layout$1.nu64be=c=>new NearUInt64BE(c);Layout$1.s8=c=>new Int(1,c);Layout$1.s16=c=>new Int(2,c);Layout$1.s24=c=>new Int(3,c);Layout$1.s32=c=>new Int(4,c);Layout$1.s40=c=>new Int(5,c);Layout$1.s48=c=>new Int(6,c);var ns64=Layout$1.ns64=c=>new NearInt64(c);Layout$1.s16be=c=>new IntBE(2,c);Layout$1.s24be=c=>new IntBE(3,c);Layout$1.s32be=c=>new IntBE(4,c);Layout$1.s40be=c=>new IntBE(5,c);Layout$1.s48be=c=>new IntBE(6,c);Layout$1.ns64be=c=>new NearInt64BE(c);Layout$1.f32=c=>new Float(c);Layout$1.f32be=c=>new FloatBE(c);Layout$1.f64=c=>new Double(c);Layout$1.f64be=c=>new DoubleBE(c);var struct=Layout$1.struct=(c,t,n)=>new Structure(c,t,n);Layout$1.bits=(c,t,n)=>new BitStructure(c,t,n);var seq=Layout$1.seq=(c,t,n)=>new Sequence(c,t,n);Layout$1.union=(c,t,n)=>new Union(c,t,n);Layout$1.unionLayoutDiscriminator=(c,t)=>new UnionLayoutDiscriminator(c,t);var blob=Layout$1.blob=(c,t)=>new Blob$1(c,t);Layout$1.cstr=c=>new CString(c);Layout$1.utf8=(c,t)=>new UTF8(c,t);Layout$1.constant=(c,t)=>new Constant(c,t);var browser$d={};Object.defineProperty(browser$d,"__esModule",{value:!0});function toBigIntLE(c){{const t=Buffer$7.from(c);t.reverse();const n=t.toString("hex");return n.length===0?BigInt(0):BigInt(`0x${n}`)}}var toBigIntLE_1=browser$d.toBigIntLE=toBigIntLE;function toBigIntBE(c){{const t=c.toString("hex");return t.length===0?BigInt(0):BigInt(`0x${t}`)}}browser$d.toBigIntBE=toBigIntBE;function toBufferLE(c,t){{const n=c.toString(16),ie=Buffer$7.from(n.padStart(t*2,"0").slice(0,t*2),"hex");return ie.reverse(),ie}}var toBufferLE_1=browser$d.toBufferLE=toBufferLE;function toBufferBE(c,t){{const n=c.toString(16);return Buffer$7.from(n.padStart(t*2,"0").slice(0,t*2),"hex")}}browser$d.toBufferBE=toBufferBE;class StructError extends TypeError{constructor(t,n){let ie;const{message:fe,explanation:ae,...le}=t,{path:he}=t,ye=he.length===0?fe:`At path: ${he.join(".")} -- ${fe}`;super(ae??ye),ae!=null&&(this.cause=ye),Object.assign(this,le),this.name=this.constructor.name,this.failures=()=>ie??(ie=[t,...n()])}}function isIterable(c){return isObject$1(c)&&typeof c[Symbol.iterator]=="function"}function isObject$1(c){return typeof c=="object"&&c!=null}function isNonArrayObject(c){return isObject$1(c)&&!Array.isArray(c)}function print$2(c){return typeof c=="symbol"?c.toString():typeof c=="string"?JSON.stringify(c):`${c}`}function shiftIterator(c){const{done:t,value:n}=c.next();return t?void 0:n}function toFailure(c,t,n,ie){if(c===!0)return;c===!1?c={}:typeof c=="string"&&(c={message:c});const{path:fe,branch:ae}=t,{type:le}=n,{refinement:he,message:ye=`Expected a value of type \`${le}\`${he?` with refinement \`${he}\``:""}, but received: \`${print$2(ie)}\``}=c;return{value:ie,type:le,refinement:he,key:fe[fe.length-1],path:fe,branch:ae,...c,message:ye}}function*toFailures(c,t,n,ie){isIterable(c)||(c=[c]);for(const fe of c){const ae=toFailure(fe,t,n,ie);ae&&(yield ae)}}function*run(c,t,n={}){const{path:ie=[],branch:fe=[c],coerce:ae=!1,mask:le=!1}=n,he={path:ie,branch:fe,mask:le};ae&&(c=t.coercer(c,he));let ye="valid";for(const me of t.validator(c,he))me.explanation=n.message,ye="not_valid",yield[me,void 0];for(let[me,xe,Ee]of t.entries(c,he)){const Se=run(xe,Ee,{path:me===void 0?ie:[...ie,me],branch:me===void 0?fe:[...fe,xe],coerce:ae,mask:le,message:n.message});for(const Me of Se)Me[0]?(ye=Me[0].refinement!=null?"not_refined":"not_valid",yield[Me[0],void 0]):ae&&(xe=Me[1],me===void 0?c=xe:c instanceof Map?c.set(me,xe):c instanceof Set?c.add(xe):isObject$1(c)&&(xe!==void 0||me in c)&&(c[me]=xe))}if(ye!=="not_valid")for(const me of t.refiner(c,he))me.explanation=n.message,ye="not_refined",yield[me,void 0];ye==="valid"&&(yield[void 0,c])}let Struct$1=class{constructor(t){const{type:n,schema:ie,validator:fe,refiner:ae,coercer:le=ye=>ye,entries:he=function*(){}}=t;this.type=n,this.schema=ie,this.entries=he,this.coercer=le,fe?this.validator=(ye,me)=>{const xe=fe(ye,me);return toFailures(xe,me,this,ye)}:this.validator=()=>[],ae?this.refiner=(ye,me)=>{const xe=ae(ye,me);return toFailures(xe,me,this,ye)}:this.refiner=()=>[]}assert(t,n){return assert$a(t,this,n)}create(t,n){return create(t,this,n)}is(t){return is(t,this)}mask(t,n){return mask(t,this,n)}validate(t,n={}){return validate$1(t,this,n)}};function assert$a(c,t,n){const ie=validate$1(c,t,{message:n});if(ie[0])throw ie[0]}function create(c,t,n){const ie=validate$1(c,t,{coerce:!0,message:n});if(ie[0])throw ie[0];return ie[1]}function mask(c,t,n){const ie=validate$1(c,t,{coerce:!0,mask:!0,message:n});if(ie[0])throw ie[0];return ie[1]}function is(c,t){return!validate$1(c,t)[0]}function validate$1(c,t,n={}){const ie=run(c,t,n),fe=shiftIterator(ie);return fe[0]?[new StructError(fe[0],function*(){for(const le of ie)le[0]&&(yield le[0])}),void 0]:[void 0,fe[1]]}function define(c,t){return new Struct$1({type:c,schema:null,validator:t})}function any(){return define("any",()=>!0)}function array(c){return new Struct$1({type:"array",schema:c,*entries(t){if(c&&Array.isArray(t))for(const[n,ie]of t.entries())yield[n,ie,c]},coercer(t){return Array.isArray(t)?t.slice():t},validator(t){return Array.isArray(t)||`Expected an array value, but received: ${print$2(t)}`}})}function boolean(){return define("boolean",c=>typeof c=="boolean")}function instance(c){return define("instance",t=>t instanceof c||`Expected a \`${c.name}\` instance, but received: ${print$2(t)}`)}function literal(c){const t=print$2(c),n=typeof c;return new Struct$1({type:"literal",schema:n==="string"||n==="number"||n==="boolean"?c:null,validator(ie){return ie===c||`Expected the literal \`${t}\`, but received: ${print$2(ie)}`}})}function never(){return define("never",()=>!1)}function nullable(c){return new Struct$1({...c,validator:(t,n)=>t===null||c.validator(t,n),refiner:(t,n)=>t===null||c.refiner(t,n)})}function number(){return define("number",c=>typeof c=="number"&&!isNaN(c)||`Expected a number, but received: ${print$2(c)}`)}function optional(c){return new Struct$1({...c,validator:(t,n)=>t===void 0||c.validator(t,n),refiner:(t,n)=>t===void 0||c.refiner(t,n)})}function record(c,t){return new Struct$1({type:"record",schema:null,*entries(n){if(isObject$1(n))for(const ie in n){const fe=n[ie];yield[ie,ie,c],yield[ie,fe,t]}},validator(n){return isNonArrayObject(n)||`Expected an object, but received: ${print$2(n)}`},coercer(n){return isNonArrayObject(n)?{...n}:n}})}function string(){return define("string",c=>typeof c=="string"||`Expected a string, but received: ${print$2(c)}`)}function tuple(c){const t=never();return new Struct$1({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const ie=Math.max(c.length,n.length);for(let fe=0;fe<ie;fe++)yield[fe,n[fe],c[fe]||t]}},validator(n){return Array.isArray(n)||`Expected an array, but received: ${print$2(n)}`},coercer(n){return Array.isArray(n)?n.slice():n}})}function type$1(c){const t=Object.keys(c);return new Struct$1({type:"type",schema:c,*entries(n){if(isObject$1(n))for(const ie of t)yield[ie,n[ie],c[ie]]},validator(n){return isNonArrayObject(n)||`Expected an object, but received: ${print$2(n)}`},coercer(n){return isNonArrayObject(n)?{...n}:n}})}function union(c){const t=c.map(n=>n.type).join(" | ");return new Struct$1({type:"union",schema:null,coercer(n,ie){for(const fe of c){const[ae,le]=fe.validate(n,{coerce:!0,mask:ie.mask});if(!ae)return le}return n},validator(n,ie){const fe=[];for(const ae of c){const[...le]=run(n,ae,ie),[he]=le;if(he[0])for(const[ye]of le)ye&&fe.push(ye);else return[]}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${print$2(n)}`,...fe]}})}function unknown(){return define("unknown",()=>!0)}function coerce(c,t,n){return new Struct$1({...c,coercer:(ie,fe)=>is(ie,t)?c.coercer(n(ie,fe),fe):c.coercer(ie,fe)})}var getRandomValues,rnds8=new Uint8Array(16);function rng(){if(!getRandomValues&&(getRandomValues=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!getRandomValues))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}const REGEX$1=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function validate(c){return typeof c=="string"&®EX$1.test(c)}var byteToHex=[];for(var i$2=0;i$2<256;++i$2)byteToHex.push((i$2+256).toString(16).substr(1));function stringify(c){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=(byteToHex[c[t+0]]+byteToHex[c[t+1]]+byteToHex[c[t+2]]+byteToHex[c[t+3]]+"-"+byteToHex[c[t+4]]+byteToHex[c[t+5]]+"-"+byteToHex[c[t+6]]+byteToHex[c[t+7]]+"-"+byteToHex[c[t+8]]+byteToHex[c[t+9]]+"-"+byteToHex[c[t+10]]+byteToHex[c[t+11]]+byteToHex[c[t+12]]+byteToHex[c[t+13]]+byteToHex[c[t+14]]+byteToHex[c[t+15]]).toLowerCase();if(!validate(n))throw TypeError("Stringified UUID is invalid");return n}var _nodeId,_clockseq,_lastMSecs=0,_lastNSecs=0;function v1(c,t,n){var ie=t&&n||0,fe=t||new Array(16);c=c||{};var ae=c.node||_nodeId,le=c.clockseq!==void 0?c.clockseq:_clockseq;if(ae==null||le==null){var he=c.random||(c.rng||rng)();ae==null&&(ae=_nodeId=[he[0]|1,he[1],he[2],he[3],he[4],he[5]]),le==null&&(le=_clockseq=(he[6]<<8|he[7])&16383)}var ye=c.msecs!==void 0?c.msecs:Date.now(),me=c.nsecs!==void 0?c.nsecs:_lastNSecs+1,xe=ye-_lastMSecs+(me-_lastNSecs)/1e4;if(xe<0&&c.clockseq===void 0&&(le=le+1&16383),(xe<0||ye>_lastMSecs)&&c.nsecs===void 0&&(me=0),me>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_lastMSecs=ye,_lastNSecs=me,_clockseq=le,ye+=122192928e5;var Ee=((ye&268435455)*1e4+me)%4294967296;fe[ie++]=Ee>>>24&255,fe[ie++]=Ee>>>16&255,fe[ie++]=Ee>>>8&255,fe[ie++]=Ee&255;var Se=ye/4294967296*1e4&268435455;fe[ie++]=Se>>>8&255,fe[ie++]=Se&255,fe[ie++]=Se>>>24&15|16,fe[ie++]=Se>>>16&255,fe[ie++]=le>>>8|128,fe[ie++]=le&255;for(var Me=0;Me<6;++Me)fe[ie+Me]=ae[Me];return t||stringify(fe)}function parse$1(c){if(!validate(c))throw TypeError("Invalid UUID");var t,n=new Uint8Array(16);return n[0]=(t=parseInt(c.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=t&255,n[4]=(t=parseInt(c.slice(9,13),16))>>>8,n[5]=t&255,n[6]=(t=parseInt(c.slice(14,18),16))>>>8,n[7]=t&255,n[8]=(t=parseInt(c.slice(19,23),16))>>>8,n[9]=t&255,n[10]=(t=parseInt(c.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=t&255,n}function stringToBytes(c){c=unescape(encodeURIComponent(c));for(var t=[],n=0;n<c.length;++n)t.push(c.charCodeAt(n));return t}var DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",URL$1="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function v35(c,t,n){function ie(fe,ae,le,he){if(typeof fe=="string"&&(fe=stringToBytes(fe)),typeof ae=="string"&&(ae=parse$1(ae)),ae.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var ye=new Uint8Array(16+fe.length);if(ye.set(ae),ye.set(fe,ae.length),ye=n(ye),ye[6]=ye[6]&15|t,ye[8]=ye[8]&63|128,le){he=he||0;for(var me=0;me<16;++me)le[he+me]=ye[me];return le}return stringify(ye)}try{ie.name=c}catch{}return ie.DNS=DNS,ie.URL=URL$1,ie}function md5$3(c){if(typeof c=="string"){var t=unescape(encodeURIComponent(c));c=new Uint8Array(t.length);for(var n=0;n<t.length;++n)c[n]=t.charCodeAt(n)}return md5ToHexEncodedArray(wordsToMd5(bytesToWords(c),c.length*8))}function md5ToHexEncodedArray(c){for(var t=[],n=c.length*32,ie="0123456789abcdef",fe=0;fe<n;fe+=8){var ae=c[fe>>5]>>>fe%32&255,le=parseInt(ie.charAt(ae>>>4&15)+ie.charAt(ae&15),16);t.push(le)}return t}function getOutputLength(c){return(c+64>>>9<<4)+14+1}function wordsToMd5(c,t){c[t>>5]|=128<<t%32,c[getOutputLength(t)-1]=t;for(var n=1732584193,ie=-271733879,fe=-1732584194,ae=271733878,le=0;le<c.length;le+=16){var he=n,ye=ie,me=fe,xe=ae;n=md5ff(n,ie,fe,ae,c[le],7,-680876936),ae=md5ff(ae,n,ie,fe,c[le+1],12,-389564586),fe=md5ff(fe,ae,n,ie,c[le+2],17,606105819),ie=md5ff(ie,fe,ae,n,c[le+3],22,-1044525330),n=md5ff(n,ie,fe,ae,c[le+4],7,-176418897),ae=md5ff(ae,n,ie,fe,c[le+5],12,1200080426),fe=md5ff(fe,ae,n,ie,c[le+6],17,-1473231341),ie=md5ff(ie,fe,ae,n,c[le+7],22,-45705983),n=md5ff(n,ie,fe,ae,c[le+8],7,1770035416),ae=md5ff(ae,n,ie,fe,c[le+9],12,-1958414417),fe=md5ff(fe,ae,n,ie,c[le+10],17,-42063),ie=md5ff(ie,fe,ae,n,c[le+11],22,-1990404162),n=md5ff(n,ie,fe,ae,c[le+12],7,1804603682),ae=md5ff(ae,n,ie,fe,c[le+13],12,-40341101),fe=md5ff(fe,ae,n,ie,c[le+14],17,-1502002290),ie=md5ff(ie,fe,ae,n,c[le+15],22,1236535329),n=md5gg(n,ie,fe,ae,c[le+1],5,-165796510),ae=md5gg(ae,n,ie,fe,c[le+6],9,-1069501632),fe=md5gg(fe,ae,n,ie,c[le+11],14,643717713),ie=md5gg(ie,fe,ae,n,c[le],20,-373897302),n=md5gg(n,ie,fe,ae,c[le+5],5,-701558691),ae=md5gg(ae,n,ie,fe,c[le+10],9,38016083),fe=md5gg(fe,ae,n,ie,c[le+15],14,-660478335),ie=md5gg(ie,fe,ae,n,c[le+4],20,-405537848),n=md5gg(n,ie,fe,ae,c[le+9],5,568446438),ae=md5gg(ae,n,ie,fe,c[le+14],9,-1019803690),fe=md5gg(fe,ae,n,ie,c[le+3],14,-187363961),ie=md5gg(ie,fe,ae,n,c[le+8],20,1163531501),n=md5gg(n,ie,fe,ae,c[le+13],5,-1444681467),ae=md5gg(ae,n,ie,fe,c[le+2],9,-51403784),fe=md5gg(fe,ae,n,ie,c[le+7],14,1735328473),ie=md5gg(ie,fe,ae,n,c[le+12],20,-1926607734),n=md5hh(n,ie,fe,ae,c[le+5],4,-378558),ae=md5hh(ae,n,ie,fe,c[le+8],11,-2022574463),fe=md5hh(fe,ae,n,ie,c[le+11],16,1839030562),ie=md5hh(ie,fe,ae,n,c[le+14],23,-35309556),n=md5hh(n,ie,fe,ae,c[le+1],4,-1530992060),ae=md5hh(ae,n,ie,fe,c[le+4],11,1272893353),fe=md5hh(fe,ae,n,ie,c[le+7],16,-155497632),ie=md5hh(ie,fe,ae,n,c[le+10],23,-1094730640),n=md5hh(n,ie,fe,ae,c[le+13],4,681279174),ae=md5hh(ae,n,ie,fe,c[le],11,-358537222),fe=md5hh(fe,ae,n,ie,c[le+3],16,-722521979),ie=md5hh(ie,fe,ae,n,c[le+6],23,76029189),n=md5hh(n,ie,fe,ae,c[le+9],4,-640364487),ae=md5hh(ae,n,ie,fe,c[le+12],11,-421815835),fe=md5hh(fe,ae,n,ie,c[le+15],16,530742520),ie=md5hh(ie,fe,ae,n,c[le+2],23,-995338651),n=md5ii(n,ie,fe,ae,c[le],6,-198630844),ae=md5ii(ae,n,ie,fe,c[le+7],10,1126891415),fe=md5ii(fe,ae,n,ie,c[le+14],15,-1416354905),ie=md5ii(ie,fe,ae,n,c[le+5],21,-57434055),n=md5ii(n,ie,fe,ae,c[le+12],6,1700485571),ae=md5ii(ae,n,ie,fe,c[le+3],10,-1894986606),fe=md5ii(fe,ae,n,ie,c[le+10],15,-1051523),ie=md5ii(ie,fe,ae,n,c[le+1],21,-2054922799),n=md5ii(n,ie,fe,ae,c[le+8],6,1873313359),ae=md5ii(ae,n,ie,fe,c[le+15],10,-30611744),fe=md5ii(fe,ae,n,ie,c[le+6],15,-1560198380),ie=md5ii(ie,fe,ae,n,c[le+13],21,1309151649),n=md5ii(n,ie,fe,ae,c[le+4],6,-145523070),ae=md5ii(ae,n,ie,fe,c[le+11],10,-1120210379),fe=md5ii(fe,ae,n,ie,c[le+2],15,718787259),ie=md5ii(ie,fe,ae,n,c[le+9],21,-343485551),n=safeAdd(n,he),ie=safeAdd(ie,ye),fe=safeAdd(fe,me),ae=safeAdd(ae,xe)}return[n,ie,fe,ae]}function bytesToWords(c){if(c.length===0)return[];for(var t=c.length*8,n=new Uint32Array(getOutputLength(t)),ie=0;ie<t;ie+=8)n[ie>>5]|=(c[ie/8]&255)<<ie%32;return n}function safeAdd(c,t){var n=(c&65535)+(t&65535),ie=(c>>16)+(t>>16)+(n>>16);return ie<<16|n&65535}function bitRotateLeft(c,t){return c<<t|c>>>32-t}function md5cmn(c,t,n,ie,fe,ae){return safeAdd(bitRotateLeft(safeAdd(safeAdd(t,c),safeAdd(ie,ae)),fe),n)}function md5ff(c,t,n,ie,fe,ae,le){return md5cmn(t&n|~t&ie,c,t,fe,ae,le)}function md5gg(c,t,n,ie,fe,ae,le){return md5cmn(t&ie|n&~ie,c,t,fe,ae,le)}function md5hh(c,t,n,ie,fe,ae,le){return md5cmn(t^n^ie,c,t,fe,ae,le)}function md5ii(c,t,n,ie,fe,ae,le){return md5cmn(n^(t|~ie),c,t,fe,ae,le)}var v3=v35("v3",48,md5$3);function v4(c,t,n){c=c||{};var ie=c.random||(c.rng||rng)();if(ie[6]=ie[6]&15|64,ie[8]=ie[8]&63|128,t){n=n||0;for(var fe=0;fe<16;++fe)t[n+fe]=ie[fe];return t}return stringify(ie)}function f$1(c,t,n,ie){switch(c){case 0:return t&n^~t&ie;case 1:return t^n^ie;case 2:return t&n^t&ie^n&ie;case 3:return t^n^ie}}function ROTL(c,t){return c<<t|c>>>32-t}function sha1$3(c){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof c=="string"){var ie=unescape(encodeURIComponent(c));c=[];for(var fe=0;fe<ie.length;++fe)c.push(ie.charCodeAt(fe))}else Array.isArray(c)||(c=Array.prototype.slice.call(c));c.push(128);for(var ae=c.length/4+2,le=Math.ceil(ae/16),he=new Array(le),ye=0;ye<le;++ye){for(var me=new Uint32Array(16),xe=0;xe<16;++xe)me[xe]=c[ye*64+xe*4]<<24|c[ye*64+xe*4+1]<<16|c[ye*64+xe*4+2]<<8|c[ye*64+xe*4+3];he[ye]=me}he[le-1][14]=(c.length-1)*8/Math.pow(2,32),he[le-1][14]=Math.floor(he[le-1][14]),he[le-1][15]=(c.length-1)*8&4294967295;for(var Ee=0;Ee<le;++Ee){for(var Se=new Uint32Array(80),Me=0;Me<16;++Me)Se[Me]=he[Ee][Me];for(var Be=16;Be<80;++Be)Se[Be]=ROTL(Se[Be-3]^Se[Be-8]^Se[Be-14]^Se[Be-16],1);for(var $e=n[0],Ce=n[1],ke=n[2],Pe=n[3],Ue=n[4],qe=0;qe<80;++qe){var He=Math.floor(qe/20),Ve=ROTL($e,5)+f$1(He,Ce,ke,Pe)+Ue+t[He]+Se[qe]>>>0;Ue=Pe,Pe=ke,ke=ROTL(Ce,30)>>>0,Ce=$e,$e=Ve}n[0]=n[0]+$e>>>0,n[1]=n[1]+Ce>>>0,n[2]=n[2]+ke>>>0,n[3]=n[3]+Pe>>>0,n[4]=n[4]+Ue>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,n[0]&255,n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,n[1]&255,n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,n[2]&255,n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,n[3]&255,n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,n[4]&255]}var v5=v35("v5",80,sha1$3);const nil="00000000-0000-0000-0000-000000000000";function version$5(c){if(!validate(c))throw TypeError("Invalid UUID");return parseInt(c.substr(14,1),16)}const esmBrowser=Object.freeze(Object.defineProperty({__proto__:null,NIL:nil,parse:parse$1,stringify,v1,v3,v4,v5,validate,version:version$5},Symbol.toStringTag,{value:"Module"})),require$$0$2=getAugmentedNamespace(esmBrowser),uuid$1=require$$0$2.v4,generateRequest$1=function(c,t,n,ie){if(typeof c!="string")throw new TypeError(c+" must be a string");ie=ie||{};const fe=typeof ie.version=="number"?ie.version:2;if(fe!==1&&fe!==2)throw new TypeError(fe+" must be 1 or 2");const ae={method:c};if(fe===2&&(ae.jsonrpc="2.0"),t){if(typeof t!="object"&&!Array.isArray(t))throw new TypeError(t+" must be an object, array or omitted");ae.params=t}if(typeof n>"u"){const le=typeof ie.generator=="function"?ie.generator:function(){return uuid$1()};ae.id=le(ae,ie)}else fe===2&&n===null?ie.notificationIdNull&&(ae.id=null):ae.id=n;return ae};var generateRequest_1=generateRequest$1;const uuid=require$$0$2.v4,generateRequest=generateRequest_1,ClientBrowser=function(c,t){if(!(this instanceof ClientBrowser))return new ClientBrowser(c,t);t||(t={}),this.options={reviver:typeof t.reviver<"u"?t.reviver:null,replacer:typeof t.replacer<"u"?t.replacer:null,generator:typeof t.generator<"u"?t.generator:function(){return uuid()},version:typeof t.version<"u"?t.version:2,notificationIdNull:typeof t.notificationIdNull=="boolean"?t.notificationIdNull:!1},this.callServer=c};var browser$c=ClientBrowser;ClientBrowser.prototype.request=function(c,t,n,ie){const fe=this;let ae=null;const le=Array.isArray(c)&&typeof t=="function";if(this.options.version===1&&le)throw new TypeError("JSON-RPC 1.0 does not support batching");if(le||!le&&c&&typeof c=="object"&&typeof t=="function")ie=t,ae=c;else{typeof n=="function"&&(ie=n,n=void 0);const me=typeof ie=="function";try{ae=generateRequest(c,t,n,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(xe){if(me)return ie(xe);throw xe}if(!me)return ae}let ye;try{ye=JSON.stringify(ae,this.options.replacer)}catch(me){return ie(me)}return this.callServer(ye,function(me,xe){fe._parseResponse(me,xe,ie)}),ae};ClientBrowser.prototype._parseResponse=function(c,t,n){if(c){n(c);return}if(!t)return n();let ie;try{ie=JSON.parse(t,this.options.reviver)}catch(fe){return n(fe)}if(n.length===3)if(Array.isArray(ie)){const fe=function(le){return typeof le.error<"u"},ae=function(le){return!fe(le)};return n(null,ie.filter(fe),ie.filter(ae))}else return n(null,ie.error,ie.result);n(null,ie)};const RpcClient=getDefaultExportFromCjs$2(browser$c);var eventemitter3={exports:{}};(function(c){var t=Object.prototype.hasOwnProperty,n="~";function ie(){}Object.create&&(ie.prototype=Object.create(null),new ie().__proto__||(n=!1));function fe(ye,me,xe){this.fn=ye,this.context=me,this.once=xe||!1}function ae(ye,me,xe,Ee,Se){if(typeof xe!="function")throw new TypeError("The listener must be a function");var Me=new fe(xe,Ee||ye,Se),Be=n?n+me:me;return ye._events[Be]?ye._events[Be].fn?ye._events[Be]=[ye._events[Be],Me]:ye._events[Be].push(Me):(ye._events[Be]=Me,ye._eventsCount++),ye}function le(ye,me){--ye._eventsCount===0?ye._events=new ie:delete ye._events[me]}function he(){this._events=new ie,this._eventsCount=0}he.prototype.eventNames=function(){var me=[],xe,Ee;if(this._eventsCount===0)return me;for(Ee in xe=this._events)t.call(xe,Ee)&&me.push(n?Ee.slice(1):Ee);return Object.getOwnPropertySymbols?me.concat(Object.getOwnPropertySymbols(xe)):me},he.prototype.listeners=function(me){var xe=n?n+me:me,Ee=this._events[xe];if(!Ee)return[];if(Ee.fn)return[Ee.fn];for(var Se=0,Me=Ee.length,Be=new Array(Me);Se<Me;Se++)Be[Se]=Ee[Se].fn;return Be},he.prototype.listenerCount=function(me){var xe=n?n+me:me,Ee=this._events[xe];return Ee?Ee.fn?1:Ee.length:0},he.prototype.emit=function(me,xe,Ee,Se,Me,Be){var $e=n?n+me:me;if(!this._events[$e])return!1;var Ce=this._events[$e],ke=arguments.length,Pe,Ue;if(Ce.fn){switch(Ce.once&&this.removeListener(me,Ce.fn,void 0,!0),ke){case 1:return Ce.fn.call(Ce.context),!0;case 2:return Ce.fn.call(Ce.context,xe),!0;case 3:return Ce.fn.call(Ce.context,xe,Ee),!0;case 4:return Ce.fn.call(Ce.context,xe,Ee,Se),!0;case 5:return Ce.fn.call(Ce.context,xe,Ee,Se,Me),!0;case 6:return Ce.fn.call(Ce.context,xe,Ee,Se,Me,Be),!0}for(Ue=1,Pe=new Array(ke-1);Ue<ke;Ue++)Pe[Ue-1]=arguments[Ue];Ce.fn.apply(Ce.context,Pe)}else{var qe=Ce.length,He;for(Ue=0;Ue<qe;Ue++)switch(Ce[Ue].once&&this.removeListener(me,Ce[Ue].fn,void 0,!0),ke){case 1:Ce[Ue].fn.call(Ce[Ue].context);break;case 2:Ce[Ue].fn.call(Ce[Ue].context,xe);break;case 3:Ce[Ue].fn.call(Ce[Ue].context,xe,Ee);break;case 4:Ce[Ue].fn.call(Ce[Ue].context,xe,Ee,Se);break;default:if(!Pe)for(He=1,Pe=new Array(ke-1);He<ke;He++)Pe[He-1]=arguments[He];Ce[Ue].fn.apply(Ce[Ue].context,Pe)}}return!0},he.prototype.on=function(me,xe,Ee){return ae(this,me,xe,Ee,!1)},he.prototype.once=function(me,xe,Ee){return ae(this,me,xe,Ee,!0)},he.prototype.removeListener=function(me,xe,Ee,Se){var Me=n?n+me:me;if(!this._events[Me])return this;if(!xe)return le(this,Me),this;var Be=this._events[Me];if(Be.fn)Be.fn===xe&&(!Se||Be.once)&&(!Ee||Be.context===Ee)&&le(this,Me);else{for(var $e=0,Ce=[],ke=Be.length;$e<ke;$e++)(Be[$e].fn!==xe||Se&&!Be[$e].once||Ee&&Be[$e].context!==Ee)&&Ce.push(Be[$e]);Ce.length?this._events[Me]=Ce.length===1?Ce[0]:Ce:le(this,Me)}return this},he.prototype.removeAllListeners=function(me){var xe;return me?(xe=n?n+me:me,this._events[xe]&&le(this,xe)):(this._events=new ie,this._eventsCount=0),this},he.prototype.off=he.prototype.removeListener,he.prototype.addListener=he.prototype.on,he.prefixed=n,he.EventEmitter=he,c.exports=he})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs$2(eventemitter3Exports);var WebSocketBrowserImpl=class extends EventEmitter{constructor(t,n,ie){super();Xn(this,"socket");this.socket=new window.WebSocket(t,ie),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=fe=>this.emit("message",fe.data),this.socket.onerror=fe=>this.emit("error",fe),this.socket.onclose=fe=>{this.emit("close",fe.code,fe.reason)}}send(t,n,ie){const fe=ie||n;try{this.socket.send(t),fe()}catch(ae){fe(ae)}}close(t,n){this.socket.close(t,n)}addEventListener(t,n,ie){this.socket.addEventListener(t,n,ie)}};function WebSocket(c,t){return new WebSocketBrowserImpl(c,t)}var DefaultDataPack=class{encode(c){return JSON.stringify(c)}decode(c){return JSON.parse(c)}},CommonClient=class extends EventEmitter{constructor(t,n="ws://localhost:8080",{autoconnect:ie=!0,reconnect:fe=!0,reconnect_interval:ae=1e3,max_reconnects:le=5,...he}={},ye,me){super();Xn(this,"address");Xn(this,"rpc_id");Xn(this,"queue");Xn(this,"options");Xn(this,"autoconnect");Xn(this,"ready");Xn(this,"reconnect");Xn(this,"reconnect_timer_id");Xn(this,"reconnect_interval");Xn(this,"max_reconnects");Xn(this,"rest_options");Xn(this,"current_reconnects");Xn(this,"generate_request_id");Xn(this,"socket");Xn(this,"webSocketFactory");Xn(this,"dataPack");this.webSocketFactory=t,this.queue={},this.rpc_id=0,this.address=n,this.autoconnect=ie,this.ready=!1,this.reconnect=fe,this.reconnect_timer_id=void 0,this.reconnect_interval=ae,this.max_reconnects=le,this.rest_options=he,this.current_reconnects=0,this.generate_request_id=ye||(()=>typeof this.rpc_id=="number"?++this.rpc_id:Number(this.rpc_id)+1),me?this.dataPack=me:this.dataPack=new DefaultDataPack,this.autoconnect&&this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){this.socket||this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(t,n,ie,fe){return!fe&&typeof ie=="object"&&(fe=ie,ie=null),new Promise((ae,le)=>{if(!this.ready)return le(new Error("socket not ready"));const he=this.generate_request_id(t,n),ye={jsonrpc:"2.0",method:t,params:n||void 0,id:he};this.socket.send(this.dataPack.encode(ye),fe,me=>{if(me)return le(me);this.queue[he]={promise:[ae,le]},ie&&(this.queue[he].timeout=setTimeout(()=>{delete this.queue[he],le(new Error("reply timeout"))},ie))})})}async login(t){const n=await this.call("rpc.login",t);if(!n)throw new Error("authentication failed");return n}async listMethods(){return await this.call("__listMethods")}notify(t,n){return new Promise((ie,fe)=>{if(!this.ready)return fe(new Error("socket not ready"));const ae={jsonrpc:"2.0",method:t,params:n};this.socket.send(this.dataPack.encode(ae),le=>{if(le)return fe(le);ie()})})}async subscribe(t){typeof t=="string"&&(t=[t]);const n=await this.call("rpc.on",t);if(typeof t=="string"&&n[t]!=="ok")throw new Error("Failed subscribing to an event '"+t+"' with: "+n[t]);return n}async unsubscribe(t){typeof t=="string"&&(t=[t]);const n=await this.call("rpc.off",t);if(typeof t=="string"&&n[t]!=="ok")throw new Error("Failed unsubscribing from an event with: "+n);return n}close(t,n){this.socket&&this.socket.close(t||1e3,n)}setAutoReconnect(t){this.reconnect=t}setReconnectInterval(t){this.reconnect_interval=t}setMaxReconnects(t){this.max_reconnects=t}getCurrentReconnects(){return this.current_reconnects}getMaxReconnects(){return this.max_reconnects}isReconnecting(){return this.reconnect_timer_id!==void 0}willReconnect(){return this.reconnect&&(this.max_reconnects===0||this.current_reconnects<this.max_reconnects)}_connect(t,n){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(t,n),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:ie})=>{ie instanceof ArrayBuffer&&(ie=Buffer$1$1.from(ie).toString());try{ie=this.dataPack.decode(ie)}catch{return}if(ie.notification&&this.listeners(ie.notification).length){if(!Object.keys(ie.params).length)return this.emit(ie.notification);const fe=[ie.notification];if(ie.params.constructor===Object)fe.push(ie.params);else for(let ae=0;ae<ie.params.length;ae++)fe.push(ie.params[ae]);return Promise.resolve().then(()=>{this.emit.apply(this,fe)})}if(!this.queue[ie.id])return ie.method?Promise.resolve().then(()=>{this.emit(ie.method,ie==null?void 0:ie.params)}):void 0;"error"in ie=="result"in ie&&this.queue[ie.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[ie.id].timeout&&clearTimeout(this.queue[ie.id].timeout),ie.error?this.queue[ie.id].promise[1](ie.error):this.queue[ie.id].promise[0](ie.result),delete this.queue[ie.id]}),this.socket.addEventListener("error",ie=>this.emit("error",ie)),this.socket.addEventListener("close",({code:ie,reason:fe})=>{this.ready&&setTimeout(()=>this.emit("close",ie,fe),0),this.ready=!1,this.socket=void 0,ie!==1e3&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||this.max_reconnects===0)?this.reconnect_timer_id=setTimeout(()=>this._connect(t,n),this.reconnect_interval):this.reconnect&&this.max_reconnects>0&&this.current_reconnects>=this.max_reconnects&&setTimeout(()=>this.emit("max_reconnects_reached",ie,fe),1))})}};class HMAC extends Hash{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,ahash(t);const ie=toBytes(n);if(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 fe=this.blockLen,ae=new Uint8Array(fe);ae.set(ie.length>fe?t.create().update(ie).digest():ie);for(let le=0;le<ae.length;le++)ae[le]^=54;this.iHash.update(ae),this.oHash=t.create();for(let le=0;le<ae.length;le++)ae[le]^=106;this.oHash.update(ae),clean(ae)}update(t){return aexists(this),this.iHash.update(t),this}digestInto(t){aexists(this),abytes(t,this.outputLen),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:ie,finished:fe,destroyed:ae,blockLen:le,outputLen:he}=this;return t=t,t.finished=fe,t.destroyed=ae,t.blockLen=le,t.outputLen=he,t.oHash=n._cloneInto(t.oHash),t.iHash=ie._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(c,t,n)=>new HMAC(c,t).update(n).digest();hmac.create=(c,t)=>new HMAC(c,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const divNearest=(c,t)=>(c+(c>=0?t:-t)/_2n$1)/t;function _splitEndoScalar(c,t,n){const[[ie,fe],[ae,le]]=t,he=divNearest(le*c,n),ye=divNearest(-fe*c,n);let me=c-he*ie-ye*ae,xe=-he*fe-ye*le;const Ee=me<_0n,Se=xe<_0n;Ee&&(me=-me),Se&&(xe=-xe);const Me=bitMask(Math.ceil(bitLen(n)/2))+_1n;if(me<_0n||me>=Me||xe<_0n||xe>=Me)throw new Error("splitScalar (endomorphism): failed, k="+c);return{k1neg:Ee,k1:me,k2neg:Se,k2:xe}}function validateSigFormat(c){if(!["compact","recovered","der"].includes(c))throw new Error('Signature format must be "compact", "recovered", or "der"');return c}function validateSigOpts(c,t){const n={};for(let ie of Object.keys(t))n[ie]=c[ie]===void 0?t[ie]:c[ie];return _abool2(n.lowS,"lowS"),_abool2(n.prehash,"prehash"),n.format!==void 0&&validateSigFormat(n.format),n}class DERErr extends Error{constructor(t=""){super(t)}}const DER={Err:DERErr,_tlv:{encode:(c,t)=>{const{Err:n}=DER;if(c<0||c>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const ie=t.length/2,fe=numberToHexUnpadded(ie);if(fe.length/2&128)throw new n("tlv.encode: long form length too big");const ae=ie>127?numberToHexUnpadded(fe.length/2|128):"";return numberToHexUnpadded(c)+ae+fe+t},decode(c,t){const{Err:n}=DER;let ie=0;if(c<0||c>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[ie++]!==c)throw new n("tlv.decode: wrong tlv");const fe=t[ie++],ae=!!(fe&128);let le=0;if(!ae)le=fe;else{const ye=fe&127;if(!ye)throw new n("tlv.decode(long): indefinite length not supported");if(ye>4)throw new n("tlv.decode(long): byte length is too big");const me=t.subarray(ie,ie+ye);if(me.length!==ye)throw new n("tlv.decode: length bytes not complete");if(me[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const xe of me)le=le<<8|xe;if(ie+=ye,le<128)throw new n("tlv.decode(long): not minimal encoding")}const he=t.subarray(ie,ie+le);if(he.length!==le)throw new n("tlv.decode: wrong value length");return{v:he,l:t.subarray(ie+le)}}},_int:{encode(c){const{Err:t}=DER;if(c<_0n)throw new t("integer: negative integers are not allowed");let n=numberToHexUnpadded(c);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(c){const{Err:t}=DER;if(c[0]&128)throw new t("invalid signature integer: negative");if(c[0]===0&&!(c[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return bytesToNumberBE(c)}},toSig(c){const{Err:t,_int:n,_tlv:ie}=DER,fe=ensureBytes("signature",c),{v:ae,l:le}=ie.decode(48,fe);if(le.length)throw new t("invalid signature: left bytes after parsing");const{v:he,l:ye}=ie.decode(2,ae),{v:me,l:xe}=ie.decode(2,ye);if(xe.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(he),s:n.decode(me)}},hexFromSig(c){const{_tlv:t,_int:n}=DER,ie=t.encode(2,n.encode(c.r)),fe=t.encode(2,n.encode(c.s)),ae=ie+fe;return t.encode(48,ae)}},_0n=BigInt(0),_1n=BigInt(1),_2n$1=BigInt(2),_3n=BigInt(3),_4n=BigInt(4);function _normFnElement(c,t){const{BYTES:n}=c;let ie;if(typeof t=="bigint")ie=t;else{let fe=ensureBytes("private key",t);try{ie=c.fromBytes(fe)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!c.isValidNot0(ie))throw new Error("invalid private key: out of range [1..N-1]");return ie}function weierstrassN(c,t={}){const n=_createCurveFields("weierstrass",c,t),{Fp:ie,Fn:fe}=n;let ae=n.CURVE;const{h:le,n:he}=ae;_validateObject(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:ye}=t;if(ye&&(!ie.is0(ae.a)||typeof ye.beta!="bigint"||!Array.isArray(ye.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const me=getWLengths(ie,fe);function xe(){if(!ie.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function Ee(se,ce,de){const{x:pe,y:ve}=ce.toAffine(),we=ie.toBytes(pe);if(_abool2(de,"isCompressed"),de){xe();const Ae=!ie.isOdd(ve);return concatBytes(pprefix(Ae),we)}else return concatBytes(Uint8Array.of(4),we,ie.toBytes(ve))}function Se(se){_abytes2(se,void 0,"Point");const{publicKey:ce,publicKeyUncompressed:de}=me,pe=se.length,ve=se[0],we=se.subarray(1);if(pe===ce&&(ve===2||ve===3)){const Ae=ie.fromBytes(we);if(!ie.isValid(Ae))throw new Error("bad point: is not on curve, wrong x");const ge=$e(Ae);let ue;try{ue=ie.sqrt(ge)}catch(Ne){const Fe=Ne instanceof Error?": "+Ne.message:"";throw new Error("bad point: is not on curve, sqrt error"+Fe)}xe();const be=ie.isOdd(ue);return(ve&1)===1!==be&&(ue=ie.neg(ue)),{x:Ae,y:ue}}else if(pe===de&&ve===4){const Ae=ie.BYTES,ge=ie.fromBytes(we.subarray(0,Ae)),ue=ie.fromBytes(we.subarray(Ae,Ae*2));if(!Ce(ge,ue))throw new Error("bad point: is not on curve");return{x:ge,y:ue}}else throw new Error(`bad point: got length ${pe}, expected compressed=${ce} or uncompressed=${de}`)}const Me=t.toBytes||Ee,Be=t.fromBytes||Se;function $e(se){const ce=ie.sqr(se),de=ie.mul(ce,se);return ie.add(ie.add(de,ie.mul(se,ae.a)),ae.b)}function Ce(se,ce){const de=ie.sqr(ce),pe=$e(se);return ie.eql(de,pe)}if(!Ce(ae.Gx,ae.Gy))throw new Error("bad curve params: generator point");const ke=ie.mul(ie.pow(ae.a,_3n),_4n),Pe=ie.mul(ie.sqr(ae.b),BigInt(27));if(ie.is0(ie.add(ke,Pe)))throw new Error("bad curve params: a or b");function Ue(se,ce,de=!1){if(!ie.isValid(ce)||de&&ie.is0(ce))throw new Error(`bad point coordinate ${se}`);return ce}function qe(se){if(!(se instanceof Ke))throw new Error("ProjectivePoint expected")}function He(se){if(!ye||!ye.basises)throw new Error("no endo");return _splitEndoScalar(se,ye.basises,fe.ORDER)}const Ve=memoized((se,ce)=>{const{X:de,Y:pe,Z:ve}=se;if(ie.eql(ve,ie.ONE))return{x:de,y:pe};const we=se.is0();ce==null&&(ce=we?ie.ONE:ie.inv(ve));const Ae=ie.mul(de,ce),ge=ie.mul(pe,ce),ue=ie.mul(ve,ce);if(we)return{x:ie.ZERO,y:ie.ZERO};if(!ie.eql(ue,ie.ONE))throw new Error("invZ was invalid");return{x:Ae,y:ge}}),Ye=memoized(se=>{if(se.is0()){if(t.allowInfinityPoint&&!ie.is0(se.Y))return;throw new Error("bad point: ZERO")}const{x:ce,y:de}=se.toAffine();if(!ie.isValid(ce)||!ie.isValid(de))throw new Error("bad point: x or y not field elements");if(!Ce(ce,de))throw new Error("bad point: equation left != right");if(!se.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Qe(se,ce,de,pe,ve){return de=new Ke(ie.mul(de.X,se),de.Y,de.Z),ce=negateCt(pe,ce),de=negateCt(ve,de),ce.add(de)}class Ke{constructor(ce,de,pe){this.X=Ue("x",ce),this.Y=Ue("y",de,!0),this.Z=Ue("z",pe),Object.freeze(this)}static CURVE(){return ae}static fromAffine(ce){const{x:de,y:pe}=ce||{};if(!ce||!ie.isValid(de)||!ie.isValid(pe))throw new Error("invalid affine point");if(ce instanceof Ke)throw new Error("projective point not allowed");return ie.is0(de)&&ie.is0(pe)?Ke.ZERO:new Ke(de,pe,ie.ONE)}static fromBytes(ce){const de=Ke.fromAffine(Be(_abytes2(ce,void 0,"point")));return de.assertValidity(),de}static fromHex(ce){return Ke.fromBytes(ensureBytes("pointHex",ce))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(ce=8,de=!0){return _e.createCache(this,ce),de||this.multiply(_3n),this}assertValidity(){Ye(this)}hasEvenY(){const{y:ce}=this.toAffine();if(!ie.isOdd)throw new Error("Field doesn't support isOdd");return!ie.isOdd(ce)}equals(ce){qe(ce);const{X:de,Y:pe,Z:ve}=this,{X:we,Y:Ae,Z:ge}=ce,ue=ie.eql(ie.mul(de,ge),ie.mul(we,ve)),be=ie.eql(ie.mul(pe,ge),ie.mul(Ae,ve));return ue&&be}negate(){return new Ke(this.X,ie.neg(this.Y),this.Z)}double(){const{a:ce,b:de}=ae,pe=ie.mul(de,_3n),{X:ve,Y:we,Z:Ae}=this;let ge=ie.ZERO,ue=ie.ZERO,be=ie.ZERO,Re=ie.mul(ve,ve),Ne=ie.mul(we,we),Fe=ie.mul(Ae,Ae),Ie=ie.mul(ve,we);return Ie=ie.add(Ie,Ie),be=ie.mul(ve,Ae),be=ie.add(be,be),ge=ie.mul(ce,be),ue=ie.mul(pe,Fe),ue=ie.add(ge,ue),ge=ie.sub(Ne,ue),ue=ie.add(Ne,ue),ue=ie.mul(ge,ue),ge=ie.mul(Ie,ge),be=ie.mul(pe,be),Fe=ie.mul(ce,Fe),Ie=ie.sub(Re,Fe),Ie=ie.mul(ce,Ie),Ie=ie.add(Ie,be),be=ie.add(Re,Re),Re=ie.add(be,Re),Re=ie.add(Re,Fe),Re=ie.mul(Re,Ie),ue=ie.add(ue,Re),Fe=ie.mul(we,Ae),Fe=ie.add(Fe,Fe),Re=ie.mul(Fe,Ie),ge=ie.sub(ge,Re),be=ie.mul(Fe,Ne),be=ie.add(be,be),be=ie.add(be,be),new Ke(ge,ue,be)}add(ce){qe(ce);const{X:de,Y:pe,Z:ve}=this,{X:we,Y:Ae,Z:ge}=ce;let ue=ie.ZERO,be=ie.ZERO,Re=ie.ZERO;const Ne=ae.a,Fe=ie.mul(ae.b,_3n);let Ie=ie.mul(de,we),je=ie.mul(pe,Ae),Te=ie.mul(ve,ge),De=ie.add(de,pe),ze=ie.add(we,Ae);De=ie.mul(De,ze),ze=ie.add(Ie,je),De=ie.sub(De,ze),ze=ie.add(de,ve);let Xe=ie.add(we,ge);return ze=ie.mul(ze,Xe),Xe=ie.add(Ie,Te),ze=ie.sub(ze,Xe),Xe=ie.add(pe,ve),ue=ie.add(Ae,ge),Xe=ie.mul(Xe,ue),ue=ie.add(je,Te),Xe=ie.sub(Xe,ue),Re=ie.mul(Ne,ze),ue=ie.mul(Fe,Te),Re=ie.add(ue,Re),ue=ie.sub(je,Re),Re=ie.add(je,Re),be=ie.mul(ue,Re),je=ie.add(Ie,Ie),je=ie.add(je,Ie),Te=ie.mul(Ne,Te),ze=ie.mul(Fe,ze),je=ie.add(je,Te),Te=ie.sub(Ie,Te),Te=ie.mul(Ne,Te),ze=ie.add(ze,Te),Ie=ie.mul(je,ze),be=ie.add(be,Ie),Ie=ie.mul(Xe,ze),ue=ie.mul(De,ue),ue=ie.sub(ue,Ie),Ie=ie.mul(De,je),Re=ie.mul(Xe,Re),Re=ie.add(Re,Ie),new Ke(ue,be,Re)}subtract(ce){return this.add(ce.negate())}is0(){return this.equals(Ke.ZERO)}multiply(ce){const{endo:de}=t;if(!fe.isValidNot0(ce))throw new Error("invalid scalar: out of range");let pe,ve;const we=Ae=>_e.cached(this,Ae,ge=>normalizeZ(Ke,ge));if(de){const{k1neg:Ae,k1:ge,k2neg:ue,k2:be}=He(ce),{p:Re,f:Ne}=we(ge),{p:Fe,f:Ie}=we(be);ve=Ne.add(Ie),pe=Qe(de.beta,Re,Fe,Ae,ue)}else{const{p:Ae,f:ge}=we(ce);pe=Ae,ve=ge}return normalizeZ(Ke,[pe,ve])[0]}multiplyUnsafe(ce){const{endo:de}=t,pe=this;if(!fe.isValid(ce))throw new Error("invalid scalar: out of range");if(ce===_0n||pe.is0())return Ke.ZERO;if(ce===_1n)return pe;if(_e.hasCache(this))return this.multiply(ce);if(de){const{k1neg:ve,k1:we,k2neg:Ae,k2:ge}=He(ce),{p1:ue,p2:be}=mulEndoUnsafe(Ke,pe,we,ge);return Qe(de.beta,ue,be,ve,Ae)}else return _e.unsafe(pe,ce)}multiplyAndAddUnsafe(ce,de,pe){const ve=this.multiplyUnsafe(de).add(ce.multiplyUnsafe(pe));return ve.is0()?void 0:ve}toAffine(ce){return Ve(this,ce)}isTorsionFree(){const{isTorsionFree:ce}=t;return le===_1n?!0:ce?ce(Ke,this):_e.unsafe(this,he).is0()}clearCofactor(){const{clearCofactor:ce}=t;return le===_1n?this:ce?ce(Ke,this):this.multiplyUnsafe(le)}isSmallOrder(){return this.multiplyUnsafe(le).is0()}toBytes(ce=!0){return _abool2(ce,"isCompressed"),this.assertValidity(),Me(Ke,this,ce)}toHex(ce=!0){return bytesToHex(this.toBytes(ce))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(ce=!0){return this.toBytes(ce)}_setWindowSize(ce){this.precompute(ce)}static normalizeZ(ce){return normalizeZ(Ke,ce)}static msm(ce,de){return pippenger(Ke,fe,ce,de)}static fromPrivateKey(ce){return Ke.BASE.multiply(_normFnElement(fe,ce))}}Ke.BASE=new Ke(ae.Gx,ae.Gy,ie.ONE),Ke.ZERO=new Ke(ie.ZERO,ie.ONE,ie.ZERO),Ke.Fp=ie,Ke.Fn=fe;const Pt=fe.BITS,_e=new wNAF(Ke,t.endo?Math.ceil(Pt/2):Pt);return Ke.BASE.precompute(8),Ke}function pprefix(c){return Uint8Array.of(c?2:3)}function getWLengths(c,t){return{secretKey:t.BYTES,publicKey:1+c.BYTES,publicKeyUncompressed:1+2*c.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function ecdh(c,t={}){const{Fn:n}=c,ie=t.randomBytes||randomBytes,fe=Object.assign(getWLengths(c.Fp,n),{seed:getMinHashLength(n.ORDER)});function ae(Me){try{return!!_normFnElement(n,Me)}catch{return!1}}function le(Me,Be){const{publicKey:$e,publicKeyUncompressed:Ce}=fe;try{const ke=Me.length;return Be===!0&&ke!==$e||Be===!1&&ke!==Ce?!1:!!c.fromBytes(Me)}catch{return!1}}function he(Me=ie(fe.seed)){return mapHashToField(_abytes2(Me,fe.seed,"seed"),n.ORDER)}function ye(Me,Be=!0){return c.BASE.multiply(_normFnElement(n,Me)).toBytes(Be)}function me(Me){const Be=he(Me);return{secretKey:Be,publicKey:ye(Be)}}function xe(Me){if(typeof Me=="bigint")return!1;if(Me instanceof c)return!0;const{secretKey:Be,publicKey:$e,publicKeyUncompressed:Ce}=fe;if(n.allowedLengths||Be===$e)return;const ke=ensureBytes("key",Me).length;return ke===$e||ke===Ce}function Ee(Me,Be,$e=!0){if(xe(Me)===!0)throw new Error("first arg must be private key");if(xe(Be)===!1)throw new Error("second arg must be public key");const Ce=_normFnElement(n,Me);return c.fromHex(Be).multiply(Ce).toBytes($e)}return Object.freeze({getPublicKey:ye,getSharedSecret:Ee,keygen:me,Point:c,utils:{isValidSecretKey:ae,isValidPublicKey:le,randomSecretKey:he,isValidPrivateKey:ae,randomPrivateKey:he,normPrivateKeyToScalar:Me=>_normFnElement(n,Me),precompute(Me=8,Be=c.BASE){return Be.precompute(Me,!1)}},lengths:fe})}function ecdsa(c,t,n={}){ahash(t),_validateObject(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const ie=n.randomBytes||randomBytes,fe=n.hmac||((de,...pe)=>hmac(t,de,concatBytes(...pe))),{Fp:ae,Fn:le}=c,{ORDER:he,BITS:ye}=le,{keygen:me,getPublicKey:xe,getSharedSecret:Ee,utils:Se,lengths:Me}=ecdh(c,n),Be={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},$e="compact";function Ce(de){const pe=he>>_1n;return de>pe}function ke(de,pe){if(!le.isValidNot0(pe))throw new Error(`invalid signature ${de}: out of range 1..Point.Fn.ORDER`);return pe}function Pe(de,pe){validateSigFormat(pe);const ve=Me.signature,we=pe==="compact"?ve:pe==="recovered"?ve+1:void 0;return _abytes2(de,we,`${pe} signature`)}class Ue{constructor(pe,ve,we){this.r=ke("r",pe),this.s=ke("s",ve),we!=null&&(this.recovery=we),Object.freeze(this)}static fromBytes(pe,ve=$e){Pe(pe,ve);let we;if(ve==="der"){const{r:be,s:Re}=DER.toSig(_abytes2(pe));return new Ue(be,Re)}ve==="recovered"&&(we=pe[0],ve="compact",pe=pe.subarray(1));const Ae=le.BYTES,ge=pe.subarray(0,Ae),ue=pe.subarray(Ae,Ae*2);return new Ue(le.fromBytes(ge),le.fromBytes(ue),we)}static fromHex(pe,ve){return this.fromBytes(hexToBytes(pe),ve)}addRecoveryBit(pe){return new Ue(this.r,this.s,pe)}recoverPublicKey(pe){const ve=ae.ORDER,{r:we,s:Ae,recovery:ge}=this;if(ge==null||![0,1,2,3].includes(ge))throw new Error("recovery id invalid");if(he*_2n$1<ve&&ge>1)throw new Error("recovery id is ambiguous for h>1 curve");const be=ge===2||ge===3?we+he:we;if(!ae.isValid(be))throw new Error("recovery id 2 or 3 invalid");const Re=ae.toBytes(be),Ne=c.fromBytes(concatBytes(pprefix((ge&1)===0),Re)),Fe=le.inv(be),Ie=He(ensureBytes("msgHash",pe)),je=le.create(-Ie*Fe),Te=le.create(Ae*Fe),De=c.BASE.multiplyUnsafe(je).add(Ne.multiplyUnsafe(Te));if(De.is0())throw new Error("point at infinify");return De.assertValidity(),De}hasHighS(){return Ce(this.s)}toBytes(pe=$e){if(validateSigFormat(pe),pe==="der")return hexToBytes(DER.hexFromSig(this));const ve=le.toBytes(this.r),we=le.toBytes(this.s);if(pe==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return concatBytes(Uint8Array.of(this.recovery),ve,we)}return concatBytes(ve,we)}toHex(pe){return bytesToHex(this.toBytes(pe))}assertValidity(){}static fromCompact(pe){return Ue.fromBytes(ensureBytes("sig",pe),"compact")}static fromDER(pe){return Ue.fromBytes(ensureBytes("sig",pe),"der")}normalizeS(){return this.hasHighS()?new Ue(this.r,le.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return bytesToHex(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return bytesToHex(this.toBytes("compact"))}}const qe=n.bits2int||function(pe){if(pe.length>8192)throw new Error("input is too large");const ve=bytesToNumberBE(pe),we=pe.length*8-ye;return we>0?ve>>BigInt(we):ve},He=n.bits2int_modN||function(pe){return le.create(qe(pe))},Ve=bitMask(ye);function Ye(de){return aInRange("num < 2^"+ye,de,_0n,Ve),le.toBytes(de)}function Qe(de,pe){return _abytes2(de,void 0,"message"),pe?_abytes2(t(de),void 0,"prehashed message"):de}function Ke(de,pe,ve){if(["recovered","canonical"].some(je=>je in ve))throw new Error("sign() legacy options not supported");const{lowS:we,prehash:Ae,extraEntropy:ge}=validateSigOpts(ve,Be);de=Qe(de,Ae);const ue=He(de),be=_normFnElement(le,pe),Re=[Ye(be),Ye(ue)];if(ge!=null&&ge!==!1){const je=ge===!0?ie(Me.secretKey):ge;Re.push(ensureBytes("extraEntropy",je))}const Ne=concatBytes(...Re),Fe=ue;function Ie(je){const Te=qe(je);if(!le.isValidNot0(Te))return;const De=le.inv(Te),ze=c.BASE.multiply(Te).toAffine(),Xe=le.create(ze.x);if(Xe===_0n)return;const Rt=le.create(De*le.create(Fe+Xe*be));if(Rt===_0n)return;let Oe=(ze.x===Xe?0:2)|Number(ze.y&_1n),Ze=Rt;return we&&Ce(Rt)&&(Ze=le.neg(Rt),Oe^=1),new Ue(Xe,Ze,Oe)}return{seed:Ne,k2sig:Ie}}function Pt(de,pe,ve={}){de=ensureBytes("message",de);const{seed:we,k2sig:Ae}=Ke(de,pe,ve);return createHmacDrbg(t.outputLen,le.BYTES,fe)(we,Ae)}function _e(de){let pe;const ve=typeof de=="string"||isBytes(de),we=!ve&&de!==null&&typeof de=="object"&&typeof de.r=="bigint"&&typeof de.s=="bigint";if(!ve&&!we)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(we)pe=new Ue(de.r,de.s);else if(ve){try{pe=Ue.fromBytes(ensureBytes("sig",de),"der")}catch(Ae){if(!(Ae instanceof DER.Err))throw Ae}if(!pe)try{pe=Ue.fromBytes(ensureBytes("sig",de),"compact")}catch{return!1}}return pe||!1}function se(de,pe,ve,we={}){const{lowS:Ae,prehash:ge,format:ue}=validateSigOpts(we,Be);if(ve=ensureBytes("publicKey",ve),pe=Qe(ensureBytes("message",pe),ge),"strict"in we)throw new Error("options.strict was renamed to lowS");const be=ue===void 0?_e(de):Ue.fromBytes(ensureBytes("sig",de),ue);if(be===!1)return!1;try{const Re=c.fromBytes(ve);if(Ae&&be.hasHighS())return!1;const{r:Ne,s:Fe}=be,Ie=He(pe),je=le.inv(Fe),Te=le.create(Ie*je),De=le.create(Ne*je),ze=c.BASE.multiplyUnsafe(Te).add(Re.multiplyUnsafe(De));return ze.is0()?!1:le.create(ze.x)===Ne}catch{return!1}}function ce(de,pe,ve={}){const{prehash:we}=validateSigOpts(ve,Be);return pe=Qe(pe,we),Ue.fromBytes(de,"recovered").recoverPublicKey(pe).toBytes()}return Object.freeze({keygen:me,getPublicKey:xe,getSharedSecret:Ee,utils:Se,lengths:Me,Point:c,sign:Pt,verify:se,recoverPublicKey:ce,Signature:Ue,hash:t})}function _weierstrass_legacy_opts_to_new(c){const t={a:c.a,b:c.b,p:c.Fp.ORDER,n:c.n,h:c.h,Gx:c.Gx,Gy:c.Gy},n=c.Fp;let ie=c.allowedPrivateKeyLengths?Array.from(new Set(c.allowedPrivateKeyLengths.map(le=>Math.ceil(le/2)))):void 0;const fe=Field(t.n,{BITS:c.nBitLength,allowedLengths:ie,modFromBytes:c.wrapPrivateKey}),ae={Fp:n,Fn:fe,allowInfinityPoint:c.allowInfinityPoint,endo:c.endo,isTorsionFree:c.isTorsionFree,clearCofactor:c.clearCofactor,fromBytes:c.fromBytes,toBytes:c.toBytes};return{CURVE:t,curveOpts:ae}}function _ecdsa_legacy_opts_to_new(c){const{CURVE:t,curveOpts:n}=_weierstrass_legacy_opts_to_new(c),ie={hmac:c.hmac,randomBytes:c.randomBytes,lowS:c.lowS,bits2int:c.bits2int,bits2int_modN:c.bits2int_modN};return{CURVE:t,curveOpts:n,hash:c.hash,ecdsaOpts:ie}}function _ecdsa_new_output_to_legacy(c,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},c,nLength(n.Fn.ORDER,n.Fn.BITS))})}function weierstrass(c){const{CURVE:t,curveOpts:n,hash:ie,ecdsaOpts:fe}=_ecdsa_legacy_opts_to_new(c),ae=weierstrassN(t,n),le=ecdsa(ae,ie,fe);return _ecdsa_new_output_to_legacy(c,le)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function createCurve(c,t){const n=ie=>weierstrass({...c,hash:ie});return{...n(t),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},secp256k1_ENDO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},_2n=BigInt(2);function sqrtMod(c){const t=secp256k1_CURVE.p,n=BigInt(3),ie=BigInt(6),fe=BigInt(11),ae=BigInt(22),le=BigInt(23),he=BigInt(44),ye=BigInt(88),me=c*c*c%t,xe=me*me*c%t,Ee=pow2(xe,n,t)*xe%t,Se=pow2(Ee,n,t)*xe%t,Me=pow2(Se,_2n,t)*me%t,Be=pow2(Me,fe,t)*Me%t,$e=pow2(Be,ae,t)*Be%t,Ce=pow2($e,he,t)*$e%t,ke=pow2(Ce,ye,t)*Ce%t,Pe=pow2(ke,he,t)*$e%t,Ue=pow2(Pe,n,t)*xe%t,qe=pow2(Ue,le,t)*Be%t,He=pow2(qe,ie,t)*me%t,Ve=pow2(He,_2n,t);if(!Fpk1.eql(Fpk1.sqr(Ve),c))throw new Error("Cannot find square root");return Ve}const Fpk1=Field(secp256k1_CURVE.p,{sqrt:sqrtMod}),secp256k1$1=createCurve({...secp256k1_CURVE,Fp:Fpk1,lowS:!0,endo:secp256k1_ENDO},sha256$5);ed25519.utils.randomPrivateKey;ed25519.getPublicKey;function isOnCurve(c){try{return ed25519.ExtendedPoint.fromHex(c),!0}catch{return!1}}const sign$2=(c,t)=>ed25519.sign(c,t.slice(0,32)),verify$1=ed25519.verify,toBuffer$1=c=>Buffer$1$1.isBuffer(c)?c:c instanceof Uint8Array?Buffer$1$1.from(c.buffer,c.byteOffset,c.byteLength):Buffer$1$1.from(c);class Struct{constructor(t){Object.assign(this,t)}encode(){return Buffer$1$1.from(serialize_1(SOLANA_SCHEMA,this))}static decode(t){return deserialize_1(SOLANA_SCHEMA,this,t)}static decodeUnchecked(t){return deserializeUnchecked_1(SOLANA_SCHEMA,this,t)}}const SOLANA_SCHEMA=new Map;var _PublicKey;const MAX_SEED_LENGTH=32,PUBLIC_KEY_LENGTH=32;function isPublicKeyData(c){return c._bn!==void 0}let uniquePublicKeyCounter=1;class PublicKey extends Struct{constructor(t){if(super({}),this._bn=void 0,isPublicKeyData(t))this._bn=t._bn;else{if(typeof t=="string"){const n=o$1.decode(t);if(n.length!=PUBLIC_KEY_LENGTH)throw new Error("Invalid public key input");this._bn=new BN$8(n)}else this._bn=new BN$8(t);if(this._bn.byteLength()>PUBLIC_KEY_LENGTH)throw new Error("Invalid public key input")}}static unique(){const t=new PublicKey(uniquePublicKeyCounter);return uniquePublicKeyCounter+=1,new PublicKey(t.toBuffer())}equals(t){return this._bn.eq(t._bn)}toBase58(){return o$1.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const t=this.toBuffer();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}toBuffer(){const t=this._bn.toArrayLike(Buffer$1$1);if(t.length===PUBLIC_KEY_LENGTH)return t;const n=Buffer$1$1.alloc(32);return t.copy(n,32-t.length),n}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(t,n,ie){const fe=Buffer$1$1.concat([t.toBuffer(),Buffer$1$1.from(n),ie.toBuffer()]),ae=sha256$4(fe);return new PublicKey(ae)}static createProgramAddressSync(t,n){let ie=Buffer$1$1.alloc(0);t.forEach(function(ae){if(ae.length>MAX_SEED_LENGTH)throw new TypeError("Max seed length exceeded");ie=Buffer$1$1.concat([ie,toBuffer$1(ae)])}),ie=Buffer$1$1.concat([ie,n.toBuffer(),Buffer$1$1.from("ProgramDerivedAddress")]);const fe=sha256$4(ie);if(isOnCurve(fe))throw new Error("Invalid seeds, address must fall off the curve");return new PublicKey(fe)}static async createProgramAddress(t,n){return this.createProgramAddressSync(t,n)}static findProgramAddressSync(t,n){let ie=255,fe;for(;ie!=0;){try{const ae=t.concat(Buffer$1$1.from([ie]));fe=this.createProgramAddressSync(ae,n)}catch(ae){if(ae instanceof TypeError)throw ae;ie--;continue}return[fe,ie]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(t,n){return this.findProgramAddressSync(t,n)}static isOnCurve(t){const n=new PublicKey(t);return isOnCurve(n.toBytes())}}_PublicKey=PublicKey;PublicKey.default=new _PublicKey("11111111111111111111111111111111");SOLANA_SCHEMA.set(PublicKey,{kind:"struct",fields:[["_bn","u256"]]});new PublicKey("BPFLoader1111111111111111111111111111111111");const PACKET_DATA_SIZE=1232,VERSION_PREFIX_MASK=127,SIGNATURE_LENGTH_IN_BYTES=64;class TransactionExpiredBlockheightExceededError extends Error{constructor(t){super(`Signature ${t} has expired: block height exceeded.`),this.signature=void 0,this.signature=t}}Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class TransactionExpiredTimeoutError extends Error{constructor(t,n){super(`Transaction was not confirmed in ${n.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${t} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=t}}Object.defineProperty(TransactionExpiredTimeoutError.prototype,"name",{value:"TransactionExpiredTimeoutError"});class TransactionExpiredNonceInvalidError extends Error{constructor(t){super(`Signature ${t} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=t}}Object.defineProperty(TransactionExpiredNonceInvalidError.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class MessageAccountKeys{constructor(t,n){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=t,this.accountKeysFromLookups=n}keySegments(){const t=[this.staticAccountKeys];return this.accountKeysFromLookups&&(t.push(this.accountKeysFromLookups.writable),t.push(this.accountKeysFromLookups.readonly)),t}get(t){for(const n of this.keySegments()){if(t<n.length)return n[t];t-=n.length}}get length(){return this.keySegments().flat().length}compileInstructions(t){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const ie=new Map;this.keySegments().flat().forEach((ae,le)=>{ie.set(ae.toBase58(),le)});const fe=ae=>{const le=ie.get(ae.toBase58());if(le===void 0)throw new Error("Encountered an unknown instruction account key during compilation");return le};return t.map(ae=>({programIdIndex:fe(ae.programId),accountKeyIndexes:ae.keys.map(le=>fe(le.pubkey)),data:ae.data}))}}const publicKey$1=(c="publicKey")=>blob(32,c),signature$2=(c="signature")=>blob(64,c),rustString=(c="string")=>{const t=struct([u32("length"),u32("lengthPadding"),blob(offset(u32(),-8),"chars")],c),n=t.decode.bind(t),ie=t.encode.bind(t),fe=t;return fe.decode=(ae,le)=>n(ae,le).chars.toString(),fe.encode=(ae,le,he)=>{const ye={chars:Buffer$1$1.from(ae,"utf8")};return ie(ye,le,he)},fe.alloc=ae=>u32().span+u32().span+Buffer$1$1.from(ae,"utf8").length,fe},authorized=(c="authorized")=>struct([publicKey$1("staker"),publicKey$1("withdrawer")],c),lockup=(c="lockup")=>struct([ns64("unixTimestamp"),ns64("epoch"),publicKey$1("custodian")],c),voteInit=(c="voteInit")=>struct([publicKey$1("nodePubkey"),publicKey$1("authorizedVoter"),publicKey$1("authorizedWithdrawer"),u8("commission")],c),voteAuthorizeWithSeedArgs=(c="voteAuthorizeWithSeedArgs")=>struct([u32("voteAuthorizationType"),publicKey$1("currentAuthorityDerivedKeyOwnerPubkey"),rustString("currentAuthorityDerivedKeySeed"),publicKey$1("newAuthorized")],c);function getAlloc(c,t){const n=fe=>{if(fe.span>=0)return fe.span;if(typeof fe.alloc=="function")return fe.alloc(t[fe.property]);if("count"in fe&&"elementLayout"in fe){const ae=t[fe.property];if(Array.isArray(ae))return ae.length*n(fe.elementLayout)}else if("fields"in fe)return getAlloc({layout:fe},t[fe.property]);return 0};let ie=0;return c.layout.fields.forEach(fe=>{ie+=n(fe)}),ie}function decodeLength(c){let t=0,n=0;for(;;){let ie=c.shift();if(t|=(ie&127)<<n*7,n+=1,!(ie&128))break}return t}function encodeLength(c,t){let n=t;for(;;){let ie=n&127;if(n>>=7,n==0){c.push(ie);break}else ie|=128,c.push(ie)}}function assert$9(c,t){if(!c)throw new Error(t||"Assertion failed")}class CompiledKeys{constructor(t,n){this.payer=void 0,this.keyMetaMap=void 0,this.payer=t,this.keyMetaMap=n}static compile(t,n){const ie=new Map,fe=le=>{const he=le.toBase58();let ye=ie.get(he);return ye===void 0&&(ye={isSigner:!1,isWritable:!1,isInvoked:!1},ie.set(he,ye)),ye},ae=fe(n);ae.isSigner=!0,ae.isWritable=!0;for(const le of t){fe(le.programId).isInvoked=!0;for(const he of le.keys){const ye=fe(he.pubkey);ye.isSigner||(ye.isSigner=he.isSigner),ye.isWritable||(ye.isWritable=he.isWritable)}}return new CompiledKeys(n,ie)}getMessageComponents(){const t=[...this.keyMetaMap.entries()];assert$9(t.length<=256,"Max static account keys length exceeded");const n=t.filter(([,ye])=>ye.isSigner&&ye.isWritable),ie=t.filter(([,ye])=>ye.isSigner&&!ye.isWritable),fe=t.filter(([,ye])=>!ye.isSigner&&ye.isWritable),ae=t.filter(([,ye])=>!ye.isSigner&&!ye.isWritable),le={numRequiredSignatures:n.length+ie.length,numReadonlySignedAccounts:ie.length,numReadonlyUnsignedAccounts:ae.length};{assert$9(n.length>0,"Expected at least one writable signer key");const[ye]=n[0];assert$9(ye===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const he=[...n.map(([ye])=>new PublicKey(ye)),...ie.map(([ye])=>new PublicKey(ye)),...fe.map(([ye])=>new PublicKey(ye)),...ae.map(([ye])=>new PublicKey(ye))];return[le,he]}extractTableLookup(t){const[n,ie]=this.drainKeysFoundInLookupTable(t.state.addresses,le=>!le.isSigner&&!le.isInvoked&&le.isWritable),[fe,ae]=this.drainKeysFoundInLookupTable(t.state.addresses,le=>!le.isSigner&&!le.isInvoked&&!le.isWritable);if(!(n.length===0&&fe.length===0))return[{accountKey:t.key,writableIndexes:n,readonlyIndexes:fe},{writable:ie,readonly:ae}]}drainKeysFoundInLookupTable(t,n){const ie=new Array,fe=new Array;for(const[ae,le]of this.keyMetaMap.entries())if(n(le)){const he=new PublicKey(ae),ye=t.findIndex(me=>me.equals(he));ye>=0&&(assert$9(ye<256,"Max lookup table index exceeded"),ie.push(ye),fe.push(he),this.keyMetaMap.delete(ae))}return[ie,fe]}}const END_OF_BUFFER_ERROR_MESSAGE="Reached end of buffer unexpectedly";function guardedShift(c){if(c.length===0)throw new Error(END_OF_BUFFER_ERROR_MESSAGE);return c.shift()}function guardedSplice(c,...t){const[n]=t;if(t.length===2?n+(t[1]??0)>c.length:n>=c.length)throw new Error(END_OF_BUFFER_ERROR_MESSAGE);return c.splice(...t)}class Message{constructor(t){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=t.header,this.accountKeys=t.accountKeys.map(n=>new PublicKey(n)),this.recentBlockhash=t.recentBlockhash,this.instructions=t.instructions,this.instructions.forEach(n=>this.indexToProgramIds.set(n.programIdIndex,this.accountKeys[n.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(t=>({programIdIndex:t.programIdIndex,accountKeyIndexes:t.accounts,data:o$1.decode(t.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new MessageAccountKeys(this.staticAccountKeys)}static compile(t){const n=CompiledKeys.compile(t.instructions,t.payerKey),[ie,fe]=n.getMessageComponents(),le=new MessageAccountKeys(fe).compileInstructions(t.instructions).map(he=>({programIdIndex:he.programIdIndex,accounts:he.accountKeyIndexes,data:o$1.encode(he.data)}));return new Message({header:ie,accountKeys:fe,recentBlockhash:t.recentBlockhash,instructions:le})}isAccountSigner(t){return t<this.header.numRequiredSignatures}isAccountWritable(t){const n=this.header.numRequiredSignatures;if(t>=this.header.numRequiredSignatures){const ie=t-n,ae=this.accountKeys.length-n-this.header.numReadonlyUnsignedAccounts;return ie<ae}else{const ie=n-this.header.numReadonlySignedAccounts;return t<ie}}isProgramId(t){return this.indexToProgramIds.has(t)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((t,n)=>!this.isProgramId(n))}serialize(){const t=this.accountKeys.length;let n=[];encodeLength(n,t);const ie=this.instructions.map(Ee=>{const{accounts:Se,programIdIndex:Me}=Ee,Be=Array.from(o$1.decode(Ee.data));let $e=[];encodeLength($e,Se.length);let Ce=[];return encodeLength(Ce,Be.length),{programIdIndex:Me,keyIndicesCount:Buffer$1$1.from($e),keyIndices:Se,dataLength:Buffer$1$1.from(Ce),data:Be}});let fe=[];encodeLength(fe,ie.length);let ae=Buffer$1$1.alloc(PACKET_DATA_SIZE);Buffer$1$1.from(fe).copy(ae);let le=fe.length;ie.forEach(Ee=>{const Me=struct([u8("programIdIndex"),blob(Ee.keyIndicesCount.length,"keyIndicesCount"),seq(u8("keyIndex"),Ee.keyIndices.length,"keyIndices"),blob(Ee.dataLength.length,"dataLength"),seq(u8("userdatum"),Ee.data.length,"data")]).encode(Ee,ae,le);le+=Me}),ae=ae.slice(0,le);const he=struct([blob(1,"numRequiredSignatures"),blob(1,"numReadonlySignedAccounts"),blob(1,"numReadonlyUnsignedAccounts"),blob(n.length,"keyCount"),seq(publicKey$1("key"),t,"keys"),publicKey$1("recentBlockhash")]),ye={numRequiredSignatures:Buffer$1$1.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Buffer$1$1.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Buffer$1$1.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Buffer$1$1.from(n),keys:this.accountKeys.map(Ee=>toBuffer$1(Ee.toBytes())),recentBlockhash:o$1.decode(this.recentBlockhash)};let me=Buffer$1$1.alloc(2048);const xe=he.encode(ye,me);return ae.copy(me,xe),me.slice(0,xe+ae.length)}static from(t){let n=[...t];const ie=guardedShift(n);if(ie!==(ie&VERSION_PREFIX_MASK))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const fe=guardedShift(n),ae=guardedShift(n),le=decodeLength(n);let he=[];for(let Se=0;Se<le;Se++){const Me=guardedSplice(n,0,PUBLIC_KEY_LENGTH);he.push(new PublicKey(Buffer$1$1.from(Me)))}const ye=guardedSplice(n,0,PUBLIC_KEY_LENGTH),me=decodeLength(n);let xe=[];for(let Se=0;Se<me;Se++){const Me=guardedShift(n),Be=decodeLength(n),$e=guardedSplice(n,0,Be),Ce=decodeLength(n),ke=guardedSplice(n,0,Ce),Pe=o$1.encode(Buffer$1$1.from(ke));xe.push({programIdIndex:Me,accounts:$e,data:Pe})}const Ee={header:{numRequiredSignatures:ie,numReadonlySignedAccounts:fe,numReadonlyUnsignedAccounts:ae},recentBlockhash:o$1.encode(Buffer$1$1.from(ye)),accountKeys:he,instructions:xe};return new Message(Ee)}}class MessageV0{constructor(t){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=t.header,this.staticAccountKeys=t.staticAccountKeys,this.recentBlockhash=t.recentBlockhash,this.compiledInstructions=t.compiledInstructions,this.addressTableLookups=t.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let t=0;for(const n of this.addressTableLookups)t+=n.readonlyIndexes.length+n.writableIndexes.length;return t}getAccountKeys(t){let n;if(t&&"accountKeysFromLookups"in t&&t.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=t.accountKeysFromLookups.writable.length+t.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");n=t.accountKeysFromLookups}else if(t&&"addressLookupTableAccounts"in t&&t.addressLookupTableAccounts)n=this.resolveAddressTableLookups(t.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new MessageAccountKeys(this.staticAccountKeys,n)}isAccountSigner(t){return t<this.header.numRequiredSignatures}isAccountWritable(t){const n=this.header.numRequiredSignatures,ie=this.staticAccountKeys.length;if(t>=ie){const fe=t-ie,ae=this.addressTableLookups.reduce((le,he)=>le+he.writableIndexes.length,0);return fe<ae}else if(t>=this.header.numRequiredSignatures){const fe=t-n,le=ie-n-this.header.numReadonlyUnsignedAccounts;return fe<le}else{const fe=n-this.header.numReadonlySignedAccounts;return t<fe}}resolveAddressTableLookups(t){const n={writable:[],readonly:[]};for(const ie of this.addressTableLookups){const fe=t.find(ae=>ae.key.equals(ie.accountKey));if(!fe)throw new Error(`Failed to find address lookup table account for table key ${ie.accountKey.toBase58()}`);for(const ae of ie.writableIndexes)if(ae<fe.state.addresses.length)n.writable.push(fe.state.addresses[ae]);else throw new Error(`Failed to find address for index ${ae} in address lookup table ${ie.accountKey.toBase58()}`);for(const ae of ie.readonlyIndexes)if(ae<fe.state.addresses.length)n.readonly.push(fe.state.addresses[ae]);else throw new Error(`Failed to find address for index ${ae} in address lookup table ${ie.accountKey.toBase58()}`)}return n}static compile(t){const n=CompiledKeys.compile(t.instructions,t.payerKey),ie=new Array,fe={writable:new Array,readonly:new Array},ae=t.addressLookupTableAccounts||[];for(const xe of ae){const Ee=n.extractTableLookup(xe);if(Ee!==void 0){const[Se,{writable:Me,readonly:Be}]=Ee;ie.push(Se),fe.writable.push(...Me),fe.readonly.push(...Be)}}const[le,he]=n.getMessageComponents(),me=new MessageAccountKeys(he,fe).compileInstructions(t.instructions);return new MessageV0({header:le,staticAccountKeys:he,recentBlockhash:t.recentBlockhash,compiledInstructions:me,addressTableLookups:ie})}serialize(){const t=Array();encodeLength(t,this.staticAccountKeys.length);const n=this.serializeInstructions(),ie=Array();encodeLength(ie,this.compiledInstructions.length);const fe=this.serializeAddressTableLookups(),ae=Array();encodeLength(ae,this.addressTableLookups.length);const le=struct([u8("prefix"),struct([u8("numRequiredSignatures"),u8("numReadonlySignedAccounts"),u8("numReadonlyUnsignedAccounts")],"header"),blob(t.length,"staticAccountKeysLength"),seq(publicKey$1(),this.staticAccountKeys.length,"staticAccountKeys"),publicKey$1("recentBlockhash"),blob(ie.length,"instructionsLength"),blob(n.length,"serializedInstructions"),blob(ae.length,"addressTableLookupsLength"),blob(fe.length,"serializedAddressTableLookups")]),he=new Uint8Array(PACKET_DATA_SIZE),me=le.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(t),staticAccountKeys:this.staticAccountKeys.map(xe=>xe.toBytes()),recentBlockhash:o$1.decode(this.recentBlockhash),instructionsLength:new Uint8Array(ie),serializedInstructions:n,addressTableLookupsLength:new Uint8Array(ae),serializedAddressTableLookups:fe},he);return he.slice(0,me)}serializeInstructions(){let t=0;const n=new Uint8Array(PACKET_DATA_SIZE);for(const ie of this.compiledInstructions){const fe=Array();encodeLength(fe,ie.accountKeyIndexes.length);const ae=Array();encodeLength(ae,ie.data.length);const le=struct([u8("programIdIndex"),blob(fe.length,"encodedAccountKeyIndexesLength"),seq(u8(),ie.accountKeyIndexes.length,"accountKeyIndexes"),blob(ae.length,"encodedDataLength"),blob(ie.data.length,"data")]);t+=le.encode({programIdIndex:ie.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(fe),accountKeyIndexes:ie.accountKeyIndexes,encodedDataLength:new Uint8Array(ae),data:ie.data},n,t)}return n.slice(0,t)}serializeAddressTableLookups(){let t=0;const n=new Uint8Array(PACKET_DATA_SIZE);for(const ie of this.addressTableLookups){const fe=Array();encodeLength(fe,ie.writableIndexes.length);const ae=Array();encodeLength(ae,ie.readonlyIndexes.length);const le=struct([publicKey$1("accountKey"),blob(fe.length,"encodedWritableIndexesLength"),seq(u8(),ie.writableIndexes.length,"writableIndexes"),blob(ae.length,"encodedReadonlyIndexesLength"),seq(u8(),ie.readonlyIndexes.length,"readonlyIndexes")]);t+=le.encode({accountKey:ie.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(fe),writableIndexes:ie.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(ae),readonlyIndexes:ie.readonlyIndexes},n,t)}return n.slice(0,t)}static deserialize(t){let n=[...t];const ie=guardedShift(n),fe=ie&VERSION_PREFIX_MASK;assert$9(ie!==fe,"Expected versioned message but received legacy message");const ae=fe;assert$9(ae===0,`Expected versioned message with version 0 but found version ${ae}`);const le={numRequiredSignatures:guardedShift(n),numReadonlySignedAccounts:guardedShift(n),numReadonlyUnsignedAccounts:guardedShift(n)},he=[],ye=decodeLength(n);for(let Be=0;Be<ye;Be++)he.push(new PublicKey(guardedSplice(n,0,PUBLIC_KEY_LENGTH)));const me=o$1.encode(guardedSplice(n,0,PUBLIC_KEY_LENGTH)),xe=decodeLength(n),Ee=[];for(let Be=0;Be<xe;Be++){const $e=guardedShift(n),Ce=decodeLength(n),ke=guardedSplice(n,0,Ce),Pe=decodeLength(n),Ue=new Uint8Array(guardedSplice(n,0,Pe));Ee.push({programIdIndex:$e,accountKeyIndexes:ke,data:Ue})}const Se=decodeLength(n),Me=[];for(let Be=0;Be<Se;Be++){const $e=new PublicKey(guardedSplice(n,0,PUBLIC_KEY_LENGTH)),Ce=decodeLength(n),ke=guardedSplice(n,0,Ce),Pe=decodeLength(n),Ue=guardedSplice(n,0,Pe);Me.push({accountKey:$e,writableIndexes:ke,readonlyIndexes:Ue})}return new MessageV0({header:le,staticAccountKeys:he,recentBlockhash:me,compiledInstructions:Ee,addressTableLookups:Me})}}const VersionedMessage={deserializeMessageVersion(c){const t=c[0],n=t&VERSION_PREFIX_MASK;return n===t?"legacy":n},deserialize:c=>{const t=VersionedMessage.deserializeMessageVersion(c);if(t==="legacy")return Message.from(c);if(t===0)return MessageV0.deserialize(c);throw new Error(`Transaction message version ${t} deserialization is not supported`)}};let TransactionStatus=function(c){return c[c.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",c[c.PROCESSED=1]="PROCESSED",c[c.TIMED_OUT=2]="TIMED_OUT",c[c.NONCE_INVALID=3]="NONCE_INVALID",c}({});const DEFAULT_SIGNATURE=Buffer$1$1.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0);class TransactionInstruction{constructor(t){this.keys=void 0,this.programId=void 0,this.data=Buffer$1$1.alloc(0),this.programId=t.programId,this.keys=t.keys,t.data&&(this.data=t.data)}toJSON(){return{keys:this.keys.map(({pubkey:t,isSigner:n,isWritable:ie})=>({pubkey:t.toJSON(),isSigner:n,isWritable:ie})),programId:this.programId.toJSON(),data:[...this.data]}}}class Transaction{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(t){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,!!t)if(t.feePayer&&(this.feePayer=t.feePayer),t.signatures&&(this.signatures=t.signatures),Object.prototype.hasOwnProperty.call(t,"nonceInfo")){const{minContextSlot:n,nonceInfo:ie}=t;this.minNonceContextSlot=n,this.nonceInfo=ie}else if(Object.prototype.hasOwnProperty.call(t,"lastValidBlockHeight")){const{blockhash:n,lastValidBlockHeight:ie}=t;this.recentBlockhash=n,this.lastValidBlockHeight=ie}else{const{recentBlockhash:n,nonceInfo:ie}=t;ie&&(this.nonceInfo=ie),this.recentBlockhash=n}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(t=>t.toJSON()),signers:this.signatures.map(({publicKey:t})=>t.toJSON())}}add(...t){if(t.length===0)throw new Error("No instructions");return t.forEach(n=>{"instructions"in n?this.instructions=this.instructions.concat(n.instructions):"data"in n&&"programId"in n&&"keys"in n?this.instructions.push(n):this.instructions.push(new TransactionInstruction(n))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let t,n;if(this.nonceInfo?(t=this.nonceInfo.nonce,this.instructions[0]!=this.nonceInfo.nonceInstruction?n=[this.nonceInfo.nonceInstruction,...this.instructions]:n=this.instructions):(t=this.recentBlockhash,n=this.instructions),!t)throw new Error("Transaction recentBlockhash required");n.length<1&&console.warn("No instructions provided");let ie;if(this.feePayer)ie=this.feePayer;else if(this.signatures.length>0&&this.signatures[0].publicKey)ie=this.signatures[0].publicKey;else throw new Error("Transaction fee payer required");for(let $e=0;$e<n.length;$e++)if(n[$e].programId===void 0)throw new Error(`Transaction instruction index ${$e} has undefined program id`);const fe=[],ae=[];n.forEach($e=>{$e.keys.forEach(ke=>{ae.push({...ke})});const Ce=$e.programId.toString();fe.includes(Ce)||fe.push(Ce)}),fe.forEach($e=>{ae.push({pubkey:new PublicKey($e),isSigner:!1,isWritable:!1})});const le=[];ae.forEach($e=>{const Ce=$e.pubkey.toString(),ke=le.findIndex(Pe=>Pe.pubkey.toString()===Ce);ke>-1?(le[ke].isWritable=le[ke].isWritable||$e.isWritable,le[ke].isSigner=le[ke].isSigner||$e.isSigner):le.push($e)}),le.sort(function($e,Ce){if($e.isSigner!==Ce.isSigner)return $e.isSigner?-1:1;if($e.isWritable!==Ce.isWritable)return $e.isWritable?-1:1;const ke={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"};return $e.pubkey.toBase58().localeCompare(Ce.pubkey.toBase58(),"en",ke)});const he=le.findIndex($e=>$e.pubkey.equals(ie));if(he>-1){const[$e]=le.splice(he,1);$e.isSigner=!0,$e.isWritable=!0,le.unshift($e)}else le.unshift({pubkey:ie,isSigner:!0,isWritable:!0});for(const $e of this.signatures){const Ce=le.findIndex(ke=>ke.pubkey.equals($e.publicKey));if(Ce>-1)le[Ce].isSigner||(le[Ce].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."));else throw new Error(`unknown signer: ${$e.publicKey.toString()}`)}let ye=0,me=0,xe=0;const Ee=[],Se=[];le.forEach(({pubkey:$e,isSigner:Ce,isWritable:ke})=>{Ce?(Ee.push($e.toString()),ye+=1,ke||(me+=1)):(Se.push($e.toString()),ke||(xe+=1))});const Me=Ee.concat(Se),Be=n.map($e=>{const{data:Ce,programId:ke}=$e;return{programIdIndex:Me.indexOf(ke.toString()),accounts:$e.keys.map(Pe=>Me.indexOf(Pe.pubkey.toString())),data:o$1.encode(Ce)}});return Be.forEach($e=>{assert$9($e.programIdIndex>=0),$e.accounts.forEach(Ce=>assert$9(Ce>=0))}),new Message({header:{numRequiredSignatures:ye,numReadonlySignedAccounts:me,numReadonlyUnsignedAccounts:xe},accountKeys:Me,recentBlockhash:t,instructions:Be})}_compile(){const t=this.compileMessage(),n=t.accountKeys.slice(0,t.header.numRequiredSignatures);return this.signatures.length===n.length&&this.signatures.every((fe,ae)=>n[ae].equals(fe.publicKey))||(this.signatures=n.map(ie=>({signature:null,publicKey:ie}))),t}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(t){return(await t.getFeeForMessage(this.compileMessage())).value}setSigners(...t){if(t.length===0)throw new Error("No signers");const n=new Set;this.signatures=t.filter(ie=>{const fe=ie.toString();return n.has(fe)?!1:(n.add(fe),!0)}).map(ie=>({signature:null,publicKey:ie}))}sign(...t){if(t.length===0)throw new Error("No signers");const n=new Set,ie=[];for(const ae of t){const le=ae.publicKey.toString();n.has(le)||(n.add(le),ie.push(ae))}this.signatures=ie.map(ae=>({signature:null,publicKey:ae.publicKey}));const fe=this._compile();this._partialSign(fe,...ie)}partialSign(...t){if(t.length===0)throw new Error("No signers");const n=new Set,ie=[];for(const ae of t){const le=ae.publicKey.toString();n.has(le)||(n.add(le),ie.push(ae))}const fe=this._compile();this._partialSign(fe,...ie)}_partialSign(t,...n){const ie=t.serialize();n.forEach(fe=>{const ae=sign$2(ie,fe.secretKey);this._addSignature(fe.publicKey,toBuffer$1(ae))})}addSignature(t,n){this._compile(),this._addSignature(t,n)}_addSignature(t,n){assert$9(n.length===64);const ie=this.signatures.findIndex(fe=>t.equals(fe.publicKey));if(ie<0)throw new Error(`unknown signer: ${t.toString()}`);this.signatures[ie].signature=Buffer$1$1.from(n)}verifySignatures(t=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),t)}_getMessageSignednessErrors(t,n){const ie={};for(const{signature:fe,publicKey:ae}of this.signatures)fe===null?n&&(ie.missing||(ie.missing=[])).push(ae):verify$1(fe,t,ae.toBytes())||(ie.invalid||(ie.invalid=[])).push(ae);return ie.invalid||ie.missing?ie:void 0}serialize(t){const{requireAllSignatures:n,verifySignatures:ie}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},t),fe=this.serializeMessage();if(ie){const ae=this._getMessageSignednessErrors(fe,n);if(ae){let le="Signature verification failed.";throw ae.invalid&&(le+=`
|
|
20
20
|
Invalid signature for public key${ae.invalid.length===1?"":"(s)"} [\`${ae.invalid.map(he=>he.toBase58()).join("`, `")}\`].`),ae.missing&&(le+=`
|
package/index.mjs
CHANGED
|
@@ -17415,9 +17415,10 @@ async function claimNFT({
|
|
|
17415
17415
|
"Already Claimed",
|
|
17416
17416
|
"This NFT has already been claimed for this order."
|
|
17417
17417
|
), new Error("NFT already claimed");
|
|
17418
|
+
const Se = me;
|
|
17418
17419
|
await ensureWalletOnChainFromConfig(
|
|
17419
17420
|
le,
|
|
17420
|
-
getChainByName(
|
|
17421
|
+
getChainByName(Se),
|
|
17421
17422
|
ae
|
|
17422
17423
|
);
|
|
17423
17424
|
const $e = await doClaimNFT(
|
|
@@ -17434,7 +17435,16 @@ async function claimNFT({
|
|
|
17434
17435
|
shopContractAddress: he
|
|
17435
17436
|
}
|
|
17436
17437
|
);
|
|
17437
|
-
|
|
17438
|
+
await sendClaim(xe, $e.transactionHash, t);
|
|
17439
|
+
const Ce = getTransactionLink({
|
|
17440
|
+
blockchain: Se,
|
|
17441
|
+
transactionHash: $e.transactionHash,
|
|
17442
|
+
isTestnet: ae === Network.TESTNET
|
|
17443
|
+
});
|
|
17444
|
+
return {
|
|
17445
|
+
...$e,
|
|
17446
|
+
transactionUrl: Ce
|
|
17447
|
+
};
|
|
17438
17448
|
}
|
|
17439
17449
|
class EVMBaseWallet extends Web3Wallet {
|
|
17440
17450
|
constructor(t, n) {
|
|
@@ -12,8 +12,8 @@ export declare class WalletRegistry {
|
|
|
12
12
|
initializeAllProviders(): Promise<void>;
|
|
13
13
|
private getWallet;
|
|
14
14
|
private getGroup;
|
|
15
|
-
doAction(wallet: Wallets, action: Actions, inputs: ActionInputs, network: Network, axiosInstance: KyInstance): Promise<{
|
|
15
|
+
doAction(wallet: Wallets, action: Actions, inputs: ActionInputs, network: Network, axiosInstance: KyInstance): Promise<import('../dtos/action-inputs').IRecordResponse | {
|
|
16
16
|
address: string;
|
|
17
|
-
} | import('../dtos/action-inputs').IClaimNFTResponse>;
|
|
17
|
+
} | import('../dtos/action-inputs').IPaymentResponse | import('../dtos/action-inputs').IClaimNFTResponse>;
|
|
18
18
|
injectWallet(wallet: Web3Wallet): WalletRegistry;
|
|
19
19
|
}
|