droplinked-web3-kit 0.0.34 → 0.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +1 -1
  2. package/index.mjs +47 -14
  3. package/package.json +1 -1
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===Chain.SKALE)return await skalePayment(n,le,ye,Se,pe,Ee,ie);ie.waiting(`The payment is custom? ${me}`),me?await handleCustomTokenApproval(n,Ee,ye,xe,ie):n.tbdValues=n.tbdValues.map(Fe=>parseInt(Fe.toString(),10)),ie.waiting("Performing static call...");try{await Se.callStatic.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{value:me?BigNumber.from(0):n.totalPrice})}catch(Fe){throw new Error("Transaction will fail: "+Fe.message)}ie.waiting("Static Call done");let Me;try{Me=await getGasPrice$1(fe)}catch(Fe){throw new Error("Failed to get gas price: "+Fe.message)}ie.waiting(`Got gas price: ${Me}`),ie.waiting("Calling estimate gas...");let Be;try{Be=await Se.estimateGas.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{value:me?BigNumber.from(0):n.totalPrice})}catch(Fe){throw new Error(`Gas estimation failed: ${Fe.message}. Please check the transaction parameters.`)}ie.waiting(`gas estimation done: ${Be.toString()}`);const $e=Be.mul(105).div(100),ke=me?BigNumber.from(0):BigNumber.from(n.totalPrice);ie.waiting(`Gas limit: ${$e.toString()}, gas price: ${Me.toString()}, base: ${ke.toString()}`);let Te;try{Te=await fe.getBalance(pe)}catch(Fe){throw new Error("Failed to get user balance: "+Fe.message)}ie.waiting(`User balance: ${Te}`);const Pe=ke.add($e.mul(Me));if(Te.lt(Pe))throw new InsufficientBalanceException;ie.waiting("Calling purchase...");const Ue=await Se.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{gasLimit:$e,value:me?BigNumber.from(0):n.totalPrice});return ie.waiting("Waiting for transaction..."),await Ue.wait(),ie.waiting("Transaction done"),{transactionHash:Ue.hash,cryptoAmount:n.totalPrice}}catch(Me){handleError(Me)}},skalePayment=async function(c,t,n,ie,fe,ae,le){try{const pe=t===Network.TESTNET?SkaleUsdcAddressForTestnet:SkaleUsdcAddressForMainnet;return c.tokenAddress=pe,await handleCustomTokenApproval(c,ae,n,fe,le),{transactionHash:(await ie.droplinkedPurchase(c.tbdValues,c.tbdReceivers,pe,"0",c.memo)).hash,cryptoAmount:c.totalPrice}}catch(pe){handleError(pe)}};function handleError(c){var t;throw c instanceof Error?((t=c.code)==null?void 0:t.toString())==="ACTION_REJECTED"||c.message.includes("User denied")||c.message.includes("User cancelled transaction")?new UserDeniedException:c:new Error("An unknown error occurred")}async function claimNFT(c,t,n){console.log({data:c,chainConfig:t,context:n});const{modalInterface:ie}=n,fe=t.provider.getSigner(),ae=getShopABI();ie.waiting("Claiming NFTs...");const le=new Contract(n.shopContractAddress,ae,fe);try{ie.waiting("Claiming NFTs..."),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 pe=c.signature.purchaseData.map(ye=>({amount:ye.amount,productId:BigNumber.from(ye.productId),nullifier:BigNumber.from(ye.nullifier)})),me=await le.claimPurchase(DROPLINKED_MANAGER,c.signature.signature,{cart:pe,shop:n.shopContractAddress});return ie.waiting("Waiting for transaction..."),await me.wait(),ie.success("Claimed NFTs!"),{transactionHash:me.hash}}catch(pe){if(console.error(pe),pe.code&&pe.code.toString()==="ACTION_REJECTED")throw n.modalInterface.error("Transaction Rejected"),new Error("Transaction Rejected");try{const me=le.interface.parseError(pe.data);throw me.name==="OwnableUnauthorizedAccount"&&n.modalInterface.error(me.name),n.modalInterface.error(pe),pe}catch(me){throw ie.error(`Unexpected error: ${me}`),me}}}var TokenStandard=(c=>(c.ERC721="ERC721",c.ERC1155="ERC1155",c.ERC20="ERC20",c))(TokenStandard||{});const airdropABI=[{inputs:[],name:"ArrayLengthMismatch",type:"error"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"airdropId",type:"string"}],name:"AirdropDone",type:"event"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address[]",name:"recipients",type:"address[]"},{internalType:"uint256[]",name:"amounts",type:"uint256[]"},{internalType:"string",name:"memo",type:"string"}],name:"distributeERC1155",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address[]",name:"recipients",type:"address[]"},{internalType:"uint256[]",name:"amounts",type:"uint256[]"},{internalType:"string",name:"memo",type:"string"}],name:"distributeERC20",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address[]",name:"recipients",type:"address[]"},{internalType:"uint256[]",name:"tokenIds",type:"uint256[]"},{internalType:"string",name:"memo",type:"string"}],name:"distributeERC721",outputs:[],stateMutability:"nonpayable",type:"function"}];async function sendTransaction(c,t,n,ie,fe){try{return await c.callStatic[t](...n),await c[t](...n)}catch(ae){throw fe.error(`Error simulating ${t} transaction ${ie+1}: ${ae.message}`),ae}}async function approveTokenForAirdrop(c,t,n,ie,fe){if(n!==TokenStandard.ERC1155)throw new Error("Only ERC1155 tokens are supported right now");const ae=["function setApprovalForAll(address, bool) public"],le=new Contract(t,ae,ie);fe.waiting("Approving token for airdrop..."),await(await le.setApprovalForAll(c,!0)).wait(),fe.waiting("Token approved for airdrop")}async function airdrop(c,t,n){const ie=t.modalInterface,fe=c.provider.getSigner();ie.waiting("Connecting to wallet..."),await checkWallet(fe,c.address),ie.waiting("Getting airdrop contract address...");const ae=await getAirdropAddress(c.chain,c.network),le=new Contract(ae,airdropABI,fe);await approveTokenForAirdrop(ae,n.tokenAddress,n.type,fe,ie),ie.waiting("Initializing airdrop");const pe=ye=>{const xe=[],Ee=[];for(const Se of ye)xe.push(Se.receiver),Ee.push(Se.amount);return{receivers:xe,amounts:Ee}},me=(ye,xe,Ee=300)=>{const Se=[];for(let Me=0;Me<ye.length;Me+=Ee)Se.push({receivers:ye.slice(Me,Me+Ee),amounts:xe.slice(Me,Me+Ee)});return Se};try{let ye;const{receivers:xe,amounts:Ee}=pe(n.receivers),Se=n.chunkSize||300,Me=me(xe,Ee,Se),Be=[];for(const[$e,ke]of Me.entries())ie.waiting(`Processing transaction ${$e+1} of ${Me.length}`),n.type===TokenStandard.ERC1155?ye=await sendTransaction(le,"distributeERC1155",[n.tokenAddress,n.tokenId,ke.receivers,ke.amounts,n.airdropId],$e,ie):n.type===TokenStandard.ERC20?ye=await sendTransaction(le,"distributeERC20",[n.tokenAddress,ke.receivers,ke.amounts,n.airdropId],$e,ie):n.type===TokenStandard.ERC721&&(ye=await sendTransaction(le,"distributeERC721",[n.tokenAddress,ke.receivers,ke.amounts,n.airdropId],$e,ie)),ie.waiting(`Transaction ${$e+1} sent: ${ye.hash}`),Be.push(ye.hash),await ye.wait(),ie.waiting(`Transaction ${$e+1} confirmed`);return{transactionHashes:Be}}catch(ye){if(ye.code&&ye.code.toString()==="ACTION_REJECTED")throw t.modalInterface.error("Transaction Rejected"),new Error("Transaction Rejected");try{const xe=le.interface.parseError(ye.data);throw t.modalInterface.error(xe.name),t.modalInterface.error(ye),ye}catch(xe){throw t.modalInterface.error(`Unexpected error: ${xe}`),xe}}}async function getShopInfo(c,t,n){const ie=(await(await n.get(`shops/v2/public/${t}`)).json()).data.deployedContracts.filter(fe=>fe.type===c);return ie.length===0?{nftContractAddress:"",shopContractAddress:""}:{nftContractAddress:ie[0].deployedNFTAddress,shopContractAddress:ie[0].deployedShopAddress}}async function getProductData(c,t){return(await(await t.get(`product-v2/public/${c}`)).json()).data}async function transformProductData(c,t){const n=await getProductData(c,t);if(!n||n.skus.length===0)throw new Error("Product not found or no SKUs available");return{productData:{acceptsManageWallet:!0,commission:n.affiliate.commissionPercent||0,description:n.description,productTitle:n.title,royalty:n.skus[0].royalty||0,type:ProductType[n.type.toUpperCase()]||ProductType.DIGITAL},skuData:n.skus.map(ie=>{var fe;return{amount:ie.inventory.quantity,imageUrl:((fe=n.images[n.defaultImageIndex])==null?void 0:fe.original)||"",skuID:ie.id,skuProperties:ie}})}}async function web3Callback(c,t,n,ie){const fe={"X-API-KEY":"ho8homr9e8p4fwii7tjiz41xs4hlbl2h4i"};return(await(await ky.create({headers:fe,prefixUrl:n==="TESTNET"?"https://web3dev.droplinked.com/":"https://web3.droplinked.com/"}).post("transactions",{json:{transaction_id:c,callback_url:ie,chain:t,network:n},headers:fe})).json()).data}async function startRecord(c,t,n,ie,fe,ae){return(await(await ae.post("web3/record/transactions",{json:{uris:fe,network:ie,data:{productId:c,skuIds:t},productId:c,skuIds:t,metadata:{},shopId:n,txType:"RECORD"}})).json()).data.id}async function startPayment(c,t,n,ie,fe,ae){return(await(await ae.post("web3/payment/transactions",{json:{network:n,token:t,shopId:fe,orderId:c}})).json()).data.id}class EVMProvider{constructor(t,n,ie){this.chain=Chain.BINANCE,this.network=Network.TESTNET,this.modalInterface=new defaultModal,this.wallet=ChainWallet.Metamask,this.chain=t,this.network=n,this.gasPredictable=ie,this.address=ZERO_ADDRESS,this.axiosInstance=ky.create({prefixUrl:this.network===Network.MAINNET?"https://apiv3.droplinked.com":"https://apiv3dev.droplinked.com"})}unstoppableLogin(t,n){throw new Error("Method not implemented.")}getBaseUrl(){return this.network===Network.MAINNET?"https://apiv3.droplinked.com":this.network===Network.TESTNET?"https://apiv3dev.droplinked.com":"http://127.0.0.1:3000"}setAxiosInstance(t){return this.axiosInstance=t,this}setNFTContractAddress(t){return this.nftContractAddress=t,this}setShopContractAddress(t){return this.shopContractAddress=t,this}setWallet(t){return this.wallet=t,this}setModal(t){return this.modalInterface=t,this}async customPayment(t){return await this.handleChain(),await droplinked_payment(this.getChainConfig(),this.getContext(),t)}async claimNFTs(t){return await this.handleWallet(this.address),await this.handleChain(),(await claimNFT(t,this.getChainConfig(),this.getContext())).transactionHash}getWalletProvider(){const t=window.ethereum;if(!t)throw new WalletNotFoundException;if(t.providerMap)if(this.wallet===ChainWallet.Metamask){if(!t.providerMap.get("MetaMask"))throw new WalletNotFoundException;return new Web3Provider(t.providers.find(n=>n.isMetaMask))}else if(this.wallet===ChainWallet.CoinBase){if(!t.providerMap.get("CoinbaseWallet"))throw new WalletNotFoundException;return new Web3Provider(t.providers.find(n=>n.isCoinbaseWallet))}else if(this.wallet===ChainWallet.Phantom){if(!t.providerMap.get("CoinbaseWallet"))throw new WalletNotFoundException;return new Web3Provider(t.providers.find(n=>n.isCoinbaseWallet))}else throw new Error("Wallet not implemented");else{if(this.wallet===ChainWallet.CoinBase){if(!window.ethereum.isCoinbaseWallet)throw new WalletNotFoundException}else if(this.wallet===ChainWallet.Metamask&&!window.ethereum.isMetaMask)throw new WalletNotFoundException;return new Web3Provider(window.ethereum)}}async deployShop(t){return await this.handleWallet(this.address),await this.handleChain(),await deployEVMShop(this.getChainConfig(),{axiosInstance:this.axiosInstance,modalInterface:this.modalInterface},t)}setAddress(t){return this.address=t,this}async handleChain(){const t=this.getWalletProvider();await addChain(t,this.chain,this.network,this.modalInterface),await isChainCorrect(t.provider,this.chain,this.network)||(console.log("Changing chain..."),await changeChain(t.provider,this.chain,this.network))}async handleWallet(t){if(!isMetamaskInstalled())throw this.modalInterface.error("Metamask is not installed"),new WalletNotFoundException;this.modalInterface.waiting("Getting accounts...");const ie=this.getWalletProvider().provider,fe=await getAccounts(ie);if(!isWalletConnected(ie)||fe.length===0){this.modalInterface.waiting("Please connect your wallet");const{address:ae}=await this.walletLogin();t.toLocaleLowerCase()!==ae.toLocaleLowerCase()&&(await window.ethereum.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),await this.handleWallet(t))}if(String(fe[0]).toLocaleLowerCase()!==t.toLocaleLowerCase()&&t!==""&&(this.modalInterface.waiting("Change your account based on the one you used to login..."),await window.ethereum.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),this.handleWallet(t)),this.chain===Chain.SKALE){const ae=await(await this.axiosInstance.post("web3/sFuelDistribution",{json:{wallet:this.address,isTestnet:this.network===Network.TESTNET}})).json();console.log(ae)}this.modalInterface.success("Wallet connected")}getChainConfig(){return{address:this.address,chain:this.chain,network:this.network,provider:this.getWalletProvider(),gasPredictable:this.gasPredictable}}getContext(){return{axiosInstance:this.axiosInstance,modalInterface:this.modalInterface,nftContract:this.nftContractAddress,shopContractAddress:this.shopContractAddress}}async walletLogin(){const{address:t,signature:n,date:ie,nonce:fe}=await evmLogin(this.getWalletProvider(),this.chain,this.network,this.modalInterface,this.axiosInstance);return this.address=t,{address:t,signature:n,date:ie,nonce:fe}}checkDeployment(){if(!this.nftContractAddress)throw new Error("NFT contract address not set");if(!this.shopContractAddress)throw new Error("Shop contract address not set")}async recordProduct(t){const{productData:n,skuData:ie}=await transformProductData(t,this.axiosInstance);if(this.checkDeployment(),!this.shopId)throw new FieldNotFound("shopId");const fe=await startRecord(t,ie.map(me=>me.skuID),this.shopId,this.chain,[],this.axiosInstance);await this.handleWallet(this.address),await this.handleChain();const ae=await recordProduct(this.getChainConfig(),this.getContext(),n,ie);await updateUris(fe,ae.metadataUrls,this.axiosInstance),await updateHash("record",fe,ae.transactionHash,this.axiosInstance);const le=`${this.getBaseUrl()}/web3/record/callback/events/${fe}`;if(!await web3Callback(ae.transactionHash,this.chain,Network[this.network],le))throw new Web3CallbackFailed(`txHash: ${ae.transactionHash}`);return{...ae,transactionId:fe,transactionHashUrl:getTransactionLink({blockchain:this.chain,transactionHash:ae.transactionHash,isTestnet:this.network!==Network.MAINNET})}}setShopId(t){return this.shopId=t,this}async executeAirdrop(t){const n=await getAirdropData(t,this.axiosInstance);return await this.handleWallet(this.address),await this.handleChain(),await airdrop(this.getChainConfig(),this.getContext(),{type:TokenStandard.ERC1155,airdropId:t,receivers:n.receivers,tokenAddress:n.tokenAddress,tokenId:n.tokenId,chunkSize:300})}async payment(t){await this.handleWallet(this.address),await this.handleChain();const{orderID:n,paymentToken:ie,paymentType:fe}=t;if(!this.shopId)throw new FieldNotFound("shopId");const ae=await startPayment(n,ie,fe,this.address,this.shopId,this.axiosInstance),le=await getCartData(n,ie,fe,this.axiosInstance),pe=le.paymentData;console.log({paymentData:pe});const me=await droplinked_payment(this.getChainConfig(),this.getContext(),pe);if(await updateHash("payment",ae,me.transactionHash,this.axiosInstance),!await web3Callback(me.transactionHash,this.chain,Network[this.network],`${this.getBaseUrl()}/web3/payment/callback/${ae}/${me.transactionHash}`))throw new Web3CallbackFailed(`txHash: ${me.transactionHash}`);return{...me,orderID:le.orderID,transactionId:ae}}async getPaymentData(t,n,ie){return await getCartData(t,ie,n,this.axiosInstance)}async paymentWithToken(t,n,ie,fe=18){await this.handleWallet(this.address),await this.handleChain();const ae=erc20ABI,le=this.getWalletProvider().getSigner(),pe=new Contract(ie,ae,le);try{await pe.callStatic.transfer(t,BigInt(Math.floor(n*1e6))*BigInt(10**(fe-6)));const me=(await pe.estimateGas.transfer(t,BigInt(Math.floor(n*1e6))*BigInt(10**(fe-6)))).toBigInt().valueOf(),ye=(await getGasPrice$1(this.getWalletProvider())).valueOf();return(await pe.transfer(t,BigInt(Math.floor(n*1e6))*BigInt(10**(fe-6)),{gasPrice:ye*BigInt(105)/BigInt(100),gasLimit:me*BigInt(105)/BigInt(100)})).hash}catch(me){throw me.reason?me.reason==="ERC20: transfer amount exceeds balance"?new Error("Insufficient token balance"):me.reason==="insufficient funds for gas * price + value"?new Error("Insufficient ETH balance"):me.reason==="bad result from backend"?new Error("Something went wrong, check your eth and token balance"):new Error(me.reason):me}}}var Web3Actions=(c=>(c.LOGIN="LOGIN",c.DEPLOY="DEPLOY",c.RECORD="RECORD",c.PAYMENT="PAYMENT",c.CLAIM="CLAIM",c.AIRDROP="AIRDROP",c))(Web3Actions||{});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)),pe=asciiToBase16(c.charCodeAt(ae+1));if(le===void 0||pe===void 0){const me=c[ae]+c[ae+1];throw new Error('hex string expected, got non-hex character "'+me+'" at index '+ae)}ie[fe]=le*16+pe}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),pe=Number(n&ae),me=ie?4:0,ye=ie?0:4;c.setUint32(t+me,le,ie),c.setUint32(t+ye,pe,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 pe=Math.min(fe-this.pos,ae-le);if(pe===fe){const me=createView(t);for(;fe<=ae-le;le+=fe)this.process(me,le);continue}ie.set(t.subarray(le,le+pe),this.pos),this.pos+=pe,le+=pe,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 pe=createView(t),me=this.outputLen;if(me%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const ye=me/4,xe=this.get();if(ye>xe.length)throw new Error("_sha2: outputLen bigger than state");for(let Ee=0;Ee<ye;Ee++)pe.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:pe}=this;return t.destroyed=le,t.finished=ae,t.length=fe,t.pos=pe,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:pe}=fromBig(c[ae],t);[ie[ae],fe[ae]]=[le,pe]}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:pe,H:me}=this;return[t,n,ie,fe,ae,le,pe,me]}set(t,n,ie,fe,ae,le,pe,me){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=pe|0,this.H=me|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:pe,F:me,G:ye,H:xe}=this;for(let Ee=0;Ee<64;Ee++){const Se=rotr(pe,6)^rotr(pe,11)^rotr(pe,25),Me=xe+Se+Chi(pe,me,ye)+SHA256_K[Ee]+SHA256_W[Ee]|0,$e=(rotr(ie,2)^rotr(ie,13)^rotr(ie,22))+Maj(ie,fe,ae)|0;xe=ye,ye=me,me=pe,pe=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,pe=pe+this.E|0,me=me+this.F|0,ye=ye+this.G|0,xe=xe+this.H|0,this.set(ie,fe,ae,le,pe,me,ye,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:pe,Dl:me,Eh:ye,El:xe,Fh:Ee,Fl:Se,Gh:Me,Gl:Be,Hh:$e,Hl:ke}=this;return[t,n,ie,fe,ae,le,pe,me,ye,xe,Ee,Se,Me,Be,$e,ke]}set(t,n,ie,fe,ae,le,pe,me,ye,xe,Ee,Se,Me,Be,$e,ke){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=pe|0,this.Dl=me|0,this.Eh=ye|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=ke|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 Fe=SHA512_W_H[Ue-15]|0,je=SHA512_W_L[Ue-15]|0,Ve=rotrSH(Fe,je,1)^rotrSH(Fe,je,8)^shrSH(Fe,je,7),Ye=rotrSL(Fe,je,1)^rotrSL(Fe,je,8)^shrSL(Fe,je,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:pe,Cl:me,Dh:ye,Dl:xe,Eh:Ee,El:Se,Fh:Me,Fl:Be,Gh:$e,Gl:ke,Hh:Te,Hl:Pe}=this;for(let Ue=0;Ue<80;Ue++){const Fe=rotrSH(Ee,Se,14)^rotrSH(Ee,Se,18)^rotrBH(Ee,Se,41),je=rotrSL(Ee,Se,14)^rotrSL(Ee,Se,18)^rotrBL(Ee,Se,41),Ve=Ee&Me^~Ee&$e,Ye=Se&Be^~Se&ke,Qe=add5L(Pe,je,Ye,SHA512_Kl[Ue],SHA512_W_L[Ue]),Ke=add5H(Qe,Te,Fe,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&pe^ae&pe,de=fe&le^fe&me^le&me;Te=$e|0,Pe=ke|0,$e=Me|0,ke=Be|0,Me=Ee|0,Be=Se|0,{h:Ee,l:Se}=add(ye|0,xe|0,Ke|0,Pt|0),ye=pe|0,xe=me|0,pe=ae|0,me=le|0,ae=ie|0,le=fe|0;const he=add3L(Pt,se,de);ie=add3H(he,Ke,_e,ce),fe=he|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:pe,l:me}=add(this.Ch|0,this.Cl|0,pe|0,me|0),{h:ye,l:xe}=add(this.Dh|0,this.Dl|0,ye|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:ke}=add(this.Gh|0,this.Gl|0,$e|0,ke|0),{h:Te,l:Pe}=add(this.Hh|0,this.Hl|0,Te|0,Pe|0),this.set(ie,fe,ae,le,pe,me,ye,xe,Ee,Se,Me,Be,$e,ke,Te,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}" `,pe=ae?` of length ${t}`:"",me=ie?`length=${fe}`:`type=${typeof c}`;throw new Error(le+"expected Uint8Array"+pe+", got "+me)}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),pe=0;const me=()=>{ae.fill(1),le.fill(0),pe=0},ye=(...Me)=>n(le,ae,...Me),xe=(Me=ie(0))=>{le=ye(fe(0),Me),ae=ye(),Me.length!==0&&(le=ye(fe(1),Me),ae=ye())},Ee=()=>{if(pe++>=1e3)throw new Error("drbg: tried 1000 values");let Me=0;const Be=[];for(;Me<t;){ae=ye();const $e=ae.slice();Be.push($e),Me+=ae.length}return concatBytes(...Be)};return(Me,Be)=>{me(),xe(Me);let $e;for(;!($e=Be(Ee()));)xe();return me(),$e}}function _validateObject(c,t,n={}){if(!c||typeof c!="object")throw new Error("expected valid options object");function ie(fe,ae,le){const pe=c[fe];if(le&&pe===void 0)return;const me=typeof pe;if(me!==ae||pe===null)throw new Error(`param "${fe}" is invalid: expected ${ae}, got ${me}`)}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 pe=ie/n,me=ie%n,ye=fe-ae*pe;ie=n,n=me,fe=ae,ae=ye}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),pe=c.mul(ae,c.sub(le,c.ONE));return assertIsSquare(c,pe,t),pe}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(pe,me)=>{let ye=pe.pow(me,le),xe=pe.mul(ye,ie);const Ee=pe.mul(ye,fe),Se=pe.mul(ye,ae),Me=pe.eql(pe.sqr(xe),me),Be=pe.eql(pe.sqr(Ee),me);ye=pe.cmov(ye,xe,Me),xe=pe.cmov(Se,Ee,Be);const $e=pe.eql(pe.sqr(xe),me),ke=pe.cmov(ye,xe,$e);return assertIsSquare(pe,ke,me),ke}}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(me,ye){if(me.is0(ye))return ye;if(FpLegendre(me,ye)!==1)throw new Error("Cannot find square root");let xe=n,Ee=me.mul(me.ONE,ae),Se=me.pow(ye,t),Me=me.pow(ye,le);for(;!me.eql(Se,me.ONE);){if(me.is0(Se))return me.ZERO;let Be=1,$e=me.sqr(Se);for(;!me.eql($e,me.ONE);)if(Be++,$e=me.sqr($e),Be===xe)throw new Error("Cannot find square root");const ke=_1n$4<<BigInt(xe-Be-1),Te=me.pow(Ee,ke);xe=Be,Ee=me.sqr(Te),Se=me.mul(Se,Ee),Me=me.mul(Me,Te)}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,pe,me)=>c.is0(pe)?le:(ie[me]=le,c.mul(le,pe)),c.ONE),ae=c.inv(fe);return t.reduceRight((le,pe,me)=>c.is0(pe)?le:(ie[me]=c.mul(le,ie[me]),c.mul(le,pe)),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,pe;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),pe=Se.allowedLengths}else typeof t=="number"&&(fe=t),ie.sqrt&&(ae=ie.sqrt);const{nBitLength:me,nByteLength:ye}=nLength(c,fe);if(ye>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let xe;const Ee=Object.freeze({ORDER:c,isLE:n,BITS:me,BYTES:ye,MASK:bitMask(me),ZERO:_0n$3,ONE:_1n$4,allowedLengths:pe,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,ye):numberToBytesBE(Se,ye),fromBytes:(Se,Me=!0)=>{if(pe){if(!pe.includes(Se.length)||Se.length>ye)throw new Error("Field.fromBytes: expected "+pe+" bytes, got "+Se.length);const $e=new Uint8Array(ye);$e.set(Se,n?0:$e.length-Se.length),Se=$e}if(Se.length!==ye)throw new Error("Field.fromBytes: expected "+ye+" 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),pe=mod(le,t-_1n$4)+_1n$4;return n?numberToBytesLE(pe,fe):numberToBytesBE(pe,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 pe=Number(c&fe),me=c>>le;pe>ie&&(pe-=ae,me+=_1n$3);const ye=t*ie,xe=ye+Math.abs(pe)-1,Ee=pe===0,Se=pe<0,Me=t%2!==0;return{nextN:me,offset:xe,isZero:Ee,isNeg:Se,isNegF:Me,offsetF:ye}}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,pe=le;for(let me=0;me<ie;me++){pe=le,ae.push(pe);for(let ye=1;ye<fe;ye++)pe=pe.add(le),ae.push(pe);le=pe.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 pe=0;pe<le.windows;pe++){const{nextN:me,offset:ye,isZero:xe,isNeg:Ee,isNegF:Se,offsetF:Me}=calcOffsets(ie,pe,le);ie=me,xe?ae=ae.add(negateCt(Se,n[Me])):fe=fe.add(negateCt(Ee,n[ye]))}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:pe,offset:me,isZero:ye,isNeg:xe}=calcOffsets(ie,le,ae);if(ie=pe,!ye){const Ee=n[me];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,pe=bitLen(BigInt(fe));let me=1;pe>12?me=pe-3:pe>4?me=pe-2:pe>0&&(me=2);const ye=bitMask(me),xe=new Array(Number(ye)+1).fill(le),Ee=Math.floor((t.BITS-1)/me)*me;let Se=le;for(let Me=Ee;Me>=0;Me-=me){xe.fill(le);for(let $e=0;$e<ae;$e++){const ke=ie[$e],Te=Number(ke>>BigInt(Me)&ye);xe[Te]=xe[Te].add(n[$e])}let Be=le;for(let $e=xe.length-1,ke=le;$e>0;$e--)ke=ke.add(xe[$e]),Be=Be.add(ke);if(Se=Se.add(Be),Me!==0)for(let $e=0;$e<me;$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 me of["p","n","h"]){const ye=t[me];if(!(typeof ye=="bigint"&&ye>_0n$2))throw new Error(`CURVE.${me} must be positive bigint`)}const fe=createField(t.p,n.Fp,ie),ae=createField(t.n,n.Fn,ie),pe=["Gx","Gy","a",c==="weierstrass"?"b":"d"];for(const me of pe)if(!fe.isValid(t[me]))throw new Error(`CURVE.${me} 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),pe=c.add(c.ONE,c.mul(t.d,c.mul(fe,ae)));return c.eql(le,pe)}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 pe=_2n$3<<BigInt(fe.BYTES*8)-_1n$2,me=ke=>ie.create(ke),ye=t.uvRatio||((ke,Te)=>{try{return{isValid:!0,value:ie.sqrt(ie.div(ke,Te))}}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(ke,Te,Pe=!1){const Ue=Pe?_1n$2:_0n$1;return aInRange("coordinate "+ke,Te,Ue,pe),Te}function Ee(ke){if(!(ke instanceof Be))throw new Error("ExtendedPoint expected")}const Se=memoized((ke,Te)=>{const{X:Pe,Y:Ue,Z:Fe}=ke,je=ke.is0();Te==null&&(Te=je?_8n$1:ie.inv(Fe));const Ve=me(Pe*Te),Ye=me(Ue*Te),Qe=ie.mul(Fe,Te);if(je)return{x:_0n$1,y:_1n$2};if(Qe!==_1n$2)throw new Error("invZ was invalid");return{x:Ve,y:Ye}}),Me=memoized(ke=>{const{a:Te,d:Pe}=ae;if(ke.is0())throw new Error("bad point: ZERO");const{X:Ue,Y:Fe,Z:je,T:Ve}=ke,Ye=me(Ue*Ue),Qe=me(Fe*Fe),Ke=me(je*je),Pt=me(Ke*Ke),_e=me(Ye*Te),se=me(Ke*me(_e+Qe)),ce=me(Pt+me(Pe*me(Ye*Qe)));if(se!==ce)throw new Error("bad point: equation left != right (1)");const de=me(Ue*Fe),he=me(je*Ve);if(de!==he)throw new Error("bad point: equation left != right (2)");return!0});class Be{constructor(Te,Pe,Ue,Fe){this.X=xe("x",Te),this.Y=xe("y",Pe),this.Z=xe("z",Ue,!0),this.T=xe("t",Fe),Object.freeze(this)}static CURVE(){return ae}static fromAffine(Te){if(Te instanceof Be)throw new Error("extended point not allowed");const{x:Pe,y:Ue}=Te||{};return xe("x",Pe),xe("y",Ue),new Be(Pe,Ue,_1n$2,me(Pe*Ue))}static fromBytes(Te,Pe=!1){const Ue=ie.BYTES,{a:Fe,d:je}=ae;Te=copyBytes(_abytes2(Te,Ue,"point")),_abool2(Pe,"zip215");const Ve=copyBytes(Te),Ye=Te[Ue-1];Ve[Ue-1]=Ye&-129;const Qe=bytesToNumberLE(Ve),Ke=Pe?pe:ie.ORDER;aInRange("point.y",Qe,_0n$1,Ke);const Pt=me(Qe*Qe),_e=me(Pt-_1n$2),se=me(je*Pt-Fe);let{isValid:ce,value:de}=ye(_e,se);if(!ce)throw new Error("bad point: invalid y coordinate");const he=(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!==he&&(de=me(-de)),Be.fromAffine({x:de,y:Qe})}static fromHex(Te,Pe=!1){return Be.fromBytes(ensureBytes("point",Te),Pe)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(Te=8,Pe=!0){return $e.createCache(this,Te),Pe||this.multiply(_2n$3),this}assertValidity(){Me(this)}equals(Te){Ee(Te);const{X:Pe,Y:Ue,Z:Fe}=this,{X:je,Y:Ve,Z:Ye}=Te,Qe=me(Pe*Ye),Ke=me(je*Fe),Pt=me(Ue*Ye),_e=me(Ve*Fe);return Qe===Ke&&Pt===_e}is0(){return this.equals(Be.ZERO)}negate(){return new Be(me(-this.X),this.Y,this.Z,me(-this.T))}double(){const{a:Te}=ae,{X:Pe,Y:Ue,Z:Fe}=this,je=me(Pe*Pe),Ve=me(Ue*Ue),Ye=me(_2n$3*me(Fe*Fe)),Qe=me(Te*je),Ke=Pe+Ue,Pt=me(me(Ke*Ke)-je-Ve),_e=Qe+Ve,se=_e-Ye,ce=Qe-Ve,de=me(Pt*se),he=me(_e*ce),ve=me(Pt*ce),we=me(se*_e);return new Be(de,he,we,ve)}add(Te){Ee(Te);const{a:Pe,d:Ue}=ae,{X:Fe,Y:je,Z:Ve,T:Ye}=this,{X:Qe,Y:Ke,Z:Pt,T:_e}=Te,se=me(Fe*Qe),ce=me(je*Ke),de=me(Ye*Ue*_e),he=me(Ve*Pt),ve=me((Fe+je)*(Qe+Ke)-se-ce),we=he-de,Ae=he+de,be=me(ce-Pe*se),ue=me(ve*we),ge=me(Ae*be),Re=me(ve*be),Ne=me(we*Ae);return new Be(ue,ge,Ne,Re)}subtract(Te){return this.add(Te.negate())}multiply(Te){if(!fe.isValidNot0(Te))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:Pe,f:Ue}=$e.cached(this,Te,Fe=>normalizeZ(Be,Fe));return normalizeZ(Be,[Pe,Ue])[0]}multiplyUnsafe(Te,Pe=Be.ZERO){if(!fe.isValid(Te))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return Te===_0n$1?Be.ZERO:this.is0()||Te===_1n$2?this:$e.unsafe(this,Te,Ue=>normalizeZ(Be,Ue),Pe)}isSmallOrder(){return this.multiplyUnsafe(le).is0()}isTorsionFree(){return $e.unsafe(this,ae.n).is0()}toAffine(Te){return Se(this,Te)}clearCofactor(){return le===_1n$2?this:this.multiplyUnsafe(le)}toBytes(){const{x:Te,y:Pe}=this.toAffine(),Ue=ie.toBytes(Pe);return Ue[Ue.length-1]|=Te&_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(Te){return normalizeZ(Be,Te)}static msm(Te,Pe){return pippenger(Be,fe,Te,Pe)}_setWindowSize(Te){this.precompute(Te)}toRawBytes(){return this.toBytes()}}Be.BASE=new Be(ae.Gx,ae.Gy,_1n$2,me(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,pe=n.randomBytes||randomBytes,me=n.adjustScalarBytes||(Ke=>Ke),ye=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=me(_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(ye(_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),he=Be(_e.context,se,Ke),ve=fe.multiply(he).toBytes(),we=Be(_e.context,ve,de,Ke),Ae=le.create(he+we*ce);if(!le.isValid(Ae))throw new Error("sign failed: invalid s");const be=concatBytes(ve,le.toBytes(Ae));return _abytes2(be,Ue.signature,"result")}const ke={zip215:!0};function Te(Ke,Pt,_e,se=ke){const{context:ce,zip215:de}=se,he=Ue.signature;Ke=ensureBytes("signature",Ke,he),Pt=ensureBytes("message",Pt),_e=ensureBytes("publicKey",_e,Ue.publicKey),de!==void 0&&_abool2(de,"zip215"),ie&&(Pt=ie(Pt));const ve=he/2,we=Ke.subarray(0,ve),Ae=bytesToNumberLE(Ke.subarray(ve,he));let be,ue,ge;try{be=c.fromBytes(_e,de),ue=c.fromBytes(we,de),ge=fe.multiplyUnsafe(Ae)}catch{return!1}if(!de&&be.isSmallOrder())return!1;const Re=Be(ce,ue.toBytes(),be.toBytes(),Pt);return ue.add(be.multiplyUnsafe(Re)).subtract(ge).clearCofactor().is0()}const Pe=ae.BYTES,Ue={secretKey:Pe,publicKey:Pe,signature:2*Pe,seed:Pe};function Fe(Ke=pe(Ue.seed)){return _abytes2(Ke,Ue.seed,"seed")}function je(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:Fe,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 me(_e).subarray(0,Pt)},randomPrivateKey:Fe,precompute(Ke=8,Pt=c.BASE){return Pt.precompute(Ke,!1)}};return Object.freeze({keygen:je,getPublicKey:Me,sign:$e,verify:Te,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,pe=c*c%ae*c%ae,me=pow2(pe,_2n$2,ae)*pe%ae,ye=pow2(me,_1n$1,ae)*c%ae,xe=pow2(ye,_5n,ae)*ye%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,ke=pow2($e,t,ae)*xe%ae;return{pow_p_5_8:pow2(ke,_2n$2,ae)*c%ae,b2:pe}}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 pe=mod(t*le*le,n),me=le,ye=mod(le*ED25519_SQRT_M1,n),xe=pe===c,Ee=pe===mod(-c,n),Se=pe===mod(-c*ED25519_SQRT_M1,n);return xe&&(le=me),(Ee||Se)&&(le=ye),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,pe){for(var me in le)pe[me]=le[me]}ie.from&&ie.alloc&&ie.allocUnsafe&&ie.allocUnsafeSlow?c.exports=n:(fe(n,t),t.Buffer=ae);function ae(le,pe,me){return ie(le,pe,me)}ae.prototype=Object.create(ie.prototype),fe(ie,ae),ae.from=function(le,pe,me){if(typeof le=="number")throw new TypeError("Argument must not be a number");return ie(le,pe,me)},ae.alloc=function(le,pe,me){if(typeof le!="number")throw new TypeError("Argument must be a number");var ye=ie(le);return pe!==void 0?typeof me=="string"?ye.fill(pe,me):ye.fill(pe):ye.fill(0),ye},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,pe=c.charAt(0),me=Math.log(le)/Math.log(256),ye=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,ke=0,Te=Me.length;ke!==Te&&Me[ke]===0;)ke++,Be++;for(var Pe=(Te-ke)*ye+1>>>0,Ue=new Uint8Array(Pe);ke!==Te;){for(var Fe=Me[ke],je=0,Ve=Pe-1;(Fe!==0||je<$e)&&Ve!==-1;Ve--,je++)Fe+=256*Ue[Ve]>>>0,Ue[Ve]=Fe%le>>>0,Fe=Fe/le>>>0;if(Fe!==0)throw new Error("Non-zero carry");$e=je,ke++}for(var Ye=Pe-$e;Ye!==Pe&&Ue[Ye]===0;)Ye++;for(var Qe=pe.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,ke=0;Me[Be]===pe;)$e++,Be++;for(var Te=(Me.length-Be)*me+1>>>0,Pe=new Uint8Array(Te);Be<Me.length;){var Ue=Me.charCodeAt(Be);if(Ue>255)return;var Fe=t[Ue];if(Fe===255)return;for(var je=0,Ve=Te-1;(Fe!==0||je<ke)&&Ve!==-1;Ve--,je++)Fe+=le*Pe[Ve]>>>0,Pe[Ve]=Fe%256>>>0,Fe=Fe/256>>>0;if(Fe!==0)throw new Error("Non-zero carry");ke=je,Be++}for(var Ye=Te-ke;Ye!==Te&&Pe[Ye]===0;)Ye++;var Qe=_Buffer.allocUnsafe($e+(Te-Ye));Qe.fill(0,0,$e);for(var Ke=$e;Ye!==Te;)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$2=basex(ALPHABET$1);const o$1=getDefaultExportFromCjs$2(bs58$2),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 pe=ae&1023,me=le&1023;fe.push(65536+(pe<<10)+me),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(pe,me){if(me===end_of_stream&&fe!==0)return fe=0,decoderError(t);if(me===end_of_stream)return finished;if(fe===0){if(inRange(me,0,127))return me;if(inRange(me,194,223))fe=1,n=me-192;else if(inRange(me,224,239))me===224&&(ae=160),me===237&&(le=159),fe=2,n=me-224;else if(inRange(me,240,244))me===240&&(ae=144),me===244&&(le=143),fe=3,n=me-240;else return decoderError(t);return n=n<<6*fe,null}if(!inRange(me,ae,le))return n=fe=ie=0,ae=128,le=191,pe.prepend(me),decoderError(t);if(ae=128,le=191,ie+=1,n+=me-128<<6*(fe-ie),ie!==fe)return null;var ye=n;return n=fe=ie=0,ye}}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$b=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$b=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 pe=c.length-1;pe>=0;pe--)(le=c[pe])&&(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$b=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$b(t,c,n);return __setModuleDefault$b(t,c),t},__importDefault$a=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$a(bnExports$3),bs58_1$1=__importDefault$a(bs58$2),encoding=__importStar$b(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$1.default.encode(Buffer$7.from(c))}lib.baseEncode=baseEncode;function baseDecode(c){return Buffer$7.from(bs58_1$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,pe]=ie.values[ae];if(le===fe){n.writeU8(ae),serializeField(c,le,t[le],pe,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 pe=deserializeField(c,t,n.key,ie),me=deserializeField(c,t,n.value,ie);fe.set(pe,me)}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],pe=deserializeField(c,ae,le,n);return new t({[ae]:pe})}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$2=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$2.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,pe)=>le+fe.encode(pe,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 pe of this.fields){let me=pe.span;if(le=0<me?me:0,pe.property!==void 0){const ye=t[pe.property];ye!==void 0&&(le=pe.encode(ye,n,ie),0>me&&(me=pe.getSpan(n,ie)))}ae=ie,ie+=me}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(pe){return le(pe)},this.configGetSourceVariant=function(pe){le=pe.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 pe=this.defaultLayout;let me=0;this.usesPrefixDiscriminator&&(me=fe.layout.span),ie=this.makeDestinationObject(),ie[fe.property]=ae,ie[pe.property]=pe.decode(t,n+me)}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 pe=0;return this.usesPrefixDiscriminator&&(pe=ae.layout.span),ae.encode(t[ae.property],n,ie),pe+le.encode(t[le.property],n,ie+pe)}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,pe)=>le+pe.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$2.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$2.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:pe}=t,me=pe.length===0?fe:`At path: ${pe.join(".")} -- ${fe}`;super(ae??me),ae!=null&&(this.cause=me),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:pe,message:me=`Expected a value of type \`${le}\`${pe?` with refinement \`${pe}\``:""}, but received: \`${print$2(ie)}\``}=c;return{value:ie,type:le,refinement:pe,key:fe[fe.length-1],path:fe,branch:ae,...c,message:me}}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,pe={path:ie,branch:fe,mask:le};ae&&(c=t.coercer(c,pe));let me="valid";for(const ye of t.validator(c,pe))ye.explanation=n.message,me="not_valid",yield[ye,void 0];for(let[ye,xe,Ee]of t.entries(c,pe)){const Se=run(xe,Ee,{path:ye===void 0?ie:[...ie,ye],branch:ye===void 0?fe:[...fe,xe],coerce:ae,mask:le,message:n.message});for(const Me of Se)Me[0]?(me=Me[0].refinement!=null?"not_refined":"not_valid",yield[Me[0],void 0]):ae&&(xe=Me[1],ye===void 0?c=xe:c instanceof Map?c.set(ye,xe):c instanceof Set?c.add(xe):isObject$1(c)&&(xe!==void 0||ye in c)&&(c[ye]=xe))}if(me!=="not_valid")for(const ye of t.refiner(c,pe))ye.explanation=n.message,me="not_refined",yield[ye,void 0];me==="valid"&&(yield[void 0,c])}let Struct$1=class{constructor(t){const{type:n,schema:ie,validator:fe,refiner:ae,coercer:le=me=>me,entries:pe=function*(){}}=t;this.type=n,this.schema=ie,this.entries=pe,this.coercer=le,fe?this.validator=(me,ye)=>{const xe=fe(me,ye);return toFailures(xe,ye,this,me)}:this.validator=()=>[],ae?this.refiner=(me,ye)=>{const xe=ae(me,ye);return toFailures(xe,ye,this,me)}: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),[pe]=le;if(pe[0])for(const[me]of le)me&&fe.push(me);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"&&REGEX$1.test(c)}var byteToHex=[];for(var i$3=0;i$3<256;++i$3)byteToHex.push((i$3+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 pe=c.random||(c.rng||rng)();ae==null&&(ae=_nodeId=[pe[0]|1,pe[1],pe[2],pe[3],pe[4],pe[5]]),le==null&&(le=_clockseq=(pe[6]<<8|pe[7])&16383)}var me=c.msecs!==void 0?c.msecs:Date.now(),ye=c.nsecs!==void 0?c.nsecs:_lastNSecs+1,xe=me-_lastMSecs+(ye-_lastNSecs)/1e4;if(xe<0&&c.clockseq===void 0&&(le=le+1&16383),(xe<0||me>_lastMSecs)&&c.nsecs===void 0&&(ye=0),ye>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_lastMSecs=me,_lastNSecs=ye,_clockseq=le,me+=122192928e5;var Ee=((me&268435455)*1e4+ye)%4294967296;fe[ie++]=Ee>>>24&255,fe[ie++]=Ee>>>16&255,fe[ie++]=Ee>>>8&255,fe[ie++]=Ee&255;var Se=me/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,pe){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 me=new Uint8Array(16+fe.length);if(me.set(ae),me.set(fe,ae.length),me=n(me),me[6]=me[6]&15|t,me[8]=me[8]&63|128,le){pe=pe||0;for(var ye=0;ye<16;++ye)le[pe+ye]=me[ye];return le}return stringify(me)}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 pe=n,me=ie,ye=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,pe),ie=safeAdd(ie,me),fe=safeAdd(fe,ye),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),pe=new Array(le),me=0;me<le;++me){for(var ye=new Uint32Array(16),xe=0;xe<16;++xe)ye[xe]=c[me*64+xe*4]<<24|c[me*64+xe*4+1]<<16|c[me*64+xe*4+2]<<8|c[me*64+xe*4+3];pe[me]=ye}pe[le-1][14]=(c.length-1)*8/Math.pow(2,32),pe[le-1][14]=Math.floor(pe[le-1][14]),pe[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]=pe[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],ke=n[1],Te=n[2],Pe=n[3],Ue=n[4],Fe=0;Fe<80;++Fe){var je=Math.floor(Fe/20),Ve=ROTL($e,5)+f$1(je,ke,Te,Pe)+Ue+t[je]+Se[Fe]>>>0;Ue=Pe,Pe=Te,Te=ROTL(ke,30)>>>0,ke=$e,$e=Ve}n[0]=n[0]+$e>>>0,n[1]=n[1]+ke>>>0,n[2]=n[2]+Te>>>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 ye=typeof ie=="function";try{ae=generateRequest(c,t,n,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(xe){if(ye)return ie(xe);throw xe}if(!ye)return ae}let me;try{me=JSON.stringify(ae,this.options.replacer)}catch(ye){return ie(ye)}return this.callServer(me,function(ye,xe){fe._parseResponse(ye,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(me,ye,xe){this.fn=me,this.context=ye,this.once=xe||!1}function ae(me,ye,xe,Ee,Se){if(typeof xe!="function")throw new TypeError("The listener must be a function");var Me=new fe(xe,Ee||me,Se),Be=n?n+ye:ye;return me._events[Be]?me._events[Be].fn?me._events[Be]=[me._events[Be],Me]:me._events[Be].push(Me):(me._events[Be]=Me,me._eventsCount++),me}function le(me,ye){--me._eventsCount===0?me._events=new ie:delete me._events[ye]}function pe(){this._events=new ie,this._eventsCount=0}pe.prototype.eventNames=function(){var ye=[],xe,Ee;if(this._eventsCount===0)return ye;for(Ee in xe=this._events)t.call(xe,Ee)&&ye.push(n?Ee.slice(1):Ee);return Object.getOwnPropertySymbols?ye.concat(Object.getOwnPropertySymbols(xe)):ye},pe.prototype.listeners=function(ye){var xe=n?n+ye:ye,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},pe.prototype.listenerCount=function(ye){var xe=n?n+ye:ye,Ee=this._events[xe];return Ee?Ee.fn?1:Ee.length:0},pe.prototype.emit=function(ye,xe,Ee,Se,Me,Be){var $e=n?n+ye:ye;if(!this._events[$e])return!1;var ke=this._events[$e],Te=arguments.length,Pe,Ue;if(ke.fn){switch(ke.once&&this.removeListener(ye,ke.fn,void 0,!0),Te){case 1:return ke.fn.call(ke.context),!0;case 2:return ke.fn.call(ke.context,xe),!0;case 3:return ke.fn.call(ke.context,xe,Ee),!0;case 4:return ke.fn.call(ke.context,xe,Ee,Se),!0;case 5:return ke.fn.call(ke.context,xe,Ee,Se,Me),!0;case 6:return ke.fn.call(ke.context,xe,Ee,Se,Me,Be),!0}for(Ue=1,Pe=new Array(Te-1);Ue<Te;Ue++)Pe[Ue-1]=arguments[Ue];ke.fn.apply(ke.context,Pe)}else{var Fe=ke.length,je;for(Ue=0;Ue<Fe;Ue++)switch(ke[Ue].once&&this.removeListener(ye,ke[Ue].fn,void 0,!0),Te){case 1:ke[Ue].fn.call(ke[Ue].context);break;case 2:ke[Ue].fn.call(ke[Ue].context,xe);break;case 3:ke[Ue].fn.call(ke[Ue].context,xe,Ee);break;case 4:ke[Ue].fn.call(ke[Ue].context,xe,Ee,Se);break;default:if(!Pe)for(je=1,Pe=new Array(Te-1);je<Te;je++)Pe[je-1]=arguments[je];ke[Ue].fn.apply(ke[Ue].context,Pe)}}return!0},pe.prototype.on=function(ye,xe,Ee){return ae(this,ye,xe,Ee,!1)},pe.prototype.once=function(ye,xe,Ee){return ae(this,ye,xe,Ee,!0)},pe.prototype.removeListener=function(ye,xe,Ee,Se){var Me=n?n+ye:ye;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,ke=[],Te=Be.length;$e<Te;$e++)(Be[$e].fn!==xe||Se&&!Be[$e].once||Ee&&Be[$e].context!==Ee)&&ke.push(Be[$e]);ke.length?this._events[Me]=ke.length===1?ke[0]:ke:le(this,Me)}return this},pe.prototype.removeAllListeners=function(ye){var xe;return ye?(xe=n?n+ye:ye,this._events[xe]&&le(this,xe)):(this._events=new ie,this._eventsCount=0),this},pe.prototype.off=pe.prototype.removeListener,pe.prototype.addListener=pe.prototype.on,pe.prefixed=n,pe.EventEmitter=pe,c.exports=pe})(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,...pe}={},me,ye){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=pe,this.current_reconnects=0,this.generate_request_id=me||(()=>typeof this.rpc_id=="number"?++this.rpc_id:Number(this.rpc_id)+1),ye?this.dataPack=ye: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 pe=this.generate_request_id(t,n),me={jsonrpc:"2.0",method:t,params:n||void 0,id:pe};this.socket.send(this.dataPack.encode(me),fe,ye=>{if(ye)return le(ye);this.queue[pe]={promise:[ae,le]},ie&&(this.queue[pe].timeout=setTimeout(()=>{delete this.queue[pe],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:pe}=this;return t=t,t.finished=fe,t.destroyed=ae,t.blockLen=le,t.outputLen=pe,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,pe=divNearest(le*c,n),me=divNearest(-fe*c,n);let ye=c-pe*ie-me*ae,xe=-pe*fe-me*le;const Ee=ye<_0n,Se=xe<_0n;Ee&&(ye=-ye),Se&&(xe=-xe);const Me=bitMask(Math.ceil(bitLen(n)/2))+_1n;if(ye<_0n||ye>=Me||xe<_0n||xe>=Me)throw new Error("splitScalar (endomorphism): failed, k="+c);return{k1neg:Ee,k1:ye,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 me=fe&127;if(!me)throw new n("tlv.decode(long): indefinite length not supported");if(me>4)throw new n("tlv.decode(long): byte length is too big");const ye=t.subarray(ie,ie+me);if(ye.length!==me)throw new n("tlv.decode: length bytes not complete");if(ye[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const xe of ye)le=le<<8|xe;if(ie+=me,le<128)throw new n("tlv.decode(long): not minimal encoding")}const pe=t.subarray(ie,ie+le);if(pe.length!==le)throw new n("tlv.decode: wrong value length");return{v:pe,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:pe,l:me}=ie.decode(2,ae),{v:ye,l:xe}=ie.decode(2,me);if(xe.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(pe),s:n.decode(ye)}},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:pe}=ae;_validateObject(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:me}=t;if(me&&(!ie.is0(ae.a)||typeof me.beta!="bigint"||!Array.isArray(me.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const ye=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:he,y:ve}=ce.toAffine(),we=ie.toBytes(he);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}=ye,he=se.length,ve=se[0],we=se.subarray(1);if(he===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 be=$e(Ae);let ue;try{ue=ie.sqrt(be)}catch(Ne){const qe=Ne instanceof Error?": "+Ne.message:"";throw new Error("bad point: is not on curve, sqrt error"+qe)}xe();const ge=ie.isOdd(ue);return(ve&1)===1!==ge&&(ue=ie.neg(ue)),{x:Ae,y:ue}}else if(he===de&&ve===4){const Ae=ie.BYTES,be=ie.fromBytes(we.subarray(0,Ae)),ue=ie.fromBytes(we.subarray(Ae,Ae*2));if(!ke(be,ue))throw new Error("bad point: is not on curve");return{x:be,y:ue}}else throw new Error(`bad point: got length ${he}, 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 ke(se,ce){const de=ie.sqr(ce),he=$e(se);return ie.eql(de,he)}if(!ke(ae.Gx,ae.Gy))throw new Error("bad curve params: generator point");const Te=ie.mul(ie.pow(ae.a,_3n),_4n),Pe=ie.mul(ie.sqr(ae.b),BigInt(27));if(ie.is0(ie.add(Te,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 Fe(se){if(!(se instanceof Ke))throw new Error("ProjectivePoint expected")}function je(se){if(!me||!me.basises)throw new Error("no endo");return _splitEndoScalar(se,me.basises,fe.ORDER)}const Ve=memoized((se,ce)=>{const{X:de,Y:he,Z:ve}=se;if(ie.eql(ve,ie.ONE))return{x:de,y:he};const we=se.is0();ce==null&&(ce=we?ie.ONE:ie.inv(ve));const Ae=ie.mul(de,ce),be=ie.mul(he,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:be}}),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(!ke(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,he,ve){return de=new Ke(ie.mul(de.X,se),de.Y,de.Z),ce=negateCt(he,ce),de=negateCt(ve,de),ce.add(de)}class Ke{constructor(ce,de,he){this.X=Ue("x",ce),this.Y=Ue("y",de,!0),this.Z=Ue("z",he),Object.freeze(this)}static CURVE(){return ae}static fromAffine(ce){const{x:de,y:he}=ce||{};if(!ce||!ie.isValid(de)||!ie.isValid(he))throw new Error("invalid affine point");if(ce instanceof Ke)throw new Error("projective point not allowed");return ie.is0(de)&&ie.is0(he)?Ke.ZERO:new Ke(de,he,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){Fe(ce);const{X:de,Y:he,Z:ve}=this,{X:we,Y:Ae,Z:be}=ce,ue=ie.eql(ie.mul(de,be),ie.mul(we,ve)),ge=ie.eql(ie.mul(he,be),ie.mul(Ae,ve));return ue&&ge}negate(){return new Ke(this.X,ie.neg(this.Y),this.Z)}double(){const{a:ce,b:de}=ae,he=ie.mul(de,_3n),{X:ve,Y:we,Z:Ae}=this;let be=ie.ZERO,ue=ie.ZERO,ge=ie.ZERO,Re=ie.mul(ve,ve),Ne=ie.mul(we,we),qe=ie.mul(Ae,Ae),Ie=ie.mul(ve,we);return Ie=ie.add(Ie,Ie),ge=ie.mul(ve,Ae),ge=ie.add(ge,ge),be=ie.mul(ce,ge),ue=ie.mul(he,qe),ue=ie.add(be,ue),be=ie.sub(Ne,ue),ue=ie.add(Ne,ue),ue=ie.mul(be,ue),be=ie.mul(Ie,be),ge=ie.mul(he,ge),qe=ie.mul(ce,qe),Ie=ie.sub(Re,qe),Ie=ie.mul(ce,Ie),Ie=ie.add(Ie,ge),ge=ie.add(Re,Re),Re=ie.add(ge,Re),Re=ie.add(Re,qe),Re=ie.mul(Re,Ie),ue=ie.add(ue,Re),qe=ie.mul(we,Ae),qe=ie.add(qe,qe),Re=ie.mul(qe,Ie),be=ie.sub(be,Re),ge=ie.mul(qe,Ne),ge=ie.add(ge,ge),ge=ie.add(ge,ge),new Ke(be,ue,ge)}add(ce){Fe(ce);const{X:de,Y:he,Z:ve}=this,{X:we,Y:Ae,Z:be}=ce;let ue=ie.ZERO,ge=ie.ZERO,Re=ie.ZERO;const Ne=ae.a,qe=ie.mul(ae.b,_3n);let Ie=ie.mul(de,we),ze=ie.mul(he,Ae),Ce=ie.mul(ve,be),De=ie.add(de,he),He=ie.add(we,Ae);De=ie.mul(De,He),He=ie.add(Ie,ze),De=ie.sub(De,He),He=ie.add(de,ve);let Xe=ie.add(we,be);return He=ie.mul(He,Xe),Xe=ie.add(Ie,Ce),He=ie.sub(He,Xe),Xe=ie.add(he,ve),ue=ie.add(Ae,be),Xe=ie.mul(Xe,ue),ue=ie.add(ze,Ce),Xe=ie.sub(Xe,ue),Re=ie.mul(Ne,He),ue=ie.mul(qe,Ce),Re=ie.add(ue,Re),ue=ie.sub(ze,Re),Re=ie.add(ze,Re),ge=ie.mul(ue,Re),ze=ie.add(Ie,Ie),ze=ie.add(ze,Ie),Ce=ie.mul(Ne,Ce),He=ie.mul(qe,He),ze=ie.add(ze,Ce),Ce=ie.sub(Ie,Ce),Ce=ie.mul(Ne,Ce),He=ie.add(He,Ce),Ie=ie.mul(ze,He),ge=ie.add(ge,Ie),Ie=ie.mul(Xe,He),ue=ie.mul(De,ue),ue=ie.sub(ue,Ie),Ie=ie.mul(De,ze),Re=ie.mul(Xe,Re),Re=ie.add(Re,Ie),new Ke(ue,ge,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 he,ve;const we=Ae=>_e.cached(this,Ae,be=>normalizeZ(Ke,be));if(de){const{k1neg:Ae,k1:be,k2neg:ue,k2:ge}=je(ce),{p:Re,f:Ne}=we(be),{p:qe,f:Ie}=we(ge);ve=Ne.add(Ie),he=Qe(de.beta,Re,qe,Ae,ue)}else{const{p:Ae,f:be}=we(ce);he=Ae,ve=be}return normalizeZ(Ke,[he,ve])[0]}multiplyUnsafe(ce){const{endo:de}=t,he=this;if(!fe.isValid(ce))throw new Error("invalid scalar: out of range");if(ce===_0n||he.is0())return Ke.ZERO;if(ce===_1n)return he;if(_e.hasCache(this))return this.multiply(ce);if(de){const{k1neg:ve,k1:we,k2neg:Ae,k2:be}=je(ce),{p1:ue,p2:ge}=mulEndoUnsafe(Ke,he,we,be);return Qe(de.beta,ue,ge,ve,Ae)}else return _e.unsafe(he,ce)}multiplyAndAddUnsafe(ce,de,he){const ve=this.multiplyUnsafe(de).add(ce.multiplyUnsafe(he));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,pe).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:ke}=fe;try{const Te=Me.length;return Be===!0&&Te!==$e||Be===!1&&Te!==ke?!1:!!c.fromBytes(Me)}catch{return!1}}function pe(Me=ie(fe.seed)){return mapHashToField(_abytes2(Me,fe.seed,"seed"),n.ORDER)}function me(Me,Be=!0){return c.BASE.multiply(_normFnElement(n,Me)).toBytes(Be)}function ye(Me){const Be=pe(Me);return{secretKey:Be,publicKey:me(Be)}}function xe(Me){if(typeof Me=="bigint")return!1;if(Me instanceof c)return!0;const{secretKey:Be,publicKey:$e,publicKeyUncompressed:ke}=fe;if(n.allowedLengths||Be===$e)return;const Te=ensureBytes("key",Me).length;return Te===$e||Te===ke}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 ke=_normFnElement(n,Me);return c.fromHex(Be).multiply(ke).toBytes($e)}return Object.freeze({getPublicKey:me,getSharedSecret:Ee,keygen:ye,Point:c,utils:{isValidSecretKey:ae,isValidPublicKey:le,randomSecretKey:pe,isValidPrivateKey:ae,randomPrivateKey:pe,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,...he)=>hmac(t,de,concatBytes(...he))),{Fp:ae,Fn:le}=c,{ORDER:pe,BITS:me}=le,{keygen:ye,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 ke(de){const he=pe>>_1n;return de>he}function Te(de,he){if(!le.isValidNot0(he))throw new Error(`invalid signature ${de}: out of range 1..Point.Fn.ORDER`);return he}function Pe(de,he){validateSigFormat(he);const ve=Me.signature,we=he==="compact"?ve:he==="recovered"?ve+1:void 0;return _abytes2(de,we,`${he} signature`)}class Ue{constructor(he,ve,we){this.r=Te("r",he),this.s=Te("s",ve),we!=null&&(this.recovery=we),Object.freeze(this)}static fromBytes(he,ve=$e){Pe(he,ve);let we;if(ve==="der"){const{r:ge,s:Re}=DER.toSig(_abytes2(he));return new Ue(ge,Re)}ve==="recovered"&&(we=he[0],ve="compact",he=he.subarray(1));const Ae=le.BYTES,be=he.subarray(0,Ae),ue=he.subarray(Ae,Ae*2);return new Ue(le.fromBytes(be),le.fromBytes(ue),we)}static fromHex(he,ve){return this.fromBytes(hexToBytes(he),ve)}addRecoveryBit(he){return new Ue(this.r,this.s,he)}recoverPublicKey(he){const ve=ae.ORDER,{r:we,s:Ae,recovery:be}=this;if(be==null||![0,1,2,3].includes(be))throw new Error("recovery id invalid");if(pe*_2n$1<ve&&be>1)throw new Error("recovery id is ambiguous for h>1 curve");const ge=be===2||be===3?we+pe:we;if(!ae.isValid(ge))throw new Error("recovery id 2 or 3 invalid");const Re=ae.toBytes(ge),Ne=c.fromBytes(concatBytes(pprefix((be&1)===0),Re)),qe=le.inv(ge),Ie=je(ensureBytes("msgHash",he)),ze=le.create(-Ie*qe),Ce=le.create(Ae*qe),De=c.BASE.multiplyUnsafe(ze).add(Ne.multiplyUnsafe(Ce));if(De.is0())throw new Error("point at infinify");return De.assertValidity(),De}hasHighS(){return ke(this.s)}toBytes(he=$e){if(validateSigFormat(he),he==="der")return hexToBytes(DER.hexFromSig(this));const ve=le.toBytes(this.r),we=le.toBytes(this.s);if(he==="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(he){return bytesToHex(this.toBytes(he))}assertValidity(){}static fromCompact(he){return Ue.fromBytes(ensureBytes("sig",he),"compact")}static fromDER(he){return Ue.fromBytes(ensureBytes("sig",he),"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 Fe=n.bits2int||function(he){if(he.length>8192)throw new Error("input is too large");const ve=bytesToNumberBE(he),we=he.length*8-me;return we>0?ve>>BigInt(we):ve},je=n.bits2int_modN||function(he){return le.create(Fe(he))},Ve=bitMask(me);function Ye(de){return aInRange("num < 2^"+me,de,_0n,Ve),le.toBytes(de)}function Qe(de,he){return _abytes2(de,void 0,"message"),he?_abytes2(t(de),void 0,"prehashed message"):de}function Ke(de,he,ve){if(["recovered","canonical"].some(ze=>ze in ve))throw new Error("sign() legacy options not supported");const{lowS:we,prehash:Ae,extraEntropy:be}=validateSigOpts(ve,Be);de=Qe(de,Ae);const ue=je(de),ge=_normFnElement(le,he),Re=[Ye(ge),Ye(ue)];if(be!=null&&be!==!1){const ze=be===!0?ie(Me.secretKey):be;Re.push(ensureBytes("extraEntropy",ze))}const Ne=concatBytes(...Re),qe=ue;function Ie(ze){const Ce=Fe(ze);if(!le.isValidNot0(Ce))return;const De=le.inv(Ce),He=c.BASE.multiply(Ce).toAffine(),Xe=le.create(He.x);if(Xe===_0n)return;const Rt=le.create(De*le.create(qe+Xe*ge));if(Rt===_0n)return;let Oe=(He.x===Xe?0:2)|Number(He.y&_1n),Ze=Rt;return we&&ke(Rt)&&(Ze=le.neg(Rt),Oe^=1),new Ue(Xe,Ze,Oe)}return{seed:Ne,k2sig:Ie}}function Pt(de,he,ve={}){de=ensureBytes("message",de);const{seed:we,k2sig:Ae}=Ke(de,he,ve);return createHmacDrbg(t.outputLen,le.BYTES,fe)(we,Ae)}function _e(de){let he;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)he=new Ue(de.r,de.s);else if(ve){try{he=Ue.fromBytes(ensureBytes("sig",de),"der")}catch(Ae){if(!(Ae instanceof DER.Err))throw Ae}if(!he)try{he=Ue.fromBytes(ensureBytes("sig",de),"compact")}catch{return!1}}return he||!1}function se(de,he,ve,we={}){const{lowS:Ae,prehash:be,format:ue}=validateSigOpts(we,Be);if(ve=ensureBytes("publicKey",ve),he=Qe(ensureBytes("message",he),be),"strict"in we)throw new Error("options.strict was renamed to lowS");const ge=ue===void 0?_e(de):Ue.fromBytes(ensureBytes("sig",de),ue);if(ge===!1)return!1;try{const Re=c.fromBytes(ve);if(Ae&&ge.hasHighS())return!1;const{r:Ne,s:qe}=ge,Ie=je(he),ze=le.inv(qe),Ce=le.create(Ie*ze),De=le.create(Ne*ze),He=c.BASE.multiplyUnsafe(Ce).add(Re.multiplyUnsafe(De));return He.is0()?!1:le.create(He.x)===Ne}catch{return!1}}function ce(de,he,ve={}){const{prehash:we}=validateSigOpts(ve,Be);return he=Qe(he,we),Ue.fromBytes(de,"recovered").recoverPublicKey(he).toBytes()}return Object.freeze({keygen:ye,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),pe=BigInt(44),me=BigInt(88),ye=c*c*c%t,xe=ye*ye*c%t,Ee=pow2(xe,n,t)*xe%t,Se=pow2(Ee,n,t)*xe%t,Me=pow2(Se,_2n,t)*ye%t,Be=pow2(Me,fe,t)*Me%t,$e=pow2(Be,ae,t)*Be%t,ke=pow2($e,pe,t)*$e%t,Te=pow2(ke,me,t)*ke%t,Pe=pow2(Te,pe,t)*$e%t,Ue=pow2(Pe,n,t)*xe%t,Fe=pow2(Ue,le,t)*Be%t,je=pow2(Fe,ie,t)*ye%t,Ve=pow2(je,_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,pe)=>{const me={chars:Buffer$1$1.from(ae,"utf8")};return ie(me,le,pe)},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 pe=le.toBase58();let me=ie.get(pe);return me===void 0&&(me={isSigner:!1,isWritable:!1,isInvoked:!1},ie.set(pe,me)),me},ae=fe(n);ae.isSigner=!0,ae.isWritable=!0;for(const le of t){fe(le.programId).isInvoked=!0;for(const pe of le.keys){const me=fe(pe.pubkey);me.isSigner||(me.isSigner=pe.isSigner),me.isWritable||(me.isWritable=pe.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(([,me])=>me.isSigner&&me.isWritable),ie=t.filter(([,me])=>me.isSigner&&!me.isWritable),fe=t.filter(([,me])=>!me.isSigner&&me.isWritable),ae=t.filter(([,me])=>!me.isSigner&&!me.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[me]=n[0];assert$9(me===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const pe=[...n.map(([me])=>new PublicKey(me)),...ie.map(([me])=>new PublicKey(me)),...fe.map(([me])=>new PublicKey(me)),...ae.map(([me])=>new PublicKey(me))];return[le,pe]}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 pe=new PublicKey(ae),me=t.findIndex(ye=>ye.equals(pe));me>=0&&(assert$9(me<256,"Max lookup table index exceeded"),ie.push(me),fe.push(pe),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(pe=>({programIdIndex:pe.programIdIndex,accounts:pe.accountKeyIndexes,data:o$1.encode(pe.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 ke=[];return encodeLength(ke,Be.length),{programIdIndex:Me,keyIndicesCount:Buffer$1$1.from($e),keyIndices:Se,dataLength:Buffer$1$1.from(ke),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 pe=struct([blob(1,"numRequiredSignatures"),blob(1,"numReadonlySignedAccounts"),blob(1,"numReadonlyUnsignedAccounts"),blob(n.length,"keyCount"),seq(publicKey$1("key"),t,"keys"),publicKey$1("recentBlockhash")]),me={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 ye=Buffer$1$1.alloc(2048);const xe=pe.encode(me,ye);return ae.copy(ye,xe),ye.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 pe=[];for(let Se=0;Se<le;Se++){const Me=guardedSplice(n,0,PUBLIC_KEY_LENGTH);pe.push(new PublicKey(Buffer$1$1.from(Me)))}const me=guardedSplice(n,0,PUBLIC_KEY_LENGTH),ye=decodeLength(n);let xe=[];for(let Se=0;Se<ye;Se++){const Me=guardedShift(n),Be=decodeLength(n),$e=guardedSplice(n,0,Be),ke=decodeLength(n),Te=guardedSplice(n,0,ke),Pe=o$1.encode(Buffer$1$1.from(Te));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(me)),accountKeys:pe,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,pe)=>le+pe.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,pe]=n.getMessageComponents(),ye=new MessageAccountKeys(pe,fe).compileInstructions(t.instructions);return new MessageV0({header:le,staticAccountKeys:pe,recentBlockhash:t.recentBlockhash,compiledInstructions:ye,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")]),pe=new Uint8Array(PACKET_DATA_SIZE),ye=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},pe);return pe.slice(0,ye)}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)},pe=[],me=decodeLength(n);for(let Be=0;Be<me;Be++)pe.push(new PublicKey(guardedSplice(n,0,PUBLIC_KEY_LENGTH)));const ye=o$1.encode(guardedSplice(n,0,PUBLIC_KEY_LENGTH)),xe=decodeLength(n),Ee=[];for(let Be=0;Be<xe;Be++){const $e=guardedShift(n),ke=decodeLength(n),Te=guardedSplice(n,0,ke),Pe=decodeLength(n),Ue=new Uint8Array(guardedSplice(n,0,Pe));Ee.push({programIdIndex:$e,accountKeyIndexes:Te,data:Ue})}const Se=decodeLength(n),Me=[];for(let Be=0;Be<Se;Be++){const $e=new PublicKey(guardedSplice(n,0,PUBLIC_KEY_LENGTH)),ke=decodeLength(n),Te=guardedSplice(n,0,ke),Pe=decodeLength(n),Ue=guardedSplice(n,0,Pe);Me.push({accountKey:$e,writableIndexes:Te,readonlyIndexes:Ue})}return new MessageV0({header:le,staticAccountKeys:pe,recentBlockhash:ye,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(Te=>{ae.push({...Te})});const ke=$e.programId.toString();fe.includes(ke)||fe.push(ke)}),fe.forEach($e=>{ae.push({pubkey:new PublicKey($e),isSigner:!1,isWritable:!1})});const le=[];ae.forEach($e=>{const ke=$e.pubkey.toString(),Te=le.findIndex(Pe=>Pe.pubkey.toString()===ke);Te>-1?(le[Te].isWritable=le[Te].isWritable||$e.isWritable,le[Te].isSigner=le[Te].isSigner||$e.isSigner):le.push($e)}),le.sort(function($e,ke){if($e.isSigner!==ke.isSigner)return $e.isSigner?-1:1;if($e.isWritable!==ke.isWritable)return $e.isWritable?-1:1;const Te={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"};return $e.pubkey.toBase58().localeCompare(ke.pubkey.toBase58(),"en",Te)});const pe=le.findIndex($e=>$e.pubkey.equals(ie));if(pe>-1){const[$e]=le.splice(pe,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 ke=le.findIndex(Te=>Te.pubkey.equals($e.publicKey));if(ke>-1)le[ke].isSigner||(le[ke].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 me=0,ye=0,xe=0;const Ee=[],Se=[];le.forEach(({pubkey:$e,isSigner:ke,isWritable:Te})=>{ke?(Ee.push($e.toString()),me+=1,Te||(ye+=1)):(Se.push($e.toString()),Te||(xe+=1))});const Me=Ee.concat(Se),Be=n.map($e=>{const{data:ke,programId:Te}=$e;return{programIdIndex:Me.indexOf(Te.toString()),accounts:$e.keys.map(Pe=>Me.indexOf(Pe.pubkey.toString())),data:o$1.encode(ke)}});return Be.forEach($e=>{assert$9($e.programIdIndex>=0),$e.accounts.forEach(ke=>assert$9(ke>=0))}),new Message({header:{numRequiredSignatures:me,numReadonlySignedAccounts:ye,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+=`
17
+ `),ae===Chain.SKALE)return await skalePayment(n,le,ye,Se,pe,Ee,ie);ie.waiting(`The payment is custom? ${me}`),me?await handleCustomTokenApproval(n,Ee,ye,xe,ie):n.tbdValues=n.tbdValues.map(Fe=>parseInt(Fe.toString(),10)),ie.waiting("Performing static call...");try{await Se.callStatic.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{value:me?BigNumber.from(0):n.totalPrice})}catch(Fe){throw new Error("Transaction will fail: "+Fe.message)}ie.waiting("Static Call done");let Me;try{Me=await getGasPrice$1(fe)}catch(Fe){throw new Error("Failed to get gas price: "+Fe.message)}ie.waiting(`Got gas price: ${Me}`),ie.waiting("Calling estimate gas...");let Be;try{Be=await Se.estimateGas.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{value:me?BigNumber.from(0):n.totalPrice})}catch(Fe){throw new Error(`Gas estimation failed: ${Fe.message}. Please check the transaction parameters.`)}ie.waiting(`gas estimation done: ${Be.toString()}`);const $e=Be.mul(105).div(100),ke=me?BigNumber.from(0):BigNumber.from(n.totalPrice);ie.waiting(`Gas limit: ${$e.toString()}, gas price: ${Me.toString()}, base: ${ke.toString()}`);let Te;try{Te=await fe.getBalance(pe)}catch(Fe){throw new Error("Failed to get user balance: "+Fe.message)}ie.waiting(`User balance: ${Te}`);const Pe=ke.add($e.mul(Me));if(Te.lt(Pe))throw new InsufficientBalanceException;ie.waiting("Calling purchase...");const Ue=await Se.droplinkedPurchase(n.tbdValues,n.tbdReceivers,n.tokenAddress,n.chainLinkRoundId,n.memo,{gasLimit:$e,value:me?BigNumber.from(0):n.totalPrice});return ie.waiting("Waiting for transaction..."),await Ue.wait(),ie.waiting("Transaction done"),{transactionHash:Ue.hash,cryptoAmount:n.totalPrice}}catch(Me){handleError(Me)}},skalePayment=async function(c,t,n,ie,fe,ae,le){try{const pe=t===Network.TESTNET?SkaleUsdcAddressForTestnet:SkaleUsdcAddressForMainnet;return c.tokenAddress=pe,await handleCustomTokenApproval(c,ae,n,fe,le),{transactionHash:(await ie.droplinkedPurchase(c.tbdValues,c.tbdReceivers,pe,"0",c.memo)).hash,cryptoAmount:c.totalPrice}}catch(pe){handleError(pe)}};function handleError(c){var t;throw c instanceof Error?((t=c.code)==null?void 0:t.toString())==="ACTION_REJECTED"||c.message.includes("User denied")||c.message.includes("User cancelled transaction")?new UserDeniedException:c:new Error("An unknown error occurred")}async function claimNFT(c,t,n){console.log({data:c,chainConfig:t,context:n});const{modalInterface:ie}=n,fe=t.provider.getSigner(),ae=getShopABI();ie.waiting("Claiming NFTs...");const le=new Contract(n.shopContractAddress,ae,fe);try{ie.waiting("Claiming NFTs..."),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 pe=c.signature.purchaseData.map(ye=>({amount:ye.amount,productId:BigNumber.from(ye.productId),nullifier:BigNumber.from(ye.nullifier)})),me=await le.claimPurchase(DROPLINKED_MANAGER,c.signature.signature,{cart:pe,shop:n.shopContractAddress});return ie.waiting("Waiting for transaction..."),await me.wait(),ie.success("Claimed NFTs!"),{transactionHash:me.hash}}catch(pe){if(console.error(pe),pe.code&&pe.code.toString()==="ACTION_REJECTED")throw n.modalInterface.error("Transaction Rejected"),new Error("Transaction Rejected");try{const me=le.interface.parseError(pe.data);throw me.name==="OwnableUnauthorizedAccount"&&n.modalInterface.error(me.name),n.modalInterface.error(pe),pe}catch(me){throw ie.error(`Unexpected error: ${me}`),me}}}var TokenStandard=(c=>(c.ERC721="ERC721",c.ERC1155="ERC1155",c.ERC20="ERC20",c))(TokenStandard||{});const airdropABI=[{inputs:[],name:"ArrayLengthMismatch",type:"error"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"airdropId",type:"string"}],name:"AirdropDone",type:"event"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address[]",name:"recipients",type:"address[]"},{internalType:"uint256[]",name:"amounts",type:"uint256[]"},{internalType:"string",name:"memo",type:"string"}],name:"distributeERC1155",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address[]",name:"recipients",type:"address[]"},{internalType:"uint256[]",name:"amounts",type:"uint256[]"},{internalType:"string",name:"memo",type:"string"}],name:"distributeERC20",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address[]",name:"recipients",type:"address[]"},{internalType:"uint256[]",name:"tokenIds",type:"uint256[]"},{internalType:"string",name:"memo",type:"string"}],name:"distributeERC721",outputs:[],stateMutability:"nonpayable",type:"function"}];async function sendTransaction(c,t,n,ie,fe){try{return await c.callStatic[t](...n),await c[t](...n)}catch(ae){throw fe.error(`Error simulating ${t} transaction ${ie+1}: ${ae.message}`),ae}}async function approveTokenForAirdrop(c,t,n,ie,fe){if(n!==TokenStandard.ERC1155)throw new Error("Only ERC1155 tokens are supported right now");const ae=["function setApprovalForAll(address, bool) public"],le=new Contract(t,ae,ie);fe.waiting("Approving token for airdrop..."),await(await le.setApprovalForAll(c,!0)).wait(),fe.waiting("Token approved for airdrop")}async function airdrop(c,t,n){const ie=t.modalInterface,fe=c.provider.getSigner();ie.waiting("Connecting to wallet..."),await checkWallet(fe,c.address),ie.waiting("Getting airdrop contract address...");const ae=await getAirdropAddress(c.chain,c.network),le=new Contract(ae,airdropABI,fe);await approveTokenForAirdrop(ae,n.tokenAddress,n.type,fe,ie),ie.waiting("Initializing airdrop");const pe=ye=>{const xe=[],Ee=[];for(const Se of ye)xe.push(Se.receiver),Ee.push(Se.amount);return{receivers:xe,amounts:Ee}},me=(ye,xe,Ee=300)=>{const Se=[];for(let Me=0;Me<ye.length;Me+=Ee)Se.push({receivers:ye.slice(Me,Me+Ee),amounts:xe.slice(Me,Me+Ee)});return Se};try{let ye;const{receivers:xe,amounts:Ee}=pe(n.receivers),Se=n.chunkSize||300,Me=me(xe,Ee,Se),Be=[];for(const[$e,ke]of Me.entries())ie.waiting(`Processing transaction ${$e+1} of ${Me.length}`),n.type===TokenStandard.ERC1155?ye=await sendTransaction(le,"distributeERC1155",[n.tokenAddress,n.tokenId,ke.receivers,ke.amounts,n.airdropId],$e,ie):n.type===TokenStandard.ERC20?ye=await sendTransaction(le,"distributeERC20",[n.tokenAddress,ke.receivers,ke.amounts,n.airdropId],$e,ie):n.type===TokenStandard.ERC721&&(ye=await sendTransaction(le,"distributeERC721",[n.tokenAddress,ke.receivers,ke.amounts,n.airdropId],$e,ie)),ie.waiting(`Transaction ${$e+1} sent: ${ye.hash}`),Be.push(ye.hash),await ye.wait(),ie.waiting(`Transaction ${$e+1} confirmed`);return{transactionHashes:Be}}catch(ye){if(ye.code&&ye.code.toString()==="ACTION_REJECTED")throw t.modalInterface.error("Transaction Rejected"),new Error("Transaction Rejected");try{const xe=le.interface.parseError(ye.data);throw t.modalInterface.error(xe.name),t.modalInterface.error(ye),ye}catch(xe){throw t.modalInterface.error(`Unexpected error: ${xe}`),xe}}}async function getShopInfo(c,t,n){const ie=(await(await n.get(`shops/v2/public/${t}`)).json()).data.deployedContracts.filter(fe=>fe.type===c);return ie.length===0?{nftContractAddress:"",shopContractAddress:""}:{nftContractAddress:ie[0].deployedNFTAddress,shopContractAddress:ie[0].deployedShopAddress}}async function getProductData(c,t){return(await(await t.get(`product-v2/public/${c}`)).json()).data}async function transformProductData(c,t){const n=await getProductData(c,t);if(!n||n.skus.length===0)throw new Error("Product not found or no SKUs available");return{productData:{acceptsManageWallet:!0,commission:n.affiliate.commissionPercent||0,description:n.description,productTitle:n.title,royalty:n.skus[0].royalty||0,type:ProductType[n.type.toUpperCase()]||ProductType.DIGITAL},skuData:n.skus.map(ie=>{var fe;return{amount:ie.inventory.quantity,imageUrl:((fe=n.images[n.defaultImageIndex])==null?void 0:fe.original)||"",skuID:ie.id,skuProperties:ie}})}}async function web3Callback(c,t,n,ie){const fe={"X-API-KEY":"ho8homr9e8p4fwii7tjiz41xs4hlbl2h4i"};return(await(await ky.create({headers:fe,prefixUrl:n==="TESTNET"?"https://web3dev.droplinked.com/":"https://web3.droplinked.com/"}).post("transactions",{json:{transaction_id:c,callback_url:ie,chain:t,network:n},headers:fe})).json()).data}async function startRecord(c,t,n,ie,fe,ae){return(await(await ae.post("web3/record/transactions",{json:{uris:fe,network:ie,data:{productId:c,skuIds:t},productId:c,skuIds:t,metadata:{},shopId:n,txType:"RECORD"}})).json()).data.id}async function startPayment(c,t,n,ie,fe,ae){return(await(await ae.post("web3/payment/transactions",{json:{network:n,token:t,shopId:fe,orderId:c}})).json()).data.id}class EVMProvider{constructor(t,n,ie){this.chain=Chain.BINANCE,this.network=Network.TESTNET,this.modalInterface=new defaultModal,this.wallet=ChainWallet.Metamask,this.chain=t,this.network=n,this.gasPredictable=ie,this.address=ZERO_ADDRESS,this.axiosInstance=ky.create({prefixUrl:this.network===Network.MAINNET?"https://apiv3.droplinked.com":"https://apiv3dev.droplinked.com"})}unstoppableLogin(t,n){throw new Error("Method not implemented.")}getBaseUrl(){return this.network===Network.MAINNET?"https://apiv3.droplinked.com":this.network===Network.TESTNET?"https://apiv3dev.droplinked.com":"http://127.0.0.1:3000"}setAxiosInstance(t){return this.axiosInstance=t,this}setNFTContractAddress(t){return this.nftContractAddress=t,this}setShopContractAddress(t){return this.shopContractAddress=t,this}setWallet(t){return this.wallet=t,this}setModal(t){return this.modalInterface=t,this}async customPayment(t){return await this.handleChain(),await droplinked_payment(this.getChainConfig(),this.getContext(),t)}async claimNFTs(t){return await this.handleWallet(this.address),await this.handleChain(),(await claimNFT(t,this.getChainConfig(),this.getContext())).transactionHash}getWalletProvider(){const t=window.ethereum;if(!t)throw new WalletNotFoundException;if(t.providerMap)if(this.wallet===ChainWallet.Metamask){if(!t.providerMap.get("MetaMask"))throw new WalletNotFoundException;return new Web3Provider(t.providers.find(n=>n.isMetaMask))}else if(this.wallet===ChainWallet.CoinBase){if(!t.providerMap.get("CoinbaseWallet"))throw new WalletNotFoundException;return new Web3Provider(t.providers.find(n=>n.isCoinbaseWallet))}else if(this.wallet===ChainWallet.Phantom){if(!t.providerMap.get("CoinbaseWallet"))throw new WalletNotFoundException;return new Web3Provider(t.providers.find(n=>n.isCoinbaseWallet))}else throw new Error("Wallet not implemented");else{if(this.wallet===ChainWallet.CoinBase){if(!window.ethereum.isCoinbaseWallet)throw new WalletNotFoundException}else if(this.wallet===ChainWallet.Metamask&&!window.ethereum.isMetaMask)throw new WalletNotFoundException;return new Web3Provider(window.ethereum)}}async deployShop(t){return await this.handleWallet(this.address),await this.handleChain(),await deployEVMShop(this.getChainConfig(),{axiosInstance:this.axiosInstance,modalInterface:this.modalInterface},t)}setAddress(t){return this.address=t,this}async handleChain(){const t=this.getWalletProvider();await addChain(t,this.chain,this.network,this.modalInterface),await isChainCorrect(t.provider,this.chain,this.network)||(console.log("Changing chain..."),await changeChain(t.provider,this.chain,this.network))}async handleWallet(t){if(!isMetamaskInstalled())throw this.modalInterface.error("Metamask is not installed"),new WalletNotFoundException;this.modalInterface.waiting("Getting accounts...");const ie=this.getWalletProvider().provider,fe=await getAccounts(ie);if(!isWalletConnected(ie)||fe.length===0){this.modalInterface.waiting("Please connect your wallet");const{address:ae}=await this.walletLogin();t.toLocaleLowerCase()!==ae.toLocaleLowerCase()&&(await window.ethereum.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),await this.handleWallet(t))}if(String(fe[0]).toLocaleLowerCase()!==t.toLocaleLowerCase()&&t!==""&&(this.modalInterface.waiting("Change your account based on the one you used to login..."),await window.ethereum.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),this.handleWallet(t)),this.chain===Chain.SKALE){const ae=await(await this.axiosInstance.post("web3/sFuelDistribution",{json:{wallet:this.address,isTestnet:this.network===Network.TESTNET}})).json();console.log(ae)}this.modalInterface.success("Wallet connected")}getChainConfig(){return{address:this.address,chain:this.chain,network:this.network,provider:this.getWalletProvider(),gasPredictable:this.gasPredictable}}getContext(){return{axiosInstance:this.axiosInstance,modalInterface:this.modalInterface,nftContract:this.nftContractAddress,shopContractAddress:this.shopContractAddress}}async walletLogin(){if(this.wallet===ChainWallet.Metamask&&!isMetamaskInstalled())throw this.modalInterface.error("Metamask is not installed"),new WalletNotFoundException;const{address:t,signature:n,date:ie,nonce:fe}=await evmLogin(this.getWalletProvider(),this.chain,this.network,this.modalInterface,this.axiosInstance);return this.address=t,{address:t,signature:n,date:ie,nonce:fe}}checkDeployment(){if(!this.nftContractAddress)throw new Error("NFT contract address not set");if(!this.shopContractAddress)throw new Error("Shop contract address not set")}async recordProduct(t){const{productData:n,skuData:ie}=await transformProductData(t,this.axiosInstance);if(this.checkDeployment(),!this.shopId)throw new FieldNotFound("shopId");const fe=await startRecord(t,ie.map(me=>me.skuID),this.shopId,this.chain,[],this.axiosInstance);await this.handleWallet(this.address),await this.handleChain();const ae=await recordProduct(this.getChainConfig(),this.getContext(),n,ie);await updateUris(fe,ae.metadataUrls,this.axiosInstance),await updateHash("record",fe,ae.transactionHash,this.axiosInstance);const le=`${this.getBaseUrl()}/web3/record/callback/events/${fe}`;if(!await web3Callback(ae.transactionHash,this.chain,Network[this.network],le))throw new Web3CallbackFailed(`txHash: ${ae.transactionHash}`);return{...ae,transactionId:fe,transactionHashUrl:getTransactionLink({blockchain:this.chain,transactionHash:ae.transactionHash,isTestnet:this.network!==Network.MAINNET})}}setShopId(t){return this.shopId=t,this}async executeAirdrop(t){const n=await getAirdropData(t,this.axiosInstance);return await this.handleWallet(this.address),await this.handleChain(),await airdrop(this.getChainConfig(),this.getContext(),{type:TokenStandard.ERC1155,airdropId:t,receivers:n.receivers,tokenAddress:n.tokenAddress,tokenId:n.tokenId,chunkSize:300})}async payment(t){await this.handleWallet(this.address),await this.handleChain();const{orderID:n,paymentToken:ie,paymentType:fe}=t;if(!this.shopId)throw new FieldNotFound("shopId");const ae=await startPayment(n,ie,fe,this.address,this.shopId,this.axiosInstance),le=await getCartData(n,ie,fe,this.axiosInstance),pe=le.paymentData;console.log({paymentData:pe});const me=await droplinked_payment(this.getChainConfig(),this.getContext(),pe);if(await updateHash("payment",ae,me.transactionHash,this.axiosInstance),!await web3Callback(me.transactionHash,this.chain,Network[this.network],`${this.getBaseUrl()}/web3/payment/callback/${ae}/${me.transactionHash}`))throw new Web3CallbackFailed(`txHash: ${me.transactionHash}`);return{...me,orderID:le.orderID,transactionId:ae}}async getPaymentData(t,n,ie){return await getCartData(t,ie,n,this.axiosInstance)}async paymentWithToken(t,n,ie,fe=18){await this.handleWallet(this.address),await this.handleChain();const ae=erc20ABI,le=this.getWalletProvider().getSigner(),pe=new Contract(ie,ae,le);try{await pe.callStatic.transfer(t,BigInt(Math.floor(n*1e6))*BigInt(10**(fe-6)));const me=(await pe.estimateGas.transfer(t,BigInt(Math.floor(n*1e6))*BigInt(10**(fe-6)))).toBigInt().valueOf(),ye=(await getGasPrice$1(this.getWalletProvider())).valueOf();return(await pe.transfer(t,BigInt(Math.floor(n*1e6))*BigInt(10**(fe-6)),{gasPrice:ye*BigInt(105)/BigInt(100),gasLimit:me*BigInt(105)/BigInt(100)})).hash}catch(me){throw me.reason?me.reason==="ERC20: transfer amount exceeds balance"?new Error("Insufficient token balance"):me.reason==="insufficient funds for gas * price + value"?new Error("Insufficient ETH balance"):me.reason==="bad result from backend"?new Error("Something went wrong, check your eth and token balance"):new Error(me.reason):me}}}var Web3Actions=(c=>(c.LOGIN="LOGIN",c.DEPLOY="DEPLOY",c.RECORD="RECORD",c.PAYMENT="PAYMENT",c.CLAIM="CLAIM",c.AIRDROP="AIRDROP",c))(Web3Actions||{});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)),pe=asciiToBase16(c.charCodeAt(ae+1));if(le===void 0||pe===void 0){const me=c[ae]+c[ae+1];throw new Error('hex string expected, got non-hex character "'+me+'" at index '+ae)}ie[fe]=le*16+pe}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),pe=Number(n&ae),me=ie?4:0,ye=ie?0:4;c.setUint32(t+me,le,ie),c.setUint32(t+ye,pe,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 pe=Math.min(fe-this.pos,ae-le);if(pe===fe){const me=createView(t);for(;fe<=ae-le;le+=fe)this.process(me,le);continue}ie.set(t.subarray(le,le+pe),this.pos),this.pos+=pe,le+=pe,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 pe=createView(t),me=this.outputLen;if(me%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const ye=me/4,xe=this.get();if(ye>xe.length)throw new Error("_sha2: outputLen bigger than state");for(let Ee=0;Ee<ye;Ee++)pe.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:pe}=this;return t.destroyed=le,t.finished=ae,t.length=fe,t.pos=pe,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:pe}=fromBig(c[ae],t);[ie[ae],fe[ae]]=[le,pe]}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:pe,H:me}=this;return[t,n,ie,fe,ae,le,pe,me]}set(t,n,ie,fe,ae,le,pe,me){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=pe|0,this.H=me|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:pe,F:me,G:ye,H:xe}=this;for(let Ee=0;Ee<64;Ee++){const Se=rotr(pe,6)^rotr(pe,11)^rotr(pe,25),Me=xe+Se+Chi(pe,me,ye)+SHA256_K[Ee]+SHA256_W[Ee]|0,$e=(rotr(ie,2)^rotr(ie,13)^rotr(ie,22))+Maj(ie,fe,ae)|0;xe=ye,ye=me,me=pe,pe=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,pe=pe+this.E|0,me=me+this.F|0,ye=ye+this.G|0,xe=xe+this.H|0,this.set(ie,fe,ae,le,pe,me,ye,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:pe,Dl:me,Eh:ye,El:xe,Fh:Ee,Fl:Se,Gh:Me,Gl:Be,Hh:$e,Hl:ke}=this;return[t,n,ie,fe,ae,le,pe,me,ye,xe,Ee,Se,Me,Be,$e,ke]}set(t,n,ie,fe,ae,le,pe,me,ye,xe,Ee,Se,Me,Be,$e,ke){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=pe|0,this.Dl=me|0,this.Eh=ye|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=ke|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 Fe=SHA512_W_H[Ue-15]|0,je=SHA512_W_L[Ue-15]|0,Ve=rotrSH(Fe,je,1)^rotrSH(Fe,je,8)^shrSH(Fe,je,7),Ye=rotrSL(Fe,je,1)^rotrSL(Fe,je,8)^shrSL(Fe,je,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:pe,Cl:me,Dh:ye,Dl:xe,Eh:Ee,El:Se,Fh:Me,Fl:Be,Gh:$e,Gl:ke,Hh:Te,Hl:Pe}=this;for(let Ue=0;Ue<80;Ue++){const Fe=rotrSH(Ee,Se,14)^rotrSH(Ee,Se,18)^rotrBH(Ee,Se,41),je=rotrSL(Ee,Se,14)^rotrSL(Ee,Se,18)^rotrBL(Ee,Se,41),Ve=Ee&Me^~Ee&$e,Ye=Se&Be^~Se&ke,Qe=add5L(Pe,je,Ye,SHA512_Kl[Ue],SHA512_W_L[Ue]),Ke=add5H(Qe,Te,Fe,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&pe^ae&pe,de=fe&le^fe&me^le&me;Te=$e|0,Pe=ke|0,$e=Me|0,ke=Be|0,Me=Ee|0,Be=Se|0,{h:Ee,l:Se}=add(ye|0,xe|0,Ke|0,Pt|0),ye=pe|0,xe=me|0,pe=ae|0,me=le|0,ae=ie|0,le=fe|0;const he=add3L(Pt,se,de);ie=add3H(he,Ke,_e,ce),fe=he|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:pe,l:me}=add(this.Ch|0,this.Cl|0,pe|0,me|0),{h:ye,l:xe}=add(this.Dh|0,this.Dl|0,ye|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:ke}=add(this.Gh|0,this.Gl|0,$e|0,ke|0),{h:Te,l:Pe}=add(this.Hh|0,this.Hl|0,Te|0,Pe|0),this.set(ie,fe,ae,le,pe,me,ye,xe,Ee,Se,Me,Be,$e,ke,Te,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}" `,pe=ae?` of length ${t}`:"",me=ie?`length=${fe}`:`type=${typeof c}`;throw new Error(le+"expected Uint8Array"+pe+", got "+me)}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),pe=0;const me=()=>{ae.fill(1),le.fill(0),pe=0},ye=(...Me)=>n(le,ae,...Me),xe=(Me=ie(0))=>{le=ye(fe(0),Me),ae=ye(),Me.length!==0&&(le=ye(fe(1),Me),ae=ye())},Ee=()=>{if(pe++>=1e3)throw new Error("drbg: tried 1000 values");let Me=0;const Be=[];for(;Me<t;){ae=ye();const $e=ae.slice();Be.push($e),Me+=ae.length}return concatBytes(...Be)};return(Me,Be)=>{me(),xe(Me);let $e;for(;!($e=Be(Ee()));)xe();return me(),$e}}function _validateObject(c,t,n={}){if(!c||typeof c!="object")throw new Error("expected valid options object");function ie(fe,ae,le){const pe=c[fe];if(le&&pe===void 0)return;const me=typeof pe;if(me!==ae||pe===null)throw new Error(`param "${fe}" is invalid: expected ${ae}, got ${me}`)}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 pe=ie/n,me=ie%n,ye=fe-ae*pe;ie=n,n=me,fe=ae,ae=ye}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),pe=c.mul(ae,c.sub(le,c.ONE));return assertIsSquare(c,pe,t),pe}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(pe,me)=>{let ye=pe.pow(me,le),xe=pe.mul(ye,ie);const Ee=pe.mul(ye,fe),Se=pe.mul(ye,ae),Me=pe.eql(pe.sqr(xe),me),Be=pe.eql(pe.sqr(Ee),me);ye=pe.cmov(ye,xe,Me),xe=pe.cmov(Se,Ee,Be);const $e=pe.eql(pe.sqr(xe),me),ke=pe.cmov(ye,xe,$e);return assertIsSquare(pe,ke,me),ke}}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(me,ye){if(me.is0(ye))return ye;if(FpLegendre(me,ye)!==1)throw new Error("Cannot find square root");let xe=n,Ee=me.mul(me.ONE,ae),Se=me.pow(ye,t),Me=me.pow(ye,le);for(;!me.eql(Se,me.ONE);){if(me.is0(Se))return me.ZERO;let Be=1,$e=me.sqr(Se);for(;!me.eql($e,me.ONE);)if(Be++,$e=me.sqr($e),Be===xe)throw new Error("Cannot find square root");const ke=_1n$4<<BigInt(xe-Be-1),Te=me.pow(Ee,ke);xe=Be,Ee=me.sqr(Te),Se=me.mul(Se,Ee),Me=me.mul(Me,Te)}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,pe,me)=>c.is0(pe)?le:(ie[me]=le,c.mul(le,pe)),c.ONE),ae=c.inv(fe);return t.reduceRight((le,pe,me)=>c.is0(pe)?le:(ie[me]=c.mul(le,ie[me]),c.mul(le,pe)),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,pe;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),pe=Se.allowedLengths}else typeof t=="number"&&(fe=t),ie.sqrt&&(ae=ie.sqrt);const{nBitLength:me,nByteLength:ye}=nLength(c,fe);if(ye>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let xe;const Ee=Object.freeze({ORDER:c,isLE:n,BITS:me,BYTES:ye,MASK:bitMask(me),ZERO:_0n$3,ONE:_1n$4,allowedLengths:pe,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,ye):numberToBytesBE(Se,ye),fromBytes:(Se,Me=!0)=>{if(pe){if(!pe.includes(Se.length)||Se.length>ye)throw new Error("Field.fromBytes: expected "+pe+" bytes, got "+Se.length);const $e=new Uint8Array(ye);$e.set(Se,n?0:$e.length-Se.length),Se=$e}if(Se.length!==ye)throw new Error("Field.fromBytes: expected "+ye+" 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),pe=mod(le,t-_1n$4)+_1n$4;return n?numberToBytesLE(pe,fe):numberToBytesBE(pe,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 pe=Number(c&fe),me=c>>le;pe>ie&&(pe-=ae,me+=_1n$3);const ye=t*ie,xe=ye+Math.abs(pe)-1,Ee=pe===0,Se=pe<0,Me=t%2!==0;return{nextN:me,offset:xe,isZero:Ee,isNeg:Se,isNegF:Me,offsetF:ye}}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,pe=le;for(let me=0;me<ie;me++){pe=le,ae.push(pe);for(let ye=1;ye<fe;ye++)pe=pe.add(le),ae.push(pe);le=pe.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 pe=0;pe<le.windows;pe++){const{nextN:me,offset:ye,isZero:xe,isNeg:Ee,isNegF:Se,offsetF:Me}=calcOffsets(ie,pe,le);ie=me,xe?ae=ae.add(negateCt(Se,n[Me])):fe=fe.add(negateCt(Ee,n[ye]))}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:pe,offset:me,isZero:ye,isNeg:xe}=calcOffsets(ie,le,ae);if(ie=pe,!ye){const Ee=n[me];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,pe=bitLen(BigInt(fe));let me=1;pe>12?me=pe-3:pe>4?me=pe-2:pe>0&&(me=2);const ye=bitMask(me),xe=new Array(Number(ye)+1).fill(le),Ee=Math.floor((t.BITS-1)/me)*me;let Se=le;for(let Me=Ee;Me>=0;Me-=me){xe.fill(le);for(let $e=0;$e<ae;$e++){const ke=ie[$e],Te=Number(ke>>BigInt(Me)&ye);xe[Te]=xe[Te].add(n[$e])}let Be=le;for(let $e=xe.length-1,ke=le;$e>0;$e--)ke=ke.add(xe[$e]),Be=Be.add(ke);if(Se=Se.add(Be),Me!==0)for(let $e=0;$e<me;$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 me of["p","n","h"]){const ye=t[me];if(!(typeof ye=="bigint"&&ye>_0n$2))throw new Error(`CURVE.${me} must be positive bigint`)}const fe=createField(t.p,n.Fp,ie),ae=createField(t.n,n.Fn,ie),pe=["Gx","Gy","a",c==="weierstrass"?"b":"d"];for(const me of pe)if(!fe.isValid(t[me]))throw new Error(`CURVE.${me} 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),pe=c.add(c.ONE,c.mul(t.d,c.mul(fe,ae)));return c.eql(le,pe)}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 pe=_2n$3<<BigInt(fe.BYTES*8)-_1n$2,me=ke=>ie.create(ke),ye=t.uvRatio||((ke,Te)=>{try{return{isValid:!0,value:ie.sqrt(ie.div(ke,Te))}}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(ke,Te,Pe=!1){const Ue=Pe?_1n$2:_0n$1;return aInRange("coordinate "+ke,Te,Ue,pe),Te}function Ee(ke){if(!(ke instanceof Be))throw new Error("ExtendedPoint expected")}const Se=memoized((ke,Te)=>{const{X:Pe,Y:Ue,Z:Fe}=ke,je=ke.is0();Te==null&&(Te=je?_8n$1:ie.inv(Fe));const Ve=me(Pe*Te),Ye=me(Ue*Te),Qe=ie.mul(Fe,Te);if(je)return{x:_0n$1,y:_1n$2};if(Qe!==_1n$2)throw new Error("invZ was invalid");return{x:Ve,y:Ye}}),Me=memoized(ke=>{const{a:Te,d:Pe}=ae;if(ke.is0())throw new Error("bad point: ZERO");const{X:Ue,Y:Fe,Z:je,T:Ve}=ke,Ye=me(Ue*Ue),Qe=me(Fe*Fe),Ke=me(je*je),Pt=me(Ke*Ke),_e=me(Ye*Te),se=me(Ke*me(_e+Qe)),ce=me(Pt+me(Pe*me(Ye*Qe)));if(se!==ce)throw new Error("bad point: equation left != right (1)");const de=me(Ue*Fe),he=me(je*Ve);if(de!==he)throw new Error("bad point: equation left != right (2)");return!0});class Be{constructor(Te,Pe,Ue,Fe){this.X=xe("x",Te),this.Y=xe("y",Pe),this.Z=xe("z",Ue,!0),this.T=xe("t",Fe),Object.freeze(this)}static CURVE(){return ae}static fromAffine(Te){if(Te instanceof Be)throw new Error("extended point not allowed");const{x:Pe,y:Ue}=Te||{};return xe("x",Pe),xe("y",Ue),new Be(Pe,Ue,_1n$2,me(Pe*Ue))}static fromBytes(Te,Pe=!1){const Ue=ie.BYTES,{a:Fe,d:je}=ae;Te=copyBytes(_abytes2(Te,Ue,"point")),_abool2(Pe,"zip215");const Ve=copyBytes(Te),Ye=Te[Ue-1];Ve[Ue-1]=Ye&-129;const Qe=bytesToNumberLE(Ve),Ke=Pe?pe:ie.ORDER;aInRange("point.y",Qe,_0n$1,Ke);const Pt=me(Qe*Qe),_e=me(Pt-_1n$2),se=me(je*Pt-Fe);let{isValid:ce,value:de}=ye(_e,se);if(!ce)throw new Error("bad point: invalid y coordinate");const he=(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!==he&&(de=me(-de)),Be.fromAffine({x:de,y:Qe})}static fromHex(Te,Pe=!1){return Be.fromBytes(ensureBytes("point",Te),Pe)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(Te=8,Pe=!0){return $e.createCache(this,Te),Pe||this.multiply(_2n$3),this}assertValidity(){Me(this)}equals(Te){Ee(Te);const{X:Pe,Y:Ue,Z:Fe}=this,{X:je,Y:Ve,Z:Ye}=Te,Qe=me(Pe*Ye),Ke=me(je*Fe),Pt=me(Ue*Ye),_e=me(Ve*Fe);return Qe===Ke&&Pt===_e}is0(){return this.equals(Be.ZERO)}negate(){return new Be(me(-this.X),this.Y,this.Z,me(-this.T))}double(){const{a:Te}=ae,{X:Pe,Y:Ue,Z:Fe}=this,je=me(Pe*Pe),Ve=me(Ue*Ue),Ye=me(_2n$3*me(Fe*Fe)),Qe=me(Te*je),Ke=Pe+Ue,Pt=me(me(Ke*Ke)-je-Ve),_e=Qe+Ve,se=_e-Ye,ce=Qe-Ve,de=me(Pt*se),he=me(_e*ce),ve=me(Pt*ce),we=me(se*_e);return new Be(de,he,we,ve)}add(Te){Ee(Te);const{a:Pe,d:Ue}=ae,{X:Fe,Y:je,Z:Ve,T:Ye}=this,{X:Qe,Y:Ke,Z:Pt,T:_e}=Te,se=me(Fe*Qe),ce=me(je*Ke),de=me(Ye*Ue*_e),he=me(Ve*Pt),ve=me((Fe+je)*(Qe+Ke)-se-ce),we=he-de,Ae=he+de,be=me(ce-Pe*se),ue=me(ve*we),ge=me(Ae*be),Re=me(ve*be),Ne=me(we*Ae);return new Be(ue,ge,Ne,Re)}subtract(Te){return this.add(Te.negate())}multiply(Te){if(!fe.isValidNot0(Te))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:Pe,f:Ue}=$e.cached(this,Te,Fe=>normalizeZ(Be,Fe));return normalizeZ(Be,[Pe,Ue])[0]}multiplyUnsafe(Te,Pe=Be.ZERO){if(!fe.isValid(Te))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return Te===_0n$1?Be.ZERO:this.is0()||Te===_1n$2?this:$e.unsafe(this,Te,Ue=>normalizeZ(Be,Ue),Pe)}isSmallOrder(){return this.multiplyUnsafe(le).is0()}isTorsionFree(){return $e.unsafe(this,ae.n).is0()}toAffine(Te){return Se(this,Te)}clearCofactor(){return le===_1n$2?this:this.multiplyUnsafe(le)}toBytes(){const{x:Te,y:Pe}=this.toAffine(),Ue=ie.toBytes(Pe);return Ue[Ue.length-1]|=Te&_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(Te){return normalizeZ(Be,Te)}static msm(Te,Pe){return pippenger(Be,fe,Te,Pe)}_setWindowSize(Te){this.precompute(Te)}toRawBytes(){return this.toBytes()}}Be.BASE=new Be(ae.Gx,ae.Gy,_1n$2,me(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,pe=n.randomBytes||randomBytes,me=n.adjustScalarBytes||(Ke=>Ke),ye=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=me(_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(ye(_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),he=Be(_e.context,se,Ke),ve=fe.multiply(he).toBytes(),we=Be(_e.context,ve,de,Ke),Ae=le.create(he+we*ce);if(!le.isValid(Ae))throw new Error("sign failed: invalid s");const be=concatBytes(ve,le.toBytes(Ae));return _abytes2(be,Ue.signature,"result")}const ke={zip215:!0};function Te(Ke,Pt,_e,se=ke){const{context:ce,zip215:de}=se,he=Ue.signature;Ke=ensureBytes("signature",Ke,he),Pt=ensureBytes("message",Pt),_e=ensureBytes("publicKey",_e,Ue.publicKey),de!==void 0&&_abool2(de,"zip215"),ie&&(Pt=ie(Pt));const ve=he/2,we=Ke.subarray(0,ve),Ae=bytesToNumberLE(Ke.subarray(ve,he));let be,ue,ge;try{be=c.fromBytes(_e,de),ue=c.fromBytes(we,de),ge=fe.multiplyUnsafe(Ae)}catch{return!1}if(!de&&be.isSmallOrder())return!1;const Re=Be(ce,ue.toBytes(),be.toBytes(),Pt);return ue.add(be.multiplyUnsafe(Re)).subtract(ge).clearCofactor().is0()}const Pe=ae.BYTES,Ue={secretKey:Pe,publicKey:Pe,signature:2*Pe,seed:Pe};function Fe(Ke=pe(Ue.seed)){return _abytes2(Ke,Ue.seed,"seed")}function je(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:Fe,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 me(_e).subarray(0,Pt)},randomPrivateKey:Fe,precompute(Ke=8,Pt=c.BASE){return Pt.precompute(Ke,!1)}};return Object.freeze({keygen:je,getPublicKey:Me,sign:$e,verify:Te,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,pe=c*c%ae*c%ae,me=pow2(pe,_2n$2,ae)*pe%ae,ye=pow2(me,_1n$1,ae)*c%ae,xe=pow2(ye,_5n,ae)*ye%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,ke=pow2($e,t,ae)*xe%ae;return{pow_p_5_8:pow2(ke,_2n$2,ae)*c%ae,b2:pe}}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 pe=mod(t*le*le,n),me=le,ye=mod(le*ED25519_SQRT_M1,n),xe=pe===c,Ee=pe===mod(-c,n),Se=pe===mod(-c*ED25519_SQRT_M1,n);return xe&&(le=me),(Ee||Se)&&(le=ye),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,pe){for(var me in le)pe[me]=le[me]}ie.from&&ie.alloc&&ie.allocUnsafe&&ie.allocUnsafeSlow?c.exports=n:(fe(n,t),t.Buffer=ae);function ae(le,pe,me){return ie(le,pe,me)}ae.prototype=Object.create(ie.prototype),fe(ie,ae),ae.from=function(le,pe,me){if(typeof le=="number")throw new TypeError("Argument must not be a number");return ie(le,pe,me)},ae.alloc=function(le,pe,me){if(typeof le!="number")throw new TypeError("Argument must be a number");var ye=ie(le);return pe!==void 0?typeof me=="string"?ye.fill(pe,me):ye.fill(pe):ye.fill(0),ye},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,pe=c.charAt(0),me=Math.log(le)/Math.log(256),ye=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,ke=0,Te=Me.length;ke!==Te&&Me[ke]===0;)ke++,Be++;for(var Pe=(Te-ke)*ye+1>>>0,Ue=new Uint8Array(Pe);ke!==Te;){for(var Fe=Me[ke],je=0,Ve=Pe-1;(Fe!==0||je<$e)&&Ve!==-1;Ve--,je++)Fe+=256*Ue[Ve]>>>0,Ue[Ve]=Fe%le>>>0,Fe=Fe/le>>>0;if(Fe!==0)throw new Error("Non-zero carry");$e=je,ke++}for(var Ye=Pe-$e;Ye!==Pe&&Ue[Ye]===0;)Ye++;for(var Qe=pe.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,ke=0;Me[Be]===pe;)$e++,Be++;for(var Te=(Me.length-Be)*me+1>>>0,Pe=new Uint8Array(Te);Be<Me.length;){var Ue=Me.charCodeAt(Be);if(Ue>255)return;var Fe=t[Ue];if(Fe===255)return;for(var je=0,Ve=Te-1;(Fe!==0||je<ke)&&Ve!==-1;Ve--,je++)Fe+=le*Pe[Ve]>>>0,Pe[Ve]=Fe%256>>>0,Fe=Fe/256>>>0;if(Fe!==0)throw new Error("Non-zero carry");ke=je,Be++}for(var Ye=Te-ke;Ye!==Te&&Pe[Ye]===0;)Ye++;var Qe=_Buffer.allocUnsafe($e+(Te-Ye));Qe.fill(0,0,$e);for(var Ke=$e;Ye!==Te;)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$2=basex(ALPHABET$1);const o$1=getDefaultExportFromCjs$2(bs58$2),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 pe=ae&1023,me=le&1023;fe.push(65536+(pe<<10)+me),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(pe,me){if(me===end_of_stream&&fe!==0)return fe=0,decoderError(t);if(me===end_of_stream)return finished;if(fe===0){if(inRange(me,0,127))return me;if(inRange(me,194,223))fe=1,n=me-192;else if(inRange(me,224,239))me===224&&(ae=160),me===237&&(le=159),fe=2,n=me-224;else if(inRange(me,240,244))me===240&&(ae=144),me===244&&(le=143),fe=3,n=me-240;else return decoderError(t);return n=n<<6*fe,null}if(!inRange(me,ae,le))return n=fe=ie=0,ae=128,le=191,pe.prepend(me),decoderError(t);if(ae=128,le=191,ie+=1,n+=me-128<<6*(fe-ie),ie!==fe)return null;var ye=n;return n=fe=ie=0,ye}}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$b=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$b=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 pe=c.length-1;pe>=0;pe--)(le=c[pe])&&(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$b=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$b(t,c,n);return __setModuleDefault$b(t,c),t},__importDefault$a=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$a(bnExports$3),bs58_1$1=__importDefault$a(bs58$2),encoding=__importStar$b(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$1.default.encode(Buffer$7.from(c))}lib.baseEncode=baseEncode;function baseDecode(c){return Buffer$7.from(bs58_1$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,pe]=ie.values[ae];if(le===fe){n.writeU8(ae),serializeField(c,le,t[le],pe,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 pe=deserializeField(c,t,n.key,ie),me=deserializeField(c,t,n.value,ie);fe.set(pe,me)}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],pe=deserializeField(c,ae,le,n);return new t({[ae]:pe})}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$2=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$2.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,pe)=>le+fe.encode(pe,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 pe of this.fields){let me=pe.span;if(le=0<me?me:0,pe.property!==void 0){const ye=t[pe.property];ye!==void 0&&(le=pe.encode(ye,n,ie),0>me&&(me=pe.getSpan(n,ie)))}ae=ie,ie+=me}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(pe){return le(pe)},this.configGetSourceVariant=function(pe){le=pe.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 pe=this.defaultLayout;let me=0;this.usesPrefixDiscriminator&&(me=fe.layout.span),ie=this.makeDestinationObject(),ie[fe.property]=ae,ie[pe.property]=pe.decode(t,n+me)}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 pe=0;return this.usesPrefixDiscriminator&&(pe=ae.layout.span),ae.encode(t[ae.property],n,ie),pe+le.encode(t[le.property],n,ie+pe)}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,pe)=>le+pe.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$2.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$2.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:pe}=t,me=pe.length===0?fe:`At path: ${pe.join(".")} -- ${fe}`;super(ae??me),ae!=null&&(this.cause=me),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:pe,message:me=`Expected a value of type \`${le}\`${pe?` with refinement \`${pe}\``:""}, but received: \`${print$2(ie)}\``}=c;return{value:ie,type:le,refinement:pe,key:fe[fe.length-1],path:fe,branch:ae,...c,message:me}}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,pe={path:ie,branch:fe,mask:le};ae&&(c=t.coercer(c,pe));let me="valid";for(const ye of t.validator(c,pe))ye.explanation=n.message,me="not_valid",yield[ye,void 0];for(let[ye,xe,Ee]of t.entries(c,pe)){const Se=run(xe,Ee,{path:ye===void 0?ie:[...ie,ye],branch:ye===void 0?fe:[...fe,xe],coerce:ae,mask:le,message:n.message});for(const Me of Se)Me[0]?(me=Me[0].refinement!=null?"not_refined":"not_valid",yield[Me[0],void 0]):ae&&(xe=Me[1],ye===void 0?c=xe:c instanceof Map?c.set(ye,xe):c instanceof Set?c.add(xe):isObject$1(c)&&(xe!==void 0||ye in c)&&(c[ye]=xe))}if(me!=="not_valid")for(const ye of t.refiner(c,pe))ye.explanation=n.message,me="not_refined",yield[ye,void 0];me==="valid"&&(yield[void 0,c])}let Struct$1=class{constructor(t){const{type:n,schema:ie,validator:fe,refiner:ae,coercer:le=me=>me,entries:pe=function*(){}}=t;this.type=n,this.schema=ie,this.entries=pe,this.coercer=le,fe?this.validator=(me,ye)=>{const xe=fe(me,ye);return toFailures(xe,ye,this,me)}:this.validator=()=>[],ae?this.refiner=(me,ye)=>{const xe=ae(me,ye);return toFailures(xe,ye,this,me)}: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),[pe]=le;if(pe[0])for(const[me]of le)me&&fe.push(me);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"&&REGEX$1.test(c)}var byteToHex=[];for(var i$3=0;i$3<256;++i$3)byteToHex.push((i$3+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 pe=c.random||(c.rng||rng)();ae==null&&(ae=_nodeId=[pe[0]|1,pe[1],pe[2],pe[3],pe[4],pe[5]]),le==null&&(le=_clockseq=(pe[6]<<8|pe[7])&16383)}var me=c.msecs!==void 0?c.msecs:Date.now(),ye=c.nsecs!==void 0?c.nsecs:_lastNSecs+1,xe=me-_lastMSecs+(ye-_lastNSecs)/1e4;if(xe<0&&c.clockseq===void 0&&(le=le+1&16383),(xe<0||me>_lastMSecs)&&c.nsecs===void 0&&(ye=0),ye>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_lastMSecs=me,_lastNSecs=ye,_clockseq=le,me+=122192928e5;var Ee=((me&268435455)*1e4+ye)%4294967296;fe[ie++]=Ee>>>24&255,fe[ie++]=Ee>>>16&255,fe[ie++]=Ee>>>8&255,fe[ie++]=Ee&255;var Se=me/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,pe){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 me=new Uint8Array(16+fe.length);if(me.set(ae),me.set(fe,ae.length),me=n(me),me[6]=me[6]&15|t,me[8]=me[8]&63|128,le){pe=pe||0;for(var ye=0;ye<16;++ye)le[pe+ye]=me[ye];return le}return stringify(me)}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 pe=n,me=ie,ye=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,pe),ie=safeAdd(ie,me),fe=safeAdd(fe,ye),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),pe=new Array(le),me=0;me<le;++me){for(var ye=new Uint32Array(16),xe=0;xe<16;++xe)ye[xe]=c[me*64+xe*4]<<24|c[me*64+xe*4+1]<<16|c[me*64+xe*4+2]<<8|c[me*64+xe*4+3];pe[me]=ye}pe[le-1][14]=(c.length-1)*8/Math.pow(2,32),pe[le-1][14]=Math.floor(pe[le-1][14]),pe[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]=pe[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],ke=n[1],Te=n[2],Pe=n[3],Ue=n[4],Fe=0;Fe<80;++Fe){var je=Math.floor(Fe/20),Ve=ROTL($e,5)+f$1(je,ke,Te,Pe)+Ue+t[je]+Se[Fe]>>>0;Ue=Pe,Pe=Te,Te=ROTL(ke,30)>>>0,ke=$e,$e=Ve}n[0]=n[0]+$e>>>0,n[1]=n[1]+ke>>>0,n[2]=n[2]+Te>>>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 ye=typeof ie=="function";try{ae=generateRequest(c,t,n,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(xe){if(ye)return ie(xe);throw xe}if(!ye)return ae}let me;try{me=JSON.stringify(ae,this.options.replacer)}catch(ye){return ie(ye)}return this.callServer(me,function(ye,xe){fe._parseResponse(ye,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(me,ye,xe){this.fn=me,this.context=ye,this.once=xe||!1}function ae(me,ye,xe,Ee,Se){if(typeof xe!="function")throw new TypeError("The listener must be a function");var Me=new fe(xe,Ee||me,Se),Be=n?n+ye:ye;return me._events[Be]?me._events[Be].fn?me._events[Be]=[me._events[Be],Me]:me._events[Be].push(Me):(me._events[Be]=Me,me._eventsCount++),me}function le(me,ye){--me._eventsCount===0?me._events=new ie:delete me._events[ye]}function pe(){this._events=new ie,this._eventsCount=0}pe.prototype.eventNames=function(){var ye=[],xe,Ee;if(this._eventsCount===0)return ye;for(Ee in xe=this._events)t.call(xe,Ee)&&ye.push(n?Ee.slice(1):Ee);return Object.getOwnPropertySymbols?ye.concat(Object.getOwnPropertySymbols(xe)):ye},pe.prototype.listeners=function(ye){var xe=n?n+ye:ye,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},pe.prototype.listenerCount=function(ye){var xe=n?n+ye:ye,Ee=this._events[xe];return Ee?Ee.fn?1:Ee.length:0},pe.prototype.emit=function(ye,xe,Ee,Se,Me,Be){var $e=n?n+ye:ye;if(!this._events[$e])return!1;var ke=this._events[$e],Te=arguments.length,Pe,Ue;if(ke.fn){switch(ke.once&&this.removeListener(ye,ke.fn,void 0,!0),Te){case 1:return ke.fn.call(ke.context),!0;case 2:return ke.fn.call(ke.context,xe),!0;case 3:return ke.fn.call(ke.context,xe,Ee),!0;case 4:return ke.fn.call(ke.context,xe,Ee,Se),!0;case 5:return ke.fn.call(ke.context,xe,Ee,Se,Me),!0;case 6:return ke.fn.call(ke.context,xe,Ee,Se,Me,Be),!0}for(Ue=1,Pe=new Array(Te-1);Ue<Te;Ue++)Pe[Ue-1]=arguments[Ue];ke.fn.apply(ke.context,Pe)}else{var Fe=ke.length,je;for(Ue=0;Ue<Fe;Ue++)switch(ke[Ue].once&&this.removeListener(ye,ke[Ue].fn,void 0,!0),Te){case 1:ke[Ue].fn.call(ke[Ue].context);break;case 2:ke[Ue].fn.call(ke[Ue].context,xe);break;case 3:ke[Ue].fn.call(ke[Ue].context,xe,Ee);break;case 4:ke[Ue].fn.call(ke[Ue].context,xe,Ee,Se);break;default:if(!Pe)for(je=1,Pe=new Array(Te-1);je<Te;je++)Pe[je-1]=arguments[je];ke[Ue].fn.apply(ke[Ue].context,Pe)}}return!0},pe.prototype.on=function(ye,xe,Ee){return ae(this,ye,xe,Ee,!1)},pe.prototype.once=function(ye,xe,Ee){return ae(this,ye,xe,Ee,!0)},pe.prototype.removeListener=function(ye,xe,Ee,Se){var Me=n?n+ye:ye;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,ke=[],Te=Be.length;$e<Te;$e++)(Be[$e].fn!==xe||Se&&!Be[$e].once||Ee&&Be[$e].context!==Ee)&&ke.push(Be[$e]);ke.length?this._events[Me]=ke.length===1?ke[0]:ke:le(this,Me)}return this},pe.prototype.removeAllListeners=function(ye){var xe;return ye?(xe=n?n+ye:ye,this._events[xe]&&le(this,xe)):(this._events=new ie,this._eventsCount=0),this},pe.prototype.off=pe.prototype.removeListener,pe.prototype.addListener=pe.prototype.on,pe.prefixed=n,pe.EventEmitter=pe,c.exports=pe})(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,...pe}={},me,ye){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=pe,this.current_reconnects=0,this.generate_request_id=me||(()=>typeof this.rpc_id=="number"?++this.rpc_id:Number(this.rpc_id)+1),ye?this.dataPack=ye: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 pe=this.generate_request_id(t,n),me={jsonrpc:"2.0",method:t,params:n||void 0,id:pe};this.socket.send(this.dataPack.encode(me),fe,ye=>{if(ye)return le(ye);this.queue[pe]={promise:[ae,le]},ie&&(this.queue[pe].timeout=setTimeout(()=>{delete this.queue[pe],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:pe}=this;return t=t,t.finished=fe,t.destroyed=ae,t.blockLen=le,t.outputLen=pe,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,pe=divNearest(le*c,n),me=divNearest(-fe*c,n);let ye=c-pe*ie-me*ae,xe=-pe*fe-me*le;const Ee=ye<_0n,Se=xe<_0n;Ee&&(ye=-ye),Se&&(xe=-xe);const Me=bitMask(Math.ceil(bitLen(n)/2))+_1n;if(ye<_0n||ye>=Me||xe<_0n||xe>=Me)throw new Error("splitScalar (endomorphism): failed, k="+c);return{k1neg:Ee,k1:ye,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 me=fe&127;if(!me)throw new n("tlv.decode(long): indefinite length not supported");if(me>4)throw new n("tlv.decode(long): byte length is too big");const ye=t.subarray(ie,ie+me);if(ye.length!==me)throw new n("tlv.decode: length bytes not complete");if(ye[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const xe of ye)le=le<<8|xe;if(ie+=me,le<128)throw new n("tlv.decode(long): not minimal encoding")}const pe=t.subarray(ie,ie+le);if(pe.length!==le)throw new n("tlv.decode: wrong value length");return{v:pe,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:pe,l:me}=ie.decode(2,ae),{v:ye,l:xe}=ie.decode(2,me);if(xe.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(pe),s:n.decode(ye)}},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:pe}=ae;_validateObject(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:me}=t;if(me&&(!ie.is0(ae.a)||typeof me.beta!="bigint"||!Array.isArray(me.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const ye=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:he,y:ve}=ce.toAffine(),we=ie.toBytes(he);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}=ye,he=se.length,ve=se[0],we=se.subarray(1);if(he===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 be=$e(Ae);let ue;try{ue=ie.sqrt(be)}catch(Ne){const qe=Ne instanceof Error?": "+Ne.message:"";throw new Error("bad point: is not on curve, sqrt error"+qe)}xe();const ge=ie.isOdd(ue);return(ve&1)===1!==ge&&(ue=ie.neg(ue)),{x:Ae,y:ue}}else if(he===de&&ve===4){const Ae=ie.BYTES,be=ie.fromBytes(we.subarray(0,Ae)),ue=ie.fromBytes(we.subarray(Ae,Ae*2));if(!ke(be,ue))throw new Error("bad point: is not on curve");return{x:be,y:ue}}else throw new Error(`bad point: got length ${he}, 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 ke(se,ce){const de=ie.sqr(ce),he=$e(se);return ie.eql(de,he)}if(!ke(ae.Gx,ae.Gy))throw new Error("bad curve params: generator point");const Te=ie.mul(ie.pow(ae.a,_3n),_4n),Pe=ie.mul(ie.sqr(ae.b),BigInt(27));if(ie.is0(ie.add(Te,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 Fe(se){if(!(se instanceof Ke))throw new Error("ProjectivePoint expected")}function je(se){if(!me||!me.basises)throw new Error("no endo");return _splitEndoScalar(se,me.basises,fe.ORDER)}const Ve=memoized((se,ce)=>{const{X:de,Y:he,Z:ve}=se;if(ie.eql(ve,ie.ONE))return{x:de,y:he};const we=se.is0();ce==null&&(ce=we?ie.ONE:ie.inv(ve));const Ae=ie.mul(de,ce),be=ie.mul(he,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:be}}),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(!ke(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,he,ve){return de=new Ke(ie.mul(de.X,se),de.Y,de.Z),ce=negateCt(he,ce),de=negateCt(ve,de),ce.add(de)}class Ke{constructor(ce,de,he){this.X=Ue("x",ce),this.Y=Ue("y",de,!0),this.Z=Ue("z",he),Object.freeze(this)}static CURVE(){return ae}static fromAffine(ce){const{x:de,y:he}=ce||{};if(!ce||!ie.isValid(de)||!ie.isValid(he))throw new Error("invalid affine point");if(ce instanceof Ke)throw new Error("projective point not allowed");return ie.is0(de)&&ie.is0(he)?Ke.ZERO:new Ke(de,he,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){Fe(ce);const{X:de,Y:he,Z:ve}=this,{X:we,Y:Ae,Z:be}=ce,ue=ie.eql(ie.mul(de,be),ie.mul(we,ve)),ge=ie.eql(ie.mul(he,be),ie.mul(Ae,ve));return ue&&ge}negate(){return new Ke(this.X,ie.neg(this.Y),this.Z)}double(){const{a:ce,b:de}=ae,he=ie.mul(de,_3n),{X:ve,Y:we,Z:Ae}=this;let be=ie.ZERO,ue=ie.ZERO,ge=ie.ZERO,Re=ie.mul(ve,ve),Ne=ie.mul(we,we),qe=ie.mul(Ae,Ae),Ie=ie.mul(ve,we);return Ie=ie.add(Ie,Ie),ge=ie.mul(ve,Ae),ge=ie.add(ge,ge),be=ie.mul(ce,ge),ue=ie.mul(he,qe),ue=ie.add(be,ue),be=ie.sub(Ne,ue),ue=ie.add(Ne,ue),ue=ie.mul(be,ue),be=ie.mul(Ie,be),ge=ie.mul(he,ge),qe=ie.mul(ce,qe),Ie=ie.sub(Re,qe),Ie=ie.mul(ce,Ie),Ie=ie.add(Ie,ge),ge=ie.add(Re,Re),Re=ie.add(ge,Re),Re=ie.add(Re,qe),Re=ie.mul(Re,Ie),ue=ie.add(ue,Re),qe=ie.mul(we,Ae),qe=ie.add(qe,qe),Re=ie.mul(qe,Ie),be=ie.sub(be,Re),ge=ie.mul(qe,Ne),ge=ie.add(ge,ge),ge=ie.add(ge,ge),new Ke(be,ue,ge)}add(ce){Fe(ce);const{X:de,Y:he,Z:ve}=this,{X:we,Y:Ae,Z:be}=ce;let ue=ie.ZERO,ge=ie.ZERO,Re=ie.ZERO;const Ne=ae.a,qe=ie.mul(ae.b,_3n);let Ie=ie.mul(de,we),ze=ie.mul(he,Ae),Ce=ie.mul(ve,be),De=ie.add(de,he),He=ie.add(we,Ae);De=ie.mul(De,He),He=ie.add(Ie,ze),De=ie.sub(De,He),He=ie.add(de,ve);let Xe=ie.add(we,be);return He=ie.mul(He,Xe),Xe=ie.add(Ie,Ce),He=ie.sub(He,Xe),Xe=ie.add(he,ve),ue=ie.add(Ae,be),Xe=ie.mul(Xe,ue),ue=ie.add(ze,Ce),Xe=ie.sub(Xe,ue),Re=ie.mul(Ne,He),ue=ie.mul(qe,Ce),Re=ie.add(ue,Re),ue=ie.sub(ze,Re),Re=ie.add(ze,Re),ge=ie.mul(ue,Re),ze=ie.add(Ie,Ie),ze=ie.add(ze,Ie),Ce=ie.mul(Ne,Ce),He=ie.mul(qe,He),ze=ie.add(ze,Ce),Ce=ie.sub(Ie,Ce),Ce=ie.mul(Ne,Ce),He=ie.add(He,Ce),Ie=ie.mul(ze,He),ge=ie.add(ge,Ie),Ie=ie.mul(Xe,He),ue=ie.mul(De,ue),ue=ie.sub(ue,Ie),Ie=ie.mul(De,ze),Re=ie.mul(Xe,Re),Re=ie.add(Re,Ie),new Ke(ue,ge,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 he,ve;const we=Ae=>_e.cached(this,Ae,be=>normalizeZ(Ke,be));if(de){const{k1neg:Ae,k1:be,k2neg:ue,k2:ge}=je(ce),{p:Re,f:Ne}=we(be),{p:qe,f:Ie}=we(ge);ve=Ne.add(Ie),he=Qe(de.beta,Re,qe,Ae,ue)}else{const{p:Ae,f:be}=we(ce);he=Ae,ve=be}return normalizeZ(Ke,[he,ve])[0]}multiplyUnsafe(ce){const{endo:de}=t,he=this;if(!fe.isValid(ce))throw new Error("invalid scalar: out of range");if(ce===_0n||he.is0())return Ke.ZERO;if(ce===_1n)return he;if(_e.hasCache(this))return this.multiply(ce);if(de){const{k1neg:ve,k1:we,k2neg:Ae,k2:be}=je(ce),{p1:ue,p2:ge}=mulEndoUnsafe(Ke,he,we,be);return Qe(de.beta,ue,ge,ve,Ae)}else return _e.unsafe(he,ce)}multiplyAndAddUnsafe(ce,de,he){const ve=this.multiplyUnsafe(de).add(ce.multiplyUnsafe(he));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,pe).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:ke}=fe;try{const Te=Me.length;return Be===!0&&Te!==$e||Be===!1&&Te!==ke?!1:!!c.fromBytes(Me)}catch{return!1}}function pe(Me=ie(fe.seed)){return mapHashToField(_abytes2(Me,fe.seed,"seed"),n.ORDER)}function me(Me,Be=!0){return c.BASE.multiply(_normFnElement(n,Me)).toBytes(Be)}function ye(Me){const Be=pe(Me);return{secretKey:Be,publicKey:me(Be)}}function xe(Me){if(typeof Me=="bigint")return!1;if(Me instanceof c)return!0;const{secretKey:Be,publicKey:$e,publicKeyUncompressed:ke}=fe;if(n.allowedLengths||Be===$e)return;const Te=ensureBytes("key",Me).length;return Te===$e||Te===ke}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 ke=_normFnElement(n,Me);return c.fromHex(Be).multiply(ke).toBytes($e)}return Object.freeze({getPublicKey:me,getSharedSecret:Ee,keygen:ye,Point:c,utils:{isValidSecretKey:ae,isValidPublicKey:le,randomSecretKey:pe,isValidPrivateKey:ae,randomPrivateKey:pe,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,...he)=>hmac(t,de,concatBytes(...he))),{Fp:ae,Fn:le}=c,{ORDER:pe,BITS:me}=le,{keygen:ye,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 ke(de){const he=pe>>_1n;return de>he}function Te(de,he){if(!le.isValidNot0(he))throw new Error(`invalid signature ${de}: out of range 1..Point.Fn.ORDER`);return he}function Pe(de,he){validateSigFormat(he);const ve=Me.signature,we=he==="compact"?ve:he==="recovered"?ve+1:void 0;return _abytes2(de,we,`${he} signature`)}class Ue{constructor(he,ve,we){this.r=Te("r",he),this.s=Te("s",ve),we!=null&&(this.recovery=we),Object.freeze(this)}static fromBytes(he,ve=$e){Pe(he,ve);let we;if(ve==="der"){const{r:ge,s:Re}=DER.toSig(_abytes2(he));return new Ue(ge,Re)}ve==="recovered"&&(we=he[0],ve="compact",he=he.subarray(1));const Ae=le.BYTES,be=he.subarray(0,Ae),ue=he.subarray(Ae,Ae*2);return new Ue(le.fromBytes(be),le.fromBytes(ue),we)}static fromHex(he,ve){return this.fromBytes(hexToBytes(he),ve)}addRecoveryBit(he){return new Ue(this.r,this.s,he)}recoverPublicKey(he){const ve=ae.ORDER,{r:we,s:Ae,recovery:be}=this;if(be==null||![0,1,2,3].includes(be))throw new Error("recovery id invalid");if(pe*_2n$1<ve&&be>1)throw new Error("recovery id is ambiguous for h>1 curve");const ge=be===2||be===3?we+pe:we;if(!ae.isValid(ge))throw new Error("recovery id 2 or 3 invalid");const Re=ae.toBytes(ge),Ne=c.fromBytes(concatBytes(pprefix((be&1)===0),Re)),qe=le.inv(ge),Ie=je(ensureBytes("msgHash",he)),ze=le.create(-Ie*qe),Ce=le.create(Ae*qe),De=c.BASE.multiplyUnsafe(ze).add(Ne.multiplyUnsafe(Ce));if(De.is0())throw new Error("point at infinify");return De.assertValidity(),De}hasHighS(){return ke(this.s)}toBytes(he=$e){if(validateSigFormat(he),he==="der")return hexToBytes(DER.hexFromSig(this));const ve=le.toBytes(this.r),we=le.toBytes(this.s);if(he==="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(he){return bytesToHex(this.toBytes(he))}assertValidity(){}static fromCompact(he){return Ue.fromBytes(ensureBytes("sig",he),"compact")}static fromDER(he){return Ue.fromBytes(ensureBytes("sig",he),"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 Fe=n.bits2int||function(he){if(he.length>8192)throw new Error("input is too large");const ve=bytesToNumberBE(he),we=he.length*8-me;return we>0?ve>>BigInt(we):ve},je=n.bits2int_modN||function(he){return le.create(Fe(he))},Ve=bitMask(me);function Ye(de){return aInRange("num < 2^"+me,de,_0n,Ve),le.toBytes(de)}function Qe(de,he){return _abytes2(de,void 0,"message"),he?_abytes2(t(de),void 0,"prehashed message"):de}function Ke(de,he,ve){if(["recovered","canonical"].some(ze=>ze in ve))throw new Error("sign() legacy options not supported");const{lowS:we,prehash:Ae,extraEntropy:be}=validateSigOpts(ve,Be);de=Qe(de,Ae);const ue=je(de),ge=_normFnElement(le,he),Re=[Ye(ge),Ye(ue)];if(be!=null&&be!==!1){const ze=be===!0?ie(Me.secretKey):be;Re.push(ensureBytes("extraEntropy",ze))}const Ne=concatBytes(...Re),qe=ue;function Ie(ze){const Ce=Fe(ze);if(!le.isValidNot0(Ce))return;const De=le.inv(Ce),He=c.BASE.multiply(Ce).toAffine(),Xe=le.create(He.x);if(Xe===_0n)return;const Rt=le.create(De*le.create(qe+Xe*ge));if(Rt===_0n)return;let Oe=(He.x===Xe?0:2)|Number(He.y&_1n),Ze=Rt;return we&&ke(Rt)&&(Ze=le.neg(Rt),Oe^=1),new Ue(Xe,Ze,Oe)}return{seed:Ne,k2sig:Ie}}function Pt(de,he,ve={}){de=ensureBytes("message",de);const{seed:we,k2sig:Ae}=Ke(de,he,ve);return createHmacDrbg(t.outputLen,le.BYTES,fe)(we,Ae)}function _e(de){let he;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)he=new Ue(de.r,de.s);else if(ve){try{he=Ue.fromBytes(ensureBytes("sig",de),"der")}catch(Ae){if(!(Ae instanceof DER.Err))throw Ae}if(!he)try{he=Ue.fromBytes(ensureBytes("sig",de),"compact")}catch{return!1}}return he||!1}function se(de,he,ve,we={}){const{lowS:Ae,prehash:be,format:ue}=validateSigOpts(we,Be);if(ve=ensureBytes("publicKey",ve),he=Qe(ensureBytes("message",he),be),"strict"in we)throw new Error("options.strict was renamed to lowS");const ge=ue===void 0?_e(de):Ue.fromBytes(ensureBytes("sig",de),ue);if(ge===!1)return!1;try{const Re=c.fromBytes(ve);if(Ae&&ge.hasHighS())return!1;const{r:Ne,s:qe}=ge,Ie=je(he),ze=le.inv(qe),Ce=le.create(Ie*ze),De=le.create(Ne*ze),He=c.BASE.multiplyUnsafe(Ce).add(Re.multiplyUnsafe(De));return He.is0()?!1:le.create(He.x)===Ne}catch{return!1}}function ce(de,he,ve={}){const{prehash:we}=validateSigOpts(ve,Be);return he=Qe(he,we),Ue.fromBytes(de,"recovered").recoverPublicKey(he).toBytes()}return Object.freeze({keygen:ye,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),pe=BigInt(44),me=BigInt(88),ye=c*c*c%t,xe=ye*ye*c%t,Ee=pow2(xe,n,t)*xe%t,Se=pow2(Ee,n,t)*xe%t,Me=pow2(Se,_2n,t)*ye%t,Be=pow2(Me,fe,t)*Me%t,$e=pow2(Be,ae,t)*Be%t,ke=pow2($e,pe,t)*$e%t,Te=pow2(ke,me,t)*ke%t,Pe=pow2(Te,pe,t)*$e%t,Ue=pow2(Pe,n,t)*xe%t,Fe=pow2(Ue,le,t)*Be%t,je=pow2(Fe,ie,t)*ye%t,Ve=pow2(je,_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,pe)=>{const me={chars:Buffer$1$1.from(ae,"utf8")};return ie(me,le,pe)},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 pe=le.toBase58();let me=ie.get(pe);return me===void 0&&(me={isSigner:!1,isWritable:!1,isInvoked:!1},ie.set(pe,me)),me},ae=fe(n);ae.isSigner=!0,ae.isWritable=!0;for(const le of t){fe(le.programId).isInvoked=!0;for(const pe of le.keys){const me=fe(pe.pubkey);me.isSigner||(me.isSigner=pe.isSigner),me.isWritable||(me.isWritable=pe.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(([,me])=>me.isSigner&&me.isWritable),ie=t.filter(([,me])=>me.isSigner&&!me.isWritable),fe=t.filter(([,me])=>!me.isSigner&&me.isWritable),ae=t.filter(([,me])=>!me.isSigner&&!me.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[me]=n[0];assert$9(me===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const pe=[...n.map(([me])=>new PublicKey(me)),...ie.map(([me])=>new PublicKey(me)),...fe.map(([me])=>new PublicKey(me)),...ae.map(([me])=>new PublicKey(me))];return[le,pe]}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 pe=new PublicKey(ae),me=t.findIndex(ye=>ye.equals(pe));me>=0&&(assert$9(me<256,"Max lookup table index exceeded"),ie.push(me),fe.push(pe),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(pe=>({programIdIndex:pe.programIdIndex,accounts:pe.accountKeyIndexes,data:o$1.encode(pe.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 ke=[];return encodeLength(ke,Be.length),{programIdIndex:Me,keyIndicesCount:Buffer$1$1.from($e),keyIndices:Se,dataLength:Buffer$1$1.from(ke),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 pe=struct([blob(1,"numRequiredSignatures"),blob(1,"numReadonlySignedAccounts"),blob(1,"numReadonlyUnsignedAccounts"),blob(n.length,"keyCount"),seq(publicKey$1("key"),t,"keys"),publicKey$1("recentBlockhash")]),me={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 ye=Buffer$1$1.alloc(2048);const xe=pe.encode(me,ye);return ae.copy(ye,xe),ye.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 pe=[];for(let Se=0;Se<le;Se++){const Me=guardedSplice(n,0,PUBLIC_KEY_LENGTH);pe.push(new PublicKey(Buffer$1$1.from(Me)))}const me=guardedSplice(n,0,PUBLIC_KEY_LENGTH),ye=decodeLength(n);let xe=[];for(let Se=0;Se<ye;Se++){const Me=guardedShift(n),Be=decodeLength(n),$e=guardedSplice(n,0,Be),ke=decodeLength(n),Te=guardedSplice(n,0,ke),Pe=o$1.encode(Buffer$1$1.from(Te));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(me)),accountKeys:pe,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,pe)=>le+pe.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,pe]=n.getMessageComponents(),ye=new MessageAccountKeys(pe,fe).compileInstructions(t.instructions);return new MessageV0({header:le,staticAccountKeys:pe,recentBlockhash:t.recentBlockhash,compiledInstructions:ye,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")]),pe=new Uint8Array(PACKET_DATA_SIZE),ye=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},pe);return pe.slice(0,ye)}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)},pe=[],me=decodeLength(n);for(let Be=0;Be<me;Be++)pe.push(new PublicKey(guardedSplice(n,0,PUBLIC_KEY_LENGTH)));const ye=o$1.encode(guardedSplice(n,0,PUBLIC_KEY_LENGTH)),xe=decodeLength(n),Ee=[];for(let Be=0;Be<xe;Be++){const $e=guardedShift(n),ke=decodeLength(n),Te=guardedSplice(n,0,ke),Pe=decodeLength(n),Ue=new Uint8Array(guardedSplice(n,0,Pe));Ee.push({programIdIndex:$e,accountKeyIndexes:Te,data:Ue})}const Se=decodeLength(n),Me=[];for(let Be=0;Be<Se;Be++){const $e=new PublicKey(guardedSplice(n,0,PUBLIC_KEY_LENGTH)),ke=decodeLength(n),Te=guardedSplice(n,0,ke),Pe=decodeLength(n),Ue=guardedSplice(n,0,Pe);Me.push({accountKey:$e,writableIndexes:Te,readonlyIndexes:Ue})}return new MessageV0({header:le,staticAccountKeys:pe,recentBlockhash:ye,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(Te=>{ae.push({...Te})});const ke=$e.programId.toString();fe.includes(ke)||fe.push(ke)}),fe.forEach($e=>{ae.push({pubkey:new PublicKey($e),isSigner:!1,isWritable:!1})});const le=[];ae.forEach($e=>{const ke=$e.pubkey.toString(),Te=le.findIndex(Pe=>Pe.pubkey.toString()===ke);Te>-1?(le[Te].isWritable=le[Te].isWritable||$e.isWritable,le[Te].isSigner=le[Te].isSigner||$e.isSigner):le.push($e)}),le.sort(function($e,ke){if($e.isSigner!==ke.isSigner)return $e.isSigner?-1:1;if($e.isWritable!==ke.isWritable)return $e.isWritable?-1:1;const Te={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"};return $e.pubkey.toBase58().localeCompare(ke.pubkey.toBase58(),"en",Te)});const pe=le.findIndex($e=>$e.pubkey.equals(ie));if(pe>-1){const[$e]=le.splice(pe,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 ke=le.findIndex(Te=>Te.pubkey.equals($e.publicKey));if(ke>-1)le[ke].isSigner||(le[ke].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 me=0,ye=0,xe=0;const Ee=[],Se=[];le.forEach(({pubkey:$e,isSigner:ke,isWritable:Te})=>{ke?(Ee.push($e.toString()),me+=1,Te||(ye+=1)):(Se.push($e.toString()),Te||(xe+=1))});const Me=Ee.concat(Se),Be=n.map($e=>{const{data:ke,programId:Te}=$e;return{programIdIndex:Me.indexOf(Te.toString()),accounts:$e.keys.map(Pe=>Me.indexOf(Pe.pubkey.toString())),data:o$1.encode(ke)}});return Be.forEach($e=>{assert$9($e.programIdIndex>=0),$e.accounts.forEach(ke=>assert$9(ke>=0))}),new Message({header:{numRequiredSignatures:me,numReadonlySignedAccounts:ye,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+=`
18
18
  Invalid signature for public key${ae.invalid.length===1?"":"(s)"} [\`${ae.invalid.map(pe=>pe.toBase58()).join("`, `")}\`].`),ae.missing&&(le+=`
19
19
  Missing signature for public key${ae.missing.length===1?"":"(s)"} [\`${ae.missing.map(pe=>pe.toBase58()).join("`, `")}\`].`),new Error(le)}}return this._serialize(fe)}_serialize(t){const{signatures:n}=this,ie=[];encodeLength(ie,n.length);const fe=ie.length+n.length*64+t.length,ae=Buffer$1$1.alloc(fe);return assert$9(n.length<256),Buffer$1$1.from(ie).copy(ae,0),n.forEach(({signature:le},pe)=>{le!==null&&(assert$9(le.length===64,"signature has invalid length"),Buffer$1$1.from(le).copy(ae,ie.length+pe*64))}),t.copy(ae,ie.length+n.length*64),assert$9(ae.length<=PACKET_DATA_SIZE,`Transaction too large: ${ae.length} > ${PACKET_DATA_SIZE}`),ae}get keys(){return assert$9(this.instructions.length===1),this.instructions[0].keys.map(t=>t.pubkey)}get programId(){return assert$9(this.instructions.length===1),this.instructions[0].programId}get data(){return assert$9(this.instructions.length===1),this.instructions[0].data}static from(t){let n=[...t];const ie=decodeLength(n);let fe=[];for(let ae=0;ae<ie;ae++){const le=guardedSplice(n,0,SIGNATURE_LENGTH_IN_BYTES);fe.push(o$1.encode(Buffer$1$1.from(le)))}return Transaction.populate(Message.from(n),fe)}static populate(t,n=[]){const ie=new Transaction;return ie.recentBlockhash=t.recentBlockhash,t.header.numRequiredSignatures>0&&(ie.feePayer=t.accountKeys[0]),n.forEach((fe,ae)=>{const le={signature:fe==o$1.encode(DEFAULT_SIGNATURE)?null:o$1.decode(fe),publicKey:t.accountKeys[ae]};ie.signatures.push(le)}),t.instructions.forEach(fe=>{const ae=fe.accounts.map(le=>{const pe=t.accountKeys[le];return{pubkey:pe,isSigner:ie.signatures.some(me=>me.publicKey.toString()===pe.toString())||t.isAccountSigner(le),isWritable:t.isAccountWritable(le)}});ie.instructions.push(new TransactionInstruction({keys:ae,programId:t.accountKeys[fe.programIdIndex],data:o$1.decode(fe.data)}))}),ie._message=t,ie._json=ie.toJSON(),ie}}class TransactionMessage{constructor(t){this.payerKey=void 0,this.instructions=void 0,this.recentBlockhash=void 0,this.payerKey=t.payerKey,this.instructions=t.instructions,this.recentBlockhash=t.recentBlockhash}static decompile(t,n){const{header:ie,compiledInstructions:fe,recentBlockhash:ae}=t,{numRequiredSignatures:le,numReadonlySignedAccounts:pe,numReadonlyUnsignedAccounts:me}=ie,ye=le-pe;assert$9(ye>0,"Message header is invalid");const xe=t.staticAccountKeys.length-le-me;assert$9(xe>=0,"Message header is invalid");const Ee=t.getAccountKeys(n),Se=Ee.get(0);if(Se===void 0)throw new Error("Failed to decompile message because no account keys were found");const Me=[];for(const Be of fe){const $e=[];for(const Te of Be.accountKeyIndexes){const Pe=Ee.get(Te);if(Pe===void 0)throw new Error(`Failed to find key for account key index ${Te}`);const Ue=Te<le;let Fe;Ue?Fe=Te<ye:Te<Ee.staticAccountKeys.length?Fe=Te-le<xe:Fe=Te-Ee.staticAccountKeys.length<Ee.accountKeysFromLookups.writable.length,$e.push({pubkey:Pe,isSigner:Te<ie.numRequiredSignatures,isWritable:Fe})}const ke=Ee.get(Be.programIdIndex);if(ke===void 0)throw new Error(`Failed to find program id for program id index ${Be.programIdIndex}`);Me.push(new TransactionInstruction({programId:ke,data:toBuffer$1(Be.data),keys:$e}))}return new TransactionMessage({payerKey:Se,instructions:Me,recentBlockhash:ae})}compileToLegacyMessage(){return Message.compile({payerKey:this.payerKey,recentBlockhash:this.recentBlockhash,instructions:this.instructions})}compileToV0Message(t){return MessageV0.compile({payerKey:this.payerKey,recentBlockhash:this.recentBlockhash,instructions:this.instructions,addressLookupTableAccounts:t})}}class VersionedTransaction{get version(){return this.message.version}constructor(t,n){if(this.signatures=void 0,this.message=void 0,n!==void 0)assert$9(n.length===t.header.numRequiredSignatures,"Expected signatures length to be equal to the number of required signatures"),this.signatures=n;else{const ie=[];for(let fe=0;fe<t.header.numRequiredSignatures;fe++)ie.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES));this.signatures=ie}this.message=t}serialize(){const t=this.message.serialize(),n=Array();encodeLength(n,this.signatures.length);const ie=struct([blob(n.length,"encodedSignaturesLength"),seq(signature$2(),this.signatures.length,"signatures"),blob(t.length,"serializedMessage")]),fe=new Uint8Array(2048),ae=ie.encode({encodedSignaturesLength:new Uint8Array(n),signatures:this.signatures,serializedMessage:t},fe);return fe.slice(0,ae)}static deserialize(t){let n=[...t];const ie=[],fe=decodeLength(n);for(let le=0;le<fe;le++)ie.push(new Uint8Array(guardedSplice(n,0,SIGNATURE_LENGTH_IN_BYTES)));const ae=VersionedMessage.deserialize(new Uint8Array(n));return new VersionedTransaction(ae,ie)}sign(t){const n=this.message.serialize(),ie=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures);for(const fe of t){const ae=ie.findIndex(le=>le.equals(fe.publicKey));assert$9(ae>=0,`Cannot sign with non signer key ${fe.publicKey.toBase58()}`),this.signatures[ae]=sign$2(n,fe.secretKey)}}addSignature(t,n){assert$9(n.byteLength===64,"Signature must be 64 bytes long");const fe=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures).findIndex(ae=>ae.equals(t));assert$9(fe>=0,`Can not add signature; \`${t.toBase58()}\` is not required to sign this transaction`),this.signatures[fe]=n}}const NUM_TICKS_PER_SECOND=160,DEFAULT_TICKS_PER_SLOT=64,NUM_SLOTS_PER_SECOND=NUM_TICKS_PER_SECOND/DEFAULT_TICKS_PER_SLOT,MS_PER_SLOT=1e3/NUM_SLOTS_PER_SECOND;new PublicKey("SysvarC1ock11111111111111111111111111111111");new PublicKey("SysvarEpochSchedu1e111111111111111111111111");new PublicKey("Sysvar1nstructions1111111111111111111111111");const SYSVAR_RECENT_BLOCKHASHES_PUBKEY=new PublicKey("SysvarRecentB1ockHashes11111111111111111111"),SYSVAR_RENT_PUBKEY=new PublicKey("SysvarRent111111111111111111111111111111111");new PublicKey("SysvarRewards111111111111111111111111111111");new PublicKey("SysvarS1otHashes111111111111111111111111111");new PublicKey("SysvarS1otHistory11111111111111111111111111");new PublicKey("SysvarStakeHistory1111111111111111111111111");class SendTransactionError extends Error{constructor({action:t,signature:n,transactionMessage:ie,logs:fe}){const ae=fe?`Logs:
20
20
  ${JSON.stringify(fe.slice(-10),null,2)}. `:"",le="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let pe;switch(t){case"send":pe=`Transaction ${n} resulted in an error.
package/index.mjs CHANGED
@@ -17671,6 +17671,8 @@ class EVMProvider {
17671
17671
  };
17672
17672
  }
17673
17673
  async walletLogin() {
17674
+ if (this.wallet === ChainWallet.Metamask && !isMetamaskInstalled())
17675
+ throw this.modalInterface.error("Metamask is not installed"), new WalletNotFoundException();
17674
17676
  const { address: t, signature: n, date: ie, nonce: fe } = await evmLogin(
17675
17677
  this.getWalletProvider(),
17676
17678
  this.chain,
@@ -17687,10 +17689,19 @@ class EVMProvider {
17687
17689
  throw new Error("Shop contract address not set");
17688
17690
  }
17689
17691
  async recordProduct(t) {
17690
- const { productData: n, skuData: ie } = await transformProductData(t, this.axiosInstance);
17691
- if (this.checkDeployment(), !this.shopId)
17692
- throw new FieldNotFound("shopId");
17693
- const fe = await startRecord(t, ie.map((me) => me.skuID), this.shopId, this.chain, [], this.axiosInstance);
17692
+ const { productData: n, skuData: ie } = await transformProductData(
17693
+ t,
17694
+ this.axiosInstance
17695
+ );
17696
+ if (this.checkDeployment(), !this.shopId) throw new FieldNotFound("shopId");
17697
+ const fe = await startRecord(
17698
+ t,
17699
+ ie.map((me) => me.skuID),
17700
+ this.shopId,
17701
+ this.chain,
17702
+ [],
17703
+ this.axiosInstance
17704
+ );
17694
17705
  await this.handleWallet(this.address), await this.handleChain();
17695
17706
  const ae = await recordProduct(
17696
17707
  this.getChainConfig(),
@@ -17698,9 +17709,19 @@ class EVMProvider {
17698
17709
  n,
17699
17710
  ie
17700
17711
  );
17701
- await updateUris(fe, ae.metadataUrls, this.axiosInstance), await updateHash("record", fe, ae.transactionHash, this.axiosInstance);
17712
+ await updateUris(fe, ae.metadataUrls, this.axiosInstance), await updateHash(
17713
+ "record",
17714
+ fe,
17715
+ ae.transactionHash,
17716
+ this.axiosInstance
17717
+ );
17702
17718
  const le = `${this.getBaseUrl()}/web3/record/callback/events/${fe}`;
17703
- if (!await web3Callback(ae.transactionHash, this.chain, Network[this.network], le))
17719
+ if (!await web3Callback(
17720
+ ae.transactionHash,
17721
+ this.chain,
17722
+ Network[this.network],
17723
+ le
17724
+ ))
17704
17725
  throw new Web3CallbackFailed(`txHash: ${ae.transactionHash}`);
17705
17726
  return {
17706
17727
  ...ae,
@@ -17730,7 +17751,14 @@ class EVMProvider {
17730
17751
  await this.handleWallet(this.address), await this.handleChain();
17731
17752
  const { orderID: n, paymentToken: ie, paymentType: fe } = t;
17732
17753
  if (!this.shopId) throw new FieldNotFound("shopId");
17733
- const ae = await startPayment(n, ie, fe, this.address, this.shopId, this.axiosInstance), le = await getCartData(
17754
+ const ae = await startPayment(
17755
+ n,
17756
+ ie,
17757
+ fe,
17758
+ this.address,
17759
+ this.shopId,
17760
+ this.axiosInstance
17761
+ ), le = await getCartData(
17734
17762
  n,
17735
17763
  ie,
17736
17764
  fe,
@@ -17742,17 +17770,22 @@ class EVMProvider {
17742
17770
  this.getContext(),
17743
17771
  pe
17744
17772
  );
17745
- if (await updateHash("payment", ae, me.transactionHash, this.axiosInstance), !await web3Callback(me.transactionHash, this.chain, Network[this.network], `${this.getBaseUrl()}/web3/payment/callback/${ae}/${me.transactionHash}`))
17773
+ if (await updateHash(
17774
+ "payment",
17775
+ ae,
17776
+ me.transactionHash,
17777
+ this.axiosInstance
17778
+ ), !await web3Callback(
17779
+ me.transactionHash,
17780
+ this.chain,
17781
+ Network[this.network],
17782
+ `${this.getBaseUrl()}/web3/payment/callback/${ae}/${me.transactionHash}`
17783
+ ))
17746
17784
  throw new Web3CallbackFailed(`txHash: ${me.transactionHash}`);
17747
17785
  return { ...me, orderID: le.orderID, transactionId: ae };
17748
17786
  }
17749
17787
  async getPaymentData(t, n, ie) {
17750
- return await getCartData(
17751
- t,
17752
- ie,
17753
- n,
17754
- this.axiosInstance
17755
- );
17788
+ return await getCartData(t, ie, n, this.axiosInstance);
17756
17789
  }
17757
17790
  async paymentWithToken(t, n, ie, fe = 18) {
17758
17791
  await this.handleWallet(this.address), await this.handleChain();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "droplinked-web3-kit",
3
- "version": "0.0.34",
3
+ "version": "0.0.35",
4
4
  "dependencies": {
5
5
  "ethers": "^5.7.2",
6
6
  "ky": "^1.7.2",