@gala-chain/launchpad-sdk 4.0.22-beta.3 → 4.0.22-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/src/LaunchpadSDK.d.ts +78 -1
- package/dist/src/LaunchpadSDK.d.ts.map +1 -1
- package/dist/src/constants/endpoints.d.ts +4 -0
- package/dist/src/constants/endpoints.d.ts.map +1 -1
- package/dist/src/constants/version.generated.d.ts +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/types/user.dto.d.ts +67 -0
- package/dist/src/types/user.dto.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"axios";import{ethers as t,JsonRpcProvider as n,Wallet as r,isAddress as o,Contract as i,Signature as s,getAddress as a,Mnemonic as c,HDNodeWallet as u,SigningKey as l,computeAddress as h}from"ethers";import{SigningType as d,SigningClient as f,ChainCallDTO as p,calculatePersonalSignPrefix as g}from"@gala-chain/connect";import{z as m}from"zod";import y from"bignumber.js";import{tickToSqrtPrice as w,getLiquidityForAmounts as b,getAmountsForLiquidity as k,liquidity0 as v,liquidity1 as E,getAmount0Delta as S,getAmount1Delta as A,Pool as T,TickData as I,CompositePoolDto as B,GetCompositePoolDto as x,QuoteExactAmountDto as C,quoteExactAmount as P,sqrtPriceToTick as N,computeSwapStep as _}from"@gala-chain/dex";import{TokenClassKey as U,TokenBalance as D}from"@gala-chain/api";import R,{v4 as F}from"uuid";import{io as L}from"socket.io-client";import O from"node:crypto";import*as M from"path";import*as $ from"fs";import*as q from"dotenv";import K from"crypto";if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}var G,W;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(G||(G={}));class z extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class j{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new z(G.SIGNATURE_FAILED,"Message prefix cannot be empty")}hasWallet(){return void 0!==this.wallet}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new z(G.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new z(G.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.wallet.signMessage(t);return{message:t,signature:n,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof z)throw e;throw new z(G.SIGNATURE_FAILED,"Failed to generate signature for authentication",e instanceof Error?e:new Error(String(e)))}}getAddress(){return this.validateWallet(),this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.validateWallet(),this.wallet.address}getPrivateKey(){if(this.validateWallet(),!this.wallet.privateKey)throw new z(G.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new z(G.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`);return`eth|${t}`}async signMessage(e){this.validateWallet();try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){if(e instanceof z)throw e;const t=e instanceof Error?e.message:String(e);throw new z(G.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,o=await this.wallet.signMessage(r);return{"x-signature":o,"x-address":this.formatAddress(this.wallet.address),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof z)throw e;throw new z(G.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(e)))}}async signTypedData(e,t,n){this.validateWallet();try{return await this.wallet.signTypedData(e,t,n)}catch(e){if(e instanceof z)throw e;throw new z(G.SIGNATURE_FAILED,"Failed to sign typed data",e instanceof Error?e:new Error(String(e)))}}async generateCustomSignature(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new z(G.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){if(e instanceof z)throw e;throw new z(G.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new z(G.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new z(G.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new z(G.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(W||(W={}));class H{constructor(e){this.levelPriority={[W.DEBUG]:0,[W.INFO]:1,[W.WARN]:2,[W.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?W.DEBUG:W.INFO)}debug(e,t){this.log(W.DEBUG,e,t)}info(e,t){this.log(W.INFO,e,t)}warn(e,t){this.log(W.WARN,e,t)}error(e,t){this.log(W.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===W.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,o=this.getConsoleMethod(e);void 0!==n?n instanceof Error?o(`${r} ${t}`,n.message,n.stack):o(`${r} ${t}`,n):o(`${r} ${t}`)}getConsoleMethod(e){switch(e){case W.DEBUG:return console.debug;case W.INFO:return console.info;case W.WARN:return console.warn;case W.ERROR:return console.error;default:return console.log}}child(e){return new H({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[W.DEBUG]>=this.levelPriority[this.minLevel]}}function V(e){if(!e||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))null!=r&&("string"==typeof r?t[n]=r:"number"==typeof r||"boolean"==typeof r?t[n]=r.toString():Array.isArray(r)?t[n]=r.join(","):t[n]="object"==typeof r?JSON.stringify(r):String(r));return t}class X{constructor(t,n={}){this.auth=t,this.debug=n.debug??!1,this.logger=new H({debug:this.debug,context:"HttpClient"}),this.axios=e.create({baseURL:n.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:n.timeout||3e4,headers:{Accept:"application/json",...n.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:V(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};e.headers&&this.logger.debug("Custom headers provided:",e.headers),e.data instanceof FormData&&(t.headers&&t.headers["Content-Type"]&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload"));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const r=await this.axios.request(t);return this.logger.debug("Response:",{status:r.status,data:r.data}),r.data}catch(e){throw this.logger.error("Error:",e),e}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){try{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}}catch(e){throw this.logger.error("Custom signature generation failed:",e),new Error(`Failed to generate custom signature for message: ${e instanceof Error?e.message:"Unknown error"}`)}}async signWithGalaChain(e,t,n=d.SIGN_TYPED_DATA){const r=this.auth.getPrivateKey(),o=new f(r);return await o.sign(e,t,n)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{try{if(e.headers||(e.headers={}),this.auth.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request headers being sent:",e.headers),e}catch(e){throw this.logger.error("Failed to add signature:",e),e}},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{if(e.response){const t={message:e.response.data?.message||e.message,error:e.response.data?.error,statusCode:e.response.status,details:e.response.data?.details,timestamp:e.response.data?.timestamp,path:e.response.data?.path};e.launchpadError=t,this.logger.error("Backend error:",t)}else e.request?this.logger.error("Network error:",e.message):this.logger.error("Request setup error:",e.message);return Promise.reject(e)})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}const Q="Token name is required and must be a string",Z=e=>`Could not find vault address for token: ${e}`;class Y extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class J extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class ee extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class te extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class ne extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class re extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.transactionHash=n,this.code=r,this.name="GSwapSwapError"}}class oe extends Error{constructor(e,t,n,r,o){super(e),this.originalError=t,this.tokenA=n,this.tokenB=r,this.code=o,this.name="GSwapPoolError"}}class ie extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.walletAddress=n,this.code=r,this.name="GSwapAssetError"}}class se extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class ae extends Y{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class ce extends Y{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function ue(e,t){return new Y(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function le(e,t){const n=t||e.charAt(0).toUpperCase()+e.slice(1);return new Y(`${n} is required`,e,"REQUIRED_FIELD")}function he(e,t,n){const r=n||e.charAt(0).toUpperCase()+e.slice(1);return new Y(`${r} must be ${t}`,e,"INVALID_FORMAT")}function de(e,t,n){return new J(e,t,n)}function fe(e,t){return new ee(e,t)}function pe(e,t,n){return new te(e,t,n)}function ge(e,t,n){const{MIN_PAGE:r,MAX_PAGE:o,MIN_LIMIT:i,MAX_LIMIT:s}=n.PAGINATION;if("number"!=typeof e||e<r||e>o)throw new Y(`Page must be a number between ${r} and ${o}`,"page","INVALID_PAGE");if("number"!=typeof t||t<i||t>s)throw new Y(`Limit must be a number between ${i} and ${s}`,"limit","INVALID_LIMIT")}const me={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9]+$/};function ye(e){return"string"==typeof e&&e.trim().length>0}function we(e){return!(!e||"string"!=typeof e)&&(me.ETH_ADDRESS.test(e)||me.BACKEND_ADDRESS.test(e)||me.CLIENT_ADDRESS.test(e))}function be(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const ke=m.string().min(3,"Token name must be at least 3 characters").max(20,"Token name must be at most 20 characters").regex(/^[a-zA-Z0-9]{3,20}$/,"Token name can only contain letters and numbers"),ve=m.string().min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),Ee=m.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Se=m.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Ae=m.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Te=m.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),Ie=m.string().regex(me.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),Be=m.string().regex(me.ETH_ADDRESS,"Invalid Ethereum address format"),xe=m.string().refine(e=>me.BACKEND_ADDRESS.test(e)||me.ETH_ADDRESS.test(e),"Address must be either eth|[40-hex-chars] or 0x[40-hex-chars] format").transform(e=>e.startsWith("0x")?`eth|${e.slice(2)}`:e),Ce=m.string().refine(e=>me.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Pe=m.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),Ne=m.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),_e=m.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Ue=m.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),De=m.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function Re(e=100){return m.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const Fe=Re(100),Le=Re(20),Oe=Re(20),Me=m.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),$e=m.string().max(255,"Filename must be at most 255 characters"),qe=m.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Ke=m.string().datetime("Must be a valid ISO 8601 date string"),Ge=m.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),We=m.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),ze=m.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),je=m.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),He=m.object({websiteUrl:Ue,telegramUrl:Ue,twitterUrl:Ue}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),Ve=m.string().min(1,"Token category must not be empty").default("Unit"),Xe=m.string().min(1,"Token collection must not be empty").default("Token"),Qe=m.object({minFeePortion:m.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>parseFloat(e)>=.1,"Minimum fee must be >= 0.1").refine(e=>parseFloat(e)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:m.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>parseFloat(e)>=.1,"Maximum fee must be >= 0.1").refine(e=>parseFloat(e)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>parseFloat(e.maxFeePortion)>=parseFloat(e.minFeePortion),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Ze=m.object({tokenName:ke,tokenSymbol:ve,tokenDescription:Ee,tokenImage:m.union([m.instanceof(File),m.instanceof(Buffer),m.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Ne.default("0"),websiteUrl:Ue,telegramUrl:Ue,twitterUrl:Ue,tokenCategory:Ve,tokenCollection:Xe,reverseBondingCurveConfiguration:Qe.optional(),privateKey:We.optional()}),Ye=m.object({file:m.union([m.instanceof(File),m.instanceof(Buffer)]),tokenName:ke}),Je=m.enum(["recent","popular"]),et=m.object({tokenName:ke.optional(),symbol:ve.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),tt=m.enum(["NATIVE","MEME"]),nt=m.enum(["IN","OUT"]),rt=m.object({from:m.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:m.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:m.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:ke}),ot=m.object({tokenName:ke,slippageToleranceFactor:m.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:m.number().min(0).max(1).optional(),privateKey:We.optional()}),it=[".png",".jpg",".jpeg",".gif",".webp",".svg"],st=m.object({file:m.union([m.instanceof(File),m.instanceof(Buffer)]),name:$e,size:Me,type:qe}),at=m.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),ct=m.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),ut=m.union([at,ct]),lt=m.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),ht=$e.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return it.includes(t)},`Filename must end with one of: ${it.join(", ")}`),dt=m.object({page:De,limit:Fe}),ft=m.object({page:De,limit:Le}),pt=m.object({page:De,limit:Oe}),gt=dt.extend({type:m.enum(["recent","popular"]).optional(),tokenName:m.string().min(1).max(50).optional(),search:m.string().min(1).max(100).optional()}),mt=ft.extend({tokenName:m.string().min(1).max(50).optional(),search:m.string().min(1).max(100).optional()}),yt=pt.extend({tradeType:m.enum(["BUY","SELL"]).optional(),tokenName:m.string().min(1).max(50).optional(),userAddress:m.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:m.string().datetime().optional(),endDate:m.string().datetime().optional(),sortOrder:m.enum(["ASC","DESC"]).default("DESC")}),wt=m.object({page:m.number().int().min(1),limit:m.number().int().min(1),total:m.number().int().min(0),totalPages:m.number().int().min(0),hasNext:m.boolean(),hasPrevious:m.boolean()});function bt(e){return m.object({data:m.array(e),page:m.number().int().min(1),limit:m.number().int().min(1),total:m.number().int().min(0),totalPages:m.number().int().min(0),hasNext:m.boolean(),hasPrevious:m.boolean()})}const kt=m.enum(["all","DEFI","ASSET"]),vt=ft.extend({type:kt.optional(),address:xe.optional(),search:Ae.optional(),tokenName:Se.optional()}),Et=m.object({address:xe.optional(),refresh:m.boolean().optional()}),St=m.object({profileImage:m.string(),fullName:Te,address:xe,privateKey:We.optional()}),At=m.object({file:m.union([m.instanceof(File),m.instanceof(Buffer)]),address:xe.optional(),privateKey:We.optional()}),Tt=m.object({created:m.number(),createdBy:m.string(),expires:m.number(),instanceId:m.string(),lockAuthority:m.string(),name:m.string(),quantity:m.string(),vestingPeriodStart:m.number()}),It=m.object({address:xe,tokenId:m.union([m.string(),m.object({collection:m.string(),category:m.string(),type:m.string(),additionalKey:m.string()}),m.object({collection:m.string(),category:m.string(),type:m.string(),additionalKey:m.string(),instance:m.string()})]).optional(),tokenName:Se.optional(),withExpired:m.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),Bt=m.enum(["buy","sell"]),xt=m.enum(["BUY","SELL"]),Ct=m.object({tradeType:Bt,tokenAmount:Pe,vaultAddress:Ce,userAddress:xe,slippageTolerance:Pe.optional(),deadline:m.number().int().positive().optional()}),Pt=m.object({tokenSymbol:ve,nativeTokenQuantity:Pe,expectedToken:Pe,maxAcceptableReverseBondingCurveFee:Ne.default("0").optional()}),Nt=m.object({tokenSymbol:ve,tokenQuantity:Pe,expectedNativeToken:Pe,maxAcceptableReverseBondingCurveFee:Ne.default("0").optional()}),_t=pt.extend({tokenName:Se.optional()}),Ut=m.object({page:m.number().int().min(1).max(1e3).default(1).optional(),limit:m.number().int().min(1).max(20).default(10).optional()}),Dt=m.enum(["NATIVE","MEME"]),Rt=m.enum(["IN","OUT"]),Ft=m.object({type:Dt,method:Rt,vaultAddress:Ce,amount:Pe}),Lt=m.object({nativeTokenQuantity:Pe}),Ot=m.object({vaultAddress:Ce}),Mt=m.object({minFeePortion:Pe,maxFeePortion:Pe});function $t(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.errors.map(e=>e.message)}}}const qt=$t(ke),Kt=$t(ve),Gt=$t(Ee),Wt=$t(xe),zt=$t(Ce),jt=$t(Pe),Ht=$t(Te),Vt=$t(Ae),Xt=$t(Se),Qt=$t(Ze),Zt=$t(He),Yt=$t(Ye),Jt=$t(et),en=$t(vt),tn=$t(Et),nn=$t(St),rn=$t(At),on=$t(It),sn=$t(Ct),an=$t(Pt),cn=$t(Nt),un=$t(_t),ln=$t(Ut),hn=$t(Ft),dn=$t(Lt),fn=$t(Ot);function pn(e,t){throw new Y(e.join("; "),t,"VALIDATION_ERROR")}function gn(e){const t=qt(e);!t.success&&t.errors&&pn(t.errors,"tokenName")}function mn(e){const t=gt.safeParse(e);t.success||pn(t.error.errors.map(e=>e.message),"pagination")}function yn(e){const t=Jt(e);!t.success&&t.errors&&pn(t.errors,"options")}function wn(e){const t=hn(e);!t.success&&t.errors&&pn(t.errors,"options")}function bn(e){const t=rt.safeParse(e);t.success||pn(t.error.errors.map(e=>e.message),"options")}function kn(e){const t=xe.safeParse(e);if(!t.success)throw new Y("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function vn(e,t,n=!0){if(!e||""===e.trim())throw new Y(`${t} cannot be empty or whitespace-only. Provide a valid numeric string or omit the parameter to auto-fetch.`,t,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Y(`${t} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,t,"INVALID_NUMERIC_STRING");const r=parseFloat(e);if(isNaN(r))throw new Y(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(r))throw new Y(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(r<0)throw new Y(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!n&&0===r)throw new Y(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var En=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=xe.safeParse(e);if(!t.success)throw new Y(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:kn,validateCheckPoolOptions:yn,validateGetAmountOptions:wn,validateGetGraphOptions:bn,validateNumericString:vn,validatePagination:mn,validateTokenName:gn});function Sn(e,t){const n=e,r=Number(n.page)||t.page,o=Number(n.limit)||t.limit,i=n.data,s=Number(n.total)||Number(i?.count)||0;return{page:r,limit:o,total:s,totalPages:Math.ceil(s/o)}}function An(e,t){return{hasNext:e<t,hasPrevious:e>1}}function Tn(e,t,n=!1){const r=!0===e.error||200!==e.status,o=n&&!e.data;if(r||o)throw new Error(e.message||t)}const In="/launchpad/upload-image",Bn="/launchpad/fetch-pool",xn="/launchpad/check-pool",Cn="/launchpad/get-graph-data",Pn="/holders",Nn="/launchpad/get-badge/",_n="/trade/",Un="/user/profile",Dn="/user/profile",Rn="/user/token-list",Fn="/user/token-hold",Ln="/v1/users/referrals/url",On="/v1/users/referrals",Mn=5,$n={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100},qn={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20};class Kn{constructor(e,t=!1){this.http=e,this.logger=new H({debug:t,context:this.constructor.name})}}class Gn{constructor(e=!1){this.logger=new H({debug:e,context:this.constructor.name})}}function Wn(e,t){return"string"==typeof e[t]}function zn(e,t){return void 0===e[t]||"string"==typeof e[t]}function jn(e,t){return void 0===e[t]||"number"==typeof e[t]}function Hn(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function Vn(e){if(!e||"object"!=typeof e)return!1;const t=e;return Wn(t,"tokenName")&&jn(t,"from")&&jn(t,"to")&&jn(t,"resolution")}class Xn extends Kn{constructor(e,t=!1){super(e,t)}async fetchSinglePage(e){const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const n=V(t),r=await this.http.get(Bn,n);if(!r)throw de("No response from pool service",500);Tn(r,"Failed to fetch pools",!0);const o=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at||e.createdAt||""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at||n.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(r.data),i=r.data.count??r.data.total??0;return{pools:o,total:i,totalPages:e.limit>0?Math.ceil(i/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:n,pageSize:r,...o}=e,i=[];if(n&&n>=t){const e=[];for(let r=t;r<=n;r++)e.push(r);for(let t=0;t<e.length;t+=5){const n=e.slice(t,t+5).map(e=>this.fetchSinglePage({...o,page:e,limit:r}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e}));(await Promise.all(n)).forEach(e=>{i.push(...e.pools)})}return i}let s=t,a=!0;for(;a;){const e=[];for(let t=0;t<5&&a;t++)e.push(s+t);const t=e.map(e=>this.fetchSinglePage({...o,page:e,limit:r}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e})),n=await Promise.all(t);for(const e of n){if(0===e.pools.length){a=!1;break}i.push(...e.pools)}s+=e.length,s>$n.SAFETY_MAX_PAGES&&(a=!1)}return i}async fetchPools(e={}){const t=e.page||$n.DEFAULT_PAGE,n=e.limit??$n.DEFAULT_LIMIT;let r;if(0!==n&&mn({page:t,limit:n}),e.tokenName&&gn(e.tokenName),"recent"===e.type?r="RECENT":"popular"===e.type&&(r="POPULAR"),n>0&&n<=20){const o=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},page:t,limit:n});return{pools:o.pools,page:t,limit:n,total:o.total,totalPages:o.totalPages,hasNext:t<o.totalPages,hasPrevious:t>1}}if(0===n){const t=$n.BACKEND_MAX_PAGE_SIZE,n=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},page:1,limit:t}),o=[...n.pools];if(n.pools.length<t)return{pools:o,page:1,limit:o.length,total:o.length,totalPages:1,hasNext:!1,hasPrevious:!1};if(n.pools.length>0){const i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},startPage:2,totalPages:n.totalPages>1?n.totalPages:null,pageSize:t});o.push(...i)}return{pools:o,page:1,limit:o.length,total:n.total||o.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const o=$n.BACKEND_MAX_PAGE_SIZE,i=Math.ceil(n/o),s=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},page:t,limit:o}),a=[...s.pools],c=Math.min(i,s.totalPages-t+1);if(c>1){const n=t+c-1,i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},startPage:t+1,totalPages:n,pageSize:o});a.push(...i)}const u=a.slice(0,n);return{pools:u,page:t,limit:n,total:s.total,totalPages:s.totalPages,hasNext:t<s.totalPages&&u.length<s.total,hasPrevious:t>1}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){yn(e),e.tokenName&&gn(e.tokenName);const t=V(e),n=await this.http.get(xn,t);if(!n)throw de("No response from pool service",500);Tn(n,"Failed to check pool");const r=n.data;return e.symbol?r?.isSymbolExist??!1:e.tokenName?r?.isNameExist??!1:r?.exists??!1}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!Vn(e))throw new Y("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:o}=e;if(gn(t),!n||!r||!o)throw new Y("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:o};bn(i);const s=V(i),a=await this.http.get(Cn,s);if(!a)throw de("No response from pool service",500);return Tn(a,"Failed to fetch graph data",!0),{dataPoints:a.data}}async fetchTokenDistribution(e){if(!e)throw le("tokenName","Token name");gn(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw ue(e);const n=encodeURIComponent(t);let r;try{r=await this.http.get(`${Pn}/${n}`)}catch(t){if(t&&"object"==typeof t&&"response"in t){const n=t;if(500===n.response?.status)throw de(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500)}throw t}if(!r)throw de("No response from pool service",500);Tn(r,"Failed to fetch token distribution",!0);const o=r.data;if(!Array.isArray(o))throw de("Invalid API response: expected array of holders",r.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw de("Invalid holder data: missing or invalid owner field",r.status);if(!e.quantity||"string"!=typeof e.quantity)throw de("Invalid holder data: missing or invalid quantity field",r.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw de(`Invalid holder quantity: "${e.quantity}"`,r.status)}const i=o.reduce((e,t)=>e.plus(t.quantity),new y(0));return{holders:o.map(e=>{const t=new y(e.quantity),n=i.isZero()?0:t.dividedBy(i).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:i.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw le("tokenName","Token name");gn(e);const t=await this.http.get(Nn,{tokenName:e});if(!t)throw de("No response from pool service",500);return Tn(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const o=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return o?.isActive||!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(t.pools&&Array.isArray(t.pools)&&t.pools.length>0)return t.pools[0].vaultAddress||null;if(t.pools&&"object"==typeof t.pools){const e=t.pools.tokens;return e?.vaultAddress||null}return null}catch{return null}}}function Qn(e,t={}){const{stringifyFields:n=[],optionalFields:r=[],fieldMappings:o={}}=t,i={};for(const[t,s]of Object.entries(e)){const e=t;if(r.includes(e)&&void 0===s)continue;if(r.includes(e)&&"string"==typeof s&&0===s.trim().length)continue;const a=o[e],c=a?String(a):t;n.includes(e)?i[c]=String(s):i[c]=s}return V(i)}const Zn={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class Yn extends Kn{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Wn(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&zn(t,"userAddress")&&jn(t,"page")&&jn(t,"limit")}(e))throw new Y("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, page?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:n,userAddress:r,page:o=$n.DEFAULT_PAGE,limit:i=$n.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!ye(t))throw new Y("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");ge(o,i,Zn);const u=function(e,t,n){return Qn({tokenName:e,page:t,limit:n},{stringifyFields:["page","limit"]})}(t,o,i),l=await this.http.get(_n,u);if(!l)throw new Y("No response from trade service","response","NO_RESPONSE");const h=(d=l.data)?Array.isArray(d)?d:d.trades:[];var d;const f=Sn(l,{page:o,limit:i}),p=An(f.page,f.totalPages);return{trades:h,...f,...p}}}function Jn(e){return e instanceof Error}function er(e){return Jn(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function tr(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function nr(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw he("file","a File object (browser) or Buffer (Node.js)");{const o=new Blob([e],{type:"image/png"});r.append(t,o,n)}}return r}const rr={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20},USER_ADDRESS:{PATTERN:/^eth\|[0-9a-fA-F]{40}$/},TOKEN_NAME:{MIN_LENGTH:1,MAX_LENGTH:50},SEARCH:{MIN_LENGTH:1,MAX_LENGTH:100},PROFILE:{FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}}};function or(e){return!(!e||"string"!=typeof e)&&rr.USER_ADDRESS.PATTERN.test(e)}const ir="Update profile",sr="Upload profile image";class ar extends Kn{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!or(t))throw new Y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const n={userAddress:t},r=await this.http.get(Un,n);if(!r)throw new Y("No response from user service","response","NO_RESPONSE");return r}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!t||""===t.trim())try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage||""}catch{t=""}const n={profileImage:t,fullName:e.fullName,userAddress:e.address},r=await this.http.signCustomMessage(ir);if(!r)throw new Y("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const o={address:r.address,message:ir,publickey:r.ethereumAddress,sign:r.signature},i=await this.http.put(Dn,n,o);if(!i)throw new Y("No response from user service","response","NO_RESPONSE");Tn(i,"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new Y("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=nr(e.file,"image",n),o=await this.http.signCustomMessage(sr);if(!o)throw new Y("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const i={address:o.address,message:sr,publickey:o.ethereumAddress,sign:o.signature},s=await this.http.request({method:"POST",url:`${In}?tokenName=${encodeURIComponent(t)}`,data:r,headers:i});if(!s)throw new Y("No response from user service","response","NO_RESPONSE");return Tn(s,"Image upload failed"),"string"==typeof s.data?s.data:""}catch(e){if(e instanceof Y)throw e;throw new Y(`Profile image upload failed: ${er(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(Rn,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(Fn,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=$n.DEFAULT_PAGE,limit:n=$n.DEFAULT_LIMIT,search:r,tokenName:o}=e,i=this.http.getAddress();if(!i)throw new Y("Wallet address not available - wallet not configured","address","NO_WALLET");const s={type:"DEFI",address:i,page:t,limit:n};return void 0!==r&&(s.search=r),void 0!==o&&(s.tokenName=o),this.fetchTokenList(s)}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},o=Qn(n.includeType?{...r,type:"all"!==t.type&&t.type?t.type:"DEFI"}:r,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),i=await this.http.get(e,o);if(!i)throw new Y("No response from user service","response","NO_RESPONSE");Tn(i,n.errorMessage,!0);const s=(a=i.data)?Array.isArray(a)?a:a.token:[];var a;const c=Sn(i,{page:t.page||$n.DEFAULT_PAGE,limit:t.limit||$n.DEFAULT_LIMIT}),u=An(c.page,c.totalPages);return{tokens:s,...c,...u}}validateGetTokenListOptions(e){if(ge(e.page,e.limit,rr),void 0!==e.address&&!or(e.address))throw new Y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(void 0!==e.search&&e.search.trim().length>0&&!((t=e.search)&&"string"==typeof t&&t.length>=rr.SEARCH.MIN_LENGTH&&t.length<=rr.SEARCH.MAX_LENGTH))throw new Y(`Search query must be between ${rr.SEARCH.MIN_LENGTH} and ${rr.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,n;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((n=e.tokenName)&&"string"==typeof n&&n.length>=rr.TOKEN_NAME.MIN_LENGTH&&n.length<=rr.TOKEN_NAME.MAX_LENGTH))throw new Y(`Token name must be between ${rr.TOKEN_NAME.MIN_LENGTH} and ${rr.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!or(e.address))throw new Y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=rr.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=rr.PROFILE.FULL_NAME.MAX_LENGTH&&rr.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new Y(`Full name must be between ${rr.PROFILE.FULL_NAME.MIN_LENGTH} and ${rr.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!or(e.address))throw new Y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class cr extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function ur(e,t,n){if(!e)throw new cr("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=at.safeParse(e);if(!t.success){const n=t.error.errors.map(e=>e.message).join("; ");throw new cr(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new cr("Filename is required when uploading Buffer objects",t,n);const r=ct.safeParse(e);if(!r.success){const e=r.error.errors.map(e=>e.message).join("; ");throw new cr(e,t,n)}if(t.length>255)throw new cr(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,n);const o=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!o.includes(n))throw new cr(`Invalid file type "${n}" is not allowed. Allowed types: ${o.join(", ")}`,t,n);const i=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),s=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!s.includes(i))throw new cr(`File extension "${i}" is not allowed. Allowed extensions: ${s.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(a!==n&&"application/octet-stream"!==a)throw new cr(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new cr("File must be a File object (browser) or Buffer (Node.js)",t,n)}const lr="Upload token image";class hr extends Kn{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;gn(t);const r=`${t}.png`;ur(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=nr(n.file,"image",e),o=await this.http.signCustomMessage(lr);if(!o)throw fe("Failed to generate signature - wallet not configured","signature");const i={address:o.address,message:lr,publickey:o.ethereumAddress,sign:o.signature},s=await this.http.request({method:"POST",url:`${In}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:i});if(!s)throw fe("No response from image upload service","response");return Tn(s,"Image upload failed"),"string"==typeof s.data?s.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw fe("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class dr{constructor(e,t=!1){this.http=e,this.poolService=new Xn(e,t),this.tradeService=new Yn(e,t),this.userService=new ar(e,t),this.imageService=new hr(e,t)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async fetchProfile(e){return this.userService.fetchProfile(e)}async updateProfile(e){return this.userService.updateProfile(e)}async uploadProfileImage(e){return this.userService.uploadProfileImage(e)}async fetchTokenList(e){return this.userService.fetchTokenList(e)}async fetchTokensHeld(e){return this.userService.fetchTokensHeld(e)}async fetchTokensCreated(e={}){return this.userService.fetchTokensCreated(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return gn(e)}}const fr={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var pr;!function(e){e.INVALID_RECIPIENT="INVALID_RECIPIENT",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.DUPLICATE_TRANSFER="DUPLICATE_TRANSFER",e.TRANSFER_LIMIT_EXCEEDED="TRANSFER_LIMIT_EXCEEDED",e.WALLET_REQUIRED="WALLET_REQUIRED"}(pr||(pr={}));class gr extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function mr(e,t="0"){return new y(null==e||""===e?t:e)}function yr(e){return w(e)}function wr(e){const t=mr(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function br(e,t=!1){const n=mr(e),r=new y(1).dividedBy(n);return t?r.toFixed():r}function kr(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThanOrEqualTo(0))throw new Error(`Value at index ${t} must be positive, got: ${e.toString()}`)})}function vr(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThan(0))throw new Error(`Value at index ${t} must be non-negative, got: ${e.toString()}`)})}function Er(e,t,n){if(e.isNaN())throw new Error(`${t} must be a valid number, got: NaN`);if(!e.isFinite()){const r=n?`${t} must be finite ${n}, got: ${e.toString()}`:`${t} must be finite, got: ${e.toString()}`;throw new Error(r)}if(e.isLessThanOrEqualTo(0)){const r=n?`${t} must be positive ${n}, got: ${e.toString()}`:`${t} must be positive, got: ${e.toString()}`;throw new Error(r)}}class Sr{static validateAmount(e){const t=new y(e);try{Er(t,"amount","for transfer")}catch(t){throw new gr(t.message,pr.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(e){if(e.length>fr.MAX_UNIQUE_KEY_LENGTH)throw new Y(`Unique key too long. Maximum length: ${fr.MAX_UNIQUE_KEY_LENGTH}`);if(!fr.UNIQUE_KEY_PATTERN.test(e))throw new gr('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',pr.INVALID_AMOUNT,{uniqueKey:e})}}}class Ar{toLaunchpadFormat(e){if(!e)return"unknown|Unit|none|none";if("string"==typeof e)return e.includes("|")?e:`${e}|Unit|none|none`;return`${e.collection||e.symbol||"unknown"}|${e.category||"Unit"}|${e.type||"none"}|${e.additionalKey||"none"}`}toTokenClass(e){if("object"==typeof e&&null!==e)return{collection:e.collection||"Token",category:e.category||"Unit",type:e.type||e.symbol||"unknown",additionalKey:e.additionalKey||"none"};if("string"!=typeof e)throw new Error("Invalid token format: expected string or object, got "+typeof e);const t=e.split("|");if(t.length<3)throw new Error(`Invalid token format: ${e}`);return{collection:t[0]||"Token",category:t[1]||"Unit",type:t[2]||"none",additionalKey:t[3]||"none"}}isGSwapFormat(e){return"string"==typeof e&&e.includes("|")}normalize(e){return"string"==typeof e&&this.isGSwapFormat(e)?e:this.toLaunchpadFormat(e)}}function Tr(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function Ir(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected at least 4 parts separated by $, got ${t.length}`);const[n,r,o,...i]=t;if(!n||!r||!o)throw new Error("Collection, category, and type must be non-empty");const s=i.join("$");if(!s)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:r,type:o,additionalKey:s}}catch(t){throw new Y(`Invalid dollar-delimited token: "${e}". Expected format: "Token$Unit$SYMBOL$additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"dollarToken","INVALID_DOLLAR_DELIMITED_TOKEN_FORMAT")}}class Br extends p{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,o){let i;if("string"==typeof r){i={...Ir(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new Br({from:e,to:t,quantity:n,tokenInstance:i,uniqueKey:o||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n,r){return new Br({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){return`${this.tokenInstance.collection}$${this.tokenInstance.category}$${this.tokenInstance.type}$${this.tokenInstance.additionalKey}`}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}class xr extends p{constructor(e){super(),this.lockAuthority=e.lockAuthority,this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.expires&&(this.expires=e.expires),void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,o){let i;if("string"==typeof r){i={...Ir(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new xr({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:i}],...void 0!==o?.expires&&{expires:o.expires},...void 0!==o?.name&&{name:o.name},uniqueKey:o?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n,r){return new xr({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==r?.expires&&{expires:r.expires},...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0].tokenInstanceKey;return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}toSigningPayload(){return{lockAuthority:this.lockAuthority,tokenInstances:this.tokenInstances,...void 0!==this.expires&&{expires:this.expires},...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class Cr extends p{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r){let o;if("string"==typeof n){o={...Ir(n),instance:"0"}}else o={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new Cr({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:o}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n){return new Cr({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==n?.name&&{name:n.name},uniqueKey:n?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0].tokenInstanceKey;return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class Pr extends p{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokens(e,t){const n=e.map(e=>{let t;if("string"==typeof e.tokenClassKey){t={...Ir(e.tokenClassKey),instance:"0"}}else t={collection:e.tokenClassKey.collection,category:e.tokenClassKey.category,type:e.tokenClassKey.type,additionalKey:e.tokenClassKey.additionalKey,instance:"0"};return{quantity:e.quantity,tokenInstanceKey:t}});return new Pr({tokenInstances:n,uniqueKey:t?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static fromTokenClassKey(e,t,n){return Pr.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new Pr({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0].tokenInstanceKey;return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class Nr{constructor(e){this.wallet=e}static generateUniqueKey(){return`${Date.now()}_${Math.random().toString(36).substring(2,8)}`}async signTransferToken(e){const t={name:"GalaChain",chainId:1},n={TransferToken:[{name:"from",type:"string"},{name:"to",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstance",type:"TokenInstance"},{name:"uniqueKey",type:"string"}],TokenInstance:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]};return{signature:await this.wallet.signTypedData(t,n,e),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signLockToken(e){const t={name:"GalaChain",chainId:1},n={LockToken:[{name:"lockAuthority",type:"string"},{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.expires?[{name:"expires",type:"uint256"}]:[],...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={lockAuthority:e.lockAuthority,tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.expires&&(r.expires=e.expires),void 0!==e.name&&(r.name=e.name);return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signBurnTokens(e){const t={name:"GalaChain",chainId:1},n={BurnTokens:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"}],TokenInstanceQuantity:[{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signUnlockToken(e){const t={name:"GalaChain",chainId:1},n={UnlockToken:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.name&&(r.name=e.name);return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const n=e.replace("0x","");return`eth|${t.getAddress(`0x${n}`).replace("0x","")}`}static fromGalaChainAddress(e){return e.startsWith("eth|")?e.substring(4):e}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...Ir(e),instance:"0"}}}function _r(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new Y(`Invalid tokenId string format: "${e}". Expected format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");if(!(t[0]&&t[1]&&t[2]&&t[3]))throw new Y(`Invalid tokenId string format: "${e}". All components (collection, category, type, additionalKey) must be non-empty`,"tokenId","INVALID_TOKEN_ID_FORMAT");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3],instance:t[4]||"0"}}if("object"==typeof e&&null!==e){if(!(e.collection&&e.category&&e.type&&e.additionalKey))throw new Y("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return"instance"in e&&void 0!==e.instance?e:{...e,instance:"0"}}throw new Y(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Ur(e){try{const[t,n]=e.split("|");if(!n)throw new Error("Missing token part after service");const r=n.split("$");if(r.length<4)throw new Error(`Invalid vault address format. Expected at least 4 parts separated by $, got ${r.length}`);if(!(r[0]&&r[1]&&r[2]&&r[3]))throw new Error("All vault address components (collection, category, type, additionalKey) must be non-empty");const o=r.slice(3,-1),i=o.length>0?o.join("$"):r[3];return{collection:r[0],category:r[1],type:r[2],additionalKey:i}}catch(t){throw new Y(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${t instanceof Error?t.message:String(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}function Dr(e){return{...Ur(e),instance:"0"}}function Rr(e){return Ur(e).type}var Fr=Object.freeze({__proto__:null,extractTokenSymbolFromVault:Rr,normalizeToTokenInstanceKey:_r,parseVaultAddressToTokenClassKey:Ur,parseVaultAddressToTokenInstance:Dr});function Lr(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.lockAuthority||"string"==typeof t.lockAuthority)&&(void 0===t.expires||"number"==typeof t.expires)&&(void 0===t.name||"string"==typeof t.name)}function Or(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.name||"string"==typeof t.name)}function Mr(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Lr)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function $r(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Or)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const qr=100,Kr=100,Gr={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/,ETH_ADDRESS_PATTERN:me.ETH_ADDRESS,BACKEND_ADDRESS_PATTERN:me.BACKEND_ADDRESS,MAX_LOCK_BATCH_SIZE:100,MAX_UNLOCK_BATCH_SIZE:100};var Wr;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(Wr||(Wr={}));class zr extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="LockError"}}function jr(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(!("string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0))||void 0!==t.lockAuthority&&"string"!=typeof t.lockAuthority||void 0!==t.expires&&"number"!=typeof t.expires||void 0!==t.name&&"string"!=typeof t.name||void 0!==t.uniqueKey&&"string"!=typeof t.uniqueKey)}function Hr(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.name||"string"==typeof t.name)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}function Vr(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)}function Xr(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Vr)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Qr=50;var Zr;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(Zr||(Zr={}));class Yr extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Jr="gala-transfer-successful",eo="token-transfer-successful",to="token-locked-successfully",no="token-unlocked-successfully",ro="transfer-successful-no-id",oo=50,io=100,so=100;function ao(e){return e&&0!==e.length?e.reduce((e,t)=>y(e).plus(t.quantity).toString(),"0"):"0"}function co(e,t){if(!e||0===e.length)return[];if(t)return e;const n=Date.now();return e.filter(e=>0===e.expires||e.expires>n)}class uo extends Kn{constructor(e,t,n,r=!1,o){super(e,r),this.wallet=t,this.tokenResolver=n,this.publicAxios=o,this.signatureHelper=t?new Nr(t):void 0}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw de("No response from GalaChain service",500);if(1!==t.Status)throw de(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",o=n?.maxFeePortion??"0",i=(await import("bignumber.js")).default,s=!new i(r).isZero()||!new i(o).isZero(),a=t.Data;return a.reverseBondingCurveMinFeePortion=r,a.reverseBondingCurveMaxFeePortion=o,a.hasReverseBondingCurveFee=s,a.isGraduated="Finished"===t.Data.saleStatus,delete a.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(!e)throw de("No response from GalaChain service",500);if(1!==e.Status)throw de(`Failed to fetch launch token fee: Status ${e.Status}`,e.Status);return e.Data.feeAmount}getChannelForCollection(e){return"MUSIC"===(e.startsWith("$")?e.slice(1).toUpperCase():e.toUpperCase())?"music":"asset"}validateFetchPoolDetailsData(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.vaultAddress)throw new Y("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new Y("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new Y("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const n=`/api/${this.getChannelForCollection(e.collection)}/token-contract/FetchBalances`,r=await this.http.post(n,e);if(!r)return null;if(1!==r.Status||!r.Data||0===r.Data.length)return null;const o=r.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!o||"0"===o.quantity)return null;const i=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`,s={quantity:o.quantity,collection:o.collection,category:o.category,tokenId:i};if(o.inUseHolds?.length){const e=co(o.inUseHolds??[],t);e.length>0&&(s.inUseHolds=e,s.inUseQuantity=ao(e))}if(o.lockedHolds?.length){const e=co(o.lockedHolds??[],t);e.length>0&&(s.lockedHolds=e,s.lockedQuantity=ao(e))}return(s.lockedQuantity||s.inUseQuantity)&&(s.availableQuantity=function(e,t="0",n="0"){return y(e).minus(t).minus(n).toString()}(s.quantity,s.lockedQuantity,s.inUseQuantity)),s}catch(e){throw de(`Failed to fetch token balance from GalaChain: ${er(e)}`,void 0,Jn(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?_r(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]},r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(1!==r.Status)throw de(`Failed to fetch token class from GalaChain: Status ${r.Status}${r.Message?` - ${r.Message}`:""}`,r.Status);if(!r.Data||0===r.Data.length)throw de(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return r.Data[0]}catch(e){if(tr(e)&&404===e.response?.status)throw de("Token not found on GalaChain",404,Jn(e)?e:void 0);const t=er(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw de(`Failed to fetch token class from GalaChain: ${t}`,void 0,Jn(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw new Y("tokenClasses array must not be empty");const t={tokenClasses:e},n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(1!==n.Status)throw de(`Failed to fetch token classes with supply from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw de("No token supply data found for requested token classes",404);return n.Data}catch(e){if(tr(e)&&404===e.response?.status)throw de("Token supply data not found on GalaChain",404,Jn(e)?e:void 0);const t=er(e);if(t.includes("Token")||t.includes("Status")||t.includes("tokenClasses"))throw e;throw de(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,Jn(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new gr("Wallet required for GALA transfer operations",pr.WALLET_REQUIRED);try{const t=be(e.recipientAddress),n=be(this.wallet.address),r=Br.forGALA(n,t,e.amount,e.uniqueKey),o=await this.signatureHelper.signTransferToken(r.toSigningPayload()),i=new Br({...r.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(i,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",i);if(!s)throw new gr("No response from GalaChain transfer service",pr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new gr("Wallet required for token transfer operations",pr.WALLET_REQUIRED);try{const t=be(e.to),n=be(this.wallet.address);let r;if(e.tokenId)r=_r(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",JSON.stringify(r,null,2));else{if(!e.tokenName)throw new gr("Must provide either tokenId or tokenName for token identification",pr.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const o=new Br({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),i=await this.signatureHelper.signTransferToken(o.toSigningPayload()),s=new Br({...o.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(s,null,2));const a=await this.http.post("/api/asset/token-contract/TransferToken",s);if(!a)throw new gr("No response from GalaChain transfer service",pr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(a,null,2)),this.extractTransactionIdFromResponse(a,"token")}catch(t){throw this.handleTransferError(t,"Token transfer failed",e)}}async resolveTokenClassKey(e){try{const t=await this.tokenResolver.resolveTokenClassKey(e);return this.logger.debug(`[DEBUG] Token class key resolution for '${e}':`,JSON.stringify(t,null,2)),t}catch(t){if(t instanceof gr)throw t;throw new gr(`Failed to resolve token class key for '${e}': ${er(t)}`,pr.TOKEN_NOT_FOUND,{tokenName:e})}}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.signatureHelper)throw new zr("Wallet required for token lock operations",Wr.WALLET_REQUIRED);try{const t=be(this.wallet.address),n=[],r=[];let o=t;const i=e.tokens.find(e=>e.lockAuthority);i?.lockAuthority&&(o=be(i.lockAuthority));const s=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const i of e.tokens){let e;if(i.tokenId)e=_r(i.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",i.tokenId);else{if(!i.tokenName)throw new zr("Must provide either tokenId or tokenName for token identification",Wr.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(i.tokenName)}n.push({owner:t,quantity:i.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:i.amount,lockAuthority:i.lockAuthority?be(i.lockAuthority):o})}const c=new xr({lockAuthority:o,tokenInstances:n,...void 0!==s?.expires&&{expires:s.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),u=await this.signatureHelper.signLockToken(c.toSigningPayload()),l=new xr({...c.toSigningPayload(),signedPayload:u});this.logger.debug("[DEBUG] Full Lock Request Payload:",JSON.stringify(l,null,2));const h=await this.http.post("/api/asset/token-contract/LockTokens",l);if(!h)throw new zr("No response from GalaChain lock service",Wr.NETWORK_ERROR);if(1!==h.Status)throw new zr(`Token lock failed: ${h.Message||`Status ${h.Status}`}`,Wr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token lock response:",JSON.stringify(h,null,2)),this.extractLockResult(h,r)}catch(t){throw this.handleLockError(t,"Token lock failed",e)}}async unlockTokens(e){if(this.validateUnlockTokensData(e),!this.wallet||!this.signatureHelper)throw new zr("Wallet required for token unlock operations",Wr.WALLET_REQUIRED);try{const t=be(this.wallet.address),n=[],r=[],o=e.tokens.find(e=>void 0!==e.name);for(const o of e.tokens){let e;if(o.tokenId)e=_r(o.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",o.tokenId);else{if(!o.tokenName)throw new zr("Must provide either tokenId or tokenName for token identification",Wr.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(o.tokenName)}n.push({owner:t,quantity:o.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:o.amount})}const i=new Cr({tokenInstances:n,...void 0!==o?.name&&{name:o.name},uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),s=await this.signatureHelper.signUnlockToken(i.toSigningPayload()),a=new Cr({...i.toSigningPayload(),signedPayload:s});this.logger.debug("[DEBUG] Full Unlock Request Payload:",JSON.stringify(a,null,2));const c=await this.http.post("/api/asset/token-contract/UnlockTokens",a);if(!c)throw new zr("No response from GalaChain unlock service",Wr.NETWORK_ERROR);if(1!==c.Status)throw new zr(`Token unlock failed: ${c.Message||`Status ${c.Status}`}`,Wr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token unlock response:",JSON.stringify(c,null,2)),this.extractUnlockResult(c,r)}catch(t){throw this.handleLockError(t,"Token unlock failed",e)}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.signatureHelper)throw new Yr("Wallet required for token burn operations",Zr.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(n.tokenId)e=_r(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(!n.tokenName)throw new Yr("Must provide either tokenId or tokenName for token identification",Zr.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new Pr({tokenInstances:t,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),r=await this.signatureHelper.signBurnTokens(n.toSigningPayload()),o=new Pr({...n.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full Burn Request Payload:",JSON.stringify(o,null,2));const i=await this.http.post("/api/asset/token-contract/BurnTokens",o);if(!i)throw new Yr("No response from GalaChain burn service",Zr.NETWORK_ERROR);if(1!==i.Status)throw new Yr(`Token burn failed: ${i.Message||`Status ${i.Status}`}`,Zr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token burn response:",JSON.stringify(i,null,2)),this.extractBurnResult(i)}catch(t){throw this.handleBurnError(t,"Token burn failed",e)}}extractBurnResult(e){const t=[];if(e.Data&&Array.isArray(e.Data))for(const n of e.Data)t.push({collection:n.collection||"",category:n.category||"",type:n.type||"",additionalKey:n.additionalKey||"",instance:n.instance||"0",quantity:n.quantity||"0",burnedBy:n.burnedBy||""});let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},burned:t}}validateBurnTokensData(e){if(!Xr(e))throw new Yr("Invalid burn data: missing required fields",Zr.VALIDATION_ERROR);if(e.tokens.length>oo)throw new Yr(`Batch size exceeds maximum limit of ${oo} tokens per burn operation`,Zr.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new Yr("Must provide either tokenId or tokenName for token identification",Zr.TOKEN_NOT_FOUND);const e=new y(t.amount);if(e.isNaN()||e.lte(0))throw new Yr("Burn amount must be a positive number",Zr.INVALID_AMOUNT,{amount:t.amount})}}handleBurnError(e,t,n){if(e instanceof Yr)return e;let r=t,o=Zr.NETWORK_ERROR;if(tr(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n;e.Message&&"string"==typeof e.Message&&(r=`${t}: ${e.Message}`);const i=String(e.Message||"").toLowerCase();i.includes("insufficient")||i.includes("balance")?o=Zr.INSUFFICIENT_BALANCE:(i.includes("not found")||i.includes("token"))&&(o=Zr.TOKEN_NOT_FOUND)}}else Jn(e)&&(r=`${t}: ${e.message}`);const i={};return void 0!==n?.tokens?.[0]?.tokenName&&(i.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(i.amount=n.tokens[0].amount),new Yr(r,o,Object.keys(i).length>0?i:void 0)}validateLockTokensData(e){if(!Mr(e))throw new zr("Invalid lock data: missing required fields",Wr.VALIDATION_ERROR);if(e.tokens.length>io)throw new zr(`Batch size exceeds maximum limit of ${io} tokens per lock operation`,Wr.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new zr("Must provide either tokenId or tokenName for token identification",Wr.TOKEN_NOT_FOUND);if(t.tokenName&&!fr.TOKEN_NAME_PATTERN.test(t.tokenName))throw new zr("Invalid token name format",Wr.TOKEN_NOT_FOUND,{tokenName:t.tokenName});const e=new y(t.amount);if(e.isNaN()||e.lte(0))throw new zr("Lock amount must be a positive number",Wr.INVALID_AMOUNT,{amount:t.amount});if(t.lockAuthority&&!we(t.lockAuthority))throw new zr("Invalid lock authority address format",Wr.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires&&(t.expires<=0||!Number.isInteger(t.expires)))throw new zr("Expires must be a positive integer (epoch milliseconds)",Wr.VALIDATION_ERROR)}}validateUnlockTokensData(e){if(!$r(e))throw new zr("Invalid unlock data: missing required fields",Wr.VALIDATION_ERROR);if(e.tokens.length>so)throw new zr(`Batch size exceeds maximum limit of ${so} tokens per unlock operation`,Wr.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new zr("Must provide either tokenId or tokenName for token identification",Wr.TOKEN_NOT_FOUND);if(t.tokenName&&!fr.TOKEN_NAME_PATTERN.test(t.tokenName))throw new zr("Invalid token name format",Wr.TOKEN_NOT_FOUND,{tokenName:t.tokenName});const e=new y(t.amount);if(e.isNaN()||e.lte(0))throw new zr("Unlock amount must be a positive number",Wr.INVALID_AMOUNT,{amount:t.amount})}}extractLockResult(e,t){let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},locked:t}}extractUnlockResult(e,t){let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof zr)return e;let r=t,o=Wr.NETWORK_ERROR;if(tr(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n;e.Message&&"string"==typeof e.Message&&(r=`${t}: ${e.Message}`);const i=String(e.Message||"").toLowerCase();i.includes("insufficient")||i.includes("balance")?o=Wr.INSUFFICIENT_BALANCE:i.includes("lock")&&i.includes("not found")?o=Wr.LOCK_NOT_FOUND:i.includes("not found")||i.includes("token")?o=Wr.TOKEN_NOT_FOUND:i.includes("authority")?o=Wr.NOT_LOCK_AUTHORITY:i.includes("expired")&&(o=Wr.LOCK_EXPIRED)}}else Jn(e)&&(r=`${t}: ${e.message}`);const i={};return void 0!==n?.tokens?.[0]?.tokenName&&(i.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(i.amount=n.tokens[0].amount),new zr(r,o,Object.keys(i).length>0?i:void 0)}validateTransferGalaData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.recipientAddress&&t.recipientAddress.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Y("Invalid GALA transfer data: missing required fields");if(!we(e.recipientAddress))throw new gr("Invalid recipient address format",pr.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Sr.validateAmount(e.amount),Sr.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.to&&t.to.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Y("Invalid token transfer data: missing required fields");if(!we(e.to))throw new gr("Invalid recipient address format",pr.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new gr("Must provide either tokenId or tokenName for token identification",pr.TOKEN_NOT_FOUND);if(e.tokenName&&!fr.TOKEN_NAME_PATTERN.test(e.tokenName))throw new gr("Invalid token name format",pr.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Sr.validateAmount(e.amount),Sr.validateUniqueKey(e.uniqueKey)}validateLockTokenData(e){if(!jr(e))throw new Y("Invalid lock token data: missing required fields");if(e.lockAuthority&&!we(e.lockAuthority))throw new gr("Invalid lock authority address format",pr.INVALID_RECIPIENT,{recipientAddress:e.lockAuthority});if(!e.tokenId&&!e.tokenName)throw new gr("Must provide either tokenId or tokenName for token identification",pr.TOKEN_NOT_FOUND);if(e.tokenName&&!fr.TOKEN_NAME_PATTERN.test(e.tokenName))throw new gr("Invalid token name format",pr.TOKEN_NOT_FOUND,{tokenName:e.tokenName});if(void 0!==e.expires&&(e.expires<=0||!Number.isInteger(e.expires)))throw new Y("Expires must be a positive integer (epoch milliseconds)");Sr.validateAmount(e.amount),Sr.validateUniqueKey(e.uniqueKey)}validateUnlockTokenData(e){if(!Hr(e))throw new Y("Invalid unlock token data: missing required fields");if(!e.tokenId&&!e.tokenName)throw new gr("Must provide either tokenId or tokenName for token identification",pr.TOKEN_NOT_FOUND);if(e.tokenName&&!fr.TOKEN_NAME_PATTERN.test(e.tokenName))throw new gr("Invalid token name format",pr.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Sr.validateAmount(e.amount),Sr.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(t){const n=this.resolveTokenInstanceFromVaultAddress(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}const n={collection:e.trim().toUpperCase(),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug(`[DEBUG] Token resolution for '${e}' (standard format):\n Token Instance: ${JSON.stringify(n,null,2)}`),n}catch(t){if(t instanceof gr)throw t;throw new gr(`Failed to resolve token '${e}': ${er(t)}`,pr.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){try{return Dr(e)}catch(e){if(e instanceof Y)throw new gr(`Invalid vault address format: ${e.message}`,pr.TOKEN_NOT_FOUND);throw new gr(`Failed to parse vault address: ${e instanceof Error?e.message:String(e)}`,pr.TOKEN_NOT_FOUND)}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const n=e;if(Array.isArray(n.Data)&&n.Data.length>0)switch(t){case"gala":return Jr;case"token":return eo;case"lock":return to;case"unlock":return no}return ro}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new gr("Operation succeeded but transaction ID could not be extracted",pr.NETWORK_ERROR)}handleTransferError(e,t,n){if(e instanceof gr)return e;if(e instanceof Y)return new gr(e.message,pr.INVALID_AMOUNT);if(tr(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t)return new gr(("string"==typeof r?.message?r.message:void 0)||"Invalid transfer request",pr.INVALID_AMOUNT);if(403===t)return new gr("Insufficient balance for transfer",pr.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new gr("Token not found",pr.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new gr("Transfer request timed out",pr.NETWORK_ERROR);const r=er(e);return new gr(r||t,pr.NETWORK_ERROR)}}class lo{constructor(e,t,n,r=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=n,this.logger=new H({debug:r,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e;if(!t&&!n)throw le("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&n)throw new Y("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS");if(n)return this.logger.debug(`Fetching spot price by tokenId: ${n}`),this._fetchDexTokenSpotPrice(n);throw new Y("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw le("tokenId","Token ID");try{const t=_r(e),n=Tr(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${n}`),!this.dexBackendHttp)throw de("DEX Backend API client not configured");const r=await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:n}});if(!r.data||"string"!=typeof r.data)throw new Y("Invalid price response: data must be a string, got "+typeof r.data,"data","INVALID_RESPONSE");const o=parseFloat(r.data);if(isNaN(o))throw new Y(`Invalid price value: could not parse "${r.data}" as number`,"data","INVALID_CALCULATION");const i=`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`;let s;try{if(this.cache){const e=this.cache.getByTokenId(i);if(e?.symbol)return s=e.symbol,this.logger.debug(`DEX spot price for ${s} (cached): $${o}`),{symbol:s,price:o}}this.logger.debug(`Symbol cache miss for ${i}, fetching from API`);s=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(i,{symbol:s}),this.logger.debug(`Cached symbol for ${i}: ${s}`)),this.logger.debug(`DEX spot price for ${s}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${e instanceof Error?e.message:String(e)}`),s=("Token"===t.collection?t.type:t.collection).toUpperCase(),this.logger.debug(`DEX spot price for ${s} (fallback): $${o}`)}return{symbol:s,price:o}}catch(e){if(e instanceof Y)throw e;throw de(`Failed to fetch DEX spot price: ${er(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!e||"string"!=typeof e)throw new Error(Q);try{if(n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const n=`${t.sellingToken.collection}|${t.sellingToken.category}|${t.sellingToken.type}|${t.sellingToken.additionalKey}`;return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${er(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const r=await t({tokenName:e,amount:"1",type:"native"}),o=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(!o)throw de("GALA price not available");const i=Number(r.amount)/1e18;if(i<=0)throw new Y(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const s=o.price/i;return{symbol:e.toUpperCase(),price:s}}catch(t){if(t instanceof Error)throw de(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw de(`Failed to calculate launchpad token spot price for ${e}: ${er(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw de("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),n={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey,symbol:t.symbol,decimals:t.decimals,name:t.name,image:t.image,description:t.description,network:t.network,...void 0!==t.contractAddress&&{contractAddress:t.contractAddress}};return this.logger.debug(`Fetched token details for ${t.symbol} from GalaChain`),n}catch(t){if((t instanceof Y||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw de(`Failed to fetch token details from GalaChain for ${e}: ${er(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw de("DEX Backend API client not configured");const e=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard/seasons"});let t;if(Array.isArray(e))t=e;else{if(!e||"object"!=typeof e)return this.logger.warn("Seasons endpoint returned invalid data:",e),[];if(Array.isArray(e.data))t=e.data;else if(e.data&&Array.isArray(e.data.seasons))t=e.data.seasons;else{if(!Array.isArray(e.seasons))return this.logger.warn("Seasons endpoint returned unexpected structure:",e),[];t=e.seasons}}const n=t.map(e=>({id:e?.id??0,name:e?.name??"",start:e?.start?new Date(e.start):new Date,end:e?.end?new Date(e.end):new Date,rulesId:e?.rules_id??0}));return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(e instanceof Error&&e.message.includes("not configured"))throw e;if(e&&"object"==typeof e&&"response"in e){const t=e;if(404===t.response?.status)return this.logger.warn("Seasons endpoint not available"),[]}throw de(`Failed to fetch DEX seasons: ${er(e)}`)}}async fetchCurrentDexSeason(){const e=await this.fetchAllDexSeasons(),t=new Date,n=e.find(e=>t>=e.start&&t<=e.end);return n?this.logger.debug(`Current DEX season: ${n.name} (ID: ${n.id})`):this.logger.debug("No active DEX season found"),n||null}async fetchDexLeaderboardBySeasonId(e){if(!e||"number"!=typeof e||e<1)throw le("seasonId","Season ID must be a positive number");try{if(!this.dexBackendHttp)throw de("DEX Backend API client not configured");const t=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard",params:{seasonId:e.toString()}});let n;if(Array.isArray(t))n=t;else{if(!t||"object"!=typeof t)return this.logger.warn("Leaderboard endpoint returned invalid data:",t),{entries:[],seasonId:e,totalEntries:0};if(t.data&&Array.isArray(t.data.leaderboard))n=t.data.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!t.data||!Array.isArray(t.data))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=t.data}}const r=n.map(e=>({wallet:e?.wallet??"",rank:e?.rank??0,totalXp:e?.total_xp??0,distributionPercent:e?.distribution_percent??0,liquidityXp:e?.liquidity_xp??0,tradingXp:e?.trading_xp??0,masteryTitles:(e?.mastery_titles??[]).map(e=>({name:e?.name??"",type:e?.type??"trade",order:e?.order??0}))}));return this.logger.debug(`Fetched leaderboard for season ${e} with ${r.length} entries`),{entries:r,seasonId:e,totalEntries:r.length}}catch(t){if(t instanceof Error&&t.message.includes("must be a positive number"))throw t;throw de(`Failed to fetch DEX leaderboard for season ${e}: ${er(t)}`)}}async fetchCurrentDexLeaderboard(){const e=await this.fetchCurrentDexSeason();return e?this.fetchDexLeaderboardBySeasonId(e.id):(this.logger.debug("Cannot fetch current leaderboard - no active season"),null)}async fetchDexAggregatedVolumeSummary(){try{if(!this.dexBackendHttp)throw de("DEX Backend API client not configured");const e=await this.dexBackendHttp.request({method:"GET",url:"/explore/volume"}),t={volume1d:e.data.volume1d,volume1dDelta:e.data.volume1dDelta,volume7d:e.data.volume7d,volume7dDelta:e.data.volume7dDelta,volume30d:e.data.volume30d,volume30dDelta:e.data.volume30dDelta};return this.logger.debug(`Fetched DEX volume summary: $${t.volume1d.toFixed(2)} (1d)`),t}catch(e){throw de(`Failed to fetch DEX volume summary: ${er(e)}`)}}}const ho=8,fo=18,po={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"};function go(e,t=18){const n=parseFloat(e);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function mo(e){return go(e,8)}function yo(e){return go(e,18)}function wo(e){return{maxAcceptableReverseBondingCurveFee:mo(e.maxAcceptableReverseBondingCurveFee)}}new H({debug:!1,context:"NumberUtils"});const bo={BuyNativeDto:class extends p{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=mo(t),this.expectedToken=yo(n),this.extraFees=wo(r)}},BuyExactDto:class extends p{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=yo(t),this.expectedNativeToken=mo(n),this.extraFees=wo(r)}},SellExactDto:class extends p{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=yo(t),this.expectedNativeToken=mo(n),this.extraFees=wo(r)}},SellNativeDto:class extends p{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=mo(t),this.expectedToken=yo(n),this.extraFees=wo(r)}}};class ko extends Gn{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,n){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const n=this.generateEIP712Types(t,e),r=g(e),o={...e,prefix:r},{signature:i,domain:s}=await this.signWithEthersWallet(n,o),a={...e,signature:i,types:n,domain:s};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(a),signatureLength:i.length}),a}catch(e){this.logger.error("❌ Signature generation failed:",e);throw pe(`Failed to sign DTO: ${er(e)}`)}}async signWithEthersWallet(e,t){try{let n,r;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)n={name:"ethereum",chainId:1},r=await this.walletProvider.signTypedData(n,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw fe("Wallet provider does not support typed data signing","walletProvider");{const o=await this.walletProvider.getNetwork();n={name:o.name,chainId:Number(o.chainId)},r=await this.walletProvider.signTypedData(n,e,t)}}return{signature:r,domain:n}}catch(e){throw pe(`Ethers.js signing failed: ${er(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const r=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),o=(e,t,r,i=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const s=o(e,t[0],r,!0);return i||n[r].push({name:e,type:(s??e)+"[]"}),s?s+"[]":void 0}if("object"==typeof t&&null!==t){if(n[e])throw new Y(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).forEach(([t,n])=>{o(t,n,e)}),i||n[r].push({name:e,type:e}),e}{let o;switch(typeof t){case"string":o="string";break;case"number":o="uint256";break;case"boolean":o="bool";break;default:throw new Y(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return i||n[r].push({name:e,type:o}),o}}};return Object.entries(r).forEach(([t,n])=>{o(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class vo extends Gn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),r=this.createGalaInstance(),o=`$service$${n.toStringKey()}$launchpad`,i=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${r.toStringKey()}$${e}`,c=[o,i,s,a,`$tokenBalance$${r.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=er(e);throw new Y(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new U;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new U;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!e||"string"!=typeof e)throw le("vaultAddress","Vault address");try{const t=Rr(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof Y)throw he("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!e||"string"!=typeof e)throw le("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw he("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw he("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw he("vaultAddress",'having at least 5 parts separated by "$"');const n=t[2];if(!n||!/^[A-Za-z]{1,10}$/.test(n))throw he("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return Ir(e)}catch(e){if(e instanceof Y)throw he("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Eo(e,t,n){if(t<0||t>1)throw new Error(`Invalid slippage tolerance factor: ${t}. Must be between 0 and 1 (e.g., 0.05 for 5%)`);const r=new y(e);if(r.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const o=r.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=r.minus(o);break;case"buy-exact":case"sell-native":i=r.plus(o);break;default:throw new Error(`Unknown operation type: ${n}`)}return i.isLessThan(0)&&(i=new y(0)),i.toFixed()}class So extends Kn{constructor(e,t,n=!1,r,o,i=.05,s=.01){super(e,n),this.tokenResolver=t,this.walletProvider=r,this.userAddress=o,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=s,this.bundleEndpoint="/bundle",r&&o&&(this.signatureService=new ko(r,n),this.tokenKeyService=new vo(n))}async submitTransaction(e){try{this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)}),this.validateBundleData(e);const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});const n=await this.http.post(this.bundleEndpoint,t);return n?(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:!!n.data,error:n.error}),this.handleBundleResponse(n)):{success:!1,error:"No response from bundle API"}}catch(e){return this.logger.error("❌ Bundle transaction submission failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}validateBundleData(e){if(!e)throw le("bundleData","Bundle data");if(!e.signedDto)throw le("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw le("method","Method name");if(!Array.isArray(e.stringsInstructions))throw he("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Y("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw he("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new Y(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new Y(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT")}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){if(e.data&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",e.data),{success:!0,data:e.data};const t=e.error||e.message||"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",t),{success:!1,error:t}}formatErrorMessage(e){if("string"==typeof e)return e;if(tr(e)&&e.response){const t=e.response.data;if(t&&"object"==typeof t){const e=t;if(e.error)return String(e.error);if(e.message)return String(e.message)}}return er(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw le("transactionId","Transaction ID");this.logger.debug("🔍 Checking bundler transaction result:",e);const t=await this.http.get(`${this.bundleEndpoint}?id=${e}`);return t?(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t}):{success:!1,error:"No response from bundler transaction query"}}catch(e){return this.logger.error("❌ Failed to get bundler transaction result:",e),{success:!1,error:this.formatErrorMessage(e)}}}async cancelTransaction(e){try{if(!e||"string"!=typeof e)throw le("transactionId","Transaction ID");this.logger.debug("🚫 Cancelling transaction:",e);const t=await this.http.delete(`${this.bundleEndpoint}/${e}`);return t?(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t}):{success:!1,error:"No response from transaction cancellation"}}catch(e){return this.logger.error("❌ Failed to cancel transaction:",e),{success:!1,error:this.formatErrorMessage(e)}}}async getHealthStatus(){try{this.logger.debug("🏥 Checking bundle service health");const e=await this.http.get(`${this.bundleEndpoint}/health`);return e?(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e}):{success:!1,error:"No response from bundle service health check"}}catch(e){return this.logger.error("❌ Bundle service health check failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:o}=e,{effectiveSlippageFactor:i,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(!o)throw new Y("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Eo(o,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:o,slippageFactor:i,adjustedMinTokens:e});const t=new bo.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(!o)throw new Y("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Eo(o,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:o,slippageFactor:i,adjustedMaxGalaCost:e});const t=new bo.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:o}=e,{effectiveSlippageFactor:i,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(!o)throw new Y("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Eo(o,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:o,slippageFactor:i,adjustedMinGala:e});const t=new bo.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(!o)throw new Y("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Eo(o,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:o,slippageFactor:i,adjustedMaxTokensToSell:e});const t=new bo.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:o,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,r),s=await this.resolveTokenNameToVault(e);if(!s)throw ue(e);return{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:s}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,o=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e||"0";return e&&(i=Eo(e,o,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:o,adjustedMaxFee:i})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:o,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw fe("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw le("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${F()}-${Date.now()}-${this.userAddress}`;const r=await this.signatureService.signDTO(e,t,this.userAddress),o=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:o,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:o,dtoKeys:Object.keys(r)});const s=await this.submitTransaction(i);if(s.success&&s.data)return this.logger.debug("✅ Bundle transaction submitted:",s.data),{success:!0,data:{transactionId:s.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(s.error||"Bundle transaction failed"))}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}var Ao,To;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Ao||(Ao={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(To||(To={}));const Io={[Ao.PROCESSED]:To.COMPLETED,[Ao.COMPLETED]:To.COMPLETED,[Ao.SUCCESS]:To.COMPLETED,[Ao.FAILED]:To.FAILED,[Ao.ERROR]:To.FAILED,[Ao.PROCESSING]:To.PROCESSING,[Ao.PENDING]:To.PENDING};class Bo extends Gn{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.reconnectCount=0,this.hasOnAnyListener=!1,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof L||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{try{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');return this.logger.error("❌ Socket.IO connection failed:",e.message),void t(e)}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=L(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts||5,reconnectionDelay:this.config.reconnectDelay||2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectCount=0,e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status||n.Status;if(r&&"string"==typeof r){if(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE){const e=this.eventBuffer.keys().next().value;if(e){const t=this.eventBufferTimeouts.get(e);t&&(clearTimeout(t),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e),this.logger.warn(`📡 [Event Buffer] Buffer full (${this.MAX_BUFFER_SIZE}), dropped oldest: ${e}`)}}this.eventBuffer.set(e,n);const t=this.eventBufferTimeouts.get(e);t&&clearTimeout(t);const o=setTimeout(()=>{this.eventBuffer.has(e)&&(this.logger.debug(`📡 [Event Buffer] Cleaning up orphaned event for ${e}`),this.eventBuffer.delete(e),this.eventBufferTimeouts.delete(e))},3e4);this.eventBufferTimeouts.set(e,o)}}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0}catch(e){t(e)}})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=this.eventBuffer.get(e);if(n){this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)});const r=this.eventBufferTimeouts.get(e);r&&(clearTimeout(r),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e)}const r=this.config.timeout||3e5,o=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),o={transactionId:e,status:To.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(o),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,o),this.socket&&this.socket.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:To.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,o=r?.data,i=r?.status||r?.Status||o?.status||o?.Status;let s=r?.message||r?.Message||o?.message||o?.Message||r?.error||o?.error;s&&"string"==typeof s||(s=i===Ao.FAILED||i===Ao.ERROR?"Transaction failed - check transaction details":i===Ao.COMPLETED||i===Ao.PROCESSED||i===Ao.SUCCESS?"Transaction completed successfully":i?`Transaction status: ${i}`:"Unknown transaction status");const a=r?.blockHash||o?.blockHash,c=r?.gasUsed||o?.gasUsed,u=r?.Data||o?.Data,l={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...a&&{blockHash:a},...c&&{gasUsed:c},...u&&{data:u}};if(this.logger.debug(`📡 Mapped status for ${e}: ${i} -> ${l.status}`),this.logger.debug(`📡 Final message: "${s}"`),n(l),l.status===To.COMPLETED||l.status===To.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${l.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===To.COMPLETED?t(e):e.status!==To.FAILED&&e.status!==To.TIMEOUT||n(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Io[t]||To.PENDING}async handleReconnect(){this.reconnectCount<this.config.reconnectAttempts?(this.reconnectCount++,this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectCount}/${this.config.reconnectAttempts}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.config.reconnectDelay)):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.eventBufferTimeouts.forEach(e=>{clearTimeout(e)}),this.eventBufferTimeouts.clear(),this.logger.debug("🧹 Cleared event buffer and timeouts"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected"))}isConnected(){return this.socket?.connected||!1}getSocket(){return this.socket}}class xo extends Gn{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!ye(e))throw new Y("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");const t=e.trim().toLowerCase(),n=this.get(t);if(n)return n;try{const n=await this.poolService.resolveTokenNameToVault(e);return n&&this.set(t,n),n}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw ue(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(e.toLowerCase())||null}set(e,t){this.cache.set(e.toLowerCase(),t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}parseVaultAddressToTokenClassKey(e){try{return Ur(e)}catch(e){if(e instanceof Y)throw he("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}async function Co(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:o=20}=t,i=[];let s=1,a=!0,c=0;for(;a&&s<=n;){r&&r.debug(`Auto-pagination: fetching page ${s} with limit ${o}`);const t=await e(s,o);if(!t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(i.push(...t.items),c=t.total,r&&r.debug(`Auto-pagination: page ${s} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${s}, exiting loop`);break}a=t.hasNext,s++}return s>n&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n}, stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${i.length}, total count: ${c}`),{items:i,total:c}}function Po(e,t=e.length,n="items"){return{...{page:1,limit:e.length||0,total:t,totalPages:Math.ceil(t/(e.length||1))||1,hasNext:!1,hasPrevious:!1},[n]:e}}class No extends Kn{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw fe("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");if(!e||"string"!=typeof e||e.length<3||e.length>20)throw fe("Token name must be a string between 3 and 20 characters","tokenName");this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(!t)throw fe(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Ur(t),r=`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`;return this.logger.debug(`Extracted token class key: ${r}`),r}catch(t){if(t instanceof Error&&t.message.includes("ConfigurationError"))throw t;throw de(`Failed to resolve token name '${e}': ${er(t)}`,500)}}async fetchPriceHistory(e){this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e);try{let t=e.tokenId;if(e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const n=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=n,this.logger.debug(`Resolved to token ID: ${n}`)}if(!t)throw fe("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return Fr}),r=n(t),o=Tr(`${r.collection}|${r.category}|${r.type}|${r.additionalKey}`),{from:i,to:s,sortOrder:a="DESC",page:c=1,limit:u=10}=e,l={token:o,page:String(c),limit:String(u)};i&&(l.from=i.toISOString()),s&&(l.to=s.toISOString());const h=function(e){if(e)return e.toLowerCase()}(a);h&&(l.order=h),this.logger.debug(`Querying price snapshots for token ${o}, page ${c}, limit ${u}`);const d=await this.http.get("/price-oracle/fetch-price",l);if(!d)throw de("No response from price history service",500);const f=this.transformApiResponseToPriceHistory(d);return this.logger.debug(`Found ${f.snapshots.length} price snapshots, total ${f.total}`),f}catch(e){if(e instanceof Error&&(e.message.includes("ConfigurationError")||e.message.includes("NetworkError")))throw e;throw de(`Failed to fetch price history: ${er(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw de("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw de("Invalid API response: missing data.meta pagination info",500);const t=e.data.data.map(e=>({price:e.price,timestamp:new Date(e.createdAt),tokenId:`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`})),n=e.data.meta,r=n.currentPage??1,o=n.totalPages??1;return{snapshots:t,page:r,limit:n.pageSize??50,total:n.totalItems??0,totalPages:o,hasNext:r<o,hasPrevious:r>1}}async fetchAllPriceHistory(e){this.logger.debug("Fetching all price history with options:",e);const t=await Co((t,n)=>this.fetchPriceHistory({...e,page:t,limit:n}).then(e=>({items:e.snapshots,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:50});return Po(t.items,t.total,"snapshots")}validateOptions(e){const{from:t,to:n,sortOrder:r,page:o=1,limit:i=10}=e;if(function(e,t,n,r={}){const{description:o="parameter",treatEmptyAsNull:i=!0}=r,s=e[t],a=e[n],c=null!=s&&(!i||""!==s),u=null!=a&&(!i||""!==a);if(!c&&!u)throw fe(`Either ${t} or ${n} must be provided (${o})`,n);if(c&&u)throw fe(`Cannot provide both ${t} and ${n}. Provide exactly one (${o}).`,n)}(e,"tokenName","tokenId",{description:"token identifier"}),t&&!(t instanceof Date)&&isNaN(new Date(t).getTime()))throw fe("from must be a valid Date","from");if(n&&!(n instanceof Date)&&isNaN(new Date(n).getTime()))throw fe("to must be a valid Date","to");if(r&&"ASC"!==r&&"DESC"!==r)throw fe('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(o)||o<1)throw fe("page must be a positive integer","page");if(!Number.isInteger(i)||i<1||i>50)throw fe("limit must be between 1 and 50","limit")}}function _o(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new Y("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:r,additionalKey:o}=e;if(!t||"string"!=typeof t)throw new Y("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!n||"string"!=typeof n)throw new Y("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!r||"string"!=typeof r)throw new Y("Token.type must be a non-empty string, got "+typeof r,"token.type","MISSING_OR_INVALID_TYPE");if(!o||"string"!=typeof o)throw new Y("Token.additionalKey must be a non-empty string, got "+typeof o,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:r,additionalKey:o}}(e);if(!e)throw new Y(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new Y("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(e.includes("|"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected 4+ parts separated by |, got ${t.length}`);const[n,r,o,...i]=t;if(!n||!r||!o)throw new Error("Collection, category, and type must be non-empty");const s=i.join("|");if(!s)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:r,type:o,additionalKey:s}}catch(t){const n=e.split("|");throw new Y(`Invalid pipe-delimited token: "${e}" (${n.length} parts). Expected format: "collection|category|type|additionalKey" (4 parts minimum). Received: [${n.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_PIPE_DELIMITED_TOKEN")}}(e);if(e.includes("$"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected 4+ parts separated by $, got ${t.length}`);const n=t[t.length-1],r=t[t.length-2],o=t[t.length-3],i=t.slice(0,t.length-3).join("$");if(!(i&&o&&r&&n))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:o,type:r,additionalKey:n}}catch(t){const n=e.split("$");throw new Y(`Invalid dollar-delimited token: "${e}" (${n.length} parts). Expected format: "collection$category$type$additionalKey" (4 parts minimum). Received: [${n.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e);throw new Y(`Plain token string "${e}" (length: ${e.length}) is not allowed - tokens must be delimited with | or $. Expected format: "GALA|Unit|none|none" or "GALA$Unit$none$none". Input: "${e}"`,"token","PLAIN_STRING_NOT_ALLOWED")}class Uo extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function Do(e){return"object"==typeof e&&null!==e&&"collection"in e&&"category"in e&&"type"in e&&"additionalKey"in e&&"string"==typeof e.collection&&"string"==typeof e.category&&"string"==typeof e.type&&"string"==typeof e.additionalKey}function Ro(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&Do(t.token0ClassKey)&&Do(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickLower&&"number"==typeof t.tickUpper&&"string"==typeof t.liquidity&&"string"==typeof t.feeGrowthInside0Last&&"string"==typeof t.feeGrowthInside1Last&&"string"==typeof t.tokensOwed0&&"string"==typeof t.tokensOwed1}class Fo{constructor(t){this.client=e.create({baseURL:t.baseUrl,timeout:t.timeout??3e4})}async getPoolData(e){try{if("string"==typeof e.token0||"string"==typeof e.token1)throw new Error(`GalaChain API getPoolData requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getPoolData(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`);const t=await this.client.post("/api/asset/dexv3-contract/GetPoolData",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.token0&&"string"==typeof t.token1&&Do(t.token0ClassKey)&&Do(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickSpacing&&"string"==typeof t.liquidity&&"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.feeGrowthGlobal0&&"string"==typeof t.feeGrowthGlobal1}(n))throw new Uo(t.status,"Invalid pool data response format",n);return n}catch(e){throw this.handleError(e,"getPoolData")}}async getPositions(e){try{const t=await this.client.post("/api/asset/dexv3-contract/GetPositions",e);this.validateResponse(t.data);const n=t.data.Data;let r;r=n&&"object"==typeof n&&"positions"in n&&Array.isArray(n.positions)?n.positions:n&&"object"==typeof n&&"positionId"in n?[n]:Array.isArray(n)?n:[];for(const e of r)if(!Ro(e))throw new Uo(t.status,"Invalid position in response",e);return{positions:r,count:r.length}}catch(e){throw this.handleError(e,"getPositions")}}async getPositionById(e,t,n,r,o,i,s){try{let a,c;if(void 0!==t&&void 0!==n&&void 0!==r&&void 0!==o&&void 0!==i){a={owner:e,token0:"string"==typeof t?{collection:t,category:"Unit",type:"none",additionalKey:"none"}:t,token1:"string"==typeof n?{collection:n,category:"Unit",type:"none",additionalKey:"none"}:n,fee:r,tickLower:o,tickUpper:i},s&&(a.positionId=s),c=`${e}/${t}/${n}/${r}`}else a={positionId:e},c=e;const u=await this.client.post("/api/asset/dexv3-contract/GetPositions",a);this.validateResponse(u.data);const l=u.data.Data;let h;if(l&&"object"==typeof l&&"positionId"in l&&!("positions"in l))h=l;else{if(!(l&&Array.isArray(l.positions)&&l.positions.length>0))throw new Uo(404,`Position not found: ${c}`);h=l.positions[0]}const d={Data:h,Status:u.status};return void 0!==u.data.Message&&(d.Message=u.data.Message),d}catch(t){throw this.handleError(t,`getPositionById(${e})`)}}async getRemoveLiquidityEstimation(e){try{const t=await this.client.post("/api/asset/dexv3-contract/GetRemoveLiquidityEstimation",e);this.validateResponse(t.data);const n=t.data.Data;if("string"!=typeof n.amount0||"string"!=typeof n.amount1)throw new Uo(t.status,"Invalid removal estimation response format",n);return n}catch(e){throw this.handleError(e,"getRemoveLiquidityEstimation")}}validateResponse(e){if(!e||"object"!=typeof e)throw new Uo(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new Uo(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new Uo(e.Status,e.Message??"Gateway error",e.Data)}handleError(t,n){if(t instanceof Uo)return t;if(e.isAxiosError(t)){const e=t.response?.status??500,r=t.response?.data?.Message??t.message,o=t.response?.data?.Data??void 0;return new Uo(e,`${n}: ${r}`,o)}return new Uo(500,`${n}: ${t instanceof Error?t.message:String(t)}`)}}class Lo{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){try{if(!e||"string"!=typeof e)throw new Uo(400,"Invalid wallet address");const r=Math.max(1,Math.floor(n/t)+1),o={};o.address=e,o.page=r,o.limit=t;const i=await this.http.get("/user/assets",o);if(!i||"object"!=typeof i)throw new Uo(500,"Invalid response format: not an object");const s=i.data;if(!s||"object"!=typeof s)throw new Uo(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new Uo(500,"Invalid response format: token array must be an array");const c=[];for(const e of a){if("object"!=typeof e||null===e)throw new Uo(500,"Invalid asset in response: asset must be an object");const t=e;if("string"!=typeof t.symbol||"string"!=typeof t.name)throw new Uo(500,"Invalid asset in response: missing symbol or name",t);const n="number"==typeof t.decimals?t.decimals:"string"==typeof t.decimals?parseInt(t.decimals,10):void 0;if("number"!=typeof n||isNaN(n))throw new Uo(500,"Invalid asset in response: decimals must be a number",t);const r={tokenId:t.compositeKey||`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:n,balance:t.quantity||"0"};t.image&&(r.imageUrl=t.image),t.verify&&(r.verified=t.verify),c.push(r)}const u={tokens:c,count:s.count??c.length};return void 0!==s.totalValue&&(u.totalValue=s.totalValue),u}catch(t){throw this.handleError(t,`getUserAssets(${e})`)}}async fetchTokenList(e={}){try{const{address:t,search:n,page:r=1,limit:o=20}=e,i={page:r,limit:Math.min(o,20)};t&&(i.address=t),n&&(i.search=n);const s=await this.http.get("/user/token-list",i);if(!s||"object"!=typeof s)throw new Uo(500,"Invalid response format: not an object");const a=s.data;if(!a||"object"!=typeof a)throw new Uo(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new Uo(500,"Invalid response format: token array must be an array");const u=[];for(const e of c){if("object"!=typeof e||null===e)throw new Uo(500,"Invalid token in response: must be an object");const t=e;if("string"!=typeof t.symbol||""===t.symbol.trim())throw new Uo(500,'Invalid token in response: missing required field "symbol"',{token:t});if("string"!=typeof t.name)throw new Uo(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new Uo(500,'Invalid token in response: missing required field "decimals"',{token:t});if("string"!=typeof t.compositeKey||""===t.compositeKey.trim())throw new Uo(500,'Invalid token in response: missing required field "compositeKey"',{token:t});u.push({image:"string"==typeof t.image?t.image:"",name:t.name,symbol:t.symbol,decimals:String(n),description:"string"==typeof t.description?t.description:"",verify:"boolean"==typeof t.verify&&t.verify,compositeKey:t.compositeKey,additionalKey:"string"==typeof t.additionalKey?t.additionalKey:"",category:"string"==typeof t.category?t.category:"",type:"string"==typeof t.type?t.type:"",collection:"string"==typeof t.collection?t.collection:"",subscribePrice:"boolean"==typeof t.subscribePrice&&t.subscribePrice,quantity:"string"==typeof t.quantity?t.quantity:"0"})}return{token:u,count:"number"==typeof a.count?a.count:u.length}}catch(e){throw this.handleError(e,"fetchTokenList")}}handleError(e,t){if(e instanceof Uo)return e;if(e instanceof Error&&e instanceof Error&&"response"in e){const n=e,r=n.response?.status??500,o=n.response?.data?.message??n.response?.data?.Message??n.message,i=n.response?.data?.Data??n.response?.data?.data??void 0;return n.response,new Uo(r,`${t}: ${o}`,i)}return new Uo(500,`${t}: ${e instanceof Error?e.message:String(e)}`)}}function Oo(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected at least 4 parts separated by |, got ${t.length}`);const[n,r,o,...i]=t;if(!n||!r||!o)throw new Error("Collection, category, and type must be non-empty");const s=i.join("|");if(!s)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:r,type:o,additionalKey:s}}catch(t){throw new Y(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}const Mo=20,$o=10;class qo extends Gn{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new Ar,this.webSocketService=t,this.dexQuoteService=n,this.getWalletAddress=e.getWalletAddress,this.galaChainBaseUrl=e.galaChainBaseUrl,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.privateKey=e.privateKey,!(e.gatewayBaseUrl&&e.bundlerBaseUrl&&e.dexBackendBaseUrl&&e.dexBackendHttp))throw new Error("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.");try{this.gatewayClient=new Fo({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new Lo(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{gatewayUrl:e.gatewayBaseUrl,dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new Error("Failed to initialize GSwapService HTTP clients")}}setPricingConcurrency(e){if(e<1)throw new Error("Pricing concurrency must be at least 1");e>100&&this.logger.warn("Pricing concurrency > 100 may cause performance issues",{concurrency:e}),this.pricingConcurrency=e,this.logger.debug("Updated pricing concurrency",{concurrency:this.pricingConcurrency})}async getSwapQuoteExactInput(e){try{if(new y(e.amount).isLessThanOrEqualTo(0))throw new ne("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new ne("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,o]=t<n?[t,n]:[n,t],i=[3e3,500,1e4];let s;for(const a of i)try{const i=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:o,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:i,fromToken:t,toToken:n,amount:e.amount}),c=new y(s.currentSqrtPrice),u=new y(s.newSqrtPrice),l=c.gt(u)?c.minus(u).dividedBy(c):new y(0),h=new y(s.amount0),d=new y(s.amount1),f=h.isNegative(),p=d.isNegative();this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":s.amount0,"quoteResult.amount1":s.amount1,"amount0BN.isNegative()":f,"amount1BN.isNegative()":p});const g=f?h:d;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:f,selectedAmount:g.toFixed(),selectedAmountAbs:g.absoluteValue().toFixed()});const m=g.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:m,feeTier:a,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,m),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e instanceof Error?e.message:"Unknown error"})}throw s||new ne("No available fee tiers for quote",{feeTiers:i,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",ne,e)}}async getSwapQuoteExactOutput(e){try{if(new y(e.amount).isLessThanOrEqualTo(0))throw new ne("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new ne("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact output",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,o]=t<n?[t,n]:[n,t],i=[3e3,500,1e4];let s;for(const a of i)try{const i=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:o,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:i,fromToken:t,toToken:n,amount:e.amount}),c=new y(s.currentSqrtPrice),u=new y(s.newSqrtPrice),l=c.gt(u)?c.minus(u).dividedBy(c):new y(0),h=i.pool.token0,d="string"==typeof h?h.split("|")[0]:"object"==typeof h&&null!==h&&"tokenName"in h?h.tokenName:String(h),f=n.split("|")[0]===d?s.amount1:s.amount0;return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:f,estimatedOutput:e.amount,feeTier:a,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(f,e.amount),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e instanceof Error?e.message:"Unknown error"})}throw s||new ne("No available fee tiers for quote",{feeTiers:i,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",ne,e)}}async executeSwap(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");this.logger.debug("Executing swap",{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),r=function(e,t=.01){const n=mr(e),r=new y(1).minus(t);return n.multipliedBy(r)}(e.estimatedOutput,e.slippageTolerance||.01),o=this.getWalletAddress();if(!o)throw new Error("Wallet address required for swap execution");let i;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});i=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:i,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:t instanceof Error?t.message:String(t)})}const s={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:r.toFixed(),feeTier:e.feeTier,walletAddress:o,slippageTolerance:e.slippageTolerance||.01};void 0!==i&&(s.currentSqrtPrice=i);const a=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:a,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const c=await this.webSocketService.waitForTransaction(a);return{transactionId:c.transactionId,status:c.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(c.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",re,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){try{if(!we(e))throw new ie(`Invalid wallet address format: "${e}". Expected format: "0x...", "eth|...", or "client|..."`,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching user assets",{walletAddress:e,page:t,limit:n});return(await this.dexBackendClient.fetchTokenList({address:e,page:t,limit:n})).token.filter(e=>"0"!==e.quantity).map(e=>this.transformRawTokenToUserAsset(e)).filter(e=>null!==e)}catch(r){this.handleGSwapError("Failed to fetch user assets",ie,r,{walletAddress:e,page:t,limit:n})}}async getAllUserAssets(e){try{if(!we(e))throw new ie(`Invalid wallet address format: "${e}". Expected format: "0x...", "eth|...", or "client|..."`,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching all user assets (auto-paginated with optimization)",{walletAddress:e});const t=[];let n=1;const r=20;let o=!0;for(;o&&n<=Mo;){const i=await this.dexBackendClient.fetchTokenList({address:e,page:n,limit:r});let s=!1;for(const e of i.token){if("0"===e.quantity){s=!0;break}const n=this.transformRawTokenToUserAsset(e);n&&t.push(n)}o=!s&&i.token.length===r,n++}return n>Mo&&this.logger.warn("Reached maximum page limit (20) while fetching user assets",{walletAddress:e,totalAssets:t.length}),this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:t.length}),t}catch(t){this.handleGSwapError("Failed to fetch all user assets",ie,t,{walletAddress:e})}}async fetchAvailableDexTokens(e={}){try{const{search:t,page:n=1,limit:r=20}=e;this.logger.debug("Fetching available DEX tokens",{search:t,page:n,limit:r});const o=await this.dexBackendClient.fetchTokenList({...void 0!==t&&{search:t},page:n,limit:r});return{tokens:o.token.map(e=>this.transformRawTokenToDexToken(e)),count:o.count,page:n,limit:r,hasMore:n*r<o.count}}catch(t){this.handleGSwapError("Failed to fetch available DEX tokens",ie,t,{...e})}}async fetchAllAvailableDexTokens(e={}){try{const{search:t}=e;this.logger.debug("Fetching all available DEX tokens (auto-paginated)",{search:t});const n=[];let r=1;const o=20;let i=!0;for(;i&&r<=Mo;){const e=await this.dexBackendClient.fetchTokenList({...void 0!==t&&{search:t},page:r,limit:o});for(const t of e.token)n.push(this.transformRawTokenToDexToken(t));i=e.token.length===o,r++}return r>Mo&&this.logger.warn("Reached maximum page limit (20) while fetching available DEX tokens",{search:t,totalTokens:n.length}),this.logger.debug("Fetched all available DEX tokens",{search:t,totalTokens:n.length}),n}catch(t){this.handleGSwapError("Failed to fetch all available DEX tokens",ie,t,e)}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),o=[500,3e3,1e4];let i=new y(0),s=0;for(const a of o)try{const e="string"==typeof n?_o(n):n,t="string"==typeof r?_o(r):r,o=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});o&&(i=i.plus(new y(o.liquidity||0)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:i.toFixed(),feeTiers:o,swapCount:s}}catch(n){this.logger.warn("Failed to fetch pool info",n);const r=n;return this.logger.debug("Pool error details",{error:new oe(`Failed to fetch pool info: ${r?.message||String(n)}`,n,e,t,this.extractGSwapErrorCode(n))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const n=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;n.has(e)||n.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const r=Array.from(n.values()),o=this.chunkArray(r,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:o.length,concurrency:t});const i=new Map;for(let e=0;e<o.length;e++){const t=o[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?i.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return i}normalizePositionResponse(e,t){const n=e=>{if(!e)return"";if("string"==typeof e)return e;if("object"==typeof e){if(e.type&&"none"!==e.type)return e.type;if(e.collection)return e.collection;if(e.symbol)return e.symbol;if(e.tokenSymbol)return e.tokenSymbol;if(e.name)return e.name}return""},r=e.token0Symbol||n(e.token0)||n(e.tokenA)||e.tokenSymbol0||"",o=e.token1Symbol||n(e.token1)||n(e.tokenB)||e.tokenSymbol1||"",i=r?this.tokenConverter.toLaunchpadFormat(r):"",s=o?this.tokenConverter.toLaunchpadFormat(o):"";return{positionId:e.positionId||e.id||"",ownerAddress:t||e.ownerAddress||e.owner||"",token0:i,token1:s,feeTier:e.feeTier||e.fee||e.feeAmount||0,tickLower:e.tickLower||e.lowerTick||0,tickUpper:e.tickUpper||e.upperTick||0,liquidity:String(e.liquidity||e.liquidityAmount||"0"),amount0:String(e.amount0||e.amountA||"0"),amount1:String(e.amount1||e.amountB||"0"),feeAmount0:String(e.feeAmount0||e.feesA||"0"),feeAmount1:String(e.feeAmount1||e.feesB||"0"),...e.createdAt&&{createdAt:new Date(e.createdAt)},...e.updatedAt&&{updatedAt:new Date(e.updatedAt)}}}parseTokenFlexible(e){try{return _o(e)}catch(t){if(t instanceof Error&&t.message?.includes("Plain token string"))return this.logger.debug("Using default TokenClassKey for simple token symbol",{token:e}),{collection:"Token",category:"Unit",type:e,additionalKey:"none"};throw t}}transformRawTokenToDexToken(e){return{image:e.image,name:e.name,symbol:e.symbol,decimals:parseInt(e.decimals,10)||18,description:e.description,verified:e.verify,compositeKey:e.compositeKey,additionalKey:e.additionalKey,category:e.category,type:e.type,collection:e.collection,subscribePrice:e.subscribePrice}}transformRawTokenToUserAsset(e){const t=e.symbol||"UNKNOWN";try{const o=e.compositeKey?_o(e.compositeKey.replace(/\$/g,"|")):_o(`${t}|Unit|none|none`);return{...this.transformRawTokenToDexToken(e),tokenId:o,balance:(n=e.quantity||"0",void 0!==r?mr(n).toFixed(r):mr(n).toFixed())}}catch(e){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:e instanceof Error?e.message:String(e)}),null}var n,r}async getUserLiquidityPositions(t,n=10,r,o){try{this.logger.debug("Fetching user liquidity positions",{ownerAddress:t,limit:n,bookmark:r});const i=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,s={user:t,limit:n,bookmark:r||""};this.logger.debug("Sending position query request",{endpoint:i,payload:s});const a=await e.post(i,s,{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==a.status||1!==a.data?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:a.status,apiStatus:a.data?.Status}),{items:[]};const c=a.data.Data||{},u=c.positions||[],l=c.nextBookMark,h=u.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(e=>this.normalizePositionResponse(e,t));let d;this.logger.debug("Retrieved liquidity positions",{count:h.length,hasNextBookmark:!!l,nextBookmark:l}),o?.withPrices&&h.length>0&&(d=await this.fetchPositionPrices(h));const f={items:h};return void 0!==l&&(f.nextBookmark=l),void 0!==d&&(f.prices=d),f}catch(e){if(e&&"object"==typeof e&&"response"in e){const n=e;this.logger.error("Position query failed with HTTP error",{status:n.response?.status,statusText:n.response?.statusText,data:n.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:t})}this.handleGSwapError("Failed to fetch user liquidity positions",se,e)}}async getAllSwapUserLiquidityPositions(e,t){try{this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const n=async t=>{const n=await this.getUserLiquidityPositions(e,$o,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},r=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:o=20}=t,i=[];let s,a=0;for(;a<n;){r&&r.debug(`Auto-pagination (bookmark): fetching page ${a+1} with pageSize ${o}`,{bookmark:s});const t=await e(s,o);let n,c,u;if(Array.isArray(t))n=t,c=void 0,u=!1;else{if(!t||"object"!=typeof t||!("items"in t)){r&&r.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}n=t.items,c=t.nextBookmark,u=!0}if(!Array.isArray(n)){r&&r.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===n.length){r&&r.debug(`Auto-pagination (bookmark): no items returned on page ${a+1}, exiting loop`);break}i.push(...n),a++,r&&r.debug(`Auto-pagination (bookmark): page ${a} returned ${n.length} items`,{hasNextBookmark:!!c,format:u?"BookmarkPaginationResult":"legacy-array"});const l=n.length<o;if(u&&(""===c||void 0===c)){r&&r.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(l){r&&r.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:n.length,pageSize:o,format:u?"BookmarkPaginationResult":"legacy-array"});break}s=c}return a>=n&&r&&r.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${n}, stopping iteration`),r&&r.debug(`Auto-pagination (bookmark): completed with total items: ${i.length}`,{pageCount:a}),{items:i,total:i.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:$o}),o=r.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:o.length}),t?.withPrices&&o.length>0){return{items:o,prices:await this.fetchPositionPrices(o)}}return o}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",se,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1),o=Oo(n),i=Oo(r),s=(await this.gatewayClient.getPositions({owner:e,token0:o,token1:i,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new Error("Invalid position data returned from API");const a=this.normalizePositionResponse(s,e);return this.logger.debug("Retrieved liquidity position",{positionId:a.positionId}),a}catch(e){this.handleGSwapError("Failed to fetch liquidity position",se,e)}}async getLiquidityPositionById(e,t,n,r,o,i,s){try{let a;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:!!n,hasToken1:!!r,hasFee:!!o,hasTickLower:void 0!==i,hasTickUpper:void 0!==s});let c=null;const u=5,l=2e3;for(let h=1;h<=u;h++)try{if(n&&r&&void 0!==o&&void 0!==i&&void 0!==s)try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:n,token1:r,feeTier:o,tickLower:i,tickUpper:s});if(a=(await this.gatewayClient.getPositionById(e,n,r,o,i,s,t)).Data,a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position via compound key",{attempt:h,positionId:t});break}throw new Error("Invalid position data from compound key lookup")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:h,error:e instanceof Error?e.message:e})}try{if(a=(await this.gatewayClient.getPositionById(t)).Data,a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position on attempt",{attempt:h,positionId:t});break}throw new Error("Invalid position data from direct lookup")}catch(n){this.logger.debug("Direct position lookup failed, trying fallback via GetUserPositions",{attempt:h,positionId:t,error:n instanceof Error?n.message:n});const r=await this.getUserLiquidityPositions(e,10);if(Array.isArray(r.items)&&r.items.length>0){const e=r.items.find(e=>(e.positionId||e.id||"").toLowerCase()===t.toLowerCase());if(e){a=e,this.logger.debug("Found position via fallback (GetUserPositions)",{attempt:h,positionId:t});break}}if(c=new Error("Position not found in owner positions"),h<u){this.logger.warn("Fallback query did not find position, retrying",{attempt:h,positionId:t,ownerAddress:e,foundCount:Array.isArray(r?.items)?r.items.length:0}),await new Promise(e=>setTimeout(e,l));continue}}}catch(e){if(h<u){this.logger.warn("Error fetching position, retrying",{attempt:h,positionId:t,error:e instanceof Error?e.message:e}),await new Promise(e=>setTimeout(e,l));continue}c=e instanceof Error?e:new Error(String(e))}if(!a||"object"!=typeof a||!("positionId"in a)&&!("id"in a))throw this.logger.error("Invalid position data returned from API after retries",{positionId:t,resultType:typeof a,resultKeys:a?Object.keys(a):"null",resultValue:JSON.stringify(a),lastError:c?.message}),c||new Error("Invalid position data returned from API");const h=this.normalizePositionResponse(a,e);return this.logger.debug("Retrieved liquidity position by ID",{positionId:h.positionId}),h}catch(e){this.handleGSwapError("Failed to fetch liquidity position by ID",se,e)}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t="string"==typeof e.token0?this.parseTokenFlexible(e.token0):e.token0,n={token0:t,token1:"string"==typeof e.token1?this.parseTokenFlexible(e.token1):e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner},r=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetPositions`;this.logger.debug("Calling position endpoint via compound key",{url:r});const o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!o.ok){if(404===o.status)throw new Error("Position not found (HTTP 404): No position exists for this compound key");if(400===o.status)throw new Error("Invalid parameters (HTTP 400): Check token format, fee (500|3000|10000), and tick ranges");throw new Error(`HTTP ${o.status}: ${o.statusText}`)}const i=await o.json();if(1!==i.Status||!i.Data)throw new Error(`Position not found: ${i.Message||"API returned no position data"}`);const s=this.normalizePositionResponse(i.Data,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:s.positionId,token0:s.token0,token1:s.token1}),s}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",se,e)}}async estimateRemoveLiquidity(e){try{this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1,owner:e.owner}),this.validateTickSpacing(e.tickLower,e.tickUpper,e.fee);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1),r=Oo(t),o=Oo(n),i=await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:o,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});return this.logger.debug("Estimated removal",{result:i}),i}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",se,e)}}async addLiquidityByPrice(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected(),this.logger.debug("Converting price range to ticks",{token0:e.token0,token1:e.token1,minPrice:e.minPrice,maxPrice:e.maxPrice,fee:e.fee});const r=_o(t),o=_o(n),i=(await this.gatewayClient.getPoolData({token0:r,token1:o,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:i,fee:e.fee});const s=new y(e.minPrice),a=new y(e.maxPrice),c=Math.floor(wr(s)),u=Math.ceil(wr(a)),l=Math.floor(c/i)*i,h=Math.ceil(u/i)*i;this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:l,tickUpper:h,tickSpacing:i});const d=this.getWalletAddress();if(!d)throw new Error("GSwapService: No wallet address available - cannot create position");const f="string"==typeof e.token0?_o(e.token0):e.token0,p="string"==typeof e.token1?_o(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${l}-${h}`,walletAddress:d});const g=await this.sendAddLiquidityToBundler({token0:f,token1:p,fee:e.fee,tickLower:l,tickUpper:h,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:d}),m={transactionId:g};if(m.positionId&&g){this.logger.debug("Position ID returned directly from backend",{transactionId:g,positionId:m.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(g);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:g,status:e.status});const t=this.getWalletAddress();if(t&&m.positionId)try{const n=await this.getLiquidityPositionById(t,m.positionId),{createdAt:r,updatedAt:o,...i}=n,s=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,a={...m,...i,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(g)}};return void 0!==s&&(a.createdAt=s),a}catch(t){return{...m,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(g)}}}}if(g){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:g}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(g);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:g,status:t.status});let r=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");const o=(await this.getUserLiquidityPositions(t,10)).items;if(o&&o.length>0){const t=e.token0.split("|")[0].toUpperCase(),i=e.token1.split("|")[0].toUpperCase(),s=[];for(const n of o){if(!n||!n.positionId)continue;const r=n.token0?.toUpperCase(),o=n.token1?.toUpperCase();if(!r||!o)continue;const a=r===t&&o===i||r===i&&o===t,c=n.feeTier===e.fee;a&&c&&s.push(n)}s.length>0&&(r=s[s.length-1],n=r.positionId,this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:o.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}let o=r;if(n)try{o=await this.getLiquidityPositionById(d,n)}catch(e){}return{...m,...o,positionId:n,status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(g)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),m}catch(e){Error,this.handleGSwapError("Failed to add liquidity by price",se,e)}}async addSwapLiquidityByTicks(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");const t=this.getWalletAddress();if(!t)throw new Error("GSwapService: No wallet address available - cannot create position");this.logger.debug("Adding liquidity by ticks with direct bundler",{token0:e.token0,token1:e.token1,fee:e.fee,walletAddress:t,tickRange:`${e.tickLower}-${e.tickUpper}`});const n="string"==typeof e.token0?_o(e.token0):e.token0,r="string"==typeof e.token1?_o(e.token1):e.token1;await this.ensureWebSocketConnected();const o=await this.sendAddLiquidityToBundler({token0:n,token1:r,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:t});this.logger.info("Liquidity transaction submitted to bundler",{transactionId:o});const i=this.webSocketService.waitForTransaction(o),s={transactionId:o};if(s.positionId&&o){this.logger.info("Position ID returned directly from backend",{transactionId:o,positionId:s.positionId});const e=await i;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:o,status:e.status});const t=this.getWalletAddress();if(t&&s.positionId)try{this.logger.debug("Fetching full position details",{positionId:s.positionId});const n=await this.getLiquidityPositionById(t,s.positionId);this.logger.debug("Fetched full position data",{positionId:n.positionId,liquidity:n.liquidity,amount0:n.amount0,amount1:n.amount1});const{createdAt:r,updatedAt:i,...a}=n,c=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,u={...s,...a,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(o)}};return void 0!==c&&(u.createdAt=c),u}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:t instanceof Error?t.message:String(t)}),{...s,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(o)}}}}if(o){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:o});const n=await i;let r;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:o,status:n.status});let a=null;const c="string"==typeof e.token0?e.token0:e.token0?.type??"unknown",u="string"==typeof e.token1?e.token1:e.token1?.type??"unknown";this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:u,fee:e.fee});try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:$o});const n=3,o=5e3,i=3e3;let s=[];for(let c=1;c<=n;c++){const u=1===c?o:i;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:n,delayMs:u}),await new Promise(e=>setTimeout(e,u)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:$o});if(s=(await this.getUserLiquidityPositions(t,$o)).items,this.logger.debug("Got positions from API",{count:s?.length||0}),s&&s.length>0){const t=("string"==typeof e.token0?e.token0.split("|")[0]:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?e.token1.split("|")[0]:e.token1.collection).toUpperCase(),o=[];for(const r of s){if(!r||!r.positionId)continue;const i=r.token0?.toUpperCase(),s=r.token1?.toUpperCase();if(!i||!s){this.logger.debug("Skipping position with empty tokens",{positionId:r.positionId});continue}const a=i===t&&s===n||i===n&&s===t,c=r.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:r.positionId,tokens:`${i}/${s}`,tokensMatch:a,fee:r.feeTier,feeMatches:c}),a&&c&&o.push(r)}if(o.length>0){a=o[o.length-1],r=a.positionId,this.logger.info("Found newly created position",{positionId:r,liquidity:a.liquidity,amount0:a.amount0,amount1:a.amount1,fee:a.feeTier}),this.logger.debug("Found newly created position",{positionId:r,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:s.length});break}this.logger.debug("No matching position found in this attempt")}else this.logger.debug("No positions returned from API in this attempt")}}catch(e){this.logger.error("Error fetching positions during discovery",{error:e instanceof Error?e.message:String(e)}),this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}this.logger.debug("Position discovery complete",{positionId:r||"not found",found:!!r}),this.logger.debug("Matched position data",{positionId:a?.positionId,liquidity:a?.liquidity,amount0:a?.amount0,amount1:a?.amount1,feeAmount0:a?.feeAmount0,feeAmount1:a?.feeAmount1,token0:a?.token0,token1:a?.token1,feeTier:a?.feeTier});let l=a;if(r)try{this.logger.debug("Fetching full position details",{positionId:r}),l=await this.getLiquidityPositionById(t,r),this.logger.debug("Fetched full position data",{positionId:l.positionId,liquidity:l.liquidity,amount0:l.amount0,amount1:l.amount1,feeAmount0:l.feeAmount0,feeAmount1:l.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:r,error:e instanceof Error?e.message:String(e)})}return{...s,...l,positionId:r,status:n.status,transactionId:n.transactionId,timestamp:new Date(n.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(o)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),s}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",se,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let r;try{const o=await t;r={status:o.status,transactionId:o.transactionId||e,timestamp:o.timestamp||Date.now(),data:o.data},this.logger.debug(`${n} transaction confirmed on-chain`,{transactionId:e,status:r.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${n} transaction, returning result with transaction ID`,{transactionId:e,error:t instanceof Error?t.message:String(t)}),{transactionId:e,status:"SUBMITTED",timestamp:new Date,wait:async t=>{try{await this.webSocketService.waitForTransaction(e)}catch{this.logger.debug("Explicit wait also timed out",{transactionId:e})}}}}return{transactionId:r.transactionId,status:r.status,timestamp:new Date(r.timestamp),wait:async t=>{await this.webSocketService.waitForTransaction(e)}}}async removeLiquidity(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});try{const t=parseFloat(e.liquidity);if(isNaN(t))throw new Error(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${e.positionId||"unknown"}`);if(0===t)throw new Error(`Cannot remove zero liquidity from position. This would waste gas fees without any effect. Position ID: ${e.positionId||"unknown"}`)}catch(e){if(e instanceof Error&&e.message.includes("Cannot remove zero liquidity"))throw e;if(e instanceof Error&&e.message.includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?_o(e.token0):e.token0,n="string"==typeof e.token1?_o(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,n,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||"");this.logger.debug("Liquidity removal submitted to bundler",{transactionId:r});const o=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,o,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",se,e)}}async collectPositionFees(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");if(e.ownerAddress&&e.positionId&&!e.token0){this.logger.debug("Fetching position data before collecting fees",{ownerAddress:e.ownerAddress,positionId:e.positionId});const t=await this.getLiquidityPositionById(e.ownerAddress,e.positionId);if(!t)throw new Error(`Position ${e.positionId} not found for owner ${e.ownerAddress}`);if(!t.token0||!t.token1)throw new Error("Position missing token information");const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1);return this.collectPositionFees({token0:n,token1:r,fee:t.feeTier,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Requested:e.amount0Max||e.amount0Requested||"0",amount1Requested:e.amount1Max||e.amount1Requested||"0",positionId:e.positionId})}if(!e.token0||!e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper)throw new Error("Missing required parameters: token0, token1, fee, tickLower, tickUpper are required when not using ownerAddress pattern");this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0?.type??"unknown",token1:"string"==typeof e.token1?e.token1:e.token1?.type??"unknown",tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?_o(e.token0):e.token0,n="string"==typeof e.token1?_o(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendCollectPositionFeesToBundler(t,n,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||"");this.logger.debug("Fee collection submitted to bundler",{transactionId:r});const o=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,o,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",se,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:r,gswapToken1:o}=this.convertTokenPair(e,t),i=_o(r),s=_o(o),a=await this.gatewayClient.getPoolData({token0:i,token1:s,fee:n}),c=this.calculatePriceFromSqrtPriceX96(new y(a.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:n,liquidity:a.liquidity.toString(),sqrtPriceX96:a.sqrtPrice.toString(),tick:a.tick,feeGrowthGlobal0X128:a.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:a.feeGrowthGlobal1.toString(),currentPrice:c.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",oe,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const r=await this.getPoolData(e,t,n),o=mr(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:o.toFixed(),invertedPrice:br(o,!0),tick:r.tick,liquidity:r.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",oe,e)}}async calculateOptimalPositionSize(e,t,n,r,o,i,s){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:r,desiredAmount1:o});const a=(await this.getPoolData(e,t,n)).tick,c=w(i),u=w(a),l=w(s),h=b(new y(r),new y(o),c,u,l),d=k(h,u,c,l),f=d[0],p=d[1],g=new y(r),m=new y(o);return{amount0:f.toFixed(),amount1:p.toFixed(),liquidity:h.toFixed(),ratio:f.dividedBy(p).toFixed(),utilizationPercent:{amount0:f.dividedBy(g).multipliedBy(100).toFixed(2),amount1:p.dividedBy(m).multipliedBy(100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",se,e)}}async validatePositionParameters(e,t,n,r,o,i,s){const a=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:r,tickUpper:o});const u=[500,3e3,1e4];u.includes(n)||a.push(`Invalid fee tier: ${n}. Must be one of: ${u.join(", ")}`);const l=this.getTickSpacing(n);let h;r%l!==0&&a.push(`tickLower must be multiple of ${l}`),o%l!==0&&a.push(`tickUpper must be multiple of ${l}`),r>=o&&a.push(`tickLower (${r}) must be less than tickUpper (${o})`);try{h=await this.getPoolData(e,t,n)}catch{return a.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}const d=new y(i),f=new y(s);if(d.isNaN()||f.isNaN())a.push("Amounts must be valid numbers");else try{vr(d,f)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}const p=h.tick;(p<r||p>o)&&c.push("Position is out of current price range - will not earn fees until price moves into range");new y(h.liquidity||"0").lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const g=0===a.length?35e4:0;return{valid:0===a.length,errors:a,warnings:c,gasEstimate:g,tickSpacing:l,currentTick:p,poolLiquidity:h.liquidity}}catch(e){const t=e;return a.includes(t?.message||"")||a.push(`Validation failed: ${t?.message||String(e)}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}}async calculateTicksForPrice(e,t,n,r,o){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:r});const i=this.getTickSpacing(o),s=new y(n),a=new y(r);if(s.gte(a))throw new Error("minPrice must be less than maxPrice");const c=Math.floor(wr(s)),u=Math.ceil(wr(a)),l=Math.floor(c/i)*i,h=Math.ceil(u/i)*i,d=Math.pow(1.0001,l),f=Math.pow(1.0001,h),p=new y(d),g=new y(f);return{tokenA:e,tokenB:t,feeTier:o,tickLower:l,tickUpper:h,tickSpacing:i,requestedMinPrice:n,requestedMaxPrice:r,actualMinPrice:p.toFixed(8),actualMaxPrice:g.toFixed(8),priceDeviation:{minPriceDeviation:p.minus(s).dividedBy(s).multipliedBy(100).toFixed(4),maxPriceDeviation:g.minus(a).dividedBy(a).multipliedBy(100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",se,e)}}async calculatePriceForTicks(e,t,n,r){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:r});const o=Math.pow(1.0001,n),i=Math.pow(1.0001,r);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const a=new y(o),c=new y(i),u={tokenA:e,tokenB:t,tickLower:n,tickUpper:r,minPrice:a.toFixed(8),maxPrice:c.toFixed(8),priceRange:`${a.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:r-n};return void 0!==s&&(u.currentPrice=s),u}catch(e){this.handleGSwapError("Failed to calculate price for ticks",se,e)}}calculateExecutionPrice(e,t){try{const n=new y(e),r=new y(t);return n.isZero()?"0":r.dividedBy(n).toFixed()}catch{return"0"}}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw new Error(`Invalid fee tier: ${e}`)}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new Error(`Invalid tickLower: ${e} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`);if(t%r!==0)throw new Error(`Invalid tickUpper: ${t} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`)}calculatePriceFromSqrtPriceX96(e){try{const t=new y(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new y(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return new y(0)}}async getPoolSlot0(t,n,r){try{this.logger.debug("Fetching pool slot0 data",{token0:t,token1:n,fee:r});const o="string"==typeof t?_o(t):t,i="string"==typeof n?_o(n):n,s=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetSlot0`,a=await e.post(s,{token0:o,token1:i,fee:r},{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==a.status||1!==a.data?.Status)throw this.logger.warn("Unexpected GetSlot0 API response",{httpStatus:a.status,apiStatus:a.data?.Status}),new oe("GetSlot0 API returned unexpected status",{httpStatus:a.status,apiStatus:a.data?.Status});const c=a.data.Data||{},u={sqrtPrice:c.sqrtPrice||"0",tick:c.tick||0,liquidity:c.liquidity||"0",grossPoolLiquidity:c.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:u.sqrtPrice,tick:u.tick,liquidity:u.liquidity}),u}catch(e){this.handleGSwapError("Failed to fetch pool slot0 data",oe,e,{token0:t,token1:n,fee:r})}}async getPositionCurrentPrice(e){try{this.logger.debug("Fetching position current price",{token0:e.token0,token1:e.token1,feeTier:e.feeTier});const t=await this.getPoolSlot0(e.token0,e.token1,e.feeTier),n=new y(t.sqrtPrice),r={price:this.calculatePriceFromSqrtPriceDecimal(n).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:r.price,tick:r.tick}),r}catch(t){this.handleGSwapError("Failed to fetch position current price",oe,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,n){try{const r=yr(t),o=yr(n);return v(e,r,o)}catch{return new y(0)}}calculateLiquidityFromAmount1(e,t,n){try{const r=yr(t),o=yr(n);return E(e,r,o)}catch{return new y(0)}}calculateAmount0FromLiquidity(e,t,n){try{const r=yr(t),o=yr(n);return S(r,o,e)}catch{return new y(0)}}calculateAmount1FromLiquidity(e,t,n){try{const r=yr(t),o=yr(n);return A(r,o,e)}catch{return new y(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(n){if(!this.privateKey)throw new Error("GSwapService: AddLiquidity requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:n.token0?.type??"unknown",token1:n.token1?.type??"unknown",fee:n.fee,tickRange:`${n.tickLower}-${n.tickUpper}`});const r=`galaswap - operation - ${F()}-${Date.now()}-${n.owner}`,o={token0:n.token0,token1:n.token1,fee:n.fee,owner:n.owner,tickLower:n.tickLower,tickUpper:n.tickUpper,amount0Desired:n.amount0Desired,amount1Desired:n.amount1Desired,amount0Min:n.amount0Min,amount1Min:n.amount1Min,positionId:"",uniqueKey:r},i=new t.Wallet(this.privateKey),s={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},a={name:"ethereum",chainId:1},c=this.calculatePersonalSignPrefix(o),u={...o,prefix:c},l=await i.signTypedData(a,s,u),h={...u,signature:l,types:s,domain:a};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:h.signature?.substring(0,20)+"...",prefix:h.prefix,tickLower:o.tickLower,tickUpper:o.tickUpper});const d=this.buildLiquidityStringsInstructions(n.token0,n.token1,n.fee,n.owner),f=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),p=await f.post("/bundle",{method:"AddLiquidity",signedDto:h,stringsInstructions:d}),g=p.data?.data||p.data?.transactionId||p.data?.id;if(!g)throw this.logger.error("Bundler response structure",{status:p.status,data:p.data,dataType:typeof p.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(p.data)}`);return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:g}),g}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(n,r,o,i,s,a,c,u,l){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const h=new t.Wallet(this.privateKey),d=await h.getAddress(),f=`galaswap - operation - ${F()}-${Date.now()}-${d}`,p={tickLower:n,tickUpper:r,amount:o,token0:i,token1:s,fee:a,amount0Min:c,amount1Min:u,positionId:l,uniqueKey:f},g={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},b=await h.signTypedData(m,g,w),k={...w,signature:b,types:g,domain:m},v=this.buildLiquidityStringsInstructions(i,s,a,d);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:n,tickUpper:r,amount:o,fee:a,positionId:l,transactionId:f});const E=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),S=await E.post("/bundle",{method:"RemoveLiquidity",signedDto:k,stringsInstructions:v}),A=S.data?.data||S.data?.transactionId||S.data?.id;if(!A)throw this.logger.error("Bundler response structure",{status:S.status,data:S.data,dataType:typeof S.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(S.data)}`);return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:A}),A}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(n,r,o,i,s,a,c,u){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const l=new t.Wallet(this.privateKey),h=await l.getAddress(),d=`galaswap - operation - ${F()}-${Date.now()}-${h}`,f={token0:n,token1:r,fee:o,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:u,uniqueKey:d},p={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},g={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(f),y={...f,prefix:m},w=await l.signTypedData(g,p,y),b={...y,signature:w,types:p,domain:g},k=this.buildLiquidityStringsInstructions(n,r,o,h);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:o,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:u,transactionId:d});const v=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),E=await v.post("/bundle",{method:"CollectPositionFees",signedDto:b,stringsInstructions:k}),S=E.data?.data||E.data?.transactionId||E.data?.id;if(!S)throw this.logger.error("Bundler response structure",{status:E.status,data:E.data,dataType:typeof E.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(E.data)}`);return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:S}),S}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(n){if(!this.privateKey)throw new Error("GSwapService: Swap requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const r=[500,3e3,1e4];if(!r.includes(n.feeTier))throw new Error(`GSwapService: Invalid fee tier ${n.feeTier}. Must be one of: ${r.join(", ")} (basis points)`);try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof n.fromToken?n.fromToken:n.fromToken?.type??"unknown",toToken:"string"==typeof n.toToken?n.toToken:n.toToken?.type??"unknown",inputAmount:n.inputAmount,minOutput:n.minOutput,feeTier:n.feeTier});let r=n.fromToken,o=n.toToken;"string"==typeof r&&(r=_o(r)),"string"==typeof o&&(o=_o(o));const i=`${r.collection}|${r.category}|${r.type}|${r.additionalKey}`,s=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`,a=i<s?[r,o,i,s]:[o,r,s,i],[c,u,l,h]=a,d="string"==typeof n.fromToken?_o(n.fromToken):n.fromToken,f=`${d.collection}|${d.category}|${d.type}|${d.additionalKey}`,p=f===l,g=`galaswap - operation - ${F()}-${Date.now()}-${n.walletAddress}`;let m;if(!n.currentSqrtPrice)throw new Error("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation");const w=new y(n.currentSqrtPrice),b=n.slippageTolerance??.01;if(p){const e=new y(1).minus(b);m=w.multipliedBy(e).toString()}else{const e=new y(1).plus(b);m=w.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:n.currentSqrtPrice,slippageTolerance:100*b+"%",zeroForOne:p,sqrtPriceLimit:m,direction:p?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const k={token0:c,token1:u,fee:n.feeTier,amount:new y(n.inputAmount).toFixed(),zeroForOne:p,sqrtPriceLimit:m,recipient:n.walletAddress,amountOutMinimum:new y(n.minOutput).multipliedBy(-1).toFixed(),uniqueKey:g};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:l,orderedToken1String:h,fromTokenStr:f,zeroForOne:p?`TRUE (${l} → ${h})`:`FALSE (${h} → ${l})`,inputAmount:n.inputAmount,expectedOutput:n.minOutput,slippageTolerance:100*(n.slippageTolerance||.01)+"%",currentSqrtPrice:n.currentSqrtPrice,swapDto:{amount:k.amount,zeroForOne:k.zeroForOne,sqrtPriceLimit:k.sqrtPriceLimit,amountOutMinimum:k.amountOutMinimum}});const v=new t.Wallet(this.privateKey),E={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},S={name:"ethereum",chainId:1},A=this.calculatePersonalSignPrefix(k),T={...k,prefix:A},I=await v.signTypedData(S,E,T),B={...T,signature:I,types:E,domain:S};this.logger.debug("Swap DTO signed",{signature:B.signature?.substring(0,20)+"...",prefix:B.prefix,zeroForOne:k.zeroForOne});const x=this.buildLiquidityStringsInstructions(c,u,n.feeTier,n.walletAddress),C=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),P=await C.post("/bundle",{method:"Swap",signedDto:B,stringsInstructions:x}),N=P.data?.data||P.data?.transactionId||P.data?.id;if(!N)throw this.logger.error("Bundler response structure",{status:P.status,data:P.data,dataType:typeof P.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(P.data)}`);return this.logger.debug("Swap transaction sent to bundler",{transactionId:N,inputAmount:n.inputAmount,minOutput:n.minOutput}),N}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,r){const o=`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`,i=`$${t.collection}$${t.category}$${t.type}$${t.additionalKey}`,s=`$pool${o}${i}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${s}`,`$tokenBalance${i}${s}`]}handleGSwapError(e,t,n,r){this.logger.error(e,n);const o=this.extractGSwapErrorCode(n),i=n,s=[`${e}: ${i?.message||String(n)}`,n];throw r&&("GSwapSwapError"===t.name&&r.transactionHash&&s.push(r.transactionHash),"GSwapPoolError"===t.name&&(r.tokenA&&s.push(r.tokenA),r.tokenB&&s.push(r.tokenB)),"GSwapAssetError"===t.name&&r.walletAddress&&s.push(r.walletAddress)),o&&s.push(o),new t(...s)}extractGSwapErrorCode(e){if(e&&"object"==typeof e){const t=e;if(t.constructor&&"GSwapSDKError"===t.constructor.name)return t.code;if("code"in t&&"string"==typeof t.code)return t.code}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}}class Ko{}Ko.BASE_PRICE=1650667151e-14,Ko.PRICE_SCALING_FACTOR=1166069e-12,Ko.TRADING_FEE_FACTOR=.001,Ko.GAS_FEE="1",Ko.MIN_UNBONDING_FEE_FACTOR=0,Ko.MAX_UNBONDING_FEE_FACTOR=.5,Ko.NET_UNBONDING_FEE_FACTOR=.5,Ko.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class Go extends Gn{constructor(e=!1){super(e),this.cache=new Map}getLRUKey(){const e=this.cache.keys().next().value;return void 0!==e?e:null}normalizeTokenName(e){return e.trim().toLowerCase().replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=Go.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n||{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeTokenName(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeTokenName(e);this.updateCacheEntry(n,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),n=this.cache.get(t);return n?.maxSupply||Ko.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeTokenName(e);return this.cache.has(t)}clear(e){if(e){const t=this.normalizeTokenName(e);this.cache.delete(t)}else this.cache.clear()}dump(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let o=0;o+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(o+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(o+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(o+=8),o+=8,n.vaultAddress&&(o+=2*n.vaultAddress.length),n.maxSupply&&(o+=2*n.maxSupply.length),n.symbol&&(o+=2*n.symbol.length),o+=32,t+=o}),{totalTokens:this.cache.size,cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.get(t)||null}setByTokenId(e,t){const n=`token:${e.toLowerCase().trim()}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.has(t)}}Go.MAX_CACHE_SIZE=1e4;class Wo extends Kn{constructor(e,t,n=void 0,r=5,o=!1){super(e,o),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=n,this.pricingConcurrency=r}setGSwapService(e){this.gswapService=e}setPricingConcurrency(e){this.pricingConcurrency=Math.max(1,Math.min(e,20))}async enrichPoolsWithPricing(e){if(!this.gswapService)return this.logger.warn("GSwap service not available, skipping pricing enrichment"),e;if(0===e.length)return e;this.logger.debug("Starting pricing enrichment",{poolCount:e.length,concurrency:this.pricingConcurrency});const t=[];for(let n=0;n<e.length;n++){const r=e[n];t.push({poolIndex:n,token:r.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:r.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${r.token0}`,{error:e.message})})}),t.push({poolIndex:n,token:r.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:r.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${r.token1}`,{error:e.message})})})}const n=new Map;for(let t=0;t<e.length;t++)n.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const r=t.slice(e,e+this.pricingConcurrency),o=await Promise.allSettled(r.map(e=>e.task));for(let e=0;e<r.length;e++){const t=r[e],i=o[e],s=n.get(t.poolIndex)||{};"fulfilled"===i.status&&i.value&&(t.isToken0?s.token0Price=i.value:s.token1Price=i.value),n.set(t.poolIndex,s)}}const r=e.map((e,t)=>{const r=n.get(t)||{},o={...e};return void 0!==r.token0Price&&(o.token0Price=r.token0Price),void 0!==r.token1Price&&(o.token1Price=r.token1Price),o}),o=r.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:o,failed:e.length-o}),r}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:r="desc",page:o=$n.DEFAULT_PAGE,limit:i=$n.DEFAULT_LIMIT,withPrices:s=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:r,page:o,limit:i,withPrices:s});const a=new URLSearchParams({page:o.toString(),limit:Math.min(i,20).toString(),sortBy:n,sortOrder:r});t&&a.append("search",t);const c=`${this.dexBackendBaseUrl}/explore/pools?${a}`;try{const e=await this.http.get(c);if(!e||!e.data)throw new Error("No response from DEX pool service");let t=e.data.pools;const n=e.data.count,r=Math.min(i,20),a=Math.ceil(n/r);return s&&(t=await this.enrichPoolsWithPricing(t)),this.logger.debug("DEX pools fetched successfully",{poolCount:t.length,total:n,totalPages:a,withPrices:s}),{pools:t,page:o,limit:r,total:n,totalPages:a,hasNext:o<a,hasPrevious:o>1}}catch(e){throw this.logger.error("Failed to fetch DEX pools",{error:e,url:c}),e}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=await Co((t,n)=>this.fetchDexPools({...e,page:t,limit:n}).then(e=>({items:e.pools,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:20});this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.items.length,totalCount:t.total,withPrices:e.withPrices});return Po(t.items,t.total,"pools")}}const zo=5;class jo extends Kn{constructor(e,t,n=!1,r=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=r}validateFetchCompositePoolDataInput(e,t,n){if(!e||"string"!=typeof e)throw new ae("token0 must be a non-empty string",{token0:e});if(!t||"string"!=typeof t)throw new ae("token1 must be a non-empty string",{token1:t});const r=e.split("|"),o=t.split("|");if(4!==r.length)throw new ae("token0 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token0:e});if(4!==o.length)throw new ae("token1 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token1:t});const i=[500,3e3,1e4];if(!Number.isInteger(n)||!i.includes(n))throw new ae(`fee must be one of: ${i.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!e||"string"!=typeof e)throw new ae("amount must be a non-empty string",{amount:e});const t=new y(e);try{Er(t,"amount","for quote calculation")}catch(t){throw new ae(t.message,{amount:e})}}convertTokenClassKey(e){const t=new U;return t.collection=e.collection,t.category=e.category,t.type=e.type,t.additionalKey=e.additionalKey,t}setCompositePoolFetchConcurrency(e){this.compositePoolFetchConcurrency=Math.max(1,Math.min(e,20)),this.logger.debug(`Composite pool fetch concurrency set to ${this.compositePoolFetchConcurrency}`)}async fetchCompositePoolData(e){const{token0:t,token1:n,fee:r,gatewayBaseUrl:o}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:r}),this.validateFetchCompositePoolDataInput(t,n,r);try{const e=Oo(t),i=Oo(n),s=this.convertTokenClassKey(e),a=this.convertTokenClassKey(i),c=new x(s,a,r),u=`${o||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,l=await this.http.post(u,c);if(!l||1!==l.Status)throw new ce(`Pool not found: ${t}/${n} with fee ${r}`);const h=function(e){return{pool:e.pool,tickDataMap:e.tickDataMap,token0Balance:e.token0Balance,token1Balance:e.token1Balance,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals,compositePoolDto:e}}(function(e){const t=new T(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,new y(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=new y(e.pool.grossPoolLiquidity),t.liquidity=new y(e.pool.liquidity),t.feeGrowthGlobal0=new y(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=new y(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=new y(e.pool.protocolFeesToken0),t.protocolFeesToken1=new y(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=new y(e.pool.maxLiquidityPerTick);const n={};Object.keys(e.tickDataMap).forEach(t=>{const r=e.tickDataMap[t],o=new I(r.poolHash,r.tick);o.initialised=r.initialised,o.liquidityNet=new y(r.liquidityNet),o.liquidityGross=new y(r.liquidityGross),o.feeGrowthOutside0=new y(r.feeGrowthOutside0),o.feeGrowthOutside1=new y(r.feeGrowthOutside1),n[t]=o});const r={...e.token0Balance},o=new D(r);o.quantity=new y(e.token0Balance.quantity);const i={...e.token1Balance},s=new D(i);return s.quantity=new y(e.token1Balance.quantity),new B(t,n,o,s,e.token0Decimals,e.token1Decimals)}(l.Data),l.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:r,liquidity:h.pool.liquidity.toString()}),h}catch(e){if(e instanceof ce)throw e;const o=e instanceof Error?e.message:String(e);throw this.logger.error("Failed to fetch composite pool data",e),new ae(`Failed to fetch composite pool data: ${o}`,{token0:t,token1:n,fee:r})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:o}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:r,amount:o}),this.validateQuoteAmount(o),!t)throw new ae("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),i=Oo(n),s=Oo(r),a=this.convertTokenClassKey(i),c=this.convertTokenClassKey(s),[u,l]=n<r?[a,c]:[c,a],h=new C(u,l,t.pool.fee,new y(o),e,t.compositePoolDto),d=await P(void 0,h);return this.logger.debug("Local quote calculated",{amount0:d.amount0,amount1:d.amount1}),{amount0:d.amount0.toString(),amount1:d.amount1.toString(),currentSqrtPrice:d.currentSqrtPrice.toString(),newSqrtPrice:d.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("Local quote calculation failed",e),new ae(`Local quote calculation failed: ${t}`,{fromToken:n,toToken:r,amount:o})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:o}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:r,amount:o}),this.validateQuoteAmount(o),!t)throw new ae("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),i=Oo(n),s=Oo(r),a=this.convertTokenClassKey(i),c=this.convertTokenClassKey(s),u=new C(a,c,t.pool.fee,new y(o),e,void 0),l=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,h=await this.http.post(l,u);if(!h||1!==h.Status)throw new ae("External quote failed: "+(h?.Message||"Unknown error"));const d=h.Data;return this.logger.debug("External quote calculated",{amount0:d.amount0,amount1:d.amount1}),{amount0:d.amount0.toString(),amount1:d.amount1.toString(),currentSqrtPrice:d.currentSqrtPrice.toString(),newSqrtPrice:d.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("External quote calculation failed",e),new ae(`External quote calculation failed: ${t}`,{fromToken:n,toToken:r,amount:o})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class Ho{constructor(){this.eventLatencies=[],this.maxLatencySamples=1e4,this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.perPoolMetrics=new Map,this.memorySnapshots=[],this.maxMemorySnapshots=100,this.recordMemory()}recordEventLatency(e){this.eventLatencies.push(e),this.eventLatencies.length>this.maxLatencySamples&&this.eventLatencies.shift(),this.eventsProcessed++,this.lastEventTime=new Date}recordEventDropped(){this.eventsDropped++}updateQueueDepth(e){this.queueDepth=e,this.maxQueueDepth=Math.max(this.maxQueueDepth,e)}recordPoolCacheHit(e,t){const n=this.getPoolMetrics(e);n.cacheHits++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}recordPoolCacheMiss(e,t){const n=this.getPoolMetrics(e);n.cacheMisses++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}getLatencyPercentiles(){if(0===this.eventLatencies.length)return{p50:0,p95:0,p99:0};const e=[...this.eventLatencies].sort((e,t)=>e-t),t=Math.floor(.5*e.length),n=Math.floor(.95*e.length),r=Math.floor(.99*e.length);return{p50:e[t]??0,p95:e[n]??0,p99:e[r]??0}}getCacheHitRate(){if(0===this.eventsProcessed)return 0;let e=0;for(const t of this.perPoolMetrics.values())e+=t.cacheHits;return e/this.eventsProcessed*100}getThroughputPerSecond(){const e=(Date.now()-this.startTime)/1e3;return 0===e?0:this.eventsProcessed/e}recordMemory(){if("undefined"!=typeof process&&process.memoryUsage){const e=process.memoryUsage().heapUsed/1024/1024;this.memorySnapshots.push(e),this.memorySnapshots.length>this.maxMemorySnapshots&&this.memorySnapshots.shift()}}getMemoryUsedMB(){return"undefined"!=typeof process&&process.memoryUsage?process.memoryUsage().heapUsed/1024/1024:0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?t.totalLatency/t.eventsProcessed:0}getPoolCacheHitRate(e){const t=this.perPoolMetrics.get(e);if(!t)return 0;const n=t.cacheHits+t.cacheMisses;return 0===n?0:t.cacheHits/n*100}getHealthMetrics(e,t,n,r,o){const i=this.getLatencyPercentiles(),s=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:i.p50,latencyP95:i.p95,latencyP99:i.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:Math.round(10*s)/10,maxMB:o,percentUsed:Math.round(s/o*1e3)/10},pools:{totalMonitored:e,hotCacheSize:t,warmCacheSize:n,coldCacheSize:r}}}reset(){this.eventLatencies=[],this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.lastEventTime=void 0,this.perPoolMetrics.clear(),this.memorySnapshots=[]}getSummary(){const e=this.eventLatencies.length>0?this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length:0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:Math.round(e),memoryUsedMB:Math.round(10*this.getMemoryUsedMB())/10,throughputPerSecond:Math.round(100*this.getThroughputPerSecond())/100}}getPoolMetrics(e){let t=this.perPoolMetrics.get(e);return t||(t={eventsProcessed:0,totalLatency:0,cacheHits:0,cacheMisses:0},this.perPoolMetrics.set(e,t)),t}}class Vo{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!e||"string"!=typeof e)return null;const t=e.split("/");if(3!==t.length)return null;const n=t[0]?.trim(),r=t[1]?.trim(),o=t[2]?.trim();if(!n||!r||!o)return null;const i=Number.parseInt(o,10);return Number.isNaN(i)?null:{token0:n,token1:r,feeTier:i}}static isValidPoolKey(e){if("string"!=typeof e)return!1;return null!==this.parsePoolKey(e)}static getToken0(e){const t=this.parsePoolKey(e);return t?.token0??null}static getToken1(e){const t=this.parsePoolKey(e);return t?.token1??null}static getFeeTier(e){const t=this.parsePoolKey(e);return t?.feeTier??null}static containsToken(e,t){const n=this.parsePoolKey(e);return!!n&&(n.token0===t||n.token1===t)}static containsTokenPair(e,t,n){const r=this.parsePoolKey(e);if(!r)return!1;const o=r.token0===t||r.token1===t,i=r.token0===n||r.token1===n;return o&&i&&t!==n}static normalizeFee(e){if(null==e)return null;const t="number"==typeof e?e:Number.parseFloat(String(e).replace("%","").trim());return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)&&t>0?t:null}static formatFeeAsPercentage(e){return`${(e/1e4).toFixed(2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class Xo{constructor(e){this.logger=e||new H({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const n=[],r=new WeakSet,o=(e,i=0)=>{if(i>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(r.has(e))return;r.add(e);const s=this.extractSwapFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))o(t,i+1)}};return o(e,0),n}extractSwapFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const n=e.Data,r=n&&"object"==typeof n&&!Array.isArray(n)?n:e,o=this.extractToken(r,"token0","fromToken","source"),i=this.extractToken(r,"token1","toToken","destination");if(!o||!i)return null;const s=this.extractAmount(r,"amount0","amountIn","inputAmount"),a=this.extractAmount(r,"amount1","amountOut","outputAmount");if(!s||!a)return null;const c=this.extractFeeTier(r);if(null===c)return null;const u=this.extractTimestamp(r),l=this.buildPoolKey(o,i,c),h=this.determineDirection(r,o,i),d={transactionId:t,poolKey:l,token0:o,token1:i,amount0:s,amount1:a,feeTier:c,direction:h,timestamp:u,exactInput:this.determineExactInput(r,h)},f=this.extractUser(r);return void 0!==f&&(d.user=f),d}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractAmount(e,...t){for(const n of t){const t=e[n];if(null!=t){const e=String(t).trim();if(/^-?\d+(\.\d+)?([eE]-?\d+)?$/.test(e))return e}}return null}extractFeeTier(e){const t=["poolFee","feeTier","fee","feeTierBps","liquidityFeeBps","feeAmount"];for(const n of t){const t=e[n],r=this.normalizeFee(t);if(null!==r)return r}return null}normalizeFee(e){if(null==e)return null;const t="number"==typeof e?e:Number.parseFloat(String(e).replace("%","").trim());return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)?t:null}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if("string"==typeof t){const e=new Date(t).getTime();if(!Number.isNaN(e))return e}}return Date.now()}extractUser(e){const t=["userAddress","user","from","sender","wallet","address"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}}determineDirection(e,t,n){const r=e.zeroForOne||e.direction;if("boolean"==typeof r)return r?"zeroForOne":"oneForZero";if("string"==typeof r){if("zerotoone"===r.toLowerCase()||"0to1"===r)return"zeroForOne";if("onetozero"===r.toLowerCase()||"1to0"===r)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===n||e.inputToken===n)return"oneForZero";const o=this.extractAmount(e,"amount0","amountIn");return o&&Number(o),"zeroForOne"}determineExactInput(e,t){if("boolean"==typeof e.exactInput)return e.exactInput;if("boolean"==typeof e.exactOutput)return!e.exactOutput;const n=void 0!==e.amountIn&&null!==e.amountIn,r=void 0!==e.amountOut&&null!==e.amountOut,o=void 0!==e.inputAmount&&null!==e.inputAmount,i=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!n||r)||!(r&&!n)&&(!(!o||i)||!(i&&!o))}buildPoolKey(e,t,n){return`${e}/${t}/${n}`}}class Qo{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,new y(e)),this.CACHE.get(t)}static clearCache(){this.CACHE.clear()}static getCacheStats(){return{size:this.CACHE.size,entries:Array.from(this.CACHE.keys())}}static trimCache(e=1e3){if(this.CACHE.size>e){const t=this.CACHE.size-e,n=Array.from(this.CACHE.keys());for(let e=0;e<t;e++)this.CACHE.delete(n[e])}}}Qo.CACHE=new Map,Qo.ZERO=new y(0),Qo.ONE=new y(1),Qo.FEE_PIPS=new y(1e6),Qo.MIN_SQRT_RATIO=new y("4295128739"),Qo.MAX_SQRT_RATIO=new y("1461446703485210103287273052203988822378723970342");const Zo={maxIterations:100,enableBigNumberCache:!0,roundingMode:y.ROUND_DOWN,debugLogging:!1};class Yo{static calculateSwapDelta(e,t,n={}){const r=Date.now(),o={...Zo,...n};try{const n=this.initializeSwapState(e,t,o);o.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const i=this.computeSwapLoop(n,e,t,o);o.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:i.stepCount,ticksCrossed:i.ticksCrossed.length,priceHitLimit:i.priceHitLimit});const s=this.createUpdatedPool(e.pool,i.state,t,o),a=this.calculateFinalAmounts(n,i.state,t);let c;if(t.actualSqrtPrice){const e=new y(s.sqrtPrice),n=new y(t.actualSqrtPrice);c=e.minus(n).abs().div(n).times(100).toNumber()}const u=Date.now()-r;o.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:u,amount0:a.amount0.toString(),amount1:a.amount1.toString(),driftPercentage:c}),u>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:u,stepCount:i.stepCount,ticksCrossed:i.ticksCrossed.length}),i.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:i.stepCount}),i.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:i.stepCount,ticksCrossed:i.ticksCrossed.length});return{updatedPool:s,updatedTicks:i.updatedTicks,amount0:a.amount0,amount1:a.amount1,feeAmount0:a.feeAmount0,feeAmount1:a.feeAmount1,ticksCrossed:i.ticksCrossed,metadata:{calculationTimeMs:u,swapSteps:i.stepCount,priceHitLimit:i.priceHitLimit,...void 0!==c&&{driftPercentage:c}}}}catch(e){this.logger.error("Swap delta calculation failed",e);const t=e instanceof Error?e.message:String(e);throw new Error(`Swap delta calculation failed: ${t}`)}}static initializeSwapState(e,t,n){const{pool:r}=e;if(!r.sqrtPrice||!r.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const o=n.enableBigNumberCache?Qo.getCached.bind(Qo):e=>new y(e),i="string"==typeof r.sqrtPrice?r.sqrtPrice:new y(r.sqrtPrice).toFixed(0),s="string"==typeof r.liquidity?r.liquidity:new y(r.liquidity).toFixed(0),a=o(i),c=o(s),u=r.tick??0,l=N(new y(i)),h=Math.abs(l-u);h>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:u,calculatedTick:l,drift:h,threshold:100});const d=o(t.amountSpecified);Er(d,"amountSpecified","for swap operation");const f="string"==typeof r.feeGrowthGlobal1?r.feeGrowthGlobal1:new y(r.feeGrowthGlobal1).toFixed(0),p="string"==typeof r.feeGrowthGlobal0?r.feeGrowthGlobal0:new y(r.feeGrowthGlobal0).toFixed(0),g=t.zeroForOne?o(f):o(p);return{sqrtPrice:a,liquidity:c,tick:u,amountSpecifiedRemaining:d,amountCalculated:Qo.ZERO,feeGrowthGlobalX:g,protocolFee:Qo.ZERO}}static computeSwapLoop(e,t,n,r){const{pool:o,tickDataMap:i}=t,s=[],a={};let c=0;const u=n.zeroForOne?Qo.MIN_SQRT_RATIO:Qo.MAX_SQRT_RATIO,l=new y("0.000001");for(;e.amountSpecifiedRemaining.gt(l)&&!e.sqrtPrice.eq(u)&&c<r.maxIterations;){c++;const[t,l]=this.findNextInitializedTick(i,e.tick,o.tickSpacing,n.zeroForOne);let h;if(r.debugLogging&&this.logger.debug(`Swap step ${c}`,{currentTick:e.tick,tickNext:t,initialized:l,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),l&&t>=-887272&&t<=887272){const e=w(t);h=e instanceof y?e:new y(String(e))}else h=u;const d=n.zeroForOne?y.max(h,u):y.min(h,u),f=this.executeSwapStep(e.sqrtPrice,d,e.liquidity,e.amountSpecifiedRemaining,o.fee,n.exactInput);if(e.sqrtPrice=f.sqrtPriceNext,n.exactInput){const t=f.amountIn.plus(f.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=Qo.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=Qo.ZERO)),e.amountCalculated=e.amountCalculated.minus(f.amountOut)}else{f.amountOut.lte(0)?e.amountSpecifiedRemaining=Qo.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(f.amountOut),e.amountCalculated=e.amountCalculated.plus(f.amountIn.plus(f.feeAmount))}if(e.liquidity.gt(0)){const t=f.feeAmount.div(e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(h)&&l){const o=i[t.toString()];if(!o)throw new Error(`Missing tick data for initialized tick ${t}`);const c=n.zeroForOne?new y(o.liquidityNet).negated():new y(o.liquidityNet);if(e.liquidity=e.liquidity.plus(c),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);s.push(t),a[t.toString()]=o,r.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:c.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(h))e.tick=n.zeroForOne?t-1:t;else{const t=N(new y(e.sqrtPrice.toString()));e.tick=t}}if(c>=r.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${r.maxIterations}). Possible infinite loop or very complex swap.`);const h=e.sqrtPrice.eq(u);return{state:e,ticksCrossed:s,priceHitLimit:h,stepCount:c,updatedTicks:a}}static createUpdatedPool(e,t,n,r){const o=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(o.sqrtPrice=t.sqrtPrice.toFixed(0),o.liquidity=t.liquidity.toFixed(0),o.tick=t.tick,n.zeroForOne?o.feeGrowthGlobal1=t.feeGrowthGlobalX.toFixed(0):o.feeGrowthGlobal0=t.feeGrowthGlobalX.toFixed(0),n.zeroForOne){const n=new y(e.protocolFeesToken0);o.protocolFeesToken0=n.plus(t.protocolFee).toFixed(0)}else{const n=new y(e.protocolFeesToken1);o.protocolFeesToken1=n.plus(t.protocolFee).toFixed(0)}return o}static calculateFinalAmounts(e,t,n){let r,o,i,s;if(n.exactInput){const e=new y(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=e.negated(),o=a,i=Qo.ZERO,s=Qo.ZERO):(r=a,o=e.negated(),i=Qo.ZERO,s=Qo.ZERO)}else{const e=new y(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=a.negated(),o=e,i=Qo.ZERO,s=Qo.ZERO):(r=e,o=a.negated(),i=Qo.ZERO,s=Qo.ZERO)}const a=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?s=a:i=a,{amount0:r,amount1:o,feeAmount0:i,feeAmount1:s}}static findNextInitializedTick(e,t,n,r){const o=Object.keys(e).map(e=>parseInt(e,10)).sort((e,t)=>e-t);if(0===o.length){return[r?-887272:887272,!1]}if(r){const e=o.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=o.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,r,o,i){vr(n),Er(r,"amountRemaining","for swap step");const s=[500,3e3,1e4];if(!s.includes(o))throw new Error(`Invalid fee tier: ${o}. Must be one of: ${s.join(", ")}`);const a=_(e,t,n,r,o,t.lt(e)),c=a[0],u=a[1],l=a[2],h=a[3],d=y.isBigNumber(c)?c:new y(String(c)),f=y.isBigNumber(u)?u:new y(String(u)),p=y.isBigNumber(l)?l:new y(String(l)),g=y.isBigNumber(h)?h:new y(String(h));return{sqrtPriceStart:e,tickNext:N(d),sqrtPriceNext:d,initialised:!1,amountIn:f,amountOut:p,feeAmount:g}}}Yo.logger=new H({debug:!1,context:"SwapDeltaCalculator"});class Jo{constructor(e,t,n,r){this.cache=new Map,this.tierSizes={hot:50,warm:200,cold:0},this.tierTTLs={hot:1/0,warm:18e5,cold:3e5},this.refetchThresholds={swapCount:50,driftPercent:.05},this.fetchPoolFn=e,this.config=t,this.metrics=n,this.logger=r||new H({debug:!1,context:"PoolCacheManager"}),this.tierSizes.cold=Math.max(0,this.config.maxPools-this.tierSizes.hot-this.tierSizes.warm),this.logger.debug(`Initialized with cache limits: hot=${this.tierSizes.hot}, warm=${this.tierSizes.warm}, cold=${this.tierSizes.cold}, max=${this.config.maxPools}`)}async getPool(e){const t=this.cache.get(e);if(t){if(!(Date.now()>t.expiresAt))return t.lastAccessTime=Date.now(),this.checkRefetchNeeded(e,t),this.metrics.recordPoolCacheHit(e,0),t.poolData;this.cache.delete(e),this.logger.debug(`Cache expired for pool ${e}`)}this.metrics.recordPoolCacheMiss(e,0);try{const t=await this.fetchPoolFn(e),n=this.determineTier(),r={poolData:t,tier:n,lastAccessTime:Date.now(),expiresAt:Date.now()+this.tierTTLs[n],swapsSinceRefetch:0,cumulativeDrift:0,lastDeltaAppliedTime:Date.now()};return this.cache.set(e,r),this.cache.size>this.config.maxPools&&this.evictLRU(),this.logger.debug(`Fetched pool ${e} (tier: ${n})`),t}catch(t){throw this.logger.error(`Failed to fetch pool ${e}:`,t),t}}updatePoolWithSwapDelta(e,t,n,r,o){const i=this.cache.get(e);if(!i)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(o){const s="zeroForOne"===t,a=s?n:r,c={transactionId:o.transactionId,timestamp:o.timestamp,amountSpecified:a,zeroForOne:s,exactInput:o.exactInput},u=Yo.calculateSwapDelta(i.poolData,c);i.poolData={...i.poolData,pool:u.updatedPool},i.swapsSinceRefetch++,i.lastDeltaAppliedTime=Date.now(),void 0!==u.metadata.driftPercentage?(i.cumulativeDrift+=u.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${u.metadata.driftPercentage.toFixed(4)}%, cumulative=${i.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${u.ticksCrossed.length} ticks crossed`)}else i.swapsSinceRefetch++,i.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(i)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${i.swapsSinceRefetch}, drift=${(100*i.cumulativeDrift).toFixed(2)}%`),i.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),i.expiresAt=Date.now(),!1}}getStats(){const e={totalCached:this.cache.size,hotCacheSize:0,warmCacheSize:0,coldCacheSize:0,memoryUsedMB:this.metrics.getMemoryUsedMB()};for(const t of this.cache.values())"hot"===t.tier?e.hotCacheSize++:"warm"===t.tier?e.warmCacheSize++:e.coldCacheSize++;return e}getPoolInfo(e){const t=this.cache.get(e);return t?{poolKey:e,tier:t.tier,lastAccessTime:new Date(t.lastAccessTime),expiresAt:new Date(t.expiresAt),swapsSinceRefetch:t.swapsSinceRefetch,cumulativeDrift:t.cumulativeDrift,isExpired:Date.now()>t.expiresAt}:null}async warmCache(e){if(this.cache.has(e))return!0;try{return await this.getPool(e),this.logger.debug(`Cache warmed for ${e}`),!0}catch(t){return this.logger.error(`Failed to warm cache for ${e}:`,t),!1}}async warmCacheBatch(e,t=5){const n={succeeded:0,failed:0,total:e.length};let r=0;const o=new Set;for(;r<e.length||o.size>0;){for(;r<e.length&&o.size<t;){const t=e[r];r++;const i=this.warmCache(t).then(e=>{e?n.succeeded++:n.failed++});o.add(i),i.finally(()=>o.delete(i))}o.size>0&&await Promise.race(o)}return this.logger.debug(`Cache warming complete: ${n.succeeded}/${n.total} succeeded`),n}clear(){this.cache.clear(),this.logger.debug("Cache cleared")}clearExpired(){const e=Date.now();let t=0;for(const[n,r]of this.cache)e>r.expiresAt&&(this.cache.delete(n),t++);t>0&&this.logger.debug(`Cleared ${t} expired entries`)}determineTier(){const e=Array.from(this.cache.values()).filter(e=>"hot"===e.tier).length,t=Array.from(this.cache.values()).filter(e=>"warm"===e.tier).length;return e<this.tierSizes.hot?"hot":t<this.tierSizes.warm?"warm":"cold"}checkRefetchNeeded(e,t){this.shouldRefetch(t)&&(this.logger.debug(`Scheduling refetch for ${e}: swaps=${t.swapsSinceRefetch}, drift=${(100*t.cumulativeDrift).toFixed(2)}%`),t.expiresAt=Date.now())}shouldRefetch(e){return e.swapsSinceRefetch>=this.refetchThresholds.swapCount||e.cumulativeDrift>=this.refetchThresholds.driftPercent}evictLRU(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"cold"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(0===e.length){this.logger.warn("No cold cache entries to evict, trying warm cache");const e=Array.from(this.cache.entries()).filter(([e,t])=>"warm"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(e.length>0){const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted warm cache entry: ${t}`)}return}const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted cold cache entry: ${t}`)}async refreshWarmAndHotTiers(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"hot"===t.tier||"warm"===t.tier).sort((e,t)=>t[1].lastAccessTime-e[1].lastAccessTime).slice(0,10);if(0===e.length)return;const t=e.map(([e,t])=>this.fetchPoolFn(e).then(n=>{t&&(t.poolData=n,t.lastAccessTime=Date.now(),t.swapsSinceRefetch=0,t.cumulativeDrift=0),this.logger.debug(`Refreshed ${e} during background warming`)}).catch(t=>{this.logger.debug(`Failed to refresh ${e} during background warming:`,t)})),n=new Promise(e=>setTimeout(()=>e(),5e3));await Promise.race([Promise.all(t),n])}}class ei{constructor(e,t,n){this.queue=[],this.isShuttingDown=!1,this.currentConcurrency=0,this.maxConcurrencyReached=0,this.eventsDropped=0,this.totalBatchesProcessed=0,this.totalBatchSize=0,this.eventsProcessedCount=0,this.processor=null,this.processingScheduled=!1,this.scheduleProcessing=e=>{"undefined"!=typeof setImmediate?setImmediate(e):Promise.resolve().then(e)},this.config=e,this.metrics=t,this.logger=n||new H({debug:!1,context:"SwapEventQueue"}),this.logger.debug(`Initialized with maxQueueSize=${this.config.maxQueueSize}, batchSize=${this.config.batchSize}, maxConcurrent=${this.config.maxConcurrent}`)}setProcessor(e){this.processor=e}enqueue(e){return this.isShuttingDown?(this.logger.debug(`Rejecting event (queue shutting down): ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):this.queue.length>=this.config.maxQueueSize?(this.logger.warn(`Queue full (${this.queue.length}/${this.config.maxQueueSize}), dropping event: ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):(this.queue.push(e),this.metrics.updateQueueDepth(this.queue.length),this.processingScheduled||this.isShuttingDown||(this.processingScheduled=!0,this.scheduleProcessing(()=>this.processNextBatch())),!0)}getQueueSize(){return this.queue.length}getStats(){return{queueSize:this.queue.length,eventsProcessed:this.eventsProcessedCount,eventsDropped:this.eventsDropped,currentConcurrent:this.currentConcurrency,maxConcurrentReached:this.maxConcurrencyReached,averageBatchSize:this.totalBatchesProcessed>0?Math.floor(this.totalBatchSize/this.totalBatchesProcessed):0,totalBatchesProcessed:this.totalBatchesProcessed}}async waitForEmpty(e){return new Promise(t=>{const n=()=>{0!==this.queue.length||0!==this.currentConcurrency?setTimeout(n,10):t()};e&&setTimeout(()=>t(),e),n()})}async shutdown(e=3e4){this.isShuttingDown=!0,this.logger.debug("Shutting down queue...");const t=Date.now();for(;this.queue.length>0||this.currentConcurrency>0;){if(Date.now()-t>e){this.logger.warn(`Queue shutdown timeout: ${this.queue.length} events remaining, ${this.currentConcurrency} processing`);break}await new Promise(e=>setTimeout(e,50))}this.logger.debug("Queue shutdown complete")}clear(){const e=this.queue.length;this.queue.length=0,this.eventsDropped+=e,this.metrics.updateQueueDepth(0),this.logger.warn(`Cleared ${e} events from queue`)}async processNextBatch(){if(this.processingScheduled=!1,this.isShuttingDown&&0===this.queue.length)return;if(this.currentConcurrency>=this.config.maxConcurrent)return void setTimeout(()=>{this.processingScheduled||(this.processingScheduled=!0,setImmediate(()=>this.processNextBatch()))},10);const e=Math.min(this.config.batchSize,this.queue.length,this.config.maxConcurrent-this.currentConcurrency);if(0===e)return;const t=this.queue.splice(0,e);this.metrics.updateQueueDepth(this.queue.length),this.currentConcurrency+=t.length,this.currentConcurrency>this.maxConcurrencyReached&&(this.maxConcurrencyReached=this.currentConcurrency),this.totalBatchSize+=t.length,this.totalBatchesProcessed++;try{const e=await Promise.allSettled(t.map(e=>this.processEvent(e)));for(let n=0;n<e.length;n++){const r=e[n];this.eventsProcessedCount++,"rejected"===r.status&&this.logger.error(`Failed to process event ${t[n].transactionId}:`,r.reason)}}finally{this.currentConcurrency-=t.length}this.queue.length>0&&!this.processingScheduled&&(this.processingScheduled=!0,this.scheduleProcessing(()=>this.processNextBatch()))}async processEvent(e){if(!this.processor)return void this.logger.warn("No processor set, discarding event:",e.transactionId);const t=Date.now();try{await this.processor(e);const n=Date.now()-t;this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class ti{constructor(e,t,n,r={},o){this.socket=null,this.maxSeenTransactions=1e4,this.listeners=[],this.onErrorCallbacks=[],this.isActive=!1,this.listenerRegistered=!1,this.handleSwapEvent=null,this.warmingIntervalHandle=null,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.reconnectDelayMs=1e3,this.logger=o||new H({debug:!1,context:"MultiPoolStateManager"}),e instanceof Promise?this.socketReady=e.then(e=>(this.socket=e,this.setupConnectionMonitoring(),e)).catch(e=>{throw this.logger.error("Failed to resolve socket promise:",e),e}):(this.socket=e,this.socketReady=Promise.resolve(e),this.setupConnectionMonitoring()),this.metrics=new Ho,this.config=this.applyDefaults(r),this.eventExtractor=new Xo(this.logger),this.quoteService=n,this.cacheManager=new Jo(t,this.config,this.metrics,this.logger),this.eventQueue=new ei(this.config,this.metrics,this.logger),this.seenTransactions=new ni(this.maxSeenTransactions),this.eventQueue.setProcessor(e=>this.processSwapEvent(e)),this.logger.debug("Initialized MultiPoolStateManager")}subscribe(e,t){this.listeners.push(t),e.onError&&this.onErrorCallbacks.push(e.onError),this.isActive||(this.setupWebSocketListener(e),this.isActive=!0);const n=this;return()=>{n.listeners=n.listeners.filter(e=>e!==t),e.onError&&(n.onErrorCallbacks=n.onErrorCallbacks.filter(t=>t!==e.onError)),0===n.listeners.length&&0===n.onErrorCallbacks.length&&n.unsubscribe()}}getHealth(){const e=this.cacheManager.getStats(),t=this.eventQueue.getStats(),n=this.metrics.getHealthMetrics(e.totalCached,e.hotCacheSize,e.warmCacheSize,e.coldCacheSize,this.getMaxMemoryMB()),r=this.determineHealthStatus(t,e),o={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectAttempts};this.socket?.connected&&(o.lastConnectionTime=new Date);const i=t.queueSize/this.config.maxQueueSize*100,s=e.totalCached/this.config.maxPools*100,a=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(r,i,s,a,n.metrics.cacheHitRate);return{...n,status:r,websocket:o,recommendations:c,detailedMetrics:{eventQueueUtilization:i,cacheUtilization:s,memoryUtilization:a}}}generateHealthRecommendations(e,t,n,r,o){const i=[];return"failed"===e&&(i.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||i.push("Reconnect WebSocket - connection lost"),t>90&&i.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(i.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&i.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),r>80&&i.push(`Memory usage ${r.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(o<50&&i.push(`Cache hit rate ${o.toFixed(1)}% is low - consider warming more pools`),r>50&&i.push("Memory usage is moderate - monitor for growth trends"),t>50&&i.push("Queue utilization is elevated - monitor for bottlenecks")),i}getSummary(){return{...this.metrics.getSummary(),queueStats:this.eventQueue.getStats(),cacheStats:this.cacheManager.getStats()}}startBackgroundWarming(){if(this.warmingIntervalHandle)return;const e=this.config.refreshIntervalMs;this.warmingIntervalHandle=setInterval(()=>{this.performBackgroundWarming().catch(e=>{this.logger.error("Background warming error:",e)})},e),this.logger.debug(`Background warming started (interval: ${e}ms)`)}stopBackgroundWarming(){this.warmingIntervalHandle&&(clearInterval(this.warmingIntervalHandle),this.warmingIntervalHandle=null,this.logger.debug("Background warming stopped"))}async performBackgroundWarming(){const e=this.cacheManager.getStats();if(0!==e.totalCached)try{await this.cacheManager.refreshWarmAndHotTiers(),this.logger.debug(`Background warming completed: ${e.totalCached} pools in cache (hot: ${e.hotCacheSize}, warm: ${e.warmCacheSize})`)}catch(e){this.logger.debug("Background warming encountered an error:",e)}}async shutdown(){this.stopBackgroundWarming(),await this.unsubscribe(),await this.eventQueue.shutdown(),this.cacheManager.clear(),this.metrics.reset()}setupConnectionMonitoring(){this.socket&&(this.socket.on("disconnect",()=>{this.logger.warn("WebSocket disconnected"),this.notifyError(new Error("WebSocket disconnected")),this.config.autoRecover&&this.attemptReconnection().catch(e=>{this.logger.error("Reconnection failed:",e)})}),this.socket.on("connect_error",e=>{this.logger.error("WebSocket connection error:",e),this.notifyError(e instanceof Error?e:new Error(String(e)))}))}async attemptReconnection(){if(this.logger.debug(`Reconnection attempt ${this.reconnectAttempts+1}/${this.maxReconnectAttempts}`),this.reconnectAttempts>=this.maxReconnectAttempts)return this.logger.error(`Max reconnection attempts (${this.maxReconnectAttempts}) exceeded - performing full reset`),void await this.performFullReset();this.reconnectAttempts<2&&(0===this.reconnectAttempts?this.logger.debug("Tier 1: Quick reconnect"):(this.logger.debug(`Tier 2: Exponential backoff (${this.reconnectDelayMs}ms)`),await new Promise(e=>setTimeout(e,this.reconnectDelayMs)),this.reconnectDelayMs=Math.min(2*this.reconnectDelayMs,3e4)));try{this.socket?.disconnect&&(this.socket.disconnect(),this.logger.debug("Disconnected for reconnection")),this.socket?.connect?.(),this.logger.debug("Reconnection initiated"),this.reconnectAttempts++}catch(e){throw this.logger.error("Failed to initiate reconnection:",e),e}}async performFullReset(){this.logger.warn("Performing full system reset due to connection failures"),this.stopBackgroundWarming();const e=this.getHealth();this.logger.debug("System state before reset:",{status:e.status,queueSize:e.eventProcessing.eventsProcessed,cachedPools:e.pools.totalMonitored,memory:`${e.memory.usedMB}MB / ${e.memory.maxMB}MB`,cacheHitRate:`${e.metrics.cacheHitRate.toFixed(2)}%`}),this.cacheManager.clear(),this.metrics.reset(),this.reconnectAttempts=0,this.reconnectDelayMs=1e3,this.notifyError(new Error("System reset: connection lost and recovery failed - please restart monitoring")),this.logger.info("System reset complete - ready for restart")}setupWebSocketListener(e){if(this.listenerRegistered)return void this.logger.debug("WebSocket listener already registered");const t=this;this.handleSwapEvent=(n,...r)=>{try{const n=Date.now(),o=r[0],i=t.eventExtractor.walkPayloadForSwaps(o,t.seenTransactions);if(0===i.length)return;t.logger.debug(`Extracted ${i.length} swaps from payload`);for(const n of i){if(t.filterSwap(n,e)){t.eventQueue.enqueue(n)||t.logger.debug(`Swap dropped due to queue overflow: ${n.transactionId}`)}}const s=Date.now()-n;t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(e instanceof Error?e:new Error(String(e)))}},this.socket?(this.socket.onAny(this.handleSwapEvent),this.listenerRegistered=!0,this.setupConnectionMonitoring()):this.logger.warn("Socket not available for listener registration"),this.startBackgroundWarming(),this.logger.debug("WebSocket listener registered for all events")}async unsubscribe(){this.stopBackgroundWarming(),this.handleSwapEvent&&this.listenerRegistered&&this.socket&&(this.socket.offAny(this.handleSwapEvent),this.listenerRegistered=!1),this.isActive=!1,this.listeners=[],this.onErrorCallbacks=[],this.logger.debug("Unsubscribed from swap events")}filterSwap(e,t){if(t.tokenFilter){if(!Vo.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,r]=t.pairTokens;if(!Vo.containsTokenPair(e.poolKey,n,r))return!1}if(t.feeTierFilter){if(Vo.normalizeFee(t.feeTierFilter)!==e.feeTier)return!1}return!t.userFilter||e.user===t.userFilter}async processSwapEvent(e){const t=Date.now();try{const n=this.cacheManager.updatePoolWithSwapDelta(e.poolKey,e.direction,e.amount0,e.amount1,e);e.poolStateUpdated=n;const r=Date.now()-t;this.metrics.recordEventLatency(r);for(const t of this.listeners)try{const n=t(e);n instanceof Promise&&await n}catch(t){this.logger.error(`Listener error for swap ${e.transactionId}:`,t)}}catch(t){this.logger.error(`Failed to process swap ${e.transactionId}:`,t),this.notifyError(t instanceof Error?t:new Error(String(t)))}}notifyError(e){for(const t of this.onErrorCallbacks)try{t(e)}catch(e){this.logger.error("Error in error callback:",e)}}determineHealthStatus(e,t){return!this.socket?.connected||e.queueSize>.9*this.config.maxQueueSize?"failed":e.queueSize>.75*this.config.maxQueueSize||t.memoryUsedMB>.9*this.getMaxMemoryMB()?"degraded":"healthy"}getMaxMemoryMB(){switch(this.config.memoryProfile){case"conservative":return 55;case"aggressive":return 530;default:return 250}}applyDefaults(e){return{memoryProfile:e.memoryProfile??"moderate",maxPools:e.maxPools??500,softLimit:e.softLimit??200,preloadTopN:e.preloadTopN??200,warmingTimeoutMs:e.warmingTimeoutMs??3e4,refreshIntervalMs:e.refreshIntervalMs??3e5,maxQueueSize:e.maxQueueSize??1e4,batchSize:e.batchSize??100,maxConcurrent:e.maxConcurrent??10,autoRecover:e.autoRecover??!0,maxParallelRefetch:e.maxParallelRefetch??20,enableDeltaOptimization:e.enableDeltaOptimization??!0,enableOfflineQuotes:e.enableOfflineQuotes??!0,metricsEnabled:e.metricsEnabled??!0,debug:e.debug??!1}}}class ni{constructor(e){this.map=new Map,this.maxSize=e}has(e){return this.map.has(e)}add(e){if(this.map.has(e))return this.map.delete(e),this.map.set(e,Date.now()),this;if(this.map.size>=this.maxSize){const e=this.map.keys().next().value;this.map.delete(e)}return this.map.set(e,Date.now()),this}delete(e){return this.map.delete(e)}clear(){this.map.clear()}get size(){return this.map.size}}class ri extends Gn{constructor(e=!1){super(e),this.cache=new Map,this.tokenIdIndex=new Map,this.fetchTimestamps=new Map}normalizeSymbol(e){return e.trim().toUpperCase()}normalizeTokenId(e){return e.trim().toUpperCase()}has(e){const t=this.cache.get(e);return void 0!==t&&t.size>0}getAll(e){const t=this.cache.get(e);return t?Array.from(t.values()):[]}getBySymbol(e,t){const n=this.normalizeSymbol(t);return this.cache.get(e)?.get(n)}getContractAddress(e,t){const n=this.getBySymbol(e,t);if(n)return"ETHEREUM"===e?n.ethereumContractAddress:n.solanaContractAddress}set(e,t){const n=new Map,r=new Map;for(const e of t){const t=this.normalizeSymbol(e.symbol);n.set(t,e);const o=this.normalizeTokenId(e.stringifiedTokenClassKey);r.set(o,e)}this.cache.set(e,n),this.tokenIdIndex.set(e,r),this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Cached ${t.length} bridgeable tokens for ${e}`)}merge(e,t){let n=this.cache.get(e);n||(n=new Map,this.cache.set(e,n));let r=this.tokenIdIndex.get(e);r||(r=new Map,this.tokenIdIndex.set(e,r));for(const e of t){const t=this.normalizeSymbol(e.symbol);n.set(t,e);const o=this.normalizeTokenId(e.stringifiedTokenClassKey);r.set(o,e)}this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Merged ${t.length} bridgeable tokens for ${e} (total: ${n.size})`)}getFetchTimestamp(e){return this.fetchTimestamps.get(e)}getStats(){const e=[];let t=0;const n={ETHEREUM:0,SOLANA:0},r={};for(const[o,i]of this.cache){e.push(o),t+=i.size,n[o]=i.size;const s=this.fetchTimestamps.get(o);s&&(r[o]=s)}return{networks:e,totalTokens:t,tokensByNetwork:n,fetchTimestamps:r}}clear(e){e?(this.cache.delete(e),this.tokenIdIndex.delete(e),this.fetchTimestamps.delete(e),this.logger.debug(`Cleared bridgeable token cache for ${e}`)):(this.cache.clear(),this.tokenIdIndex.clear(),this.fetchTimestamps.clear(),this.logger.debug("Cleared all bridgeable token caches"))}size(e){return this.cache.get(e)?.size??0}isTokenBridgeable(e,t){return void 0!==this.getBySymbol(e,t)}getByTokenId(e,t){const n=this.normalizeTokenId(t);return this.tokenIdIndex.get(e)?.get(n)}getCachedNetworks(){return Array.from(this.cache.keys())}dump(){const e={};for(const t of["ETHEREUM","SOLANA"])this.has(t)&&(e[t]=this.getAll(t));return e}}const oi=1e3,ii=1e3;class si{constructor(e,t=!1){this.dexApiHttp=e,this.logger=new H({debug:t,context:"BridgeableTokenService"}),this.cache=new ri(t)}resolveTokenSymbol(e){if("string"==typeof e){const t=e.split("|");if(4!==t.length)throw new Y(`Invalid tokenId format: "${e}". Expected pipe-delimited format "collection|category|type|additionalKey" (e.g., "GALA|Unit|none|none") or TokenClassKey object.`,"tokenId","INVALID_FORMAT");const n=t[0],r=t[2];return"Token"===n?r:n}if(!e.collection||!e.category||!e.type||void 0===e.additionalKey)throw new Y("Invalid TokenClassKey: must have collection, category, type, and additionalKey fields.","tokenId","INVALID_FORMAT");return"Token"===e.collection?e.type:e.collection}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:r=ii}=e,o=Math.min(r,oi);this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${o})`);try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{canBridgeTo:t.toLowerCase(),limit:o,offset:n}}),r=this.transformTokens(e.tokens,t);return 0===n?this.cache.set(t,r):this.cache.merge(t,r),{tokens:r,network:t,fetchedAt:Date.now(),tokenCount:r.length}}catch(e){throw this.logger.error(`Failed to fetch bridgeable tokens for ${t}:`,e),de(`Failed to fetch bridgeable tokens for ${t}: ${er(e)}`,void 0,e instanceof Error?e:void 0)}}async fetchAllBridgeableTokensByNetwork(e){if(this.cache.has(e)){const t=this.cache.getAll(e);return this.logger.debug(`Returning ${t.length} cached bridgeable tokens for ${e}`),{tokens:t,network:e,fetchedAt:this.cache.getFetchTimestamp(e)||Date.now(),tokenCount:t.length}}this.logger.debug(`Fetching all bridgeable tokens for ${e} (no cache)`);const t=[];let n=0,r=!0;for(;r;)try{const o=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{canBridgeTo:e.toLowerCase(),limit:oi,offset:n}}),i=this.transformTokens(o.tokens,e);t.push(...i),r=o.tokens.length===oi,n+=oi,this.logger.debug(`Fetched ${t.length} tokens so far for ${e} (hasMore=${r})`)}catch(t){throw this.logger.error(`Failed to fetch bridgeable tokens for ${e} at offset ${n}:`,t),de(`Failed to fetch bridgeable tokens for ${e}: ${er(t)}`,void 0,t instanceof Error?t:void 0)}return this.cache.set(e,t),{tokens:t,network:e,fetchedAt:Date.now(),tokenCount:t.length}}async fetchAllTokensBridgeableToEthereum(){return this.fetchAllBridgeableTokensByNetwork("ETHEREUM")}async fetchAllTokensBridgeableToSolana(){return this.fetchAllBridgeableTokensByNetwork("SOLANA")}async isTokenBridgeableToNetwork(e){const{tokenId:t,network:n}=e,r=this.resolveTokenSymbol(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const o=this.cache.getBySymbol(n,r),i=void 0!==o,s=i?"ETHEREUM"===n?o.ethereumContractAddress:o.solanaContractAddress:void 0,a={isBridgeable:i,tokenSymbol:r,network:n};return void 0!==s&&(a.contractAddress=s),a}async isTokenBridgeableToEthereum(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"ETHEREUM"})}async isTokenBridgeableToSolana(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"SOLANA"})}async getTokenBySymbol(e,t){const n=this.cache.getBySymbol(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getBySymbol(t,e))}async getTokenByTokenId(e,t){const n=this.cache.getByTokenId(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getByTokenId(t,e))}async getContractAddress(e,t){const n=await this.getTokenBySymbol(e,t);if(n)return"ETHEREUM"===t?n.ethereumContractAddress:n.solanaContractAddress}async getSupportedTokenSymbols(e){return this.cache.has(e)||await this.fetchAllBridgeableTokensByNetwork(e),this.cache.getAll(e).map(e=>e.symbol)}async preload(){this.logger.debug("Preloading bridgeable tokens for all networks"),await Promise.all([this.fetchAllBridgeableTokensByNetwork("ETHEREUM"),this.fetchAllBridgeableTokensByNetwork("SOLANA")]),this.logger.debug("Preloading complete")}getCacheStats(){return this.cache.getStats()}clearCache(e){this.cache.clear(e)}transformTokens(e,t){return e.map(e=>{const t=e.otherNetworks?.find(e=>"Ethereum"===e.network),n=e.otherNetworks?.find(e=>"Solana"===e.network),r=e.canBridgeTo.map(e=>e.network).filter(e=>"Ethereum"===e||"Solana"===e),o={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,verified:e.verified,supportedChains:r};return t?.contractAddress&&(o.ethereumContractAddress=t.contractAddress),t?.symbol&&(o.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(o.ethereumAllowanceSlot=t.allowanceStorageSlot),n?.contractAddress&&(o.solanaContractAddress=n.contractAddress),n?.symbol&&(o.solanaSymbol=n.symbol),e.image&&(o.image=e.image),e.description&&(o.description=e.description),o})}}class ai extends Gn{constructor(e=!1){super(e),this.lastFetchedAt=null,this.cache=new Map}normalizeTokenId(e){return e.trim().toUpperCase()}has(){return this.cache.size>0}getAll(){return Array.from(this.cache.values())}getByTokenId(e){const t=this.normalizeTokenId(e);return this.cache.get(t)}set(e){this.cache.clear();for(const t of e){const e=this.normalizeTokenId(t.stringifiedTokenClassKey);this.cache.set(e,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Cached ${e.length} wrappable tokens`)}merge(e){for(const t of e){const e=this.normalizeTokenId(t.stringifiedTokenClassKey);this.cache.set(e,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Merged ${e.length} wrappable tokens (total: ${this.cache.size})`)}getFetchTimestamp(){return this.lastFetchedAt}getStats(){return{tokenCount:this.cache.size,isPopulated:this.cache.size>0,lastFetchedAt:this.lastFetchedAt}}clear(){this.cache.clear(),this.lastFetchedAt=null,this.logger.debug("Cleared wrappable token cache")}size(){return this.cache.size}isTokenWrappable(e){return void 0!==this.getByTokenId(e)}getWrapCounterpart(e){const t=this.getByTokenId(e);if(t)return this.getByTokenId(t.wrapCounterpart)}}const ci=1e3,ui=1e3;class li{constructor(e,t=!1){this.dexApiHttp=e,this.logger=new H({debug:t,context:"WrappableTokenService"}),this.cache=new ai(t)}normalizeTokenId(e){if("string"==typeof e){if(!e||!e.trim())throw new Y("tokenId must be a non-empty string","tokenId","INVALID_FORMAT");if(4!==e.split("|").length)throw new Y(`Invalid tokenId format: "${e}". Expected pipe-delimited format "collection|category|type|additionalKey" (e.g., "$MUSIC|Unit|none|none") or TokenClassKey object.`,"tokenId","INVALID_FORMAT");return e}if(!e.collection||!e.category||!e.type||void 0===e.additionalKey)throw new Y("Invalid TokenClassKey: must have collection, category, type, and additionalKey fields.","tokenId","INVALID_FORMAT");return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}async fetchWrappableTokens(e={}){const{offset:t=0,limit:n=ui}=e,r=Math.min(n,ci);this.logger.debug(`Fetching wrappable tokens (offset=${t}, limit=${r})`);try{const e={wrappable:!0,limit:r,offset:t},n=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:e});if(!n||!Array.isArray(n.tokens))throw new Y("Invalid API response: expected { tokens: WrappableTokenApiResponse[] }","response","INVALID_RESPONSE");const o=this.transformTokens(n.tokens);try{0===t?this.cache.set(o):this.cache.merge(o)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:o,fetchedAt:Date.now(),tokenCount:o.length}}catch(e){throw this.logger.error("Failed to fetch wrappable tokens:",e),de(`Failed to fetch wrappable tokens: ${er(e)}`,void 0,e instanceof Error?e:void 0)}}async fetchAllWrappableTokens(){if(this.cache.has()){const e=this.cache.getAll();return this.logger.debug(`Returning ${e.length} cached wrappable tokens`),{tokens:e,fetchedAt:this.cache.getFetchTimestamp()||Date.now(),tokenCount:e.length}}this.logger.debug("Fetching all wrappable tokens");const e=[];let t=0,n=!0;for(;n;)try{const r={wrappable:!0,limit:ci,offset:t},o=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:r});if(!o||!Array.isArray(o.tokens))throw new Y("Invalid API response: expected { tokens: WrappableTokenApiResponse[] }","response","INVALID_RESPONSE");const i=this.transformTokens(o.tokens);e.push(...i),n=o.tokens.length===ci,t+=ci,this.logger.debug(`Fetched ${e.length} tokens so far (hasMore=${n})`)}catch(e){throw this.logger.error(`Failed to fetch wrappable tokens at offset ${t}:`,e),de(`Failed to fetch wrappable tokens: ${er(e)}`,void 0,e instanceof Error?e:void 0)}try{this.cache.set(e)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:e,fetchedAt:Date.now(),tokenCount:e.length}}async getWrappableToken(e){const t=this.normalizeTokenId(e),n=this.cache.getByTokenId(t);return n||(this.cache.has()?void 0:(await this.fetchAllWrappableTokens(),this.cache.getByTokenId(t)))}async getWrapCounterpart(e){const t=await this.getWrappableToken(e);if(t)return this.getWrappableToken(t.wrapCounterpart)}async isTokenWrappable(e){const t=this.normalizeTokenId(e);this.cache.has()||await this.fetchAllWrappableTokens();const n=this.cache.getByTokenId(t),r=void 0!==n,o={isWrappable:r,tokenId:t};return r&&n&&(o.wrapCounterpart=n.wrapCounterpart),o}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}transformTokens(e){return e.map(e=>{const t={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,wrapCounterpart:e.wrap,swappable:e.swappable,verified:e.verified};return e.channel&&(t.channel=e.channel),void 0!==e.trending&&(t.trending=e.trending),e.image&&(t.image=e.image),e.description&&(t.description=e.description),e.currentPrices&&(t.currentPrices=e.currentPrices),t})}}function hi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function di(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var fi,pi,gi,mi,yi,wi;function bi(){return mi?gi:(mi=1,gi={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys})}var ki=function(){if(wi)return yi;wi=1;const e=pi?fi:(pi=1,fi={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify}),t=bi().isFunction,n=bi().isBoolean,r=bi().isObject,o=bi().isArray,i=bi().isRegex,s=bi().assign,a=bi().keys;return yi=function(c,u){u=u||s({},e),t(u)&&(u={compare:u});const l=u.space||e.space,h=n(u.cycles)?u.cycles:e.cycles,d=u.replacer||e.replacer,f=u.stringify||e.stringify,p=u.compare&&(g=u.compare,function(e){return function(t,n){const r={key:t,value:e[t]},o={key:n,value:e[n]};return g(r,o)}});var g;h||f(c);const m=[];return function e(t,n,s,c){const u=l?"\n"+new Array(c+1).join(l):"",g=l?": ":":";if(s=function(e){return null==e?e:i(e)?e.toString():e.toJSON?e.toJSON():e}(s),void 0!==(s=d.call(t,n,s))){if(!r(s)||null===s)return f(s);if(o(s)){const t=[];for(let n=0;n<s.length;n++){const r=e(s,n,s[n],c+1)||f(null);t.push(u+l+r)}return"["+t.join(",")+u+"]"}{if(h){if(-1!==m.indexOf(s))return f("[Circular]");m.push(s)}const t=a(s).sort(p&&p(s)),n=[];for(let r=0;r<t.length;r++){const o=t[r],i=e(s,o,s[o],c+1);if(!i)continue;const a=f(o)+g+i;n.push(u+l+a)}return m.splice(m.indexOf(s),1),"{"+n.join(",")+u+"}"}}}({"":c},"",c,0)},yi}(),vi=hi(ki);const Ei={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},Si={ASSET:1,MUSIC:3};function Ai(e){return Object.values(Si).includes(e)}const Ti=12,Ii=15e3,Bi=27e5,xi={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},Ci="https://ethereum.publicnode.com",Pi="https://api.mainnet-beta.solana.com",Ni="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",_i="0x6a1734E09f3099a3675645D214ce547080ea67e0",Ui="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",Di="https://dex-api-platform-dex-prod-gala.gala.com",Ri=[{symbol:"GALA",amount:"1",contractAddress:"0xd1d2Eb1B1e90B638588728b4130137D262C87cae",bridgeUsesPermit:!0,decimals:8},{symbol:"GWETH",amount:"0.0001",contractAddress:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",bridgeUsesPermit:!1,decimals:18},{symbol:"GUSDC",amount:"1",contractAddress:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",bridgeUsesPermit:!1,decimals:6},{symbol:"GUSDT",amount:"1",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",bridgeUsesPermit:!1,decimals:6},{symbol:"GWTRX",amount:"1",contractAddress:"0x50327c6c5a14DCaDE707ABad2E27eB517df87AB5",bridgeUsesPermit:!1,decimals:6},{symbol:"GWBTC",amount:"0.00001",contractAddress:"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",bridgeUsesPermit:!1,decimals:8}],Fi=[{symbol:"GALA",amount:"1",contractAddress:"0x9fBFf09325C1967A135AC9b4860b1cf89aca52DA",bridgeUsesPermit:!0,decimals:8},{symbol:"GWETH",amount:"0.0001",contractAddress:"0xC3F00B9CbC4221D85A66EEbe928551d0d8dD9158",bridgeUsesPermit:!1,decimals:18},{symbol:"GUSDC",amount:"1",contractAddress:"0x081e78E33bfa612b23A99ef61e7c194649AA318E",bridgeUsesPermit:!1,decimals:6},{symbol:"GUSDT",amount:"1",contractAddress:"0x461e3595f087bfb0E32B6e44BCbF4C74D99B0001",bridgeUsesPermit:!1,decimals:6},{symbol:"GWBTC",amount:"0.00001",contractAddress:"0x5f69276935EF17e5aF5289b60aFBf6d48B344770",bridgeUsesPermit:!1,decimals:8}];function Li(e){return"PROD"===e?Ri:Fi}function Oi(e){return"PROD"===e?Ni:_i}const Mi=Ri,$i=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],qi={GALA:{descriptor:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},decimals:8,channel:"asset"},GWETH:{descriptor:{collection:"GWETH",category:"Unit",type:"none",additionalKey:"none"},decimals:18,channel:"asset"},GUSDC:{descriptor:{collection:"GUSDC",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GUSDT:{descriptor:{collection:"GUSDT",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GWTRX:{descriptor:{collection:"GWTRX",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GWBTC:{descriptor:{collection:"GWBTC",category:"Unit",type:"none",additionalKey:"none"},decimals:8,channel:"asset"},GSOL:{descriptor:{collection:"GSOL",category:"Unit",type:"none",additionalKey:"none"},decimals:9,channel:"asset"}},Ki=["function decimals() view returns (uint8)","function balanceOf(address owner) view returns (uint256)","function approve(address spender, uint256 value) returns (bool)","function allowance(address owner, address spender) view returns (uint256)","function transfer(address to, uint256 value) returns (bool)","function name() view returns (string)","function nonces(address owner) view returns (uint256)","function permit(address owner,address spender,uint256 value,uint256 deadline,uint8 v,bytes32 r,bytes32 s)"],Gi=["function bridgeOut(address token,uint256 amount,uint256 tokenId,uint16 destinationChainId,bytes recipient) external","function bridgeOutWithPermit(address token,uint256 amount,uint16 destinationChainId,bytes recipient,uint256 deadline,uint8 v,bytes32 r,bytes32 s) external"],Wi={BRIDGE_OUT:Buffer.from([27,194,57,119,215,165,247,150]),BRIDGE_OUT_NATIVE:Buffer.from([243,44,75,224,249,206,98,79])};function zi(e){const t=e.toUpperCase(),n=qi[t];if(n)return n;if(!t.startsWith("G")){const e=qi[`G${t}`];if(e)return e}}function ji(e){const t=e.toUpperCase();return Mi.find(e=>e.symbol.toUpperCase()===t||e.symbol.toUpperCase()===`G${t}`)}function Hi(e){const t=e.toUpperCase();return $i.find(e=>e.symbol.toUpperCase()===t||e.symbol.toUpperCase()===`G${t}`)}function Vi(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}const Xi={name:"GalaConnect",chainId:1},Qi=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],Zi=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Yi=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Ji=[{name:"name",type:"string"},{name:"symbol",type:"string"}],es={GalaTransaction:Qi,destinationChainTxFee:[{name:"bridgeToken",type:"bridgeToken"},{name:"bridgeTokenIsNonFungible",type:"bool"},{name:"estimatedPricePerTxFeeUnit",type:"string"},{name:"estimatedTotalTxFeeInExternalToken",type:"string"},{name:"estimatedTotalTxFeeInGala",type:"string"},{name:"estimatedTxFeeUnitsTotal",type:"string"},{name:"galaDecimals",type:"uint256"},{name:"galaExchangeRate",type:"galaExchangeRate"},{name:"timestamp",type:"uint256"},{name:"signingIdentity",type:"string"},{name:"signature",type:"string"}],bridgeToken:Zi,galaExchangeRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"baseToken",type:"baseToken"},{name:"exchangeRate",type:"string"},{name:"externalQuoteToken",type:"externalQuoteToken"}],baseToken:Yi,externalQuoteToken:Ji,tokenInstance:Yi},ts={GalaTransaction:Qi,destinationChainTxFee:[{name:"bridgeToken",type:"bridgeToken"},{name:"bridgeTokenIsNonFungible",type:"bool"},{name:"estimatedPricePerTxFeeUnit",type:"string"},{name:"estimatedTotalTxFeeInExternalToken",type:"string"},{name:"estimatedTotalTxFeeInGala",type:"string"},{name:"estimatedTxFeeUnitsTotal",type:"string"},{name:"galaDecimals",type:"uint256"},{name:"galaExchangeCrossRate",type:"galaExchangeCrossRate"},{name:"timestamp",type:"uint256"},{name:"signingIdentity",type:"string"},{name:"signature",type:"string"}],bridgeToken:Zi,galaExchangeCrossRate:[{name:"baseTokenCrossRate",type:"baseTokenCrossRate"},{name:"crossRate",type:"string"},{name:"externalCrossRateToken",type:"externalCrossRateToken"},{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"quoteTokenCrossRate",type:"quoteTokenCrossRate"},{name:"source",type:"string"},{name:"timestamp",type:"uint256"}],baseTokenCrossRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"exchangeRate",type:"string"},{name:"externalBaseToken",type:"externalBaseToken"},{name:"externalQuoteToken",type:"externalQuoteToken"},{name:"signature",type:"string"}],externalBaseToken:Ji,externalQuoteToken:Ji,externalCrossRateToken:Ji,quoteTokenCrossRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"baseToken",type:"baseToken"},{name:"exchangeRate",type:"string"},{name:"externalQuoteToken",type:"externalQuoteToken"},{name:"signature",type:"string"}],baseToken:Yi,tokenInstance:Yi};function ns(e){return e?ts:es}const rs={GalaTransaction:[{name:"quantity",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"destinationChainId",type:"uint256"},{name:"recipient",type:"string"},{name:"wrap",type:"bool"},{name:"uniqueKey",type:"string"}],tokenInstance:Yi};class os{constructor(e){this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService,this.wallet=e.wallet,this.walletAddress=e.walletAddress,this.logger=e.logger??new H({debug:!1,context:"WrapService"})}async wrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new Y(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new Y(`Cannot wrap ${t.symbol} - it's already on asset channel. Use unwrapToken() instead.`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new Y(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...e.recipient&&{recipient:e.recipient},...e.memo&&{memo:e.memo},isWrap:!0})}async unwrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new Y(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new Y(`Cannot unwrap ${t.symbol} - it's not on asset channel. Use wrapToken() instead.`,"tokenId","NOT_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new Y(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...e.recipient&&{recipient:e.recipient},...e.memo&&{memo:e.memo},isWrap:!1})}async estimateWrapFee(e,t){const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new Y(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new Y(`Cannot wrap ${n.symbol} - it's already on asset channel`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const r=this.determineChannelRouting(n,!0);return{fee:"0",feeToken:"GALA",authorizationType:r.authType,feeChannel:r.sourceChannel}}async estimateUnwrapFee(e,t){const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new Y(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new Y(`Cannot unwrap ${n.symbol} - it's not on asset channel`,"tokenId","NOT_ON_ASSET_CHANNEL");const r=this.determineChannelRouting(n,!1);return{fee:"0",feeToken:"GALA",authorizationType:r.authType,feeChannel:r.sourceChannel}}async getWrapStatus(e){return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:o,isWrap:i}=e;if(!this.wallet||!this.walletAddress)throw new Y("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const s=this.walletAddress,a=this.determineChannelRouting(t,i),c=`galaswap-operation-${O.randomUUID()}`,u=rs,l={quantity:r,tokenInstance:{collection:t.galaChainDescriptor.collection,category:t.galaChainDescriptor.category,type:t.galaChainDescriptor.type,additionalKey:t.galaChainDescriptor.additionalKey,instance:"0"},destinationChainId:a.destinationChannelId,recipient:o||s,wrap:!0,uniqueKey:c};this.logger.debug?.(`[WrapService] ${i?"Wrap":"Unwrap"} message (pre-signing):`,JSON.stringify(l,null,2));try{const e=await this.wallet.signTypedData(Xi,u,l),o=`Ethereum Signed Message:\n${vi({domain:Xi,message:l,primaryType:"GalaTransaction",types:u}).length}`,s={...l,signature:e,prefix:o,types:u,domain:Xi};this.logger.debug?.(`[WrapService] ${i?"Wrap":"Unwrap"} request (signed):`,JSON.stringify(s,null,2));const c=await this.galaConnectClient.requestBridgeOut(s);if(this.logger.debug?.("[WrapService] Response:",JSON.stringify(c,null,2)),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(c)){const e=`Status=${c.Status}`,o=c.Message?`: ${c.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:`GalaChain request failed (${e}${o})`}}if(function(e){return"object"==typeof e&&null!==e&&"Data"in e&&"string"==typeof e.Data}(c)){const e=c.Data;this.logger.debug?.("[WrapService] Step 1 complete, bridgeRequestId:",e);const o={bridgeFromChannel:a.sourceChannel,bridgeRequestId:e};this.logger.debug?.("[WrapService] Step 2 - BridgeTokenOut payload:",JSON.stringify(o,null,2));const s=await this.galaConnectClient.bridgeTokenOut(o);return this.logger.debug?.("[WrapService] BridgeTokenOut response:",JSON.stringify(s,null,2)),1!==s.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:`BridgeTokenOut failed: ${JSON.stringify(s)}`}:{success:!0,transactionId:s.Hash||e,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:`Unexpected response format from GalaChain: ${JSON.stringify(c)}`}}catch(e){const o=e instanceof Error?e.message:"Unknown error";return this.logger.error?.("[WrapService] Error:",o),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:o}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel||"music",destinationChannelId:Si.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Si.MUSIC,authType:"automatic"}}requireWallet(){if(!this.walletAddress)throw new Y("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}}function is(e){const t=function(e){const t=Qt(e);return t.success?[]:t.errors||["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}const ss="/api/asset/launchpad-contract/CallNativeTokenIn",as="/api/asset/launchpad-contract/CallNativeTokenOut",cs="/api/asset/launchpad-contract/CallMemeTokenIn",us="/api/asset/launchpad-contract/CallMemeTokenOut";class ls extends p{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,e.websiteUrl&&(this.websiteUrl=e.websiteUrl),e.telegramUrl&&(this.telegramUrl=e.telegramUrl),e.twitterUrl&&(this.twitterUrl=e.twitterUrl),this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function hs(e){if(!e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.Status&&void 0!==t.Data&&"object"==typeof t.Data&&null!==t.Data&&"string"==typeof t.Data.calculatedQuantity&&void 0!==t.Data.extraFees&&"object"==typeof t.Data.extraFees&&null!==t.Data.extraFees&&"string"==typeof t.Data.extraFees.reverseBondingCurve&&"string"==typeof t.Data.extraFees.transactionFees}const ds={NATIVE:"native",EXACT:"exact"},fs={RECENT:"recent",POPULAR:"popular"},ps={LOCAL:"local",EXTERNAL:"external"};class gs{static calculateBuyWithExact(e,t){const n=parseFloat(e),r=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:s,GAS_FEE:a}=Ko,c=this.roundUp(o*(Math.exp((r+n)*i)-Math.exp(r*i))/i,8),u=new y(c).multipliedBy(s).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:a}}static calculateBuyWithNative(e,t){const n=parseFloat(e),r=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:s,GAS_FEE:a}=Ko,c=Math.log(n*i/o+Math.exp(r*i))/i-r,u=new y(c).multipliedBy(s).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:a}}static calculateSellWithExact(e,t,n,r,o){const i=parseFloat(e),s=parseFloat(t),a=parseFloat(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:l,GAS_FEE:h}=Ko,d=c*(Math.exp(s*u)-Math.exp((s-i)*u))/u,f=new y(d),p=r+s/a*(o-r),g=f.multipliedBy(p).toFixed(8,y.ROUND_UP),m=f.multipliedBy(l).toFixed();return{amount:d.toString(),reverseBondingCurveFee:g,transactionFee:m,gasFee:h}}static calculateSellWithNative(e,t,n,r,o){const i=parseFloat(e),s=parseFloat(t),a=parseFloat(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:l,GAS_FEE:h}=Ko;if(i>=c*(Math.exp(s*u)-1)/u){const e=new y(i),t=r+s/a*(o-r),n=e.multipliedBy(t).toFixed(8,y.ROUND_UP),c=e.multipliedBy(l).toFixed();return{amount:s.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:h}}const d=s-Math.log(Math.exp(s*u)-i*u/c)/u,f=new y(i),p=r+s/a*(o-r),g=f.multipliedBy(p).toFixed(8,y.ROUND_UP),m=f.multipliedBy(l).toFixed();return{amount:d.toString(),reverseBondingCurveFee:g,transactionFee:m,gasFee:h}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class ms{constructor(e,t,n,r,o,i,s="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=o,this.dexApiHttp=i,this.defaultCalculateAmountMode=s,this.metadataCache=new Go}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;gn(t);const r=`${t}.png`;ur(n.file,r,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&n.file instanceof File)e.append("image",n.file);else{if(!Buffer.isBuffer(n.file))throw he("file","a File object (browser) or Buffer (Node.js)");{const r=`${n.tokenName||t}.png`,o=new Blob([n.file],{type:"image/png"});e.append("image",o,r)}}const r=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(n.tokenName||t)}`,data:e,headers:{}});if(!0===r.error||200!==r.status||!r.data?.imageUrl)throw de(r.message||"Image upload failed - no URL returned",r.status);return r.data.imageUrl}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw fe("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){mn(e),e.tokenName&&gn(e.tokenName);const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const n=V(t),r=await this.http.get("/launchpad/fetch-pool",n);if(!0===r.error||200!==r.status||!r.data)throw de(r.message||"Failed to fetch pools",r.status);let o=[];const i=(await import("bignumber.js")).default;if(r.data.tokens)if(Array.isArray(r.data.tokens))o=r.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!new i(t).isZero()||!new i(n).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}});else{const e=r.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",s=!new i(t).isZero()||!new i(n).isZero();o=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:s,createdAt:e.created_at||e.createdAt||""}]}else r.data.pools&&Array.isArray(r.data.pools)&&(o=r.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!new i(t).isZero()||!new i(n).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:s,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return Jb});o.forEach(e=>{if(!a(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=s(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=r.data.count??r.data.total??0,u=r.data.page??e.page??1,l=r.data.limit??e.limit??10,h=l>0?Math.ceil(c/l):1;return{pools:o,page:u,limit:l,total:c,totalPages:h,hasNext:u<h,hasPrevious:u>1}}async _getAmount(e){if(wn(e),!this.galaChainHttp)throw fe("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:n}=((e,t,n,r)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:ss,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:as,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:cs,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:us,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};throw he("type-method","one of: NATIVE-IN, NATIVE-OUT, MEME-IN, MEME-OUT")})(e.type,e.method,e.vaultAddress,e.amount);try{const e=await this.galaChainHttp.post(t,n);if(!hs(e))throw de("Malformed response data from GalaChain gateway");if(1!==e.Status)throw de(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:r,extraFees:o}=e.Data;return{amount:r,reverseBondingCurveFee:o.reverseBondingCurve,transactionFee:o.transactionFees,gasFee:"1"}}catch(r){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:n,error:r instanceof Error?r.message:r}),r}}async checkPool(e){yn(e),e.tokenName&&gn(e.tokenName);const t=V(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw de(n.message||"Failed to check pool",n.status);const r=n.data;return e.symbol?r?.isSymbolExist??!1:e.tokenName?r?.isNameExist??!1:r?.exists??!1}async fetchVolumeData(e){if(!Vn(e))throw new Y("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:o}=e;if(gn(t),!n||!r||!o)throw new Y("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:o};bn(i);const s=V(i),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status||!a.data)throw de(a.message||"Failed to fetch graph data",a.status);return{dataPoints:a.data}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={page:e.page||1,limit:e.limit||10};return e.search&&(n.search=e.search),e.tokenName&&(n.tokenName=e.tokenName),t&&(n.type=t),this.fetchPoolsFromAPI(n)}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async calculateBuyAmount(e){if(!e||"object"!=typeof e)throw new Y("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:n,type:r,currentSupply:o}=e,i=e.mode??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw new Y(`Invalid calculation mode "${i}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new Y("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!n||"string"!=typeof n)throw new Y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==ds.NATIVE&&r!==ds.EXACT)throw new Y('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===i?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",o))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e,o=await this.tokenResolver.resolveTokenToVault(t);if(!o)throw new Y(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return r===ds.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:o,amount:n}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:o,amount:n})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:o,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new Y(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new Y("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!n||"string"!=typeof n)throw new Y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==ds.EXACT&&r!==ds.NATIVE)throw new Y('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==o&&{currentSupply:o},...void 0!==i&&{maxSupply:i},...void 0!==s&&{reverseBondingCurveMaxFeeFactor:s},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e,o=await this.tokenResolver.resolveTokenToVault(t);if(!o)throw new Y(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return r===ds.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:o,amount:n}):this._getAmount({type:"MEME",method:"IN",vaultAddress:o,amount:n})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:o}=e;if(!n||"string"!=typeof n)throw new Y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==ds.NATIVE&&r!==ds.EXACT)throw new Y('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==o&&vn(o,"currentSupply");const i=!o;if(i&&!t)throw new Y("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&gn(t);let s=o;if(i){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===ds.EXACT?gs.calculateBuyWithExact(n,s):gs.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:o,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!n||"string"!=typeof n)throw new Y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==ds.EXACT&&r!==ds.NATIVE)throw new Y('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==o&&vn(o,"currentSupply");const c=!o||!i||void 0===s||void 0===a;if(c&&!t)throw new Y("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&gn(t);let u=o,l=i,h=s,d=a;if(c&&t){const e=this.metadataCache.get(t);l=l??this.metadataCache.getMaxSupply(t),h=h??e?.reverseBondingCurveMaxFeeFactor,d=d??e?.reverseBondingCurveMinFeeFactor,u||(u=await this.fetchCurrentSupply(t));if(void 0===h||void 0===d){const e=await this.fetchPoolDetailsForCalculation(t);h=h??e.reverseBondingCurveMaxFeeFactor,d=d??e.reverseBondingCurveMinFeeFactor}}return r===ds.EXACT?gs.calculateSellWithExact(n,u,l,d,h):gs.calculateSellWithNative(n,u,l,d,h)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Wn(t,"tokenName")&&Hn(t)&&zn(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:n,calculateAmountMode:r,currentSupply:o}=t;gn(n);const i=await this.tokenResolver.resolveTokenToVault(n);if(!i)throw new Y(Z(n),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw fe("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:i});if(1!==s.Status)throw de(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=(await import("bignumber.js")).default,u=o??new c(a.maxSupply).minus(a.sellingTokenQuantity).toFixed(),l=a.sellingTokenQuantity;if("0"===l)throw new Y(`Token ${n} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const h={tokenName:n,amount:l,type:"exact",currentSupply:u,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(h),remainingTokens:l}}async launchToken(e){if(!this.bundleHttp)throw fe("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");is(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new Y("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration,r=Number(t),o=Number(n);if(isNaN(r)||isNaN(o))throw new Y("Reverse bonding curve fees must be valid numbers","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG");if(r<.1)throw new Y("Minimum fee must be >= 0.1","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG");if(o>.5)throw new Y("Maximum fee must be <= 0.5","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG");if(o<r)throw new Y("Maximum fee must be >= minimum fee","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG")}let n="";if(e.tokenImage)if(e.tokenImage instanceof File||Buffer.isBuffer(e.tokenImage)){const t=await this.uploadImageByTokenName({tokenName:e.tokenName,options:{file:e.tokenImage,tokenName:e.tokenName}});if(!t)throw de("Image upload failed: No URL returned");n=t}else"string"==typeof e.tokenImage&&(n=e.tokenImage);const r=`galaswap - operation - ${F()}-${Date.now()}-${this.http.getAddress()}`,o={tokenName:e.tokenName.trim(),tokenSymbol:e.tokenSymbol.trim().toUpperCase(),tokenDescription:e.tokenDescription.trim(),tokenImage:n.trim(),preBuyQuantity:t.toString(),tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:r};e.websiteUrl?.trim()&&(o.websiteUrl=e.websiteUrl.trim()),e.telegramUrl?.trim()&&(o.telegramUrl=e.telegramUrl.trim()),e.twitterUrl?.trim()&&(o.twitterUrl=e.twitterUrl.trim()),o.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration?.minFeePortion?.toString()||"0.1",maxFeePortion:e.reverseBondingCurveConfiguration?.maxFeePortion?.toString()||"0.5"};const i=new ls(o),s=await this.http.signWithGalaChain("CreateSale",i,d.SIGN_TYPED_DATA),{signature:a,types:c,domain:u,prefix:l}=s,h={tokenName:i.tokenName,tokenSymbol:i.tokenSymbol,tokenDescription:i.tokenDescription,tokenImage:i.tokenImage,preBuyQuantity:i.preBuyQuantity,...i.websiteUrl&&{websiteUrl:i.websiteUrl},...i.telegramUrl&&{telegramUrl:i.telegramUrl},...i.twitterUrl&&{twitterUrl:i.twitterUrl},tokenCategory:i.tokenCategory,tokenCollection:i.tokenCollection,uniqueKey:i.uniqueKey,signature:a,types:c,domain:u,...l&&{prefix:l},...i.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:i.reverseBondingCurveConfiguration}},f=`${e.tokenName.trim()}$Unit$none$none`,p="GALA$Unit$none$none";let g;if(parseFloat(t)>0){const e=`$service$${f}$launchpad`;g=[e,`$token$${f}$${e}`,`$tokenBalance$${f}$${e}`,`$tokenBalance$${f}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`]}else{const e=`$service$${f}$launchpad`;g=[e,`$token$${f}$${e}`,`$tokenBalance$${f}$${e}`]}const m={signedDto:h,stringsInstructions:g,method:"CreateSale"},y=await this.bundleHttp.post("/bundle",m);if(y.error||!y.data)throw de(y.message||"Token launch failed");return y.data}async fetchTokenDistribution(e){if(!e)throw le("tokenName","Token name");gn(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Y(Z(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const n=encodeURIComponent(t),r=await this.http.get(`/holders/${n}`);if(!0===r.error||200!==r.status||!r.data)throw de(r.message||"Failed to fetch token distribution",r.status);const o=r.data;if(!Array.isArray(o))throw de("Invalid API response: expected array of holders",r.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw de("Invalid holder data: missing or invalid owner field",r.status);if(!e.quantity||"string"!=typeof e.quantity)throw de("Invalid holder data: missing or invalid quantity field",r.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw de(`Invalid holder quantity: "${e.quantity}"`,r.status)}const i=o.reduce((e,t)=>e.plus(t.quantity),new y(0));return{holders:o.map(e=>{const t=new y(e.quantity),n=i.isZero()?0:t.dividedBy(i).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:i.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw le("tokenName","Token name");gn(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw de(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const o=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return o?.isActive||!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.nativeTokenQuantity&&(void 0===t.vaultAddress||"string"==typeof t.vaultAddress)}(e))throw new Y("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw fe("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},n=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!hs(n))throw de("Malformed response data from GalaChain gateway");if(1!==n.Status)throw de(`GalaChain calculation failed with status ${n.Status}`,n.Status);const{calculatedQuantity:r,extraFees:o}=n.Data;return{amount:r,reverseBondingCurveFee:o.reverseBondingCurve,transactionFee:o.transactionFees,gasFee:"1"}}catch(e){if(e instanceof Error){const t=new Error(`Pre-mint calculation failed: ${e.message}`);throw e.stack&&(t.stack=e.stack),t}throw new Error(`Pre-mint calculation failed: ${String(e)}`)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Y(Z(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw fe("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw de(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,o=new(0,(await import("bignumber.js")).default)(r.maxSupply).minus(r.sellingTokenQuantity).toFixed(),i=r.sellingTokenQuantity,s=r.maxSupply;let a=.5,c=0;r.reverseBondingCurveConfiguration?(a=parseFloat(r.reverseBondingCurveConfiguration.maxFeePortion),c=parseFloat(r.reverseBondingCurveConfiguration.minFeePortion)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const u=a-c;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:u}),{currentSupply:o,remainingTokens:i,maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:u}}async fetchCurrentSupply(e){gn(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Y(Z(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw fe("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw de(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,o=new(0,(await import("bignumber.js")).default)(r.maxSupply).minus(r.sellingTokenQuantity).toFixed(),i=r.maxSupply;return this.metadataCache.set(e,{maxSupply:i}),o}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return kn(e)}validateTokenName(e){return gn(e)}validatePagination(e){return mn(e)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw fe("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw le("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),n=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&n.push({symbol:e.symbol,price:e.currentPrices.usd})}),n}catch(e){throw de(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Wn(t,"tokenName")&&Hn(t)&&zn(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:n,calculateAmountMode:r,currentSupply:o}=t;if(!n||"string"!=typeof n)throw le("tokenName","Token name (string)");try{const e={tokenName:n,amount:"1",type:"native",...void 0!==r&&{mode:r},...void 0!==o&&{currentSupply:o}},t=await this.calculateBuyAmount(e),i=(await this.fetchTokenPrice("GALA"))[0];if(!i)throw de("GALA price not available");const s=Number(t.amount);if(s<=0)throw new Y(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");const a=i.price/s;return{symbol:n.toUpperCase(),price:a}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${n}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${n}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}class ys{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw new Error("requestsPerSecond must be greater than zero");this.minIntervalMs=1e3/e}async schedule(e){let t,n;const r=new Promise((e,r)=>{t=e,n=r});if(this.pendingPromise=this.pendingPromise.then(async()=>{const r=Date.now()-this.lastTimestamp,o=Math.max(0,this.minIntervalMs-r);o>0&&await new Promise(e=>setTimeout(e,o)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}function ws(e,t){const n=new y(e);if(!n.isFinite())throw new Error(`Invalid amount: ${e}`);const r=n.multipliedBy(new y(10).pow(t));if(!r.isInteger())throw new Error(`Amount ${e} cannot be represented with ${t} decimals`);return BigInt(r.toFixed(0))}function bs(e,t){return new y(e.toString()).dividedBy(new y(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}function ks(e,t=6){const n=new y(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!n.isZero())return n.toExponential(2);const r=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return n.toFixed(r).replace(/\.?0+$/,"")}function vs(e,t){const n=new y(e),r=new y(t);return n.comparedTo(r)}const Es={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Ss=new Set([408,429,500,502,503,504]),As=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function Ts(e){if(e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Ss.has(t.status);if("number"==typeof t.statusCode)return Ss.has(t.statusCode);if("string"==typeof t.code&&("ECONNRESET"===t.code||"ECONNREFUSED"===t.code||"ETIMEDOUT"===t.code||"ENOTFOUND"===t.code||"EAI_AGAIN"===t.code))return!0}const t=e instanceof Error?e.message:String(e);return As.some(e=>e.test(t))}function Is(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),r=Math.min(n,t.maxDelayMs),o=r*t.jitterFactor*Math.random();return Math.floor(r+o)}function Bs(e){let t;if("string"==typeof e)t=function(e){const t=e.split("|");if(t.length<4)throw new Error(`Invalid token string format: "${e}". Expected "collection|category|type|additionalKey" format.`);return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}(e);else{if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.collection&&"string"==typeof t.category&&"string"==typeof t.type&&"string"==typeof t.additionalKey}(e))throw new Error('Invalid tokenId format. Expected pipe-delimited string (e.g., "GALA|Unit|none|none") or TokenClassKey object.');t=e}var n;return{tokenClassKey:t,stringified:`${(n=t).collection}|${n.category}|${n.type}|${n.additionalKey}`}}class xs extends Error{constructor(e,t,n){super(`GalaConnect request to ${t} failed with status ${e}${n?`: ${JSON.stringify(n)}`:""}`),this.status=e,this.path=t,this.responseBody=n,this.name="GalaConnectHttpError"}}const Cs=Di,Ps="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",Ns=12,_s=!0,Us=3,Ds=1e3;class Rs{constructor(e){this.baseUrl=e.baseUrl??Cs,this.galachainBaseUrl=e.galachainBaseUrl??Ps,this.walletAddress=e.walletAddress,this.rateLimiter=new ys(e.requestsPerSecond??Ns),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??_s;this.retryOptions=t?{maxRetries:e.maxRetries??Us,initialDelayMs:e.retryInitialDelayMs??Ds,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>Ts(e instanceof xs?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){const t=new URL("/v1/connect/bridge-configurations",this.baseUrl);t.searchParams.set("searchprefix",e);const n=await this.request(t.toString(),{method:"GET"});if(!n.ok)throw new xs(n.status,"/v1/connect/bridge-configurations",await this.safeParseJson(n));return(await n.json()).data.tokens}async fetchBridgeFee(e){return this.postJson("/v1/bridge/fee",e,{skipWalletHeader:!0})}async requestBridgeOut(e){return this.postJson("/v1/RequestTokenBridgeOut",e)}async bridgeTokenOut(e){return this.postJson("/v1/BridgeTokenOut",e)}async getBridgeStatus(e){return this.postJson("/v1/bridge/status",{hash:e})}async registerBridgeTransaction(e){return this.postJson("/v1/bridge/transaction",e)}async fetchBalances(e="asset"){return this.postJson("/v1/FetchBalances",{owner:this.walletAddress,channel:e},{baseUrl:this.galachainBaseUrl})}async postJson(e,t,n={}){const r=n.baseUrl??this.baseUrl,o=new URL(e,r),i=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,s=await this.request(o.toString(),{method:"POST",headers:i,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)}),a=await s.text();let c;if(a)try{c=JSON.parse(a)}catch(t){const n=new Error(`Failed to parse JSON response from ${e}: ${t.message}`);if(!s.ok)throw new xs(s.status,e,{parseError:n.message,rawBody:a.slice(0,500)});throw n}if(!s.ok)throw new xs(s.status,e,c);return c}async request(e,t){const n=async()=>this.rateLimiter.schedule(async()=>{const n={...this.defaultHeaders,...t.headers};""===n["X-Wallet-Address"]?delete n["X-Wallet-Address"]:n["X-Wallet-Address"]||(n["X-Wallet-Address"]=this.walletAddress);const r=await fetch(e,{...t,headers:n});if(this.retryOptions&&!r.ok){const t=r.status;if(429===t||t>=500){const n=r.clone(),o=await this.safeParseJson(n);throw new xs(t,e,o)}}return r});return this.retryOptions?async function(e,t={}){const n={...Es,...t},r=t.shouldRetry??(e=>Ts(e));let o;for(let i=1;i<=n.maxRetries+1;i++)try{return await e()}catch(e){if(o=e,i>n.maxRetries)break;if(!r(e,i))break;const s=Is(i,n);t.onRetry&&t.onRetry(e,i,s),await new Promise(e=>setTimeout(e,s))}throw o}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}var Fs;!function(e){e[e.PENDING=0]="PENDING",e[e.SUBMITTED=1]="SUBMITTED",e[e.CONFIRMED=2]="CONFIRMED",e[e.PROCESSING=3]="PROCESSING",e[e.FINALIZING=4]="FINALIZING",e[e.COMPLETED=5]="COMPLETED",e[e.FAILED=6]="FAILED",e[e.DELIVERY_FAILED=7]="DELIVERY_FAILED"}(Fs||(Fs={}));class Ls{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:o}=t,i=Date.now();for(;;){const t=await this.getStatus(e);if(o&&o(t),t.status===Fs.COMPLETED||t.status===Fs.FAILED||t.status===Fs.DELIVERY_FAILED)return t;if(Date.now()-i>r)throw new Error(`Bridge transaction ${e} timed out after ${r}ms. Last status: ${t.status}`);await new Promise(e=>setTimeout(e,n))}}}class Os extends Ls{constructor(e){if(super(),this.network="Ethereum",this.tokenMetadataCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,!e.ethereumPrivateKey||!/^0x[a-fA-F0-9]{64}$/.test(e.ethereumPrivateKey))throw new Error("Invalid Ethereum private key format. Expected 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)");const t=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new n(t),this.ethereumWallet=new r(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenConfigs=new Map;const o=e.tokenConfigs??Mi;for(const e of o)this.tokenConfigs.set(e.symbol.toUpperCase(),e)}async estimateFee(e,t){const n=await this.getTokenMetadata(e),r=await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor});return{estimatedFeeInGala:r.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:r.estimatedTotalTxFeeInExternalToken,feeToken:r.bridgeToken,pricePerUnit:r.estimatedPricePerTxFeeUnit,estimatedGasUnits:r.estimatedTxFeeUnitsTotal,exchangeRate:r.galaExchangeRate?.exchangeRate??"0",timestamp:r.timestamp,raw:r}}async bridgeOut(e){const{amount:t,recipientAddress:n,tokenSymbol:r}=e;if(!r)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const i=r,s=parseFloat(t);if(isNaN(s)||s<=0)throw new Error(`Invalid bridge amount for ${i}: "${t}". Amount must be a positive number.`);if(!o(n))throw new Error(`Invalid Ethereum recipient address: "${n}". Expected valid 0x-prefixed address.`);const a=await this.getTokenMetadata(i),c=await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:a.descriptor}),u={destinationChainId:Ei.ETHEREUM,destinationChainTxFee:c,quantity:t,recipient:n,tokenInstance:{...a.descriptor,instance:"0"}},l=await this.buildBridgeOutPayload(u),h=await this.galaConnectClient.requestBridgeOut(l),d=this.extractBridgeRequestId(h);if(!d)throw new Error("Bridge request ID missing from RequestTokenBridgeOut response");const f=await this.galaConnectClient.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:d}),p=f.Hash??f.hash??"";if(!p)throw new Error("BridgeTokenOut response missing transaction hash");return{direction:"outbound",fromChain:"GalaChain",toChain:"Ethereum",transactionHash:p,tokenSymbol:i,amount:t,feePaid:c.estimatedTotalTxFeeInGala,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${p}`}}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:o,tokenSymbol:s}=e;if(!s)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const a=s,c=parseFloat(t);if(isNaN(c)||c<=0)throw new Error(`Invalid bridge amount for ${a}: "${t}". Amount must be a positive number.`);if(n&&!/^0x[a-fA-F0-9]{64}$/.test(n))throw new Error("Invalid sourcePrivateKey format. Expected 0x-prefixed 64-character hex string.");const u=n?new r(n,this.ethereumProvider):this.ethereumWallet,l=this.tokenConfigs.get(a.toUpperCase());if(!l)throw new Error(`Token ${a} not supported for Ethereum bridge`);const h=await this.getTokenMetadata(a),d=new i(l.contractAddress,Ki,u),f=await d.decimals(),p=Number(f),g=ws(t,p),m=BigInt(await d.balanceOf(u.address));if(m<g){const e=bs(g,p),t=bs(m,p);throw new Error(`Insufficient ${a} balance on Ethereum. Needed ${e}, have ${t}`)}const y=this.normalizeGalaChainAddress(o??this.galaChainWalletAddress),w=await this.executeBridgeDeposit({wallet:u,tokenContract:d,tokenConfig:l,amountBaseUnits:g,decimals:p,recipient:y,metadata:h});return{direction:"inbound",fromChain:"Ethereum",toChain:"GalaChain",transactionHash:w.txHash,tokenSymbol:a,amount:t,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${w.txHash}`}}async getStatus(e){const t=await this.galaConnectClient.getBridgeStatus(e),n=t.status;return{status:n,statusDescription:t.statusDescription,fromChain:t.fromChain,toChain:t.toChain,quantity:t.quantity,transactionHash:t.emitterTransactionHash,tokenInstance:t.tokenInstance,isComplete:5===n,isFailed:6===n||7===n}}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(e.toUpperCase())}isValidAddress(e){return/^0x[a-fA-F0-9]{40}$/.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const n=this.tokenConfigs.get(e.toUpperCase());if(!n){const t=Array.from(this.tokenConfigs.keys()).join(", ");throw new Error(`Token ${e} not supported for Ethereum. Supported: ${t}`)}const r=t??this.ethereumWalletAddress;if(!o(r))throw new Error(`Invalid Ethereum address: "${r}"`);const s=new i(n.contractAddress,Ki,this.ethereumProvider);return bs(await s.balanceOf(r),n.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;if(!o(t))throw new Error(`Invalid Ethereum address: "${t}"`);return bs(await this.ethereumProvider.getBalance(t),18)}async getEthereumTransactionStatus(e){if(!/^0x[a-fA-F0-9]{64}$/.test(e))throw new Error(`Invalid Ethereum transaction hash format: "${e}". Expected 0x-prefixed 64-character hex string (66 total characters).`);const t=e.toLowerCase();try{const e=await this.ethereumProvider.getTransactionReceipt(t);if(e){const n=await this.ethereumProvider.getBlockNumber()-e.blockNumber+1;if(!(1===e.status))return{confirmed:!1,status:"failed",blockNumber:e.blockNumber,confirmations:n,transactionHash:t,gasUsed:e.gasUsed.toString(),effectiveGasPrice:e.gasPrice?.toString(),error:"Transaction reverted during execution"};return{confirmed:!0,status:n>=Os.ETHEREUM_FINALITY_THRESHOLD?"finalized":"confirmed",blockNumber:e.blockNumber,confirmations:n,transactionHash:t,gasUsed:e.gasUsed.toString(),effectiveGasPrice:e.gasPrice?.toString()}}return await this.ethereumProvider.getTransaction(t)?{confirmed:!1,status:"pending",transactionHash:t}:{confirmed:!1,status:"not_found",transactionHash:t,error:"Transaction not found on Ethereum network"}}catch(e){return{confirmed:!1,status:"not_found",transactionHash:t,error:`Failed to query transaction status: ${e instanceof Error?e.message:String(e)}`}}}async getTokenMetadata(e){const t=this.tokenMetadataCache.get(e.toUpperCase());if(t)return t;const n=qi[e.toUpperCase()];if(n)return this.tokenMetadataCache.set(e.toUpperCase(),n),n;let r=e,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified);if(i||e.startsWith("G")||(r=`G${e}`,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified)),!i)throw new Error(`Unable to locate token metadata for ${e}`);const s={descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:i.decimals,...i.channel&&{channel:i.channel}};return this.tokenMetadataCache.set(e.toUpperCase(),s),s}async buildBridgeOutPayload(e){const t=e.uniqueKey??`galaconnect-operation-${O.randomUUID()}`,n="string"==typeof e.destinationChainId?Number(e.destinationChainId):e.destinationChainId,r=this.normalizeDestinationChainTxFee(e.destinationChainTxFee),o=Boolean(r.galaExchangeCrossRate),i=o?{...r,galaExchangeRate:void 0}:{...r,galaExchangeCrossRate:void 0},s={destinationChainId:n,destinationChainTxFee:this.sanitizeObject(i),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:t},a=ns(o),c=await this.ethereumWallet.signTypedData(Xi,a,s),u=`Ethereum Signed Message:\n${vi({domain:Xi,message:s,primaryType:"GalaTransaction",types:a}).length}`;return{...s,signature:c,prefix:u,types:a,domain:Xi}}async executeBridgeDeposit(e){const t=new i(this.ethereumBridgeContract,Gi,e.wallet),n=(new TextEncoder).encode(e.recipient);let r;r=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,t,e.amountBaseUnits,n):await this.bridgeWithApproval(e.wallet,e.tokenContract,t,e.tokenConfig,e.amountBaseUnits,n);if(!await r.wait())throw new Error("Bridge transaction receipt not available");await this.delay(3e4);const o={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:bs(e.amountBaseUnits,e.decimals),tokenInstance:o,fromChain:"Ethereum",toChain:"GC",hash:r.hash}),{txHash:r.hash}}async bridgeWithPermit(e,t,n,r,o,i){const a=await this.ethereumProvider.getNetwork(),c=await t.name(),u=await t.nonces(e.address),l=BigInt(Math.floor(Date.now()/1e3)+3600),h=await e.signTypedData({name:c,version:"1",chainId:Number(a.chainId),verifyingContract:n.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:e.address,spender:this.ethereumBridgeContract,value:o,nonce:u,deadline:l}),d=s.from(h);return r.bridgeOutWithPermit(n.contractAddress,o,Ei.GALA_CHAIN,i,l,d.v,d.r,d.s)}async bridgeWithApproval(e,t,n,r,o,i){const s=await t.allowance(e.address,this.ethereumBridgeContract);if(BigInt(s)<o){const e=await t.approve(this.ethereumBridgeContract,o);await e.wait()}return n.bridgeOut(r.contractAddress,o,0,Ei.GALA_CHAIN,i)}normalizeDestinationChainTxFee(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Number(e.galaDecimals):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Number(e.timestamp):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Number(e.galaExchangeRate.timestamp):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Number(n.timestamp):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Number(n.baseTokenCrossRate.timestamp):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Number(n.quoteTokenCrossRate.timestamp):n.quoteTokenCrossRate.timestamp})}return t}sanitizeObject(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=this.sanitizeObject(r):t[n]=r);return t}extractBridgeRequestId(e){if("string"==typeof e.Data)return e.Data;if(null!=e.data){if("string"==typeof e.data)return e.data;if("object"==typeof e.data){const t=e.data;if("string"==typeof t.Data)return t.Data}}}async delay(e){return new Promise(t=>setTimeout(t,e))}normalizeGalaChainAddress(e){let t;if(e.startsWith("eth|"))t=e.slice(4);else{if(e.startsWith("client|"))return e;t=e}if((t.startsWith("0x")||t.startsWith("0X"))&&(t=t.slice(2)),!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid GalaChain address format: ${e}`);return`eth|${a("0x"+t).slice(2)}`}}Os.ETHEREUM_FINALITY_THRESHOLD=12;var Ms,$s={},qs={};function Ks(){if(Ms)return qs;Ms=1,qs.byteLength=function(e){var t=i(e),n=t[0],r=t[1];return 3*(n+r)/4-r},qs.toByteArray=function(e){var r,o,s=i(e),a=s[0],c=s[1],u=new n(function(e,t,n){return 3*(t+n)/4-n}(0,a,c)),l=0,h=c>0?a-4:a;for(o=0;o<h;o+=4)r=t[e.charCodeAt(o)]<<18|t[e.charCodeAt(o+1)]<<12|t[e.charCodeAt(o+2)]<<6|t[e.charCodeAt(o+3)],u[l++]=r>>16&255,u[l++]=r>>8&255,u[l++]=255&r;2===c&&(r=t[e.charCodeAt(o)]<<2|t[e.charCodeAt(o+1)]>>4,u[l++]=255&r);1===c&&(r=t[e.charCodeAt(o)]<<10|t[e.charCodeAt(o+1)]<<4|t[e.charCodeAt(o+2)]>>2,u[l++]=r>>8&255,u[l++]=255&r);return u},qs.fromByteArray=function(t){for(var n,r=t.length,o=r%3,i=[],s=16383,c=0,u=r-o;c<u;c+=s)i.push(a(t,c,c+s>u?u:c+s));1===o?(n=t[r-1],i.push(e[n>>2]+e[n<<4&63]+"==")):2===o&&(n=(t[r-2]<<8)+t[r-1],i.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"="));return i.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)e[o]=r[o],t[r.charCodeAt(o)]=o;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function s(t){return e[t>>18&63]+e[t>>12&63]+e[t>>6&63]+e[63&t]}function a(e,t,n){for(var r,o=[],i=t;i<n;i+=3)r=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),o.push(s(r));return o.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,qs}var Gs,Ws,zs={};function js(){return Gs||(Gs=1,zs.read=function(e,t,n,r,o){var i,s,a=8*o-r-1,c=(1<<a)-1,u=c>>1,l=-7,h=n?o-1:0,d=n?-1:1,f=e[t+h];for(h+=d,i=f&(1<<-l)-1,f>>=-l,l+=a;l>0;i=256*i+e[t+h],h+=d,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=r;l>0;s=256*s+e[t+h],h+=d,l-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,r),i-=u}return(f?-1:1)*s*Math.pow(2,i-r)},zs.write=function(e,t,n,r,o,i){var s,a,c,u=8*i-o-1,l=(1<<u)-1,h=l>>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:i-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(s++,c/=2),s+h>=l?(a=0,s=l):s+h>=1?(a=(t*c-1)*Math.pow(2,o),s+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,o),s=0));o>=8;e[n+f]=255&a,f+=p,a/=256,o-=8);for(s=s<<o|a,u+=o;u>0;e[n+f]=255&s,f+=p,s/=256,u-=8);e[n+f-p]|=128*g}),zs}var Hs=(Ws||(Ws=1,function(e){const t=Ks(),n=js(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;function i(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=i(n);const o=r.write(e,t);return o!==n&&(r=r.slice(0,o)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);const o=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||V(e.length)?i(0):l(e):"Buffer"===e.type&&Array.isArray(e.data)?l(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),i(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=i(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function d(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(o)return r?-1:W(e).length;t=(""+t).toLowerCase(),o=!0}}function p(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return B(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return j(W(t,e.length-n),e,n,r)}function k(e,t,n,r){return j(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return j(z(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function A(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=o,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let o=0;for(n=0;n<e.length;++n){let t=e[n];if(H(t,Uint8Array))o+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)g(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?A(this,0,e):p.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,o){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){i=u[e],a=l[e];break}return i<a?-1:a<i?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function B(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function x(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=X[e[r]];return o}function C(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function P(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function U(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function F(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,8),n.write(e,t,r,o,52,8),r+8}s.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return _(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=Q(function(e,t=0){return _(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const o=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),o},s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{const i=s.isBuffer(e)?e:s.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%a]}return this};const L={};function O(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function M(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,o,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,o,i)}function q(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}O("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),O("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),O("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=M(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=M(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function z(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function H(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}($s)),$s);const Vs="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Xs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Qs(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Zs(e,...t){if(!Xs(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ys(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Qs(e.outputLen),Qs(e.blockLen)}function Js(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ea(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ta(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function na(e,t){return e<<32-t|e>>>t}const ra=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),oa=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ia(e){if(Zs(e),ra)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=oa[e[n]];return t}const sa=48,aa=57,ca=65,ua=70,la=97,ha=102;function da(e){return e>=sa&&e<=aa?e-sa:e>=ca&&e<=ua?e-(ca-10):e>=la&&e<=ha?e-(la-10):void 0}function fa(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(ra)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,o=0;t<n;t++,o+=2){const n=da(e.charCodeAt(o)),i=da(e.charCodeAt(o+1));if(void 0===n||void 0===i){const t=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+o)}r[t]=16*n+i}return r}function pa(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),Zs(e),e}function ga(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Zs(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const o=e[t];n.set(o,r),r+=o.length}return n}class ma{}function ya(e){const t=t=>e().update(pa(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function wa(e=32){if(Vs&&"function"==typeof Vs.getRandomValues)return Vs.getRandomValues(new Uint8Array(e));if(Vs&&"function"==typeof Vs.randomBytes)return Uint8Array.from(Vs.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function ba(e,t,n){return e&t^~e&n}function ka(e,t,n){return e&t^e&n^t&n}class va extends ma{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=ta(this.buffer)}update(e){Js(this),Zs(e=pa(e));const{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){const s=Math.min(r-this.pos,o-i);if(s===r){const t=ta(e);for(;r<=o-i;i+=r)this.process(t,i);continue}n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Js(this),function(e,t){Zs(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:o}=this;let{pos:i}=this;t[i++]=128,ea(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(n,0),i=0);for(let e=i;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),c=r?4:0,u=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+u,a,r)}(n,r-8,BigInt(8*this.length),o),this.process(n,0);const s=ta(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)s.setUint32(4*e,u[e],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=o,e.length=r,e.pos=s,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Ea=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Sa=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Aa=BigInt(2**32-1),Ta=BigInt(32);function Ia(e,t=!1){return t?{h:Number(e&Aa),l:Number(e>>Ta&Aa)}:{h:0|Number(e>>Ta&Aa),l:0|Number(e&Aa)}}const Ba=(e,t,n)=>e>>>n,xa=(e,t,n)=>e<<32-n|t>>>n,Ca=(e,t,n)=>e>>>n|t<<32-n,Pa=(e,t,n)=>e<<32-n|t>>>n,Na=(e,t,n)=>e<<64-n|t>>>n-32,_a=(e,t,n)=>e>>>n-32|t<<64-n;function Ua(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:0|o}}const Da=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Ra=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Fa=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),La=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,Oa=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Ma=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0,$a=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]),qa=new Uint32Array(64);class Ka extends va{constructor(e=32){super(64,e,8,!1),this.A=0|Ea[0],this.B=0|Ea[1],this.C=0|Ea[2],this.D=0|Ea[3],this.E=0|Ea[4],this.F=0|Ea[5],this.G=0|Ea[6],this.H=0|Ea[7]}get(){const{A:e,B:t,C:n,D:r,E:o,F:i,G:s,H:a}=this;return[e,t,n,r,o,i,s,a]}set(e,t,n,r,o,i,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|i,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)qa[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=qa[e-15],n=qa[e-2],r=na(t,7)^na(t,18)^t>>>3,o=na(n,17)^na(n,19)^n>>>10;qa[e]=o+qa[e-7]+r+qa[e-16]|0}let{A:n,B:r,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(na(s,6)^na(s,11)^na(s,25))+ba(s,a,c)+$a[e]+qa[e]|0,l=(na(n,2)^na(n,13)^na(n,22))+ka(n,r,o)|0;u=c,c=a,a=s,s=i+t|0,i=o,o=r,r=n,n=t+l|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,o,i,s,a,c,u)}roundClean(){ea(qa)}destroy(){this.set(0,0,0,0,0,0,0,0),ea(this.buffer)}}const Ga=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){const{h:n,l:s}=Ia(e[i],t);[r[i],o[i]]=[n,s]}return[r,o]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),Wa=(()=>Ga[0])(),za=(()=>Ga[1])(),ja=new Uint32Array(80),Ha=new Uint32Array(80);class Va extends va{constructor(e=64){super(128,e,16,!1),this.Ah=0|Sa[0],this.Al=0|Sa[1],this.Bh=0|Sa[2],this.Bl=0|Sa[3],this.Ch=0|Sa[4],this.Cl=0|Sa[5],this.Dh=0|Sa[6],this.Dl=0|Sa[7],this.Eh=0|Sa[8],this.El=0|Sa[9],this.Fh=0|Sa[10],this.Fl=0|Sa[11],this.Gh=0|Sa[12],this.Gl=0|Sa[13],this.Hh=0|Sa[14],this.Hl=0|Sa[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:o,Cl:i,Dh:s,Dl:a,Eh:c,El:u,Fh:l,Fl:h,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[e,t,n,r,o,i,s,a,c,u,l,h,d,f,p,g]}set(e,t,n,r,o,i,s,a,c,u,l,h,d,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|o,this.Cl=0|i,this.Dh=0|s,this.Dl=0|a,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|h,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let n=0;n<16;n++,t+=4)ja[n]=e.getUint32(t),Ha[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ja[e-15],n=0|Ha[e-15],r=Ca(t,n,1)^Ca(t,n,8)^Ba(t,0,7),o=Pa(t,n,1)^Pa(t,n,8)^xa(t,n,7),i=0|ja[e-2],s=0|Ha[e-2],a=Ca(i,s,19)^Na(i,s,61)^Ba(i,0,6),c=Pa(i,s,19)^_a(i,s,61)^xa(i,s,6),u=Fa(o,c,Ha[e-7],Ha[e-16]),l=La(u,r,a,ja[e-7],ja[e-16]);ja[e]=0|l,Ha[e]=0|u}let{Ah:n,Al:r,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:l,El:h,Fh:d,Fl:f,Gh:p,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Ca(l,h,14)^Ca(l,h,18)^Na(l,h,41),w=Pa(l,h,14)^Pa(l,h,18)^_a(l,h,41),b=l&d^~l&p,k=Oa(y,w,h&f^~h&g,za[e],Ha[e]),v=Ma(k,m,t,b,Wa[e],ja[e]),E=0|k,S=Ca(n,r,28)^Na(n,r,34)^Na(n,r,39),A=Pa(n,r,28)^_a(n,r,34)^_a(n,r,39),T=n&o^n&s^o&s,I=r&i^r&a^i&a;m=0|p,y=0|g,p=0|d,g=0|f,d=0|l,f=0|h,({h:l,l:h}=Ua(0|c,0|u,0|v,0|E)),c=0|s,u=0|a,s=0|o,a=0|i,o=0|n,i=0|r;const B=Da(E,A,I);n=Ra(B,v,S,T),r=0|B}({h:n,l:r}=Ua(0|this.Ah,0|this.Al,0|n,0|r)),({h:o,l:i}=Ua(0|this.Bh,0|this.Bl,0|o,0|i)),({h:s,l:a}=Ua(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:u}=Ua(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:h}=Ua(0|this.Eh,0|this.El,0|l,0|h)),({h:d,l:f}=Ua(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=Ua(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:y}=Ua(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,o,i,s,a,c,u,l,h,d,f,p,g,m,y)}roundClean(){ea(ja,Ha)}destroy(){ea(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Xa=ya(()=>new Ka),Qa=ya(()=>new Va),Za=BigInt(0),Ya=BigInt(1);function Ja(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function ec(e,t,n=""){const r=Xs(e),o=e?.length,i=void 0!==t;if(!r||i&&o!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(r?`length=${o}`:"type="+typeof e))}return e}function tc(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function nc(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Za:BigInt("0x"+e)}function rc(e){return nc(ia(e))}function oc(e){return Zs(e),nc(ia(Uint8Array.from(e).reverse()))}function ic(e,t){return fa(e.toString(16).padStart(2*t,"0"))}function sc(e,t){return ic(e,t).reverse()}function ac(e,t,n){let r;if("string"==typeof t)try{r=fa(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Xs(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const o=r.length;if("number"==typeof n&&o!==n)throw new Error(e+" of length "+n+" expected, got "+o);return r}function cc(e){return Uint8Array.from(e)}const uc=e=>"bigint"==typeof e&&Za<=e;function lc(e,t,n,r){if(!function(e,t,n){return uc(e)&&uc(t)&&uc(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function hc(e){let t;for(t=0;e>Za;e>>=Ya,t+=1);return t}const dc=e=>(Ya<<BigInt(e))-Ya;function fc(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const o=e[t];if(r&&void 0===o)return;const i=typeof o;if(i!==n||null===o)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function pc(e){const t=new WeakMap;return(n,...r)=>{const o=t.get(n);if(void 0!==o)return o;const i=e(n,...r);return t.set(n,i),i}}const gc=BigInt(0),mc=BigInt(1),yc=BigInt(2),wc=BigInt(3),bc=BigInt(4),kc=BigInt(5),vc=BigInt(7),Ec=BigInt(8),Sc=BigInt(9),Ac=BigInt(16);function Tc(e,t){const n=e%t;return n>=gc?n:t+n}function Ic(e,t,n){let r=e;for(;t-- >gc;)r*=r,r%=n;return r}function Bc(e,t){if(e===gc)throw new Error("invert: expected non-zero number");if(t<=gc)throw new Error("invert: expected positive modulus, got "+t);let n=Tc(e,t),r=t,o=gc,i=mc;for(;n!==gc;){const e=r%n,t=o-i*(r/n);r=n,n=e,o=i,i=t}if(r!==mc)throw new Error("invert: does not exist");return Tc(o,t)}function xc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Cc(e,t){const n=(e.ORDER+mc)/bc,r=e.pow(t,n);return xc(e,r,t),r}function Pc(e,t){const n=(e.ORDER-kc)/Ec,r=e.mul(t,yc),o=e.pow(r,n),i=e.mul(t,o),s=e.mul(e.mul(i,yc),o),a=e.mul(i,e.sub(s,e.ONE));return xc(e,a,t),a}function Nc(e){if(e<wc)throw new Error("sqrt is not defined for small field");let t=e-mc,n=0;for(;t%yc===gc;)t/=yc,n++;let r=yc;const o=Lc(e);for(;1===Rc(o,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Cc;let i=o.pow(r,t);const s=(t+mc)/yc;return function(e,r){if(e.is0(r))return r;if(1!==Rc(e,r))throw new Error("Cannot find square root");let o=n,a=e.mul(e.ONE,i),c=e.pow(r,t),u=e.pow(r,s);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===o)throw new Error("Cannot find square root");const r=mc<<BigInt(o-t-1),i=e.pow(a,r);o=t,a=e.sqr(i),c=e.mul(c,a),u=e.mul(u,i)}return u}}function _c(e){return e%bc===wc?Cc:e%Ec===kc?Pc:e%Ac===Sc?function(e){const t=Lc(e),n=Nc(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+vc)/Ac;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,r);const c=e.mul(n,o),u=e.mul(n,i),l=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);n=e.cmov(n,a,l),a=e.cmov(u,c,h);const d=e.eql(e.sqr(a),t),f=e.cmov(n,a,d);return xc(e,f,t),f}}(e):Nc(e)}const Uc=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Dc(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce((t,n,o)=>e.is0(n)?t:(r[o]=t,e.mul(t,n)),e.ONE),i=e.inv(o);return t.reduceRight((t,n,o)=>e.is0(n)?t:(r[o]=e.mul(t,r[o]),e.mul(t,n)),i),r}function Rc(e,t){const n=(e.ORDER-mc)/yc,r=e.pow(t,n),o=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Fc(e,t){void 0!==t&&Qs(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Lc(e,t,n=!1,r={}){if(e<=gc)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,i,s,a=!1;if("object"==typeof t&&null!=t){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(o=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),s=e.allowedLengths}else"number"==typeof t&&(o=t),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:u}=Fc(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const h=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:u,MASK:dc(c),ZERO:gc,ONE:mc,allowedLengths:s,create:t=>Tc(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return gc<=t&&t<e},is0:e=>e===gc,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&mc)===mc,neg:t=>Tc(-t,e),eql:(e,t)=>e===t,sqr:t=>Tc(t*t,e),add:(t,n)=>Tc(t+n,e),sub:(t,n)=>Tc(t-n,e),mul:(t,n)=>Tc(t*n,e),pow:(e,t)=>function(e,t,n){if(n<gc)throw new Error("invalid exponent, negatives unsupported");if(n===gc)return e.ONE;if(n===mc)return t;let r=e.ONE,o=t;for(;n>gc;)n&mc&&(r=e.mul(r,o)),o=e.sqr(o),n>>=mc;return r}(h,e,t),div:(t,n)=>Tc(t*Bc(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Bc(t,e),sqrt:i||(t=>(l||(l=_c(e)),l(h,t))),toBytes:e=>n?sc(e,u):ic(e,u),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>u)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);const e=new Uint8Array(u);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+t.length);let o=n?oc(t):rc(t);if(a&&(o=Tc(o,e)),!r&&!h.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o},invertBatch:e=>Dc(h,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(h)}function Oc(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Mc(e){const t=Oc(e);return t+Math.ceil(t/2)}const $c=BigInt(0),qc=BigInt(1);function Kc(e,t){const n=t.negate();return e?n:t}function Gc(e,t){const n=Dc(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Wc(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function zc(e,t){Wc(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:dc(e),maxNumber:n,shiftBy:BigInt(e)}}function jc(e,t,n){const{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n;let a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=qc);const u=t*r;return{nextN:c,offset:u+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:u}}const Hc=new WeakMap,Vc=new WeakMap;function Xc(e){return Vc.get(e)||1}function Qc(e){if(e!==$c)throw new Error("invalid wNAF")}class Zc{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>$c;)t&qc&&(n=n.add(r)),r=r.double(),t>>=qc;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=zc(t,this.bits),o=[];let i=e,s=i;for(let e=0;e<n;e++){s=i,o.push(s);for(let e=1;e<r;e++)s=s.add(i),o.push(s);i=s.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,o=this.BASE;const i=zc(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:u,isNegF:l,offsetF:h}=jc(n,e,i);n=s,c?o=o.add(Kc(l,t[h])):r=r.add(Kc(u,t[a]))}return Qc(n),{p:r,f:o}}wNAFUnsafe(e,t,n,r=this.ZERO){const o=zc(e,this.bits);for(let e=0;e<o.windows&&n!==$c;e++){const{nextN:i,offset:s,isZero:a,isNeg:c}=jc(n,e,o);if(n=i,!a){const e=t[s];r=r.add(c?e.negate():e)}}return Qc(n),r}getPrecomputes(e,t,n){let r=Hc.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Hc.set(t,r))),r}cached(e,t,n){const r=Xc(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const o=Xc(e);return 1===o?this._unsafeLadder(e,t,r):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,r)}createCache(e,t){Wc(t,this.bits),Vc.set(e,t),Hc.delete(e)}hasCache(e){return 1!==Xc(e)}}function Yc(e,t,n,r){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}(n,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}(r,t);const o=n.length,i=r.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=hc(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=dc(c),l=new Array(Number(u)+1).fill(s);let h=s;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){l.fill(s);for(let t=0;t<i;t++){const o=r[t],i=Number(o>>BigInt(e)&u);l[i]=l[i].add(n[t])}let t=s;for(let e=l.length-1,n=s;e>0;e--)n=n.add(l[e]),t=t.add(n);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function Jc(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){fc(e,Uc.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Lc(e,{isLE:n})}function eu(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>$c))throw new Error(`CURVE.${e} must be positive bigint`)}const o=Jc(t.p,n.Fp,r),i=Jc(t.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of s)if(!o.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:o,Fn:i}}const tu=BigInt(0),nu=BigInt(1),ru=BigInt(2),ou=BigInt(8);function iu(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');fc(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:i,Fn:s}=e,a=n.randomBytes||wa,c=n.adjustScalarBytes||(e=>e),u=n.domain||((e,t,n)=>{if(Ja(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return s.create(oc(e))}function h(e){const{head:n,prefix:r,scalar:i}=function(e){const n=m.secretKey;e=ac("private key",e,n);const r=ac("hashed private key",t(e),2*n),o=c(r.slice(0,n));return{head:o,prefix:r.slice(n,2*n),scalar:l(o)}}(e),s=o.multiply(i),a=s.toBytes();return{head:n,prefix:r,scalar:i,point:s,pointBytes:a}}function d(e){return h(e).pointBytes}function f(e=Uint8Array.of(),...n){const o=ga(...n);return l(t(u(o,ac("context",e),!!r)))}const p={zip215:!0};const g=i.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function y(e=a(m.seed)){return ec(e,m.seed,"seed")}const w={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:function(e){return Xs(e)&&e.length===s.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},toMontgomery(t){const{y:n}=e.fromBytes(t),r=m.publicKey,o=32===r;if(!o&&57!==r)throw new Error("only defined for 25519 and 448");const s=o?i.div(nu+n,nu-n):i.div(n-nu,n+nu);return i.toBytes(s)},toMontgomerySecret(e){const n=m.secretKey;ec(e,n);const r=t(e.subarray(0,n));return c(r).subarray(0,n)},randomPrivateKey:y,precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=w.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign:function(e,t,n={}){e=ac("message",e),r&&(e=r(e));const{prefix:i,scalar:a,pointBytes:c}=h(t),u=f(n.context,i,e),l=o.multiply(u).toBytes(),d=f(n.context,l,c,e),p=s.create(u+d*a);if(!s.isValid(p))throw new Error("sign failed: invalid s");return ec(ga(l,s.toBytes(p)),m.signature,"result")},verify:function(t,n,i,s=p){const{context:a,zip215:c}=s,u=m.signature;t=ac("signature",t,u),n=ac("message",n),i=ac("publicKey",i,m.publicKey),void 0!==c&&Ja(c,"zip215"),r&&(n=r(n));const l=u/2,h=t.subarray(0,l),d=oc(t.subarray(l,u));let g,y,w;try{g=e.fromBytes(i,c),y=e.fromBytes(h,c),w=o.multiplyUnsafe(d)}catch(e){return!1}if(!c&&g.isSmallOrder())return!1;const b=f(a,y.toBytes(),g.toBytes(),n);return y.add(g.multiplyUnsafe(b)).subtract(w).clearCofactor().is0()},utils:w,Point:e,lengths:m})}function su(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:o}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n={Fp:e.Fp,Fn:Lc(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}(e),i=function(e,t={}){const n=eu("edwards",e,t,t.FpFnLE),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s}=i;fc(t,{},{uvRatio:"function"});const a=ru<<BigInt(8*o.BYTES)-nu,c=e=>r.create(e),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch(e){return{isValid:!1,value:tu}}});if(!function(e,t,n,r){const o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(e,t,n=!1){return lc("coordinate "+e,t,n?nu:tu,a),t}function h(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const d=pc((e,t)=>{const{X:n,Y:o,Z:i}=e,s=e.is0();null==t&&(t=s?ou:r.inv(i));const a=c(n*t),u=c(o*t),l=r.mul(i,t);if(s)return{x:tu,y:nu};if(l!==nu)throw new Error("invZ was invalid");return{x:a,y:u}}),f=pc(e=>{const{a:t,d:n}=i;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:o,Z:s,T:a}=e,u=c(r*r),l=c(o*o),h=c(s*s),d=c(h*h),f=c(u*t);if(c(h*c(f+l))!==c(d+c(n*c(u*l))))throw new Error("bad point: equation left != right (1)");if(c(r*o)!==c(s*a))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(e,t,n,r){this.X=l("x",e),this.Y=l("y",t),this.Z=l("z",n,!0),this.T=l("t",r),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return l("x",t),l("y",n),new p(t,n,nu,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:o,d:s}=i;e=cc(ec(e,n,"point")),Ja(t,"zip215");const l=cc(e),h=e[n-1];l[n-1]=-129&h;const d=oc(l),f=t?a:r.ORDER;lc("point.y",d,tu,f);const g=c(d*d),m=c(g-nu),y=c(s*g-o);let{isValid:w,value:b}=u(m,y);if(!w)throw new Error("bad point: invalid y coordinate");const k=(b&nu)===nu,v=!!(128&h);if(!t&&b===tu&&v)throw new Error("bad point: x=0 and x_0=1");return v!==k&&(b=c(-b)),p.fromAffine({x:b,y:d})}static fromHex(e,t=!1){return p.fromBytes(ac("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(ru),this}assertValidity(){f(this)}equals(e){h(e);const{X:t,Y:n,Z:r}=this,{X:o,Y:i,Z:s}=e,a=c(t*s),u=c(o*r),l=c(n*s),d=c(i*r);return a===u&&l===d}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:n,Z:r}=this,o=c(t*t),s=c(n*n),a=c(ru*c(r*r)),u=c(e*o),l=t+n,h=c(c(l*l)-o-s),d=u+s,f=d-a,g=u-s,m=c(h*f),y=c(d*g),w=c(h*g),b=c(f*d);return new p(m,y,b,w)}add(e){h(e);const{a:t,d:n}=i,{X:r,Y:o,Z:s,T:a}=this,{X:u,Y:l,Z:d,T:f}=e,g=c(r*u),m=c(o*l),y=c(a*n*f),w=c(s*d),b=c((r+o)*(u+l)-g-m),k=w-y,v=w+y,E=c(m-t*g),S=c(b*k),A=c(v*E),T=c(b*E),I=c(k*v);return new p(S,A,I,T)}subtract(e){return this.add(e.negate())}multiply(e){if(!o.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=g.cached(this,e,e=>Gc(p,e));return Gc(p,[t,n])[0]}multiplyUnsafe(e,t=p.ZERO){if(!o.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===tu?p.ZERO:this.is0()||e===nu?this:g.unsafe(this,e,e=>Gc(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return s===nu?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&nu?128:0,n}toHex(){return ia(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(e){return Gc(p,e)}static msm(e,t){return Yc(p,o,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,nu,c(i.Gx*i.Gy)),p.ZERO=new p(tu,nu,nu,tu),p.Fp=r,p.Fn=o;const g=new Zc(p,o.BITS);return p.BASE.precompute(8),p}(t,n);return function(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(e,iu(i,r,o))}const au=BigInt(1),cu=BigInt(2);BigInt(3);const uu=BigInt(5),lu=BigInt(8),hu=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),du=(()=>({p:hu,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:lu,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function fu(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const pu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function gu(e,t){const n=hu,r=Tc(t*t*t,n),o=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=hu,s=e*e%i*e%i,a=Ic(s,cu,i)*s%i,c=Ic(a,au,i)*e%i,u=Ic(c,uu,i)*c%i,l=Ic(u,t,i)*u%i,h=Ic(l,n,i)*l%i,d=Ic(h,r,i)*h%i,f=Ic(d,o,i)*d%i,p=Ic(f,o,i)*d%i,g=Ic(p,t,i)*u%i;return{pow_p_5_8:Ic(g,cu,i)*e%i,b2:s}}(e*Tc(r*r*t,n)).pow_p_5_8;let i=Tc(e*r*o,n);const s=Tc(t*i*i,n),a=i,c=Tc(i*pu,n),u=s===e,l=s===Tc(-e,n),h=s===Tc(-e*pu,n);return u&&(i=a),(l||h)&&(i=c),(Tc(i,n)&mc)===mc&&(i=Tc(-i,n)),{isValid:u||l,value:i}}const mu=(()=>Lc(du.p,{isLE:!0}))(),yu=(()=>({...du,Fp:mu,hash:Qa,adjustScalarBytes:fu,uvRatio:gu}))(),wu=(()=>su(yu))();var bu,ku={exports:{}},vu=di(Object.freeze({__proto__:null,default:{}})),Eu=ku.exports;function Su(){return bu||(bu=1,function(e,t){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function o(e,t,n){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var i;"object"==typeof e?e.exports=o:t.BN=o,o.BN=o,o.wordSize=26;try{i="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:vu.Buffer}catch(e){}function s(e,t){var r=e.charCodeAt(t);return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+e)}function a(e,t,n){var r=s(e,n);return n-1>=t&&(r|=s(e,n-1)<<4),r}function c(e,t,r,o){for(var i=0,s=0,a=Math.min(e.length,r),c=t;c<a;c++){var u=e.charCodeAt(c)-48;i*=o,s=u>=49?u-49+10:u>=17?u-17+10:u,n(u>=0&&s<o,"Invalid character"),i+=s}return i}function u(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var o=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(o++,this.negative=1),o<e.length&&(16===t?this._parseHex(e,o,r):(this._parseBase(e,t,o),"le"===r&&this._initArray(this.toArray(),t,r)))},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var o=0;o<this.length;o++)this.words[o]=0;var i,s,a=0;if("be"===r)for(o=e.length-1,i=0;o>=0;o-=3)s=e[o]|e[o-1]<<8|e[o-2]<<16,this.words[i]|=s<<a&67108863,this.words[i+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);else if("le"===r)for(o=0,i=0;o<e.length;o+=3)s=e[o]|e[o+1]<<8|e[o+2]<<16,this.words[i]|=s<<a&67108863,this.words[i+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);return this._strip()},o.prototype._parseHex=function(e,t,n){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var o,i=0,s=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)o=a(e,t,r)<<i,this.words[s]|=67108863&o,i>=18?(i-=18,s+=1,this.words[s]|=o>>>26):i+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)o=a(e,t,r)<<i,this.words[s]|=67108863&o,i>=18?(i-=18,s+=1,this.words[s]|=o>>>26):i+=8;this._strip()},o.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,o=1;o<=67108863;o*=t)r++;r--,o=o/t|0;for(var i=e.length-n,s=i%r,a=Math.min(i,i-s)+n,u=0,l=n;l<a;l+=r)u=c(e,l,l+r,t),this.imuln(o),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u);if(0!==s){var h=1;for(u=c(e,l,e.length,t),l=0;l<s;l++)h*=t;this.imuln(h),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u)}this._strip()},o.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},o.prototype._move=function(e){u(e,this)},o.prototype.clone=function(){var e=new o(null);return this.copy(e),e},o.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},o.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=l}catch(e){o.prototype.inspect=l}else o.prototype.inspect=l;function l(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var h=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function p(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var o=0|e.words[0],i=0|t.words[0],s=o*i,a=67108863&s,c=s/67108864|0;n.words[0]=a;for(var u=1;u<r;u++){for(var l=c>>>26,h=67108863&c,d=Math.min(u,t.length-1),f=Math.max(0,u-e.length+1);f<=d;f++){var p=u-f|0;l+=(s=(o=0|e.words[p])*(i=0|t.words[f])+h)/67108864|0,h=67108863&s}n.words[u]=0|h,c=0|l}return 0!==c?n.words[u]=0|c:n.length--,n._strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var o=0,i=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<o|i)).toString(16);i=a>>>24-o&16777215,(o+=2)>=26&&(o-=26,s--),r=0!==i||s!==this.length-1?h[6-c.length]+c+r:c+r}for(0!==i&&(r=i.toString(16)+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var u=d[e],l=f[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modrn(l).toString(e);r=(p=p.idivn(l)).isZero()?g+r:h[u-g.length]+g+r}for(this.isZero()&&(r="0"+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16,2)},i&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(i,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){this._strip();var o=this.byteLength(),i=r||Math.max(1,o);n(o<=i,"byte array longer than desired length"),n(i>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,i);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,o),s},o.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,o=0,i=0;o<this.length;o++){var s=this.words[o]<<i|r;e[n++]=255&s,n<e.length&&(e[n++]=s>>8&255),n<e.length&&(e[n++]=s>>16&255),6===i?(n<e.length&&(e[n++]=s>>24&255),r=0,i=0):(r=s>>>24,i+=2)}if(n<e.length)for(e[n++]=r;n<e.length;)e[n++]=0},o.prototype._toArrayLikeBE=function(e,t){for(var n=e.length-1,r=0,o=0,i=0;o<this.length;o++){var s=this.words[o]<<i|r;e[n--]=255&s,n>=0&&(e[n--]=s>>8&255),n>=0&&(e[n--]=s>>16&255),6===i?(n>=0&&(e[n--]=s>>24&255),r=0,i=0):(r=s>>>24,i+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 8191&t||(n+=13,t>>>=13),127&t||(n+=7,t>>>=7),15&t||(n+=4,t>>>=4),3&t||(n+=2,t>>>=2),1&t||n++,n},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var n=this._zeroBits(this.words[t]);if(e+=n,26!==n)break}return e},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},o.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return 0!==this.negative},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this._strip()},o.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},o.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;n<t.length;n++)this.words[n]=this.words[n]&e.words[n];return this.length=t.length,this._strip()},o.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},o.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;r<n.length;r++)this.words[r]=t.words[r]^n.words[r];if(this!==t)for(;r<t.length;r++)this.words[r]=t.words[r];return this.length=t.length,this._strip()},o.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},o.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var o=0;o<t;o++)this.words[o]=67108863&~this.words[o];return r>0&&(this.words[o]=~this.words[o]&67108863>>26-r),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,o=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<<o:this.words[r]&~(1<<o),this._strip()},o.prototype.iadd=function(e){var t,n,r;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(n=this,r=e):(n=e,r=this);for(var o=0,i=0;i<r.length;i++)t=(0|n.words[i])+(0|r.words[i])+o,this.words[i]=67108863&t,o=t>>>26;for(;0!==o&&i<n.length;i++)t=(0|n.words[i])+o,this.words[i]=67108863&t,o=t>>>26;if(this.length=n.length,0!==o)this.words[this.length]=o,this.length++;else if(n!==this)for(;i<n.length;i++)this.words[i]=n.words[i];return this},o.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,o=this.cmp(e);if(0===o)return this.negative=0,this.length=1,this.words[0]=0,this;o>0?(n=this,r=e):(n=e,r=this);for(var i=0,s=0;s<r.length;s++)i=(t=(0|n.words[s])-(0|r.words[s])+i)>>26,this.words[s]=67108863&t;for(;0!==i&&s<n.length;s++)i=(t=(0|n.words[s])+i)>>26,this.words[s]=67108863&t;if(0===i&&s<n.length&&n!==this)for(;s<n.length;s++)this.words[s]=n.words[s];return this.length=Math.max(this.length,s),n!==this&&(this.negative=1),this._strip()},o.prototype.sub=function(e){return this.clone().isub(e)};var g=function(e,t,n){var r,o,i,s=e.words,a=t.words,c=n.words,u=0,l=0|s[0],h=8191&l,d=l>>>13,f=0|s[1],p=8191&f,g=f>>>13,m=0|s[2],y=8191&m,w=m>>>13,b=0|s[3],k=8191&b,v=b>>>13,E=0|s[4],S=8191&E,A=E>>>13,T=0|s[5],I=8191&T,B=T>>>13,x=0|s[6],C=8191&x,P=x>>>13,N=0|s[7],_=8191&N,U=N>>>13,D=0|s[8],R=8191&D,F=D>>>13,L=0|s[9],O=8191&L,M=L>>>13,$=0|a[0],q=8191&$,K=$>>>13,G=0|a[1],W=8191&G,z=G>>>13,j=0|a[2],H=8191&j,V=j>>>13,X=0|a[3],Q=8191&X,Z=X>>>13,Y=0|a[4],J=8191&Y,ee=Y>>>13,te=0|a[5],ne=8191&te,re=te>>>13,oe=0|a[6],ie=8191&oe,se=oe>>>13,ae=0|a[7],ce=8191&ae,ue=ae>>>13,le=0|a[8],he=8191&le,de=le>>>13,fe=0|a[9],pe=8191&fe,ge=fe>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(u+(r=Math.imul(h,q))|0)+((8191&(o=(o=Math.imul(h,K))+Math.imul(d,q)|0))<<13)|0;u=((i=Math.imul(d,K))+(o>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(p,q),o=(o=Math.imul(p,K))+Math.imul(g,q)|0,i=Math.imul(g,K);var ye=(u+(r=r+Math.imul(h,W)|0)|0)+((8191&(o=(o=o+Math.imul(h,z)|0)+Math.imul(d,W)|0))<<13)|0;u=((i=i+Math.imul(d,z)|0)+(o>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,q),o=(o=Math.imul(y,K))+Math.imul(w,q)|0,i=Math.imul(w,K),r=r+Math.imul(p,W)|0,o=(o=o+Math.imul(p,z)|0)+Math.imul(g,W)|0,i=i+Math.imul(g,z)|0;var we=(u+(r=r+Math.imul(h,H)|0)|0)+((8191&(o=(o=o+Math.imul(h,V)|0)+Math.imul(d,H)|0))<<13)|0;u=((i=i+Math.imul(d,V)|0)+(o>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(k,q),o=(o=Math.imul(k,K))+Math.imul(v,q)|0,i=Math.imul(v,K),r=r+Math.imul(y,W)|0,o=(o=o+Math.imul(y,z)|0)+Math.imul(w,W)|0,i=i+Math.imul(w,z)|0,r=r+Math.imul(p,H)|0,o=(o=o+Math.imul(p,V)|0)+Math.imul(g,H)|0,i=i+Math.imul(g,V)|0;var be=(u+(r=r+Math.imul(h,Q)|0)|0)+((8191&(o=(o=o+Math.imul(h,Z)|0)+Math.imul(d,Q)|0))<<13)|0;u=((i=i+Math.imul(d,Z)|0)+(o>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(S,q),o=(o=Math.imul(S,K))+Math.imul(A,q)|0,i=Math.imul(A,K),r=r+Math.imul(k,W)|0,o=(o=o+Math.imul(k,z)|0)+Math.imul(v,W)|0,i=i+Math.imul(v,z)|0,r=r+Math.imul(y,H)|0,o=(o=o+Math.imul(y,V)|0)+Math.imul(w,H)|0,i=i+Math.imul(w,V)|0,r=r+Math.imul(p,Q)|0,o=(o=o+Math.imul(p,Z)|0)+Math.imul(g,Q)|0,i=i+Math.imul(g,Z)|0;var ke=(u+(r=r+Math.imul(h,J)|0)|0)+((8191&(o=(o=o+Math.imul(h,ee)|0)+Math.imul(d,J)|0))<<13)|0;u=((i=i+Math.imul(d,ee)|0)+(o>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(I,q),o=(o=Math.imul(I,K))+Math.imul(B,q)|0,i=Math.imul(B,K),r=r+Math.imul(S,W)|0,o=(o=o+Math.imul(S,z)|0)+Math.imul(A,W)|0,i=i+Math.imul(A,z)|0,r=r+Math.imul(k,H)|0,o=(o=o+Math.imul(k,V)|0)+Math.imul(v,H)|0,i=i+Math.imul(v,V)|0,r=r+Math.imul(y,Q)|0,o=(o=o+Math.imul(y,Z)|0)+Math.imul(w,Q)|0,i=i+Math.imul(w,Z)|0,r=r+Math.imul(p,J)|0,o=(o=o+Math.imul(p,ee)|0)+Math.imul(g,J)|0,i=i+Math.imul(g,ee)|0;var ve=(u+(r=r+Math.imul(h,ne)|0)|0)+((8191&(o=(o=o+Math.imul(h,re)|0)+Math.imul(d,ne)|0))<<13)|0;u=((i=i+Math.imul(d,re)|0)+(o>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(C,q),o=(o=Math.imul(C,K))+Math.imul(P,q)|0,i=Math.imul(P,K),r=r+Math.imul(I,W)|0,o=(o=o+Math.imul(I,z)|0)+Math.imul(B,W)|0,i=i+Math.imul(B,z)|0,r=r+Math.imul(S,H)|0,o=(o=o+Math.imul(S,V)|0)+Math.imul(A,H)|0,i=i+Math.imul(A,V)|0,r=r+Math.imul(k,Q)|0,o=(o=o+Math.imul(k,Z)|0)+Math.imul(v,Q)|0,i=i+Math.imul(v,Z)|0,r=r+Math.imul(y,J)|0,o=(o=o+Math.imul(y,ee)|0)+Math.imul(w,J)|0,i=i+Math.imul(w,ee)|0,r=r+Math.imul(p,ne)|0,o=(o=o+Math.imul(p,re)|0)+Math.imul(g,ne)|0,i=i+Math.imul(g,re)|0;var Ee=(u+(r=r+Math.imul(h,ie)|0)|0)+((8191&(o=(o=o+Math.imul(h,se)|0)+Math.imul(d,ie)|0))<<13)|0;u=((i=i+Math.imul(d,se)|0)+(o>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(_,q),o=(o=Math.imul(_,K))+Math.imul(U,q)|0,i=Math.imul(U,K),r=r+Math.imul(C,W)|0,o=(o=o+Math.imul(C,z)|0)+Math.imul(P,W)|0,i=i+Math.imul(P,z)|0,r=r+Math.imul(I,H)|0,o=(o=o+Math.imul(I,V)|0)+Math.imul(B,H)|0,i=i+Math.imul(B,V)|0,r=r+Math.imul(S,Q)|0,o=(o=o+Math.imul(S,Z)|0)+Math.imul(A,Q)|0,i=i+Math.imul(A,Z)|0,r=r+Math.imul(k,J)|0,o=(o=o+Math.imul(k,ee)|0)+Math.imul(v,J)|0,i=i+Math.imul(v,ee)|0,r=r+Math.imul(y,ne)|0,o=(o=o+Math.imul(y,re)|0)+Math.imul(w,ne)|0,i=i+Math.imul(w,re)|0,r=r+Math.imul(p,ie)|0,o=(o=o+Math.imul(p,se)|0)+Math.imul(g,ie)|0,i=i+Math.imul(g,se)|0;var Se=(u+(r=r+Math.imul(h,ce)|0)|0)+((8191&(o=(o=o+Math.imul(h,ue)|0)+Math.imul(d,ce)|0))<<13)|0;u=((i=i+Math.imul(d,ue)|0)+(o>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(R,q),o=(o=Math.imul(R,K))+Math.imul(F,q)|0,i=Math.imul(F,K),r=r+Math.imul(_,W)|0,o=(o=o+Math.imul(_,z)|0)+Math.imul(U,W)|0,i=i+Math.imul(U,z)|0,r=r+Math.imul(C,H)|0,o=(o=o+Math.imul(C,V)|0)+Math.imul(P,H)|0,i=i+Math.imul(P,V)|0,r=r+Math.imul(I,Q)|0,o=(o=o+Math.imul(I,Z)|0)+Math.imul(B,Q)|0,i=i+Math.imul(B,Z)|0,r=r+Math.imul(S,J)|0,o=(o=o+Math.imul(S,ee)|0)+Math.imul(A,J)|0,i=i+Math.imul(A,ee)|0,r=r+Math.imul(k,ne)|0,o=(o=o+Math.imul(k,re)|0)+Math.imul(v,ne)|0,i=i+Math.imul(v,re)|0,r=r+Math.imul(y,ie)|0,o=(o=o+Math.imul(y,se)|0)+Math.imul(w,ie)|0,i=i+Math.imul(w,se)|0,r=r+Math.imul(p,ce)|0,o=(o=o+Math.imul(p,ue)|0)+Math.imul(g,ce)|0,i=i+Math.imul(g,ue)|0;var Ae=(u+(r=r+Math.imul(h,he)|0)|0)+((8191&(o=(o=o+Math.imul(h,de)|0)+Math.imul(d,he)|0))<<13)|0;u=((i=i+Math.imul(d,de)|0)+(o>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(O,q),o=(o=Math.imul(O,K))+Math.imul(M,q)|0,i=Math.imul(M,K),r=r+Math.imul(R,W)|0,o=(o=o+Math.imul(R,z)|0)+Math.imul(F,W)|0,i=i+Math.imul(F,z)|0,r=r+Math.imul(_,H)|0,o=(o=o+Math.imul(_,V)|0)+Math.imul(U,H)|0,i=i+Math.imul(U,V)|0,r=r+Math.imul(C,Q)|0,o=(o=o+Math.imul(C,Z)|0)+Math.imul(P,Q)|0,i=i+Math.imul(P,Z)|0,r=r+Math.imul(I,J)|0,o=(o=o+Math.imul(I,ee)|0)+Math.imul(B,J)|0,i=i+Math.imul(B,ee)|0,r=r+Math.imul(S,ne)|0,o=(o=o+Math.imul(S,re)|0)+Math.imul(A,ne)|0,i=i+Math.imul(A,re)|0,r=r+Math.imul(k,ie)|0,o=(o=o+Math.imul(k,se)|0)+Math.imul(v,ie)|0,i=i+Math.imul(v,se)|0,r=r+Math.imul(y,ce)|0,o=(o=o+Math.imul(y,ue)|0)+Math.imul(w,ce)|0,i=i+Math.imul(w,ue)|0,r=r+Math.imul(p,he)|0,o=(o=o+Math.imul(p,de)|0)+Math.imul(g,he)|0,i=i+Math.imul(g,de)|0;var Te=(u+(r=r+Math.imul(h,pe)|0)|0)+((8191&(o=(o=o+Math.imul(h,ge)|0)+Math.imul(d,pe)|0))<<13)|0;u=((i=i+Math.imul(d,ge)|0)+(o>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(O,W),o=(o=Math.imul(O,z))+Math.imul(M,W)|0,i=Math.imul(M,z),r=r+Math.imul(R,H)|0,o=(o=o+Math.imul(R,V)|0)+Math.imul(F,H)|0,i=i+Math.imul(F,V)|0,r=r+Math.imul(_,Q)|0,o=(o=o+Math.imul(_,Z)|0)+Math.imul(U,Q)|0,i=i+Math.imul(U,Z)|0,r=r+Math.imul(C,J)|0,o=(o=o+Math.imul(C,ee)|0)+Math.imul(P,J)|0,i=i+Math.imul(P,ee)|0,r=r+Math.imul(I,ne)|0,o=(o=o+Math.imul(I,re)|0)+Math.imul(B,ne)|0,i=i+Math.imul(B,re)|0,r=r+Math.imul(S,ie)|0,o=(o=o+Math.imul(S,se)|0)+Math.imul(A,ie)|0,i=i+Math.imul(A,se)|0,r=r+Math.imul(k,ce)|0,o=(o=o+Math.imul(k,ue)|0)+Math.imul(v,ce)|0,i=i+Math.imul(v,ue)|0,r=r+Math.imul(y,he)|0,o=(o=o+Math.imul(y,de)|0)+Math.imul(w,he)|0,i=i+Math.imul(w,de)|0;var Ie=(u+(r=r+Math.imul(p,pe)|0)|0)+((8191&(o=(o=o+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;u=((i=i+Math.imul(g,ge)|0)+(o>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(O,H),o=(o=Math.imul(O,V))+Math.imul(M,H)|0,i=Math.imul(M,V),r=r+Math.imul(R,Q)|0,o=(o=o+Math.imul(R,Z)|0)+Math.imul(F,Q)|0,i=i+Math.imul(F,Z)|0,r=r+Math.imul(_,J)|0,o=(o=o+Math.imul(_,ee)|0)+Math.imul(U,J)|0,i=i+Math.imul(U,ee)|0,r=r+Math.imul(C,ne)|0,o=(o=o+Math.imul(C,re)|0)+Math.imul(P,ne)|0,i=i+Math.imul(P,re)|0,r=r+Math.imul(I,ie)|0,o=(o=o+Math.imul(I,se)|0)+Math.imul(B,ie)|0,i=i+Math.imul(B,se)|0,r=r+Math.imul(S,ce)|0,o=(o=o+Math.imul(S,ue)|0)+Math.imul(A,ce)|0,i=i+Math.imul(A,ue)|0,r=r+Math.imul(k,he)|0,o=(o=o+Math.imul(k,de)|0)+Math.imul(v,he)|0,i=i+Math.imul(v,de)|0;var Be=(u+(r=r+Math.imul(y,pe)|0)|0)+((8191&(o=(o=o+Math.imul(y,ge)|0)+Math.imul(w,pe)|0))<<13)|0;u=((i=i+Math.imul(w,ge)|0)+(o>>>13)|0)+(Be>>>26)|0,Be&=67108863,r=Math.imul(O,Q),o=(o=Math.imul(O,Z))+Math.imul(M,Q)|0,i=Math.imul(M,Z),r=r+Math.imul(R,J)|0,o=(o=o+Math.imul(R,ee)|0)+Math.imul(F,J)|0,i=i+Math.imul(F,ee)|0,r=r+Math.imul(_,ne)|0,o=(o=o+Math.imul(_,re)|0)+Math.imul(U,ne)|0,i=i+Math.imul(U,re)|0,r=r+Math.imul(C,ie)|0,o=(o=o+Math.imul(C,se)|0)+Math.imul(P,ie)|0,i=i+Math.imul(P,se)|0,r=r+Math.imul(I,ce)|0,o=(o=o+Math.imul(I,ue)|0)+Math.imul(B,ce)|0,i=i+Math.imul(B,ue)|0,r=r+Math.imul(S,he)|0,o=(o=o+Math.imul(S,de)|0)+Math.imul(A,he)|0,i=i+Math.imul(A,de)|0;var xe=(u+(r=r+Math.imul(k,pe)|0)|0)+((8191&(o=(o=o+Math.imul(k,ge)|0)+Math.imul(v,pe)|0))<<13)|0;u=((i=i+Math.imul(v,ge)|0)+(o>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(O,J),o=(o=Math.imul(O,ee))+Math.imul(M,J)|0,i=Math.imul(M,ee),r=r+Math.imul(R,ne)|0,o=(o=o+Math.imul(R,re)|0)+Math.imul(F,ne)|0,i=i+Math.imul(F,re)|0,r=r+Math.imul(_,ie)|0,o=(o=o+Math.imul(_,se)|0)+Math.imul(U,ie)|0,i=i+Math.imul(U,se)|0,r=r+Math.imul(C,ce)|0,o=(o=o+Math.imul(C,ue)|0)+Math.imul(P,ce)|0,i=i+Math.imul(P,ue)|0,r=r+Math.imul(I,he)|0,o=(o=o+Math.imul(I,de)|0)+Math.imul(B,he)|0,i=i+Math.imul(B,de)|0;var Ce=(u+(r=r+Math.imul(S,pe)|0)|0)+((8191&(o=(o=o+Math.imul(S,ge)|0)+Math.imul(A,pe)|0))<<13)|0;u=((i=i+Math.imul(A,ge)|0)+(o>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(O,ne),o=(o=Math.imul(O,re))+Math.imul(M,ne)|0,i=Math.imul(M,re),r=r+Math.imul(R,ie)|0,o=(o=o+Math.imul(R,se)|0)+Math.imul(F,ie)|0,i=i+Math.imul(F,se)|0,r=r+Math.imul(_,ce)|0,o=(o=o+Math.imul(_,ue)|0)+Math.imul(U,ce)|0,i=i+Math.imul(U,ue)|0,r=r+Math.imul(C,he)|0,o=(o=o+Math.imul(C,de)|0)+Math.imul(P,he)|0,i=i+Math.imul(P,de)|0;var Pe=(u+(r=r+Math.imul(I,pe)|0)|0)+((8191&(o=(o=o+Math.imul(I,ge)|0)+Math.imul(B,pe)|0))<<13)|0;u=((i=i+Math.imul(B,ge)|0)+(o>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(O,ie),o=(o=Math.imul(O,se))+Math.imul(M,ie)|0,i=Math.imul(M,se),r=r+Math.imul(R,ce)|0,o=(o=o+Math.imul(R,ue)|0)+Math.imul(F,ce)|0,i=i+Math.imul(F,ue)|0,r=r+Math.imul(_,he)|0,o=(o=o+Math.imul(_,de)|0)+Math.imul(U,he)|0,i=i+Math.imul(U,de)|0;var Ne=(u+(r=r+Math.imul(C,pe)|0)|0)+((8191&(o=(o=o+Math.imul(C,ge)|0)+Math.imul(P,pe)|0))<<13)|0;u=((i=i+Math.imul(P,ge)|0)+(o>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(O,ce),o=(o=Math.imul(O,ue))+Math.imul(M,ce)|0,i=Math.imul(M,ue),r=r+Math.imul(R,he)|0,o=(o=o+Math.imul(R,de)|0)+Math.imul(F,he)|0,i=i+Math.imul(F,de)|0;var _e=(u+(r=r+Math.imul(_,pe)|0)|0)+((8191&(o=(o=o+Math.imul(_,ge)|0)+Math.imul(U,pe)|0))<<13)|0;u=((i=i+Math.imul(U,ge)|0)+(o>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(O,he),o=(o=Math.imul(O,de))+Math.imul(M,he)|0,i=Math.imul(M,de);var Ue=(u+(r=r+Math.imul(R,pe)|0)|0)+((8191&(o=(o=o+Math.imul(R,ge)|0)+Math.imul(F,pe)|0))<<13)|0;u=((i=i+Math.imul(F,ge)|0)+(o>>>13)|0)+(Ue>>>26)|0,Ue&=67108863;var De=(u+(r=Math.imul(O,pe))|0)+((8191&(o=(o=Math.imul(O,ge))+Math.imul(M,pe)|0))<<13)|0;return u=((i=Math.imul(M,ge))+(o>>>13)|0)+(De>>>26)|0,De&=67108863,c[0]=me,c[1]=ye,c[2]=we,c[3]=be,c[4]=ke,c[5]=ve,c[6]=Ee,c[7]=Se,c[8]=Ae,c[9]=Te,c[10]=Ie,c[11]=Be,c[12]=xe,c[13]=Ce,c[14]=Pe,c[15]=Ne,c[16]=_e,c[17]=Ue,c[18]=De,0!==u&&(c[19]=u,n.length++),n};function m(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,o=0,i=0;i<n.length-1;i++){var s=o;o=0;for(var a=67108863&r,c=Math.min(i,t.length-1),u=Math.max(0,i-e.length+1);u<=c;u++){var l=i-u,h=(0|e.words[l])*(0|t.words[u]),d=67108863&h;a=67108863&(d=d+a|0),o+=(s=(s=s+(h/67108864|0)|0)+(d>>>26)|0)>>>26,s&=67108863}n.words[i]=a,r=s,s=o}return 0!==r?n.words[i]=r:n.length--,n._strip()}function y(e,t,n){return m(e,t,n)}Math.imul||(g=p),o.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?g(this,e,t):n<63?p(this,e,t):n<1024?m(this,e,t):y(this,e,t)},o.prototype.mul=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},o.prototype.mulf=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),y(this,e,t)},o.prototype.imul=function(e){return this.clone().mulTo(e,this)},o.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var r=0,o=0;o<this.length;o++){var i=(0|this.words[o])*e,s=(67108863&i)+(67108863&r);r>>=26,r+=i/67108864|0,r+=s>>>26,this.words[o]=67108863&s}return 0!==r&&(this.words[o]=r,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n<t.length;n++){var r=n/26|0,o=n%26;t[n]=e.words[r]>>>o&1}return t}(e);if(0===t.length)return new o(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var i=n.sqr();r<t.length;r++,i=i.sqr())0!==t[r]&&(n=n.mul(i));return n},o.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,o=(e-r)/26,i=67108863>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&i,c=(0|this.words[t])-a<<r;this.words[t]=c|s,s=a>>>26-r}s&&(this.words[t]=s,this.length++)}if(0!==o){for(t=this.length-1;t>=0;t--)this.words[t+o]=this.words[t];for(t=0;t<o;t++)this.words[t]=0;this.length+=o}return this._strip()},o.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},o.prototype.iushrn=function(e,t,r){var o;n("number"==typeof e&&e>=0),o=t?(t-t%26)/26:0;var i=e%26,s=Math.min((e-i)/26,this.length),a=67108863^67108863>>>i<<i,c=r;if(o-=s,o=Math.max(0,o),c){for(var u=0;u<s;u++)c.words[u]=this.words[u];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,u=0;u<this.length;u++)this.words[u]=this.words[u+s];else this.words[0]=0,this.length=1;var l=0;for(u=this.length-1;u>=0&&(0!==l||u>=o);u--){var h=0|this.words[u];this.words[u]=l<<26-i|h>>>i,l=h&a}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,o=1<<t;return!(this.length<=r||!(this.words[r]&o))},o.prototype.imaskn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var o=67108863^67108863>>>t<<t;this.words[this.length-1]&=o}return this._strip()},o.prototype.maskn=function(e){return this.clone().imaskn(e)},o.prototype.iaddn=function(e){return n("number"==typeof e),n(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<=e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},o.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this._strip()},o.prototype.addn=function(e){return this.clone().iaddn(e)},o.prototype.subn=function(e){return this.clone().isubn(e)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(e,t,r){var o,i,s=e.length+r;this._expand(s);var a=0;for(o=0;o<e.length;o++){i=(0|this.words[o+r])+a;var c=(0|e.words[o])*t;a=((i-=67108863&c)>>26)-(c/67108864|0),this.words[o+r]=67108863&i}for(;o<this.length-r;o++)a=(i=(0|this.words[o+r])+a)>>26,this.words[o+r]=67108863&i;if(0===a)return this._strip();for(n(-1===a),a=0,o=0;o<this.length;o++)a=(i=-(0|this.words[o])+a)>>26,this.words[o]=67108863&i;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,s=0|i.words[i.length-1];0!=(n=26-this._countBits(s))&&(i=i.ushln(n),r.iushln(n),s=0|i.words[i.length-1]);var a,c=r.length-i.length;if("mod"!==t){(a=new o(null)).length=c+1,a.words=new Array(a.length);for(var u=0;u<a.length;u++)a.words[u]=0}var l=r.clone()._ishlnsubmul(i,1,c);0===l.negative&&(r=l,a&&(a.words[c]=1));for(var h=c-1;h>=0;h--){var d=67108864*(0|r.words[i.length+h])+(0|r.words[i.length+h-1]);for(d=Math.min(d/s|0,67108863),r._ishlnsubmul(i,d,h);0!==r.negative;)d--,r.negative=0,r._ishlnsubmul(i,1,h),r.isZero()||(r.negative^=1);a&&(a.words[h]=d)}return a&&a._strip(),r._strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(i=a.div.neg()),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:i,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(i=a.div.neg()),{div:i,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),o=e.andln(1),i=n.cmp(r);return i<0||1===o&&0===i?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,o=0,i=this.length-1;i>=0;i--)o=(r*o+(0|this.words[i]))%e;return t?-o:o},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,o=this.length-1;o>=0;o--){var i=(0|this.words[o])+67108864*r;this.words[o]=i/e|0,r=i%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),s=new o(0),a=new o(0),c=new o(1),u=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++u;for(var l=r.clone(),h=t.clone();!t.isZero();){for(var d=0,f=1;0===(t.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||s.isOdd())&&(i.iadd(l),s.isub(h)),i.iushrn(1),s.iushrn(1);for(var p=0,g=1;0===(r.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(h)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(a),s.isub(c)):(r.isub(t),a.isub(i),c.isub(s))}return{a:a,b:c,gcd:r.iushln(u)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,s=new o(1),a=new o(0),c=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var u=0,l=1;0===(t.words[0]&l)&&u<26;++u,l<<=1);if(u>0)for(t.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var h=0,d=1;0===(r.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(r.iushrn(h);h-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),s.isub(a)):(r.isub(t),a.isub(s))}return(i=0===t.cmpn(1)?s:a).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var o=t.cmp(n);if(o<0){var i=t;t=n,n=i}else if(0===o||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return!(1&this.words[0])},o.prototype.isOdd=function(){return!(1&~this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,o=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=o,this;for(var i=o,s=r;0!==i&&s<this.length;s++){var a=0|this.words[s];i=(a+=i)>>>26,a&=67108863,this.words[s]=a}return 0!==i&&(this.words[s]=i,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var o=0|this.words[0];t=o===e?0:o<e?-1:1}return 0!==this.negative?0|-t:t},o.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},o.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,n=this.length-1;n>=0;n--){var r=0|this.words[n],o=0|e.words[n];if(r!==o){r<o?t=-1:r>o&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var w={k256:null,p224:null,p192:null,p25519:null};function b(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function k(){b.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){b.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function E(){b.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){b.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function T(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}b.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},b.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t<this.n?-1:n.ucmp(this.p);return 0===r?(n.words[0]=0,n.length=1):r>0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},b.prototype.split=function(e,t){e.iushrn(this.n,0,t)},b.prototype.imulK=function(e){return e.imul(this.k)},r(k,b),k.prototype.split=function(e,t){for(var n=4194303,r=Math.min(e.length,9),o=0;o<r;o++)t.words[o]=e.words[o];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var i=e.words[9];for(t.words[t.length++]=i&n,o=10;o<e.length;o++){var s=0|e.words[o];e.words[o-10]=(s&n)<<4|i>>>22,i=s}i>>>=22,e.words[o-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},k.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n<e.length;n++){var r=0|e.words[n];t+=977*r,e.words[n]=67108863&t,t=64*r+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},r(v,b),r(E,b),r(S,b),S.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,o=67108863&r;r>>>=26,e.words[n]=o,t=r}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(w[e])return w[e];var t;if("k256"===e)t=new k;else if("p224"===e)t=new v;else if("p192"===e)t=new E;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new S}return w[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0===(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(u(e,e.umod(this.m)._forceRed(this)),e)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},A.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),s=0;!i.isZero()&&0===i.andln(1);)s++,i.iushrn(1);n(!i.isZero());var a=new o(1).toRed(this),c=a.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var h=this.pow(l,i),d=this.pow(e,i.addn(1).iushrn(1)),f=this.pow(e,i),p=s;0!==f.cmp(a);){for(var g=f,m=0;0!==g.cmp(a);m++)g=g.redSqr();n(m<p);var y=this.pow(h,new o(1).iushln(p-m-1));d=d.redMul(y),h=y.redSqr(),f=f.redMul(h),p=m}return d},A.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},A.prototype.pow=function(e,t){if(t.isZero())return new o(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new o(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var i=n[0],s=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),r=t.length-1;r>=0;r--){for(var u=t.words[r],l=c-1;l>=0;l--){var h=u>>l&1;i!==n[0]&&(i=this.sqr(i)),0!==h||0!==s?(s<<=1,s|=h,(4===++a||0===r&&0===l)&&(i=this.mul(i,n[s]),a=0,s=0)):a=0}c=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new T(e)},r(T,A),T.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},T.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},T.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=n.isub(r).iushrn(this.shift),i=o;return o.cmp(this.m)>=0?i=o.isub(this.m):o.cmpn(0)<0&&(i=o.iadd(this.m)),i._forceRed(this)},T.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(ku,Eu)),ku.exports}var Au,Tu,Iu,Bu,xu,Cu,Pu=hi(Su()),Nu={exports:{}},_u={};function Uu(){return Au||(Au=1,function(e){var t=Ks(),n=js(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;var o=2147483647;function i(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|f(e,t),r=i(n),o=r.write(e,t);o!==n&&(r=r.slice(0,o));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(M(e,Uint8Array)){var t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(M(e,ArrayBuffer)||e&&M(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(M(e,SharedArrayBuffer)||e&&M(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);var o=function(e){if(s.isBuffer(e)){var t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||$(e.length)?i(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),i(e<0?0:0|d(e))}function l(e){for(var t=e.length<0?0:0|d(e.length),n=i(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function d(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||M(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var o=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return F(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(e).length;default:if(o)return r?-1:F(e).length;t=(""+t).toLowerCase(),o=!0}}function p(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return B(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),$(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){var i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){var l=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===l?0:i-l)){if(-1===l&&(l=i),i-l+1===c)return l*s}else-1!==l&&(i-=i-l),l=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){for(var h=!0,d=0;d<c;d++)if(u(e,i+d)!==u(t,d)){h=!1;break}if(h)return i}return-1}function w(e,t,n,r){n=Number(n)||0;var o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;var i=t.length;r>i/2&&(r=i/2);for(var s=0;s<r;++s){var a=parseInt(t.substr(2*s,2),16);if($(a))return s;e[n+s]=a}return s}function b(e,t,n,r){return O(F(t,e.length-n),e,n,r)}function k(e,t,n,r){return O(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return O(L(t),e,n,r)}function E(e,t,n,r){return O(function(e,t){for(var n,r,o,i=[],s=0;s<e.length&&!((t-=2)<0);++s)r=(n=e.charCodeAt(s))>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function A(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o<n;){var i,s,a,c,u=e[o],l=null,h=u>239?4:u>223?3:u>191?2:1;if(o+h<=n)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(i=e[o+1]))&&(c=(31&u)<<6|63&i)>127&&(l=c);break;case 3:i=e[o+1],s=e[o+2],128==(192&i)&&128==(192&s)&&(c=(15&u)<<12|(63&i)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:i=e[o+1],s=e[o+2],a=e[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),o+=h}return function(e){var t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=o,s.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(M(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),M(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=s.allocUnsafe(t),o=0;for(n=0;n<e.length;++n){var i=e[n];if(M(i,Uint8Array))o+i.length>r.length?s.from(i).copy(r,o):Uint8Array.prototype.set.call(r,i,o);else{if(!s.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(r,o)}o+=i.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},s.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},s.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},s.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?A(this,0,e):p.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var t="",n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,o){if(M(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n),h=0;h<c;++h)if(u[h]!==l[h]){i=u[h],a=l[h];break}return i<a?-1:a<i?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var T=4096;function I(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function B(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function x(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var o="",i=t;i<n;++i)o+=q[e[i]];return o}function C(e,t,n){for(var r=e.slice(t,n),o="",i=0;i<r.length-1;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}function P(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,r,o,i){return t=+t,r>>>=0,i||_(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function D(e,t,r,o,i){return t=+t,r>>>=0,i||_(e,0,r,8),n.write(e,t,r,o,52,8),r+8}s.prototype.slice=function(e,t){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e+--t],o=1;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return r>=(o*=128)&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t>>>=0,n>>>=0,r)||N(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){(e=+e,t>>>=0,n>>>=0,r)||N(this,e,t,n,Math.pow(2,8*n)-1,0);var o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var o=Math.pow(2,8*n-1);N(this,e,t,n,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i<n&&(s*=256);)e<0&&0===a&&0!==this[t+i-1]&&(a=1),this[t+i]=(e/s|0)-a&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var o=Math.pow(2,8*n-1);N(this,e,t,n,o-1,-o)}var i=n-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s|0)-a&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return D(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return D(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var o=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),o},s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var o=e.charCodeAt(0);("utf8"===r&&o<128||"latin1"===r)&&(e=o)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var i;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i<n;++i)this[i]=e;else{var a=s.isBuffer(e)?e:s.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<n-t;++i)this[i+t]=a[i%c]}return this};var R=/[^+/0-9A-Za-z-_]/g;function F(e,t){var n;t=t||1/0;for(var r=e.length,o=null,i=[],s=0;s<r;++s){if((n=e.charCodeAt(s))>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function L(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(R,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function O(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function M(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function $(e){return e!=e}var q=function(){for(var e="0123456789abcdef",t=new Array(256),n=0;n<16;++n)for(var r=16*n,o=0;o<16;++o)t[r+o]=e[n]+e[o];return t}()}(_u)),_u}function Du(){return Tu||(Tu=1,function(e,t){var n=Uu(),r=n.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=i),o(r,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var o=r(e);return void 0!==t?"string"==typeof n?o.fill(t,n):o.fill(t):o.fill(0),o},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(Nu,Nu.exports)),Nu.exports}var Ru=function(){if(Cu)return xu;Cu=1;var e=function(){if(Bu)return Iu;Bu=1;var e=Du().Buffer;return Iu=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<t.length;o++){var i=t.charAt(o),s=i.charCodeAt(0);if(255!==n[s])throw new TypeError(i+" is ambiguous");n[s]=o}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,o=0,i=0;t[r]===c;)o++,r++;for(var s=(t.length-r)*u+1>>>0,l=new Uint8Array(s);r<t.length;){var h=t.charCodeAt(r);if(h>255)return;var d=n[h];if(255===d)return;for(var f=0,p=s-1;(0!==d||f<i)&&-1!==p;p--,f++)d+=a*l[p]>>>0,l[p]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");i=f,r++}for(var g=s-i;g!==s&&0===l[g];)g++;var m=e.allocUnsafe(o+(s-g));m.fill(0,0,o);for(var y=o;g!==s;)m[y++]=l[g++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,o=0,i=0,s=n.length;i!==s&&0===n[i];)i++,r++;for(var u=(s-i)*l+1>>>0,h=new Uint8Array(u);i!==s;){for(var d=n[i],f=0,p=u-1;(0!==d||f<o)&&-1!==p;p--,f++)d+=256*h[p]>>>0,h[p]=d%a>>>0,d=d/a>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,i++}for(var g=u-o;g!==u&&0===h[g];)g++;for(var m=c.repeat(r);g<u;++g)m+=t.charAt(h[g]);return m},decodeUnsafe:h,decode:function(e){var t=h(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},Iu}();return xu=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}(),Fu=hi(Ru);const Lu=Xa;var Ou,Mu,$u,qu,Ku={};function Gu(){if(qu)return $u;qu=1;var e=function(){if(Mu)return Ou;Mu=1;var e=Du().Buffer;return Ou=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<t.length;o++){var i=t.charAt(o),s=i.charCodeAt(0);if(255!==n[s])throw new TypeError(i+" is ambiguous");n[s]=o}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,o=0,i=0;t[r]===c;)o++,r++;for(var s=(t.length-r)*u+1>>>0,l=new Uint8Array(s);r<t.length;){var h=t.charCodeAt(r);if(h>255)return;var d=n[h];if(255===d)return;for(var f=0,p=s-1;(0!==d||f<i)&&-1!==p;p--,f++)d+=a*l[p]>>>0,l[p]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");i=f,r++}for(var g=s-i;g!==s&&0===l[g];)g++;var m=e.allocUnsafe(o+(s-g));m.fill(0,0,o);for(var y=o;g!==s;)m[y++]=l[g++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,o=0,i=0,s=n.length;i!==s&&0===n[i];)i++,r++;for(var u=(s-i)*l+1>>>0,h=new Uint8Array(u);i!==s;){for(var d=n[i],f=0,p=u-1;(0!==d||f<o)&&-1!==p;p--,f++)d+=256*h[p]>>>0,h[p]=d%a>>>0,d=d/a>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,i++}for(var g=u-o;g!==u&&0===h[g];)g++;for(var m=c.repeat(r);g<u;++g)m+=t.charAt(h[g]);return m},decodeUnsafe:h,decode:function(e){var t=h(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},Ou}();return $u=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}function Wu(e,t,n){return t<=e&&e<=n}function zu(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function ju(e){this.tokens=[].slice.call(e)}ju.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():-1},prepend:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.unshift(t.pop());else this.tokens.unshift(e)},push:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.push(t.shift());else this.tokens.push(e)}};var Hu=-1;function Vu(e,t){if(e)throw TypeError("Decoder error");return t||65533}var Xu="utf-8";function Qu(e,t){if(!(this instanceof Qu))return new Qu(e,t);if((e=void 0!==e?String(e).toLowerCase():Xu)!==Xu)throw new Error("Encoding not supported. Only utf-8 is supported");t=zu(t),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=Boolean(t.fatal),this._ignoreBOM=Boolean(t.ignoreBOM),Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}function Zu(e,t){if(!(this instanceof Zu))return new Zu(e,t);if((e=void 0!==e?String(e).toLowerCase():Xu)!==Xu)throw new Error("Encoding not supported. Only utf-8 is supported");t=zu(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function Yu(e){var t=e.fatal,n=0,r=0,o=0,i=128,s=191;this.handler=function(e,a){if(-1===a&&0!==o)return o=0,Vu(t);if(-1===a)return Hu;if(0===o){if(Wu(a,0,127))return a;if(Wu(a,194,223))o=1,n=a-192;else if(Wu(a,224,239))224===a&&(i=160),237===a&&(s=159),o=2,n=a-224;else{if(!Wu(a,240,244))return Vu(t);240===a&&(i=144),244===a&&(s=143),o=3,n=a-240}return n<<=6*o,null}if(!Wu(a,i,s))return n=o=r=0,i=128,s=191,e.prepend(a),Vu(t);if(i=128,s=191,n+=a-128<<6*(o-(r+=1)),r!==o)return null;var c=n;return n=o=r=0,c}}function Ju(e){e.fatal,this.handler=function(e,t){if(-1===t)return Hu;if(Wu(t,0,127))return t;var n,r;Wu(t,128,2047)?(n=1,r=192):Wu(t,2048,65535)?(n=2,r=224):Wu(t,65536,1114111)&&(n=3,r=240);for(var o=[(t>>6*n)+r];n>0;){var i=t>>6*(n-1);o.push(128|63&i),n-=1}return o}}Qu.prototype={decode:function(e,t){var n;n="object"==typeof e&&e instanceof ArrayBuffer?new Uint8Array(e):"object"==typeof e&&"buffer"in e&&e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(0),t=zu(t),this._streaming||(this._decoder=new Yu({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,o=new ju(n),i=[];!o.endOfStream()&&(r=this._decoder.handler(o,o.read()))!==Hu;)null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r));if(!this._streaming){do{if((r=this._decoder.handler(o,o.read()))===Hu)break;null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r))}while(!o.endOfStream());this._decoder=null}return i.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===i[0]?(this._BOMseen=!0,i.shift()):this._BOMseen=!0)),function(e){for(var t="",n=0;n<e.length;++n){var r=e[n];r<=65535?t+=String.fromCharCode(r):(r-=65536,t+=String.fromCharCode(55296+(r>>10),56320+(1023&r)))}return t}(i)}},Zu.prototype={encode:function(e,t){e=e?String(e):"",t=zu(t),this._streaming||(this._encoder=new Ju(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],o=new ju(function(e){for(var t=String(e),n=t.length,r=0,o=[];r<n;){var i=t.charCodeAt(r);if(i<55296||i>57343)o.push(i);else if(56320<=i&&i<=57343)o.push(65533);else if(55296<=i&&i<=56319)if(r===n-1)o.push(65533);else{var s=e.charCodeAt(r+1);if(56320<=s&&s<=57343){var a=1023&i,c=1023&s;o.push(65536+(a<<10)+c),r+=1}else o.push(65533)}r+=1}return o}(e));!o.endOfStream()&&(n=this._encoder.handler(o,o.read()))!==Hu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(o,o.read()))!==Hu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var el,tl=di(Object.freeze({__proto__:null,TextDecoder:Qu,TextEncoder:Zu}));var nl,rl,ol=function(){if(el)return Ku;el=1;var e=Ku&&Ku.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),t=Ku&&Ku.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=Ku&&Ku.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},r=Ku&&Ku.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(null!=n)for(var o in n)"default"!==o&&Object.hasOwnProperty.call(n,o)&&e(r,n,o);return t(r,n),r},o=Ku&&Ku.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ku,"__esModule",{value:!0}),Ku.deserializeUnchecked=Ku.deserialize=Ku.serialize=Ku.BinaryReader=Ku.BinaryWriter=Ku.BorshError=Ku.baseDecode=Ku.baseEncode=void 0;const i=o(Su()),s=o(Gu()),a=r(tl),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});Ku.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),s.default.encode(Buffer.from(e))},Ku.baseDecode=function(e){return Buffer.from(s.default.decode(e))};const u=1024;class l extends Error{constructor(e){super(e),this.fieldPath=[],this.originalMessage=e}addToFieldPath(e){this.fieldPath.splice(0,0,e),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}Ku.BorshError=l;class h{constructor(){this.buf=Buffer.alloc(u),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(u)]))}writeU8(e){this.maybeResize(),this.buf.writeUInt8(e,this.length),this.length+=1}writeU16(e){this.maybeResize(),this.buf.writeUInt16LE(e,this.length),this.length+=2}writeU32(e){this.maybeResize(),this.buf.writeUInt32LE(e,this.length),this.length+=4}writeU64(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",64)))}writeBuffer(e){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),e,Buffer.alloc(u)]),this.length+=e.length}writeString(e){this.maybeResize();const t=Buffer.from(e,"utf8");this.writeU32(t.length),this.writeBuffer(t)}writeFixedArray(e){this.writeBuffer(Buffer.from(e))}writeArray(e,t){this.maybeResize(),this.writeU32(e.length);for(const n of e)this.maybeResize(),t(n)}toArray(){return this.buf.subarray(0,this.length)}}function d(e,t,n){const r=n.value;n.value=function(...e){try{return r.apply(this,e)}catch(e){if(e instanceof RangeError){const t=e.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(t)>=0)throw new l("Reached the end of buffer when deserializing")}throw e}}}Ku.BinaryWriter=h;class f{constructor(e){this.buf=e,this.offset=0}readU8(){const e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readU16(){const e=this.buf.readUInt16LE(this.offset);return this.offset+=2,e}readU32(){const e=this.buf.readUInt32LE(this.offset);return this.offset+=4,e}readU64(){const e=this.readBuffer(8);return new i.default(e,"le")}readU128(){const e=this.readBuffer(16);return new i.default(e,"le")}readU256(){const e=this.readBuffer(32);return new i.default(e,"le")}readU512(){const e=this.readBuffer(64);return new i.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new l(`Expected buffer length ${e} isn't within bounds`);const t=this.buf.slice(this.offset,this.offset+e);return this.offset+=e,t}readString(){const e=this.readU32(),t=this.readBuffer(e);try{return c.decode(t)}catch(e){throw new l(`Error decoding UTF-8 string: ${e}`)}}readFixedArray(e){return new Uint8Array(this.readBuffer(e))}readArray(e){const t=this.readU32(),n=Array();for(let r=0;r<t;++r)n.push(e());return n}}function p(e){return e.charAt(0).toUpperCase()+e.slice(1)}function g(e,t,n,r,o){try{if("string"==typeof r)o[`write${p(r)}`](n);else if(r instanceof Array)if("number"==typeof r[0]){if(n.length!==r[0])throw new l(`Expecting byte array of length ${r[0]}, but got ${n.length} bytes`);o.writeFixedArray(n)}else if(2===r.length&&"number"==typeof r[1]){if(n.length!==r[1])throw new l(`Expecting byte array of length ${r[1]}, but got ${n.length} bytes`);for(let t=0;t<r[1];t++)g(e,null,n[t],r[0],o)}else o.writeArray(n,n=>{g(e,t,n,r[0],o)});else if(void 0!==r.kind)switch(r.kind){case"option":null==n?o.writeU8(0):(o.writeU8(1),g(e,t,n,r.type,o));break;case"map":o.writeU32(n.size),n.forEach((n,i)=>{g(e,t,i,r.key,o),g(e,t,n,r.value,o)});break;default:throw new l(`FieldType ${r} unrecognized`)}else m(e,n,o)}catch(e){throw e instanceof l&&e.addToFieldPath(t),e}}function m(e,t,n){if("function"==typeof t.borshSerialize)return void t.borshSerialize(n);const r=e.get(t.constructor);if(!r)throw new l(`Class ${t.constructor.name} is missing in schema`);if("struct"===r.kind)r.fields.map(([r,o])=>{g(e,r,t[r],o,n)});else{if("enum"!==r.kind)throw new l(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`);{const o=t[r.field];for(let i=0;i<r.values.length;++i){const[s,a]=r.values[i];if(s===o){n.writeU8(i),g(e,s,t[s],a,n);break}}}}}function y(e,t,n,r){try{if("string"==typeof n)return r[`read${p(n)}`]();if(n instanceof Array){if("number"==typeof n[0])return r.readFixedArray(n[0]);if("number"==typeof n[1]){const t=[];for(let o=0;o<n[1];o++)t.push(y(e,null,n[0],r));return t}return r.readArray(()=>y(e,t,n[0],r))}if("option"===n.kind){return r.readU8()?y(e,t,n.type,r):void 0}if("map"===n.kind){let o=new Map;const i=r.readU32();for(let s=0;s<i;s++){const i=y(e,t,n.key,r),s=y(e,t,n.value,r);o.set(i,s)}return o}return w(e,n,r)}catch(e){throw e instanceof l&&e.addToFieldPath(t),e}}function w(e,t,n){if("function"==typeof t.borshDeserialize)return t.borshDeserialize(n);const r=e.get(t);if(!r)throw new l(`Class ${t.name} is missing in schema`);if("struct"===r.kind){const r={};for(const[o,i]of e.get(t).fields)r[o]=y(e,o,i,n);return new t(r)}if("enum"===r.kind){const o=n.readU8();if(o>=r.values.length)throw new l(`Enum index: ${o} is out of range`);const[i,s]=r.values[o],a=y(e,i,s,n);return new t({[i]:a})}throw new l(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`)}return n([d],f.prototype,"readU8",null),n([d],f.prototype,"readU16",null),n([d],f.prototype,"readU32",null),n([d],f.prototype,"readU64",null),n([d],f.prototype,"readU128",null),n([d],f.prototype,"readU256",null),n([d],f.prototype,"readU512",null),n([d],f.prototype,"readString",null),n([d],f.prototype,"readFixedArray",null),n([d],f.prototype,"readArray",null),Ku.BinaryReader=f,Ku.serialize=function(e,t,n=h){const r=new n;return m(e,t,r),r.toArray()},Ku.deserialize=function(e,t,n,r=f){const o=new r(n),i=w(e,t,o);if(o.offset<n.length)throw new l(`Unexpected ${n.length-o.offset} bytes after deserialized data`);return i},Ku.deserializeUnchecked=function(e,t,n,r=f){return w(e,t,new r(n))},Ku}(),il={},sl={};function al(){return nl||(nl=1,function(e){const t=Ks(),n=js(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;function i(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=i(n);const o=r.write(e,t);o!==n&&(r=r.slice(0,o));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);const o=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?i(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),i(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=i(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function d(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(o)return r?-1:W(e).length;t=(""+t).toLowerCase(),o=!0}}function p(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return B(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return j(W(t,e.length-n),e,n,r)}function k(e,t,n,r){return j(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return j(z(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function A(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=o,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let o=0;for(n=0;n<e.length;++n){let t=e[n];if(H(t,Uint8Array))o+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)g(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?A(this,0,e):p.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,o){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){i=u[e],a=l[e];break}return i<a?-1:a<i?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function B(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function x(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=X[e[r]];return o}function C(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function P(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function U(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function F(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,8),n.write(e,t,r,o,52,8),r+8}s.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){N(this,e,t,n,Math.pow(2,8*n)-1,0)}let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){N(this,e,t,n,Math.pow(2,8*n)-1,0)}let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return _(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=Q(function(e,t=0){return _(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const o=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),o},s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{const i=s.isBuffer(e)?e:s.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%a]}return this};const L={};function O(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function M(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,o,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,o,i)}function q(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}O("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),O("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),O("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=M(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=M(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function z(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function H(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(sl)),sl}var cl=function(){if(rl)return il;rl=1,Object.defineProperty(il,"__esModule",{value:!0}),il.s16=il.s8=il.nu64be=il.u48be=il.u40be=il.u32be=il.u24be=il.u16be=il.nu64=il.u48=il.u40=il.u32=il.u24=il.u16=il.u8=il.offset=il.greedy=il.Constant=il.UTF8=il.CString=il.Blob=il.Boolean=il.BitField=il.BitStructure=il.VariantLayout=il.Union=il.UnionLayoutDiscriminator=il.UnionDiscriminator=il.Structure=il.Sequence=il.DoubleBE=il.Double=il.FloatBE=il.Float=il.NearInt64BE=il.NearInt64=il.NearUInt64BE=il.NearUInt64=il.IntBE=il.Int=il.UIntBE=il.UInt=il.OffsetLayout=il.GreedyCount=il.ExternalLayout=il.bindConstructorLayout=il.nameWithProperty=il.Layout=il.uint8ArrayToBuffer=il.checkUint8Array=void 0,il.constant=il.utf8=il.cstr=il.blob=il.unionLayoutDiscriminator=il.union=il.seq=il.bits=il.struct=il.f64be=il.f64=il.f32be=il.f32=il.ns64be=il.s48be=il.s40be=il.s32be=il.s24be=il.s16be=il.ns64=il.s48=il.s40=il.s32=il.s24=void 0;const e=al();function t(e){if(!(e instanceof Uint8Array))throw new TypeError("b must be a Uint8Array")}function n(n){return t(n),e.Buffer.from(n.buffer,n.byteOffset,n.length)}il.checkUint8Array=t,il.uint8ArrayToBuffer=n;let r=class{constructor(e,t){if(!Number.isInteger(e))throw new TypeError("span must be an integer");this.span=e,this.property=t}makeDestinationObject(){return{}}getSpan(e,t){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(e){const t=Object.create(this.constructor.prototype);return Object.assign(t,this),t.property=e,t}fromArray(e){}};function o(e,t){return t.property?e+"["+t.property+"]":e}il.Layout=r,il.nameWithProperty=o,il.bindConstructorLayout=function(e,t){if("function"!=typeof e)throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(e,"layout_"))throw new Error("Class is already bound to a layout");if(!(t&&t instanceof r))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");e.layout_=t,t.boundConstructor_=e,t.makeDestinationObject=()=>new e,Object.defineProperty(e.prototype,"encode",{value(e,n){return t.encode(this,e,n)},writable:!0}),Object.defineProperty(e,"decode",{value:(e,n)=>t.decode(e,n),writable:!0})};class i extends r{isCount(){throw new Error("ExternalLayout is abstract")}}il.ExternalLayout=i;class s extends i{constructor(e=1,t){if(!Number.isInteger(e)||0>=e)throw new TypeError("elementSpan must be a (positive) integer");super(-1,t),this.elementSpan=e}isCount(){return!0}decode(e,n=0){t(e);const r=e.length-n;return Math.floor(r/this.elementSpan)}encode(e,t,n){return 0}}il.GreedyCount=s;class a extends i{constructor(e,t=0,n){if(!(e instanceof r))throw new TypeError("layout must be a Layout");if(!Number.isInteger(t))throw new TypeError("offset must be integer or undefined");super(e.span,n||e.property),this.layout=e,this.offset=t}isCount(){return this.layout instanceof c||this.layout instanceof u}decode(e,t=0){return this.layout.decode(e,t+this.offset)}encode(e,t,n=0){return this.layout.encode(e,t,n+this.offset)}}il.OffsetLayout=a;class c extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readUIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntLE(e,r,this.span),this.span}}il.UInt=c;class u extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readUIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntBE(e,r,this.span),this.span}}il.UIntBE=u;class l extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeIntLE(e,r,this.span),this.span}}il.Int=l;class h extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeIntBE(e,r,this.span),this.span}}il.IntBE=h;const d=Math.pow(2,32);function f(e){const t=Math.floor(e/d);return{hi32:t,lo32:e-t*d}}function p(e,t){return e*d+t}class g extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),o=r.readUInt32LE(t);return p(r.readUInt32LE(t+4),o)}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeUInt32LE(o.lo32,r),i.writeUInt32LE(o.hi32,r+4),8}}il.NearUInt64=g;class m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return p(r.readUInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeUInt32BE(o.hi32,r),i.writeUInt32BE(o.lo32,r+4),8}}il.NearUInt64BE=m;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),o=r.readUInt32LE(t);return p(r.readInt32LE(t+4),o)}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeUInt32LE(o.lo32,r),i.writeInt32LE(o.hi32,r+4),8}}il.NearInt64=y;class w extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return p(r.readInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeInt32BE(o.hi32,r),i.writeUInt32BE(o.lo32,r+4),8}}il.NearInt64BE=w;class b extends r{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatLE(t)}encode(e,t,r=0){return n(t).writeFloatLE(e,r),4}}il.Float=b;class k extends r{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatBE(t)}encode(e,t,r=0){return n(t).writeFloatBE(e,r),4}}il.FloatBE=k;class v extends r{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleLE(t)}encode(e,t,r=0){return n(t).writeDoubleLE(e,r),8}}il.Double=v;class E extends r{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleBE(t)}encode(e,t,r=0){return n(t).writeDoubleBE(e,r),8}}il.DoubleBE=E;class S extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof i&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let o=-1;!(t instanceof i)&&0<e.span&&(o=t*e.span),super(o,n),this.elementLayout=e,this.count=t}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0,r=this.count;if(r instanceof i&&(r=r.decode(e,t)),0<this.elementLayout.span)n=r*this.elementLayout.span;else{let o=0;for(;o<r;)n+=this.elementLayout.getSpan(e,t+n),++o}return n}decode(e,t=0){const n=[];let r=0,o=this.count;for(o instanceof i&&(o=o.decode(e,t));r<o;)n.push(this.elementLayout.decode(e,t)),t+=this.elementLayout.getSpan(e,t),r+=1;return n}encode(e,t,n=0){const r=this.elementLayout,o=e.reduce((e,o)=>e+r.encode(o,t,n+e),0);return this.count instanceof i&&this.count.encode(e.length,t,n),o}}il.Sequence=S;class A extends r{constructor(e,t,n){if(!Array.isArray(e)||!e.reduce((e,t)=>e&&t instanceof r,!0))throw new TypeError("fields must be array of Layout instances");"boolean"==typeof t&&void 0===n&&(n=t,t=void 0);for(const t of e)if(0>t.span&&void 0===t.property)throw new Error("fields cannot contain unnamed variable-length layout");let o=-1;try{o=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(o,t),this.fields=e,this.decodePrefixes=!!n}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;try{n=this.fields.reduce((n,r)=>{const o=r.getSpan(e,t);return t+=o,n+o},0)}catch(e){throw new RangeError("indeterminate span")}return n}decode(e,n=0){t(e);const r=this.makeDestinationObject();for(const t of this.fields)if(void 0!==t.property&&(r[t.property]=t.decode(e,n)),n+=t.getSpan(e,n),this.decodePrefixes&&e.length===n)break;return r}encode(e,t,n=0){const r=n;let o=0,i=0;for(const r of this.fields){let s=r.span;if(i=0<s?s:0,void 0!==r.property){const o=e[r.property];void 0!==o&&(i=r.encode(o,t,n),0>s&&(s=r.getSpan(t,n)))}o=n,n+=s}return o+i-r}fromArray(e){const t=this.makeDestinationObject();for(const n of this.fields)void 0!==n.property&&0<e.length&&(t[n.property]=e.shift());return t}layoutFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}offsetOf(e){if("string"!=typeof e)throw new TypeError("property must be string");let t=0;for(const n of this.fields){if(n.property===e)return t;0>n.span?t=-1:0<=t&&(t+=n.span)}}}il.Structure=A;class T{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,n){throw new Error("UnionDiscriminator is abstract")}}il.UnionDiscriminator=T;class I extends T{constructor(e,t){if(!(e instanceof i&&e.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,n){return this.layout.encode(e,t,n)}}il.UnionLayoutDiscriminator=I;class B extends r{constructor(e,t,n){let o;if(e instanceof c||e instanceof u)o=new I(new a(e));else if(e instanceof i&&e.isCount())o=new I(e);else{if(!(e instanceof T))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");o=e}if(void 0===t&&(t=null),!(null===t||t instanceof r))throw new TypeError("defaultLayout must be null or a Layout");if(null!==t){if(0>t.span)throw new Error("defaultLayout must have constant span");void 0===t.property&&(t=t.replicate("content"))}let s=-1;t&&(s=t.span,0<=s&&(e instanceof c||e instanceof u)&&(s+=o.layout.span)),super(s,n),this.discriminator=o,this.usesPrefixDiscriminator=e instanceof c||e instanceof u,this.defaultLayout=t,this.registry={};let l=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(e){return l(e)},this.configGetSourceVariant=function(e){l=e.bind(this)}}getSpan(e,t=0){if(0<=this.span)return this.span;const n=this.getVariant(e,t);if(!n)throw new Error("unable to determine span for unrecognized variant");return n.getSpan(e,t)}defaultGetSourceVariant(e){if(Object.prototype.hasOwnProperty.call(e,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(e,this.defaultLayout.property))return;const t=this.registry[e[this.discriminator.property]];if(t&&(!t.layout||t.property&&Object.prototype.hasOwnProperty.call(e,t.property)))return t}else for(const t in this.registry){const n=this.registry[t];if(n.property&&Object.prototype.hasOwnProperty.call(e,n.property))return n}throw new Error("unable to infer src variant")}decode(e,t=0){let n;const r=this.discriminator,o=r.decode(e,t),i=this.registry[o];if(void 0===i){const i=this.defaultLayout;let s=0;this.usesPrefixDiscriminator&&(s=r.layout.span),n=this.makeDestinationObject(),n[r.property]=o,n[i.property]=i.decode(e,t+s)}else n=i.decode(e,t);return n}encode(e,t,n=0){const r=this.getSourceVariant(e);if(void 0===r){const r=this.discriminator,o=this.defaultLayout;let i=0;return this.usesPrefixDiscriminator&&(i=r.layout.span),r.encode(e[r.property],t,n),i+o.encode(e[o.property],t,n+i)}return r.encode(e,t,n)}addVariant(e,t,n){const r=new x(this,e,t,n);return this.registry[e]=r,r}getVariant(e,t=0){let n;return n=e instanceof Uint8Array?this.discriminator.decode(e,t):e,this.registry[n]}}il.Union=B;class x extends r{constructor(e,t,n,o){if(!(e instanceof B))throw new TypeError("union must be a Union");if(!Number.isInteger(t)||0>t)throw new TypeError("variant must be a (non-negative) integer");if("string"==typeof n&&void 0===o&&(o=n,n=null),n){if(!(n instanceof r))throw new TypeError("layout must be a Layout");if(null!==e.defaultLayout&&0<=n.span&&n.span>e.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if("string"!=typeof o)throw new TypeError("variant must have a String property")}let i=e.span;0>e.span&&(i=n?n.span:0,0<=i&&e.usesPrefixDiscriminator&&(i+=e.discriminator.layout.span)),super(i,o),this.union=e,this.variant=t,this.layout=n||null}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span);let r=0;return this.layout&&(r=this.layout.getSpan(e,t+n)),n+r}decode(e,t=0){const n=this.makeDestinationObject();if(this!==this.union.getVariant(e,t))throw new Error("variant mismatch");let r=0;return this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout?n[this.property]=this.layout.decode(e,t+r):this.property?n[this.property]=!0:this.union.usesPrefixDiscriminator&&(n[this.union.discriminator.property]=this.variant),n}encode(e,t,n=0){let r=0;if(this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(e,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,t,n);let o=r;if(this.layout&&(this.layout.encode(e[this.property],t,n+r),o+=this.layout.getSpan(t,n+r),0<=this.union.span&&o>this.union.span))throw new Error("encoded variant overruns containing union");return o}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function C(e){return 0>e&&(e+=4294967296),e}il.VariantLayout=x;class P extends r{constructor(e,t,n){if(!(e instanceof c||e instanceof u))throw new TypeError("word must be a UInt or UIntBE layout");if("string"==typeof t&&void 0===n&&(n=t,t=!1),4<e.span)throw new RangeError("word cannot exceed 32 bits");super(e.span,n),this.word=e,this.msb=!!t,this.fields=[];let r=0;this._packedSetValue=function(e){return r=C(e),this},this._packedGetValue=function(){return r}}decode(e,t=0){const n=this.makeDestinationObject(),r=this.word.decode(e,t);this._packedSetValue(r);for(const t of this.fields)void 0!==t.property&&(n[t.property]=t.decode(e));return n}encode(e,t,n=0){const r=this.word.decode(t,n);this._packedSetValue(r);for(const t of this.fields)if(void 0!==t.property){const n=e[t.property];void 0!==n&&t.encode(n)}return this.word.encode(this._packedGetValue(),t,n)}addField(e,t){const n=new N(this,e,t);return this.fields.push(n),n}addBoolean(e){const t=new _(this,e);return this.fields.push(t),t}fieldFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}}il.BitStructure=P;class N{constructor(e,t,n){if(!(e instanceof P))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(t)||0>=t)throw new TypeError("bits must be positive integer");const r=8*e.span,o=e.fields.reduce((e,t)=>e+t.bits,0);if(t+o>r)throw new Error("bits too long for span remainder ("+(r-o)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=o,this.container.msb&&(this.start=r-o-t),this.wordMask=C(this.valueMask<<this.start),this.property=n}decode(e,t){return C(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==C(e&this.valueMask))throw new TypeError(o("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=C(e<<this.start);this.container._packedSetValue(C(t&~this.wordMask)|n)}}il.BitField=N;class _ extends N{constructor(e,t){super(e,1,t)}decode(e,t){return!!super.decode(e,t)}encode(e){"boolean"==typeof e&&(e=+e),super.encode(e)}}il.Boolean=_;class U extends r{constructor(e,t){if(!(e instanceof i&&e.isCount()||Number.isInteger(e)&&0<=e))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let n=-1;e instanceof i||(n=e),super(n,t),this.length=e}getSpan(e,t){let n=this.span;return 0>n&&(n=this.length.decode(e,t)),n}decode(e,t=0){let r=this.span;return 0>r&&(r=this.length.decode(e,t)),n(e).slice(t,t+r)}encode(e,t,r){let s=this.length;if(this.length instanceof i&&(s=e.length),!(e instanceof Uint8Array&&s===e.length))throw new TypeError(o("Blob.encode",this)+" requires (length "+s+") Uint8Array as src");if(r+s>t.length)throw new RangeError("encoding overruns Uint8Array");const a=n(e);return n(t).write(a.toString("hex"),r,s,"hex"),this.length instanceof i&&this.length.encode(s,t,r),s}}il.Blob=U;class D extends r{constructor(e){super(-1,e)}getSpan(e,n=0){t(e);let r=n;for(;r<e.length&&0!==e[r];)r+=1;return 1+r-n}decode(e,t=0){const r=this.getSpan(e,t);return n(e).slice(t,t+r-1).toString("utf-8")}encode(t,r,o=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),s=i.length;if(o+s>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return i.copy(a,o),a[o+s]=0,s+1}}il.CString=D;class R extends r{constructor(e,t){if("string"==typeof e&&void 0===t&&(t=e,e=void 0),void 0===e)e=-1;else if(!Number.isInteger(e))throw new TypeError("maxSpan must be an integer");super(-1,t),this.maxSpan=e}getSpan(e,n=0){return t(e),e.length-n}decode(e,t=0){const r=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpan<r)throw new RangeError("text length exceeds maxSpan");return n(e).slice(t,t+r).toString("utf-8")}encode(t,r,o=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),s=i.length;if(0<=this.maxSpan&&this.maxSpan<s)throw new RangeError("text length exceeds maxSpan");if(o+s>r.length)throw new RangeError("encoding overruns Buffer");return i.copy(n(r),o),s}}il.UTF8=R;class F extends r{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,n){return 0}}return il.Constant=F,il.greedy=(e,t)=>new s(e,t),il.offset=(e,t,n)=>new a(e,t,n),il.u8=e=>new c(1,e),il.u16=e=>new c(2,e),il.u24=e=>new c(3,e),il.u32=e=>new c(4,e),il.u40=e=>new c(5,e),il.u48=e=>new c(6,e),il.nu64=e=>new g(e),il.u16be=e=>new u(2,e),il.u24be=e=>new u(3,e),il.u32be=e=>new u(4,e),il.u40be=e=>new u(5,e),il.u48be=e=>new u(6,e),il.nu64be=e=>new m(e),il.s8=e=>new l(1,e),il.s16=e=>new l(2,e),il.s24=e=>new l(3,e),il.s32=e=>new l(4,e),il.s40=e=>new l(5,e),il.s48=e=>new l(6,e),il.ns64=e=>new y(e),il.s16be=e=>new h(2,e),il.s24be=e=>new h(3,e),il.s32be=e=>new h(4,e),il.s40be=e=>new h(5,e),il.s48be=e=>new h(6,e),il.ns64be=e=>new w(e),il.f32=e=>new b(e),il.f32be=e=>new k(e),il.f64=e=>new v(e),il.f64be=e=>new E(e),il.struct=(e,t,n)=>new A(e,t,n),il.bits=(e,t,n)=>new P(e,t,n),il.seq=(e,t,n)=>new S(e,t,n),il.union=(e,t,n)=>new B(e,t,n),il.unionLayoutDiscriminator=(e,t)=>new I(e,t),il.blob=(e,t)=>new U(e,t),il.cstr=e=>new D(e),il.utf8=(e,t)=>new R(e,t),il.constant=(e,t)=>new F(e,t),il}(),ul=1,ll=2,hl=3,dl=4,fl=5,pl=6,gl=7,ml=8,yl=9,wl=10,bl=-32700,kl=-32603,vl=-32602,El=-32601,Sl=-32600,Al=-32016,Tl=-32015,Il=-32014,Bl=-32013,xl=-32012,Cl=-32011,Pl=-32010,Nl=-32009,_l=-32008,Ul=-32007,Dl=-32006,Rl=-32005,Fl=-32004,Ll=-32003,Ol=-32002,Ml=-32001,$l=28e5,ql=2800001,Kl=2800002,Gl=2800003,Wl=2800004,zl=2800005,jl=2800006,Hl=2800007,Vl=2800008,Xl=2800009,Ql=2800010,Zl=2800011,Yl=323e4,Jl=32300001,eh=3230002,th=3230003,nh=3230004,rh=361e4,oh=3610001,ih=3610002,sh=3610003,ah=3610004,ch=3610005,uh=3610006,lh=3610007,hh=3611e3,dh=3704e3,fh=3704001,ph=3704002,gh=3704003,mh=3704004,yh=4128e3,wh=4128001,bh=4128002,kh=4615e3,vh=4615001,Eh=4615002,Sh=4615003,Ah=4615004,Th=4615005,Ih=4615006,Bh=4615007,xh=4615008,Ch=4615009,Ph=4615010,Nh=4615011,_h=4615012,Uh=4615013,Dh=4615014,Rh=4615015,Fh=4615016,Lh=4615017,Oh=4615018,Mh=4615019,$h=4615020,qh=4615021,Kh=4615022,Gh=4615023,Wh=4615024,zh=4615025,jh=4615026,Hh=4615027,Vh=4615028,Xh=4615029,Qh=4615030,Zh=4615031,Yh=4615032,Jh=4615033,ed=4615034,td=4615035,nd=4615036,rd=4615037,od=4615038,id=4615039,sd=4615040,ad=4615041,cd=4615042,ud=4615043,ld=4615044,hd=4615045,dd=4615046,fd=4615047,pd=4615048,gd=4615049,md=4615050,yd=4615051,wd=4615052,bd=4615053,kd=4615054,vd=5508e3,Ed=5508001,Sd=5508002,Ad=5508003,Td=5508004,Id=5508005,Bd=5508006,xd=5508007,Cd=5508008,Pd=5508009,Nd=5508010,_d=5508011,Ud=5663e3,Dd=5663001,Rd=5663002,Fd=5663003,Ld=5663004,Od=5663005,Md=5663006,$d=5663007,qd=5663008,Kd=5663009,Gd=5663010,Wd=5663011,zd=5663012,jd=5663013,Hd=5663014,Vd=5663015,Xd=5663016,Qd=5663017,Zd=5663018,Yd=5663019,Jd=5663020,ef=705e4,tf=7050001,nf=7050002,rf=7050003,of=7050004,sf=7050005,af=7050006,cf=7050007,uf=7050008,lf=7050009,hf=7050010,df=7050011,ff=7050012,pf=7050013,gf=7050014,mf=7050015,yf=7050016,wf=7050017,bf=7050018,kf=7050019,vf=7050020,Ef=7050021,Sf=7050022,Af=7050023,Tf=7050024,If=7050025,Bf=7050026,xf=7050027,Cf=7050028,Pf=7050029,Nf=7050030,_f=7050031,Uf=7050032,Df=7050033,Rf=7050034,Ff=7050035,Lf=7050036,Of=8078e3,Mf=8078001,$f=8078002,qf=8078003,Kf=8078004,Gf=8078005,Wf=8078006,zf=8078007,jf=8078008,Hf=8078009,Vf=8078010,Xf=8078011,Qf=8078012,Zf=8078013,Yf=8078014,Jf=8078015,ep=8078016,tp=8078017,np=8078018,rp=8078019,op=8078020,ip=8078021,sp=8078022,ap=81e5,cp=8100001,up=8100002,lp=8100003,hp=819e4,dp=8190001,fp=8190002,pp=8190003,gp=8190004,mp=99e5,yp=9900001,wp=9900002,bp=9900003,kp=9900004;function vp(e){if(Array.isArray(e)){return"%5B"+e.map(vp).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Ep([e,t]){return`${e}=${vp(t)}`}var Sp={[Yl]:"Account not found at address: $address",[nh]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[th]:"Expected decoded account at address: $address",[eh]:"Failed to decode account data at address: $address",[Jl]:"Accounts not found at addresses: $addresses",[Xl]:"Unable to find a viable program address bump seed.",[Kl]:"$putativeAddress is not a base58-encoded address.",[$l]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[Gl]:"The `CryptoKey` must be an `Ed25519` public key.",[Zl]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[Vl]:"Invalid seeds; point must fall off the Ed25519 curve.",[Wl]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[jl]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[Hl]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[zl]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Ql]:"Program address cannot end with PDA marker.",[ql]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[dl]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[ul]:"The network has progressed past the last block for which this transaction could have been committed.",[Of]:"Codec [$codecDescription] cannot decode empty byte arrays.",[sp]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[op]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Gf]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[Wf]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Kf]:"Encoder and decoder must either both be fixed-size or variable-size.",[jf]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[$f]:"Expected a fixed-size codec, got a variable-size one.",[Zf]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[qf]:"Expected a variable-size codec, got a fixed-size one.",[rp]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Mf]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[np]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[Hf]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Vf]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[Jf]:"Invalid literal union variant. Expected one of [$variants], got $value.",[zf]:"Expected [$codecDescription] to have $expected items, got $actual.",[Qf]:"Invalid value $value for base $base with alphabet $alphabet.",[ep]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[Xf]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[Yf]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[ip]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[tp]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[hh]:"No random values implementation could be found.",[Ch]:"instruction requires an uninitialized account",[Gh]:"instruction tries to borrow reference for an account which is already borrowed",[Wh]:"instruction left account with an outstanding borrowed reference",[qh]:"program other than the account's owner changed the size of the account data",[Th]:"account data too small for instruction",[Kh]:"instruction expected an executable account",[dd]:"An account does not have enough lamports to be rent-exempt",[pd]:"Program arithmetic overflowed",[hd]:"Failed to serialize or deserialize account data: $encodedData",[kd]:"Builtin programs must consume compute units",[Yh]:"Cross-program invocation call depth too deep",[od]:"Computational budget exceeded",[jh]:"custom program error: #$code",[Lh]:"instruction contains duplicate accounts",[zh]:"instruction modifications of multiply-passed account differ",[Qh]:"executable accounts must be rent exempt",[Vh]:"instruction changed executable accounts data",[Xh]:"instruction changed the balance of an executable account",[Oh]:"instruction changed executable bit of an account",[Dh]:"instruction modified data of an account it does not own",[Uh]:"instruction spent from the balance of an account it does not own",[vh]:"generic instruction error",[md]:"Provided owner is not allowed",[ud]:"Account is immutable",[ld]:"Incorrect authority provided",[Bh]:"incorrect program id for instruction",[Ih]:"insufficient funds for instruction",[Ah]:"invalid account data for instruction",[fd]:"Invalid account owner",[Eh]:"invalid program argument",[Hh]:"program returned invalid error code",[Sh]:"invalid instruction data",[rd]:"Failed to reallocate account data",[nd]:"Provided seeds do not result in a valid address",[yd]:"Accounts data allocations exceeded the maximum allowed per transaction",[wd]:"Max accounts exceeded",[bd]:"Max instruction trace length exceeded",[td]:"Length of the seed is too long for address generation",[Jh]:"An account required by the instruction is missing",[xh]:"missing required signature for instruction",[_h]:"instruction illegally modified the program id of an account",[$h]:"insufficient account keys for instruction",[id]:"Cross-program invocation with unauthorized signer or writable account",[sd]:"Failed to create program execution environment",[cd]:"Program failed to compile",[ad]:"Program failed to complete",[Fh]:"instruction modified data of a read-only account",[Rh]:"instruction changed the balance of a read-only account",[ed]:"Cross-program invocation reentrancy not allowed for this instruction",[Mh]:"instruction modified rent epoch of an account",[Nh]:"sum of account balances before and after instruction do not match",[Ph]:"instruction requires an initialized account",[kh]:"",[Zh]:"Unsupported program id",[gd]:"Unsupported sysvar",[yh]:"The instruction does not have any accounts.",[wh]:"The instruction does not have any data.",[bh]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[fl]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[ll]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[wp]:"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[kp]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[yp]:"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[mp]:"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[bp]:"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[kl]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[vl]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Sl]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[El]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[bl]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[xl]:"$__serverMessage",[Ml]:"$__serverMessage",[Fl]:"$__serverMessage",[Il]:"$__serverMessage",[Pl]:"$__serverMessage",[Nl]:"$__serverMessage",[Al]:"Minimum context slot has not been reached",[Rl]:"Node is unhealthy; behind by $numSlotsBehind slots",[_l]:"No snapshot",[Ol]:"Transaction simulation failed",[Ul]:"$__serverMessage",[Cl]:"Transaction history is not available from this node",[Dl]:"$__serverMessage",[Bl]:"Transaction signature length mismatch",[Ll]:"Transaction signature verification failure",[Tl]:"$__serverMessage",[dh]:"Key pair bytes must be of length 64, got $byteLength.",[fh]:"Expected private key bytes with length 32. Actual length: $actualLength.",[ph]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[mh]:"The provided private key does not match the provided public key.",[gh]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[pl]:"Lamports value must be in the range [0, 2e64-1]",[gl]:"`$value` cannot be parsed as a `BigInt`",[wl]:"$message",[ml]:"`$value` cannot be parsed as a `Number`",[hl]:"No nonce account could be found at address `$nonceAccountAddress`",[hp]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[fp]:"WebSocket was closed before payload could be added to the send buffer",[pp]:"WebSocket connection closed",[gp]:"WebSocket failed to connect",[dp]:"Failed to obtain a subscription id from the server",[lp]:"Could not find an API plan for RPC method: `$method`",[ap]:"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",[up]:"HTTP error ($statusCode): $message",[cp]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[vd]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[Ed]:"The provided value does not implement the `KeyPairSigner` interface",[Ad]:"The provided value does not implement the `MessageModifyingSigner` interface",[Td]:"The provided value does not implement the `MessagePartialSigner` interface",[Sd]:"The provided value does not implement any of the `MessageSigner` interfaces",[Bd]:"The provided value does not implement the `TransactionModifyingSigner` interface",[xd]:"The provided value does not implement the `TransactionPartialSigner` interface",[Cd]:"The provided value does not implement the `TransactionSendingSigner` interface",[Id]:"The provided value does not implement any of the `TransactionSigner` interfaces",[Pd]:"More than one `TransactionSendingSigner` was identified.",[Nd]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[_d]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[lh]:"Cannot export a non-extractable key.",[oh]:"No digest implementation could be found.",[rh]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[ih]:"This runtime does not support the generation of Ed25519 key pairs.\n\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.",[sh]:"No signature verification implementation could be found.",[ah]:"No key generation implementation could be found.",[ch]:"No signing implementation could be found.",[uh]:"No key export implementation could be found.",[yl]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[yf]:"Transaction processing left an account with an outstanding borrowed reference",[tf]:"Account in use",[nf]:"Account loaded twice",[rf]:"Attempt to debit an account but found no record of a prior credit.",[Af]:"Transaction loads an address table account that doesn't exist",[cf]:"This transaction has already been processed",[uf]:"Blockhash not found",[lf]:"Loader call chain is too deep",[mf]:"Transactions are currently disabled due to cluster maintenance",[Nf]:"Transaction contains a duplicate instruction ($index) that is not allowed",[sf]:"Insufficient funds for fee",[_f]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[af]:"This account may not be used to pay transaction fees",[df]:"Transaction contains an invalid account reference",[If]:"Transaction loads an address table account with invalid data",[Bf]:"Transaction address table lookup uses an invalid index",[Tf]:"Transaction loads an address table account with an invalid owner",[Df]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[pf]:"This program may not be used for executing instructions",[xf]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[kf]:"Transaction loads a writable account that cannot be written",[Uf]:"Transaction exceeded max loaded accounts data size cap",[hf]:"Transaction requires a fee but has no signature present",[of]:"Attempt to load a program that does not exist",[Ff]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Rf]:"ResanitizationNeeded",[gf]:"Transaction failed to sanitize accounts offsets correctly",[ff]:"Transaction did not pass signature verification",[Sf]:"Transaction locked too many accounts",[Lf]:"Sum of account balances before and after transaction do not match",[ef]:"The transaction failed with the error `$errorName`",[bf]:"Transaction version is unsupported",[Ef]:"Transaction would exceed account data limit within the block",[Pf]:"Transaction would exceed total account data limit",[vf]:"Transaction would exceed max account limit within the block",[wf]:"Transaction would exceed max Block Cost Limit",[Cf]:"Transaction would exceed max Vote Cost Limit",[Vd]:"Attempted to sign a transaction with an address that is not a signer for it",[Gd]:"Transaction is missing an address at index: $index.",[Xd]:"Transaction has no expected signers therefore it cannot be encoded",[Jd]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Rd]:"Transaction does not have a blockhash lifetime",[Fd]:"Transaction is not a durable nonce transaction",[Od]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Md]:"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",[qd]:"No fee payer set in CompiledTransaction",[$d]:"Could not find program address at index $index",[Zd]:"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",[Yd]:"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",[Wd]:"Transaction is missing a fee payer.",[zd]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Hd]:"Transaction first instruction is not advance nonce account instruction.",[jd]:"Transaction with no instructions cannot be durable nonce transaction.",[Ud]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Dd]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Qd]:"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.",[Kd]:"Transaction is missing signatures for addresses: $addresses.",[Ld]:"Transaction version must be in the range [0, 127]. `$actualVersion` given"},Ap="i",Tp="t";function Ip(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=Sp[e];if(0===n.length)return"";let r;function o(e){if(2===r[Tp]){const o=n.slice(r[Ap]+1,e);i.push(o in t?`${t[o]}`:`$${o}`)}else 1===r[Tp]&&i.push(n.slice(r[Ap],e))}const i=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Ap]:0,[Tp]:"\\"===n[0]?0:"$"===n[0]?2:1});let i;switch(r[Tp]){case 0:i={[Ap]:t,[Tp]:1};break;case 1:"\\"===e?i={[Ap]:t,[Tp]:0}:"$"===e&&(i={[Ap]:t,[Tp]:2});break;case 2:"\\"===e?i={[Ap]:t,[Tp]:0}:"$"===e?i={[Ap]:t,[Tp]:2}:e.match(/\w/)||(i={[Ap]:t,[Tp]:1})}i&&(r!==i&&o(t),r=i)}),o(),i.join("")}(e,t);{let n=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(n+=` '${function(e){const t=Object.entries(e).map(Ep).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Bp=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;if(t){const{cause:e,...o}=t;e&&(r={cause:e}),Object.keys(o).length>0&&(n=o)}super(Ip(e,n),r),this.context={__code:e,...n},this.name="SolanaError"}};function xp(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function Cp(e){return 1!==e?.endian}function Pp(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Bp(Xf,{codecDescription:e,max:n,min:t,value:r})}(e.name,e.range[0],e.range[1],t);const o=new ArrayBuffer(e.size);return e.set(new DataView(o),t,Cp(e.config)),n.set(new Uint8Array(o),r),r+e.size}},Object.freeze({...t,encode:e=>{const n=new Uint8Array(function(e,t){return"fixedSize"in t?t.fixedSize:t.getSizeFromValue(e)}(e,t));return t.write(e,n,0),n}});var t}function Np(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Bp(Of,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const o=n.length-r;if(o<t)throw new Bp(Mf,{bytesLength:o,codecDescription:e,expected:t})}(e.name,e.size,t,n);const r=new DataView(function(e,t,n){const r=e.byteOffset+(t??0),o=n??e.byteLength;return e.buffer.slice(r,r+o)}(t,n,e.size));return[e.get(r,Cp(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var _p=(e={})=>function(e,t){if(xp(e)!==xp(t))throw new Bp(Kf);if(xp(e)&&xp(t)&&e.fixedSize!==t.fixedSize)throw new Bp(Gf,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!xp(e)&&!xp(t)&&e.maxSize!==t.maxSize)throw new Bp(Wf,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>Pp({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>Np({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class Up extends TypeError{constructor(e,t){let n;const{message:r,explanation:o,...i}=e,{path:s}=e,a=0===s.length?r:`At path: ${s.join(".")} -- ${r}`;super(o??a),null!=o&&(this.cause=a),Object.assign(this,i),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Dp(e){return"object"==typeof e&&null!=e}function Rp(e){return Dp(e)&&!Array.isArray(e)}function Fp(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Lp(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:o,branch:i}=t,{type:s}=n,{refinement:a,message:c=`Expected a value of type \`${s}\`${a?` with refinement \`${a}\``:""}, but received: \`${Fp(r)}\``}=e;return{value:r,type:s,refinement:a,key:o[o.length-1],path:o,branch:i,...e,message:c}}function*Op(e,t,n,r){var o;Dp(o=e)&&"function"==typeof o[Symbol.iterator]||(e=[e]);for(const o of e){const e=Lp(o,t,n,r);e&&(yield e)}}function*Mp(e,t,n={}){const{path:r=[],branch:o=[e],coerce:i=!1,mask:s=!1}=n,a={path:r,branch:o,mask:s};i&&(e=t.coercer(e,a));let c="valid";for(const r of t.validator(e,a))r.explanation=n.message,c="not_valid",yield[r,void 0];for(let[u,l,h]of t.entries(e,a)){const t=Mp(l,h,{path:void 0===u?r:[...r,u],branch:void 0===u?o:[...o,l],coerce:i,mask:s,message:n.message});for(const n of t)n[0]?(c=null!=n[0].refinement?"not_refined":"not_valid",yield[n[0],void 0]):i&&(l=n[1],void 0===u?e=l:e instanceof Map?e.set(u,l):e instanceof Set?e.add(l):Dp(e)&&(void 0!==l||u in e)&&(e[u]=l))}if("not_valid"!==c)for(const r of t.refiner(e,a))r.explanation=n.message,c="not_refined",yield[r,void 0];"valid"===c&&(yield[void 0,e])}let $p=class{constructor(e){const{type:t,schema:n,validator:r,refiner:o,coercer:i=e=>e,entries:s=function*(){}}=e;this.type=t,this.schema=n,this.entries=s,this.coercer=i,this.validator=r?(e,t)=>Op(r(e,t),t,this,e):()=>[],this.refiner=o?(e,t)=>Op(o(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=Gp(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return qp(e,this,t)}is(e){return Kp(e,this)}mask(e,t){return function(e,t,n){const r=Gp(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return Gp(e,this,t)}};function qp(e,t,n){const r=Gp(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function Kp(e,t){return!Gp(e,t)[0]}function Gp(e,t,n={}){const r=Mp(e,t,n),o=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(o[0]){return[new Up(o[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,o[1]]}function Wp(e,t){return new $p({type:e,schema:null,validator:t})}function zp(e){return new $p({type:"array",schema:e,*entries(t){if(e&&Array.isArray(t))for(const[n,r]of t.entries())yield[n,r,e]},coercer:e=>Array.isArray(e)?e.slice():e,validator:e=>Array.isArray(e)||`Expected an array value, but received: ${Fp(e)}`})}function jp(){return Wp("boolean",e=>"boolean"==typeof e)}function Hp(e){return Wp("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Fp(t)}`)}function Vp(e){const t=Fp(e),n=typeof e;return new $p({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Fp(n)}`})}function Xp(e){return new $p({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function Qp(){return Wp("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Fp(e)}`)}function Zp(e){return new $p({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function Yp(e,t){return new $p({type:"record",schema:null,*entries(n){if(Dp(n))for(const r in n){const o=n[r];yield[r,r,e],yield[r,o,t]}},validator:e=>Rp(e)||`Expected an object, but received: ${Fp(e)}`,coercer:e=>Rp(e)?{...e}:e})}function Jp(){return Wp("string",e=>"string"==typeof e||`Expected a string, but received: ${Fp(e)}`)}function eg(e){const t=Wp("never",()=>!1);return new $p({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(e.length,n.length);for(let o=0;o<r;o++)yield[o,n[o],e[o]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${Fp(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function tg(e){const t=Object.keys(e);return new $p({type:"type",schema:e,*entries(n){if(Dp(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Rp(e)||`Expected an object, but received: ${Fp(e)}`,coercer:e=>Rp(e)?{...e}:e})}function ng(e){const t=e.map(e=>e.type).join(" | ");return new $p({type:"union",schema:null,coercer(t,n){for(const r of e){const[e,o]=r.validate(t,{coerce:!0,mask:n.mask});if(!e)return o}return t},validator(n,r){const o=[];for(const t of e){const[...e]=Mp(n,t,r),[i]=e;if(!i[0])return[];for(const[t]of e)t&&o.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Fp(n)}`,...o]}})}function rg(){return Wp("unknown",()=>!0)}function og(e,t,n){return new $p({...e,coercer:(r,o)=>Kp(r,t)?e.coercer(n(r,o),o):e.coercer(r,o)})}var ig,sg,ag,cg;var ug,lg=function(){if(cg)return ag;cg=1;const e=R.v4,t=function(){if(sg)return ig;sg=1;const e=R.v4;return ig=function(t,n,r,o){if("string"!=typeof t)throw new TypeError(t+" must be a string");const i="number"==typeof(o=o||{}).version?o.version:2;if(1!==i&&2!==i)throw new TypeError(i+" must be 1 or 2");const s={method:t};if(2===i&&(s.jsonrpc="2.0"),n){if("object"!=typeof n&&!Array.isArray(n))throw new TypeError(n+" must be an object, array or omitted");s.params=n}if(void 0===r){const t="function"==typeof o.generator?o.generator:function(){return e()};s.id=t(s,o)}else 2===i&&null===r?o.notificationIdNull&&(s.id=null):s.id=r;return s}}(),n=function(t,r){if(!(this instanceof n))return new n(t,r);r||(r={}),this.options={reviver:void 0!==r.reviver?r.reviver:null,replacer:void 0!==r.replacer?r.replacer:null,generator:void 0!==r.generator?r.generator:function(){return e()},version:void 0!==r.version?r.version:2,notificationIdNull:"boolean"==typeof r.notificationIdNull&&r.notificationIdNull},this.callServer=t};return ag=n,n.prototype.request=function(e,n,r,o){const i=this;let s=null;const a=Array.isArray(e)&&"function"==typeof n;if(1===this.options.version&&a)throw new TypeError("JSON-RPC 1.0 does not support batching");if(a||!a&&e&&"object"==typeof e&&"function"==typeof n)o=n,s=e;else{"function"==typeof r&&(o=r,r=void 0);const i="function"==typeof o;try{s=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(i)return o(e);throw e}if(!i)return s}let c;try{c=JSON.stringify(s,this.options.replacer)}catch(e){return o(e)}return this.callServer(c,function(e,t){i._parseResponse(e,t,o)}),s},n.prototype._parseResponse=function(e,t,n){if(e)return void n(e);if(!t)return n();let r;try{r=JSON.parse(t,this.options.reviver)}catch(e){return n(e)}if(3===n.length){if(Array.isArray(r)){const e=function(e){return void 0!==e.error},t=function(t){return!e(t)};return n(null,r.filter(e),r.filter(t))}return n(null,r.error,r.result)}n(null,r)},ag}(),hg=hi(lg),dg={};var fg,pg=(ug||(ug=1,function(e){const t=Ks(),n=js(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;function i(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=i(n);const o=r.write(e,t);return o!==n&&(r=r.slice(0,o)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);const o=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||V(e.length)?i(0):l(e):"Buffer"===e.type&&Array.isArray(e.data)?l(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),i(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=i(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function d(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(o)return r?-1:W(e).length;t=(""+t).toLowerCase(),o=!0}}function p(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return B(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return j(W(t,e.length-n),e,n,r)}function k(e,t,n,r){return j(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return j(z(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function A(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=o,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let o=0;for(n=0;n<e.length;++n){let t=e[n];if(H(t,Uint8Array))o+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)g(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?A(this,0,e):p.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,o){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){i=u[e],a=l[e];break}return i<a?-1:a<i?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function B(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function x(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=X[e[r]];return o}function C(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function P(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function U(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function F(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,8),n.write(e,t,r,o,52,8),r+8}s.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return _(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=Q(function(e,t=0){return _(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const o=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),o},s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{const i=s.isBuffer(e)?e:s.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%a]}return this};const L={};function O(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function M(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,o,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,o,i)}function q(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}O("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),O("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),O("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=M(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=M(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function z(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function H(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(dg)),dg),gg={exports:{}};var mg=(fg||(fg=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function i(e,t,r,i,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,i||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,i=r.length,s=new Array(i);o<i;o++)s[o]=r[o].fn;return s},a.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,o,i,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,u,l=this._events[a],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,i),!0;case 6:return l.fn.call(l.context,t,r,o,i,s),!0}for(u=1,c=new Array(h-1);u<h;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var d,f=l.length;for(u=0;u<f;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),h){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l[u].fn.apply(l[u].context,c)}}return!0},a.prototype.on=function(e,t,n){return i(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,o){var i=n?n+e:e;if(!this._events[i])return this;if(!t)return s(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||s(this,i);else{for(var c=0,u=[],l=a.length;c<l;c++)(a[c].fn!==t||o&&!a[c].once||r&&a[c].context!==r)&&u.push(a[c]);u.length?this._events[i]=1===u.length?u[0]:u:s(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&s(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(gg)),gg.exports),yg=hi(mg),wg=class extends yg{socket;constructor(e,t){super(),this.socket=new window.WebSocket(e,t.protocols),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=e=>this.emit("message",e.data),this.socket.onerror=e=>this.emit("error",e),this.socket.onclose=e=>{this.emit("close",e.code,e.reason)}}send(e,t,n){const r=n||t;try{this.socket.send(e),r()}catch(e){r(e)}}close(e,t){this.socket.close(e,t)}addEventListener(e,t,n){this.socket.addEventListener(e,t,n)}};var bg=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},kg=class extends yg{address;rpc_id;queue;options;autoconnect;ready;reconnect;reconnect_timer_id;reconnect_interval;max_reconnects;rest_options;current_reconnects;generate_request_id;socket;webSocketFactory;dataPack;constructor(e,t="ws://localhost:8080",{autoconnect:n=!0,reconnect:r=!0,reconnect_interval:o=1e3,max_reconnects:i=5,...s}={},a,c){super(),this.webSocketFactory=e,this.queue={},this.rpc_id=0,this.address=t,this.autoconnect=n,this.ready=!1,this.reconnect=r,this.reconnect_timer_id=void 0,this.reconnect_interval=o,this.max_reconnects=i,this.rest_options=s,this.current_reconnects=0,this.generate_request_id=a||(()=>"number"==typeof this.rpc_id?++this.rpc_id:Number(this.rpc_id)+1),this.dataPack=c||new bg,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(e,t,n,r){return r||"object"!=typeof n||(r=n,n=null),new Promise((o,i)=>{if(!this.ready)return i(new Error("socket not ready"));const s=this.generate_request_id(e,t),a={jsonrpc:"2.0",method:e,params:t||void 0,id:s};this.socket.send(this.dataPack.encode(a),r,e=>{if(e)return i(e);this.queue[s]={promise:[o,i]},n&&(this.queue[s].timeout=setTimeout(()=>{delete this.queue[s],i(new Error("reply timeout"))},n))})})}async login(e){const t=await this.call("rpc.login",e);if(!t)throw new Error("authentication failed");return t}async listMethods(){return await this.call("__listMethods")}notify(e,t){return new Promise((n,r)=>{if(!this.ready)return r(new Error("socket not ready"));const o={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(o),e=>{if(e)return r(e);n()})})}async subscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.on",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed subscribing to an event '"+e+"' with: "+t[e]);return t}async unsubscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.off",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed unsubscribing from an event with: "+t);return t}close(e,t){this.socket&&this.socket.close(e||1e3,t)}setAutoReconnect(e){this.reconnect=e}setReconnectInterval(e){this.reconnect_interval=e}setMaxReconnects(e){this.max_reconnects=e}getCurrentReconnects(){return this.current_reconnects}getMaxReconnects(){return this.max_reconnects}isReconnecting(){return void 0!==this.reconnect_timer_id}willReconnect(){return this.reconnect&&(0===this.max_reconnects||this.current_reconnects<this.max_reconnects)}_connect(e,t){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(e,t),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:e})=>{e instanceof ArrayBuffer&&(e=pg.Buffer.from(e).toString());try{e=this.dataPack.decode(e)}catch(e){return}if(e.notification&&this.listeners(e.notification).length){if(!Object.keys(e.params).length)return this.emit(e.notification);const t=[e.notification];if(e.params.constructor===Object)t.push(e.params);else for(let n=0;n<e.params.length;n++)t.push(e.params[n]);return Promise.resolve().then(()=>{this.emit.apply(this,t)})}if(!this.queue[e.id])return e.method?Promise.resolve().then(()=>{this.emit(e.method,e?.params)}):void 0;"error"in e=="result"in e&&this.queue[e.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[e.id].timeout&&clearTimeout(this.queue[e.id].timeout),e.error?this.queue[e.id].promise[1](e.error):this.queue[e.id].promise[0](e.result),delete this.queue[e.id]}),this.socket.addEventListener("error",e=>this.emit("error",e)),this.socket.addEventListener("close",({code:n,reason:r})=>{this.ready&&setTimeout(()=>this.emit("close",n,r),0),this.ready=!1,this.socket=void 0,1e3!==n&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||0===this.max_reconnects)?this.reconnect_timer_id=setTimeout(()=>this._connect(e,t),this.reconnect_interval):this.reconnect&&this.max_reconnects>0&&this.current_reconnects>=this.max_reconnects&&setTimeout(()=>this.emit("max_reconnects_reached",n,r),1))})}};class vg extends ma{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ys(e);const n=pa(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<o.length;e++)o[e]^=54;this.iHash.update(o),this.oHash=e.create();for(let e=0;e<o.length;e++)o[e]^=106;this.oHash.update(o),ea(o)}update(e){return Js(this),this.iHash.update(e),this}digestInto(e){Js(this),Zs(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:i,outputLen:s}=this;return e.finished=r,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Eg=(e,t,n)=>new vg(e,t).update(n).digest();Eg.create=(e,t)=>new vg(e,t);const Sg=(e,t)=>(e+(e>=0?t:-t)/Pg)/t;function Ag(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Tg(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Ja(n.lowS,"lowS"),Ja(n.prehash,"prehash"),void 0!==n.format&&Ag(n.format),n}class Ig extends Error{constructor(e=""){super(e)}}const Bg={Err:Ig,_tlv:{encode:(e,t)=>{const{Err:n}=Bg;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,o=tc(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?tc(o.length/2|128):"";return tc(e)+i+o+t},decode(e,t){const{Err:n}=Bg;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const o=t[r++];let i=0;if(!!(128&o)){const e=127&o;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const s=t.subarray(r,r+e);if(s.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===s[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of s)i=i<<8|e;if(r+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=o;const s=t.subarray(r,r+i);if(s.length!==i)throw new n("tlv.decode: wrong value length");return{v:s,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Bg;if(e<xg)throw new t("integer: negative integers are not allowed");let n=tc(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Bg;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return rc(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Bg,o=ac("signature",e),{v:i,l:s}=r.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:u,l:l}=r.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(e){const{_tlv:t,_int:n}=Bg,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},xg=BigInt(0),Cg=BigInt(1),Pg=BigInt(2),Ng=BigInt(3),_g=BigInt(4);function Ug(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let o=ac("private key",t);try{r=e.fromBytes(o)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function Dg(e,t={}){const n=eu("weierstrass",e,t),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s,n:a}=i;fc(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Fg(r,o);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,n){const{x:o,y:i}=t.toAffine(),s=r.toBytes(o);if(Ja(n,"isCompressed"),n){l();return ga(Rg(!r.isOdd(i)),s)}return ga(Uint8Array.of(4),s,r.toBytes(i))},d=t.fromBytes||function(e){ec(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=u,o=e.length,i=e[0],s=e.subarray(1);if(o!==t||2!==i&&3!==i){if(o===n&&4===i){const e=r.BYTES,t=r.fromBytes(s.subarray(0,e)),n=r.fromBytes(s.subarray(e,2*e));if(!p(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${o}, expected compressed=${t} or uncompressed=${n}`)}{const e=r.fromBytes(s);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=f(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}l();return!(1&~i)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function f(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,i.a)),i.b)}function p(e,t){const n=r.sqr(t),o=f(e);return r.eql(n,o)}if(!p(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const g=r.mul(r.pow(i.a,Ng),_g),m=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(g,m)))throw new Error("bad curve params: a or b");function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function w(e){if(!(e instanceof S))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,o],[i,s]]=t,a=Sg(s*e,n),c=Sg(-o*e,n);let u=e-a*r-c*i,l=-a*o-c*s;const h=u<xg,d=l<xg;h&&(u=-u),d&&(l=-l);const f=dc(Math.ceil(hc(n)/2))+Cg;if(u<xg||u>=f||l<xg||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:u,k2neg:d,k2:l}}(e,c.basises,o.ORDER)}const k=pc((e,t)=>{const{X:n,Y:o,Z:i}=e;if(r.eql(i,r.ONE))return{x:n,y:o};const s=e.is0();null==t&&(t=s?r.ONE:r.inv(i));const a=r.mul(n,t),c=r.mul(o,t),u=r.mul(i,t);if(s)return{x:r.ZERO,y:r.ZERO};if(!r.eql(u,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),v=pc(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:o}=e.toAffine();if(!r.isValid(n)||!r.isValid(o))throw new Error("bad point: x or y not field elements");if(!p(n,o))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(e,t,n,o,i){return n=new S(r.mul(n.X,e),n.Y,n.Z),t=Kc(o,t),n=Kc(i,n),t.add(n)}class S{constructor(e,t,n){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof S)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?S.ZERO:new S(t,n,r.ONE)}static fromBytes(e){const t=S.fromAffine(d(ec(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return S.fromBytes(ac("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return T.createCache(this,e),t||this.multiply(Ng),this}assertValidity(){v(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){w(e);const{X:t,Y:n,Z:o}=this,{X:i,Y:s,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(i,o)),u=r.eql(r.mul(n,a),r.mul(s,o));return c&&u}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,n=r.mul(t,Ng),{X:o,Y:s,Z:a}=this;let c=r.ZERO,u=r.ZERO,l=r.ZERO,h=r.mul(o,o),d=r.mul(s,s),f=r.mul(a,a),p=r.mul(o,s);return p=r.add(p,p),l=r.mul(o,a),l=r.add(l,l),c=r.mul(e,l),u=r.mul(n,f),u=r.add(c,u),c=r.sub(d,u),u=r.add(d,u),u=r.mul(c,u),c=r.mul(p,c),l=r.mul(n,l),f=r.mul(e,f),p=r.sub(h,f),p=r.mul(e,p),p=r.add(p,l),l=r.add(h,h),h=r.add(l,h),h=r.add(h,f),h=r.mul(h,p),u=r.add(u,h),f=r.mul(s,a),f=r.add(f,f),h=r.mul(f,p),c=r.sub(c,h),l=r.mul(f,d),l=r.add(l,l),l=r.add(l,l),new S(c,u,l)}add(e){w(e);const{X:t,Y:n,Z:o}=this,{X:s,Y:a,Z:c}=e;let u=r.ZERO,l=r.ZERO,h=r.ZERO;const d=i.a,f=r.mul(i.b,Ng);let p=r.mul(t,s),g=r.mul(n,a),m=r.mul(o,c),y=r.add(t,n),b=r.add(s,a);y=r.mul(y,b),b=r.add(p,g),y=r.sub(y,b),b=r.add(t,o);let k=r.add(s,c);return b=r.mul(b,k),k=r.add(p,m),b=r.sub(b,k),k=r.add(n,o),u=r.add(a,c),k=r.mul(k,u),u=r.add(g,m),k=r.sub(k,u),h=r.mul(d,b),u=r.mul(f,m),h=r.add(u,h),u=r.sub(g,h),h=r.add(g,h),l=r.mul(u,h),g=r.add(p,p),g=r.add(g,p),m=r.mul(d,m),b=r.mul(f,b),g=r.add(g,m),m=r.sub(p,m),m=r.mul(d,m),b=r.add(b,m),p=r.mul(g,b),l=r.add(l,p),p=r.mul(k,b),u=r.mul(y,u),u=r.sub(u,p),p=r.mul(y,g),h=r.mul(k,h),h=r.add(h,p),new S(u,l,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(S.ZERO)}multiply(e){const{endo:n}=t;if(!o.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,i;const s=e=>T.cached(this,e,e=>Gc(S,e));if(n){const{k1neg:t,k1:o,k2neg:a,k2:c}=b(e),{p:u,f:l}=s(o),{p:h,f:d}=s(c);i=l.add(d),r=E(n.beta,u,h,t,a)}else{const{p:t,f:n}=s(e);r=t,i=n}return Gc(S,[r,i])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!o.isValid(e))throw new Error("invalid scalar: out of range");if(e===xg||r.is0())return S.ZERO;if(e===Cg)return r;if(T.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:o,k2neg:i,k2:s}=b(e),{p1:a,p2:c}=function(e,t,n,r){let o=t,i=e.ZERO,s=e.ZERO;for(;n>$c||r>$c;)n&qc&&(i=i.add(o)),r&qc&&(s=s.add(o)),o=o.double(),n>>=qc,r>>=qc;return{p1:i,p2:s}}(S,r,o,s);return E(n.beta,a,c,t,i)}return T.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){const r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return k(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===Cg||(e?e(S,this):T.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===Cg?this:e?e(S,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return Ja(e,"isCompressed"),this.assertValidity(),h(S,this,e)}toHex(e=!0){return ia(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return Gc(S,e)}static msm(e,t){return Yc(S,o,e,t)}static fromPrivateKey(e){return S.BASE.multiply(Ug(o,e))}}S.BASE=new S(i.Gx,i.Gy,r.ONE),S.ZERO=new S(r.ZERO,r.ONE,r.ZERO),S.Fp=r,S.Fn=o;const A=o.BITS,T=new Zc(S,t.endo?Math.ceil(A/2):A);return S.BASE.precompute(8),S}function Rg(e){return Uint8Array.of(e?2:3)}function Fg(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Lg(e,t={}){const{Fn:n}=e,r=t.randomBytes||wa,o=Object.assign(Fg(e.Fp,n),{seed:Mc(n.ORDER)});function i(e){try{return!!Ug(n,e)}catch(e){return!1}}function s(e=r(o.seed)){return function(e,t,n=!1){const r=e.length,o=Oc(t),i=Mc(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const s=Tc(n?oc(e):rc(e),t-mc)+mc;return n?sc(s,o):ic(s,o)}(ec(e,o.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(Ug(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:i,publicKeyUncompressed:s}=o;if(n.allowedLengths||r===i)return;const a=ac("key",t).length;return a===i||a===s}const u={isValidSecretKey:i,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:i}=o;try{const o=t.length;return(!0!==n||o===r)&&((!1!==n||o===i)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:s,isValidPrivateKey:i,randomPrivateKey:s,normPrivateKeyToScalar:e=>Ug(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,o=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(r))throw new Error("second arg must be public key");const i=Ug(n,t);return e.fromHex(r).multiply(i).toBytes(o)},keygen:function(e){const t=s(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:u,lengths:o})}function Og(e,t,n={}){Ys(t),fc(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||wa,o=n.hmac||((e,...n)=>Eg(t,e,ga(...n))),{Fp:i,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,lengths:f}=Lg(e,n),p={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},g="compact";function m(e){return e>a>>Cg}function y(e,t){if(!s.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class w{constructor(e,t,n){this.r=y("r",e),this.s=y("s",t),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=g){let n;if(function(e,t){Ag(t);const n=f.signature;ec(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=Bg.toSig(ec(e));return new w(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=s.BYTES,o=e.subarray(0,r),i=e.subarray(r,2*r);return new w(s.fromBytes(o),s.fromBytes(i),n)}static fromHex(e,t){return this.fromBytes(fa(e),t)}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const n=i.ORDER,{r:r,s:o,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*Pg<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const u=2===c||3===c?r+a:r;if(!i.isValid(u))throw new Error("recovery id 2 or 3 invalid");const l=i.toBytes(u),h=e.fromBytes(ga(Rg(!(1&c)),l)),d=s.inv(u),f=k(ac("msgHash",t)),p=s.create(-f*d),g=s.create(o*d),m=e.BASE.multiplyUnsafe(p).add(h.multiplyUnsafe(g));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=g){if(Ag(e),"der"===e)return fa(Bg.hexFromSig(this));const t=s.toBytes(this.r),n=s.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return ga(Uint8Array.of(this.recovery),t,n)}return ga(t,n)}toHex(e){return ia(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(ac("sig",e),"compact")}static fromDER(e){return w.fromBytes(ac("sig",e),"der")}normalizeS(){return this.hasHighS()?new w(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return ia(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ia(this.toBytes("compact"))}}const b=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=rc(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},k=n.bits2int_modN||function(e){return s.create(b(e))},v=dc(c);function E(e){return lc("num < 2^"+c,e,xg,v),s.toBytes(e)}function S(e,n){return ec(e,void 0,"message"),n?ec(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,lengths:f,Point:e,sign:function(n,i,a={}){n=ac("message",n);const{seed:c,k2sig:u}=function(t,n,o){if(["recovered","canonical"].some(e=>e in o))throw new Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=Tg(o,p);t=S(t,a);const u=k(t),l=Ug(s,n),h=[E(l),E(u)];if(null!=c&&!1!==c){const e=!0===c?r(f.secretKey):c;h.push(ac("extraEntropy",e))}const d=ga(...h),g=u;return{seed:d,k2sig:function(t){const n=b(t);if(!s.isValidNot0(n))return;const r=s.inv(n),o=e.BASE.multiply(n).toAffine(),a=s.create(o.x);if(a===xg)return;const c=s.create(r*s.create(g+a*l));if(c===xg)return;let u=(o.x===a?0:2)|Number(o.y&Cg),h=c;return i&&m(c)&&(h=s.neg(c),u^=1),new w(a,h,u)}}}(n,i,a);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),o=e=>Uint8Array.of(e);let i=r(e),s=r(e),a=0;const c=()=>{i.fill(1),s.fill(0),a=0},u=(...e)=>n(s,i,...e),l=(e=r(0))=>{s=u(o(0),e),i=u(),0!==e.length&&(s=u(o(1),e),i=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=u();const t=i.slice();n.push(t),e+=i.length}return ga(...n)};return(e,t)=>{let n;for(c(),l(e);!(n=t(h()));)l();return c(),n}}(t.outputLen,s.BYTES,o)(c,u)},verify:function(t,n,r,o={}){const{lowS:i,prehash:a,format:c}=Tg(o,p);if(r=ac("publicKey",r),n=S(ac("message",n),a),"strict"in o)throw new Error("options.strict was renamed to lowS");const u=void 0===c?function(e){let t;const n="string"==typeof e||Xs(e),r=!n&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!n&&!r)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(r)t=new w(e.r,e.s);else if(n){try{t=w.fromBytes(ac("sig",e),"der")}catch(e){if(!(e instanceof Bg.Err))throw e}if(!t)try{t=w.fromBytes(ac("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):w.fromBytes(ac("sig",t),c);if(!1===u)return!1;try{const t=e.fromBytes(r);if(i&&u.hasHighS())return!1;const{r:o,s:a}=u,c=k(n),l=s.inv(a),h=s.create(c*l),d=s.create(o*l),f=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(d));if(f.is0())return!1;return s.create(f.x)===o}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=Tg(n,p);return t=S(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function Mg(e){const{CURVE:t,curveOpts:n}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:Lc(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function $g(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=Mg(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Fc(n.Fn.ORDER,n.Fn.BITS))})}(e,Og(Dg(t,n),r,o))}const qg={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Kg={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Gg=BigInt(2);const Wg=Lc(qg.p,{sqrt:function(e){const t=qg.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,l=u*u*e%t,h=Ic(l,n,t)*l%t,d=Ic(h,n,t)*l%t,f=Ic(d,Gg,t)*u%t,p=Ic(f,o,t)*f%t,g=Ic(p,i,t)*p%t,m=Ic(g,a,t)*g%t,y=Ic(m,c,t)*m%t,w=Ic(y,a,t)*g%t,b=Ic(w,n,t)*l%t,k=Ic(b,s,t)*p%t,v=Ic(k,r,t)*u%t,E=Ic(v,Gg,t);if(!Wg.eql(Wg.sqr(E),e))throw new Error("Cannot find square root");return E}}),zg=function(e,t){const n=t=>$g({...e,hash:t});return{...n(t),create:n}}({...qg,Fp:Wg,lowS:!0,endo:Kg},Xa);wu.utils.randomPrivateKey;const jg=()=>{const e=wu.utils.randomPrivateKey(),t=Hg(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},Hg=wu.getPublicKey;function Vg(e){try{return wu.ExtendedPoint.fromHex(e),!0}catch{return!1}}const Xg=wu.verify,Qg=e=>Hs.Buffer.isBuffer(e)?e:e instanceof Uint8Array?Hs.Buffer.from(e.buffer,e.byteOffset,e.byteLength):Hs.Buffer.from(e);class Zg{constructor(e){Object.assign(this,e)}encode(){return Hs.Buffer.from(ol.serialize(Yg,this))}static decode(e){return ol.deserialize(Yg,this,e)}static decodeUnchecked(e){return ol.deserializeUnchecked(Yg,this,e)}}const Yg=new Map;var Jg;const em=32;let tm=1;class nm extends Zg{constructor(e){if(super({}),this._bn=void 0,function(e){return void 0!==e._bn}(e))this._bn=e._bn;else{if("string"==typeof e){const t=Fu.decode(e);if(t.length!=em)throw new Error("Invalid public key input");this._bn=new Pu(t)}else this._bn=new Pu(e);if(this._bn.byteLength()>em)throw new Error("Invalid public key input")}}static unique(){const e=new nm(tm);return tm+=1,new nm(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Fu.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(Hs.Buffer);if(e.length===em)return e;const t=Hs.Buffer.alloc(32);return e.copy(t,32-e.length),t}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,n){const r=Hs.Buffer.concat([e.toBuffer(),Hs.Buffer.from(t),n.toBuffer()]),o=Lu(r);return new nm(o)}static createProgramAddressSync(e,t){let n=Hs.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=Hs.Buffer.concat([n,Qg(e)])}),n=Hs.Buffer.concat([n,t.toBuffer(),Hs.Buffer.from("ProgramDerivedAddress")]);const r=Lu(n);if(Vg(r))throw new Error("Invalid seeds, address must fall off the curve");return new nm(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{const o=e.concat(Hs.Buffer.from([r]));n=this.createProgramAddressSync(o,t)}catch(e){if(e instanceof TypeError)throw e;r--;continue}return[n,r]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){return Vg(new nm(e).toBytes())}}Jg=nm,nm.default=new Jg("11111111111111111111111111111111"),Yg.set(nm,{kind:"struct",fields:[["_bn","u256"]]}),new nm("BPFLoader1111111111111111111111111111111111");const rm=1232;class om extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(om.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class im extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(im.prototype,"name",{value:"TransactionExpiredTimeoutError"});class sm extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(sm.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class am{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const t of this.keySegments()){if(e<t.length)return t[e];e-=t.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const t=new Map;this.keySegments().flat().forEach((e,n)=>{t.set(e.toBase58(),n)});const n=e=>{const n=t.get(e.toBase58());if(void 0===n)throw new Error("Encountered an unknown instruction account key during compilation");return n};return e.map(e=>({programIdIndex:n(e.programId),accountKeyIndexes:e.keys.map(e=>n(e.pubkey)),data:e.data}))}}const cm=(e="publicKey")=>cl.blob(32,e),um=(e="string")=>{const t=cl.struct([cl.u32("length"),cl.u32("lengthPadding"),cl.blob(cl.offset(cl.u32(),-8),"chars")],e),n=t.decode.bind(t),r=t.encode.bind(t),o=t;return o.decode=(e,t)=>n(e,t).chars.toString(),o.encode=(e,t,n)=>{const o={chars:Hs.Buffer.from(e,"utf8")};return r(o,t,n)},o.alloc=e=>cl.u32().span+cl.u32().span+Hs.Buffer.from(e,"utf8").length,o};function lm(e,t){const n=e=>{if(e.span>=0)return e.span;if("function"==typeof e.alloc)return e.alloc(t[e.property]);if("count"in e&&"elementLayout"in e){const r=t[e.property];if(Array.isArray(r))return r.length*n(e.elementLayout)}else if("fields"in e)return lm({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function hm(e){let t=0,n=0;for(;;){let r=e.shift();if(t|=(127&r)<<7*n,n+=1,!(128&r))break}return t}function dm(e,t){let n=t;for(;;){let t=127&n;if(n>>=7,0==n){e.push(t);break}t|=128,e.push(t)}}function fm(e,t){if(!e)throw new Error(t||"Assertion failed")}class pm{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const n=new Map,r=e=>{const t=e.toBase58();let r=n.get(t);return void 0===r&&(r={isSigner:!1,isWritable:!1,isInvoked:!1},n.set(t,r)),r},o=r(t);o.isSigner=!0,o.isWritable=!0;for(const t of e){r(t.programId).isInvoked=!0;for(const e of t.keys){const t=r(e.pubkey);t.isSigner||=e.isSigner,t.isWritable||=e.isWritable}}return new pm(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];fm(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,e])=>e.isSigner&&e.isWritable),n=e.filter(([,e])=>e.isSigner&&!e.isWritable),r=e.filter(([,e])=>!e.isSigner&&e.isWritable),o=e.filter(([,e])=>!e.isSigner&&!e.isWritable),i={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:o.length};{fm(t.length>0,"Expected at least one writable signer key");const[e]=t[0];fm(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[i,[...t.map(([e])=>new nm(e)),...n.map(([e])=>new nm(e)),...r.map(([e])=>new nm(e)),...o.map(([e])=>new nm(e))]]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[r,o]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==r.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:r},{writable:n,readonly:o}]}drainKeysFoundInLookupTable(e,t){const n=new Array,r=new Array;for(const[o,i]of this.keyMetaMap.entries())if(t(i)){const t=new nm(o),i=e.findIndex(e=>e.equals(t));i>=0&&(fm(i<256,"Max lookup table index exceeded"),n.push(i),r.push(t),this.keyMetaMap.delete(o))}return[n,r]}}const gm="Reached end of buffer unexpectedly";function mm(e){if(0===e.length)throw new Error(gm);return e.shift()}function ym(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(gm);return e.splice(...t)}class wm{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(e=>new nm(e)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(e=>this.indexToProgramIds.set(e.programIdIndex,this.accountKeys[e.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Fu.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new am(this.staticAccountKeys)}static compile(e){const t=pm.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),o=new am(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Fu.encode(e.data)}));return new wm({header:n,accountKeys:r,recentBlockhash:e.recentBlockhash,instructions:o})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){return e-t<this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];dm(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(Fu.decode(e.data));let o=[];dm(o,t.length);let i=[];return dm(i,r.length),{programIdIndex:n,keyIndicesCount:Hs.Buffer.from(o),keyIndices:t,dataLength:Hs.Buffer.from(i),data:r}});let r=[];dm(r,n.length);let o=Hs.Buffer.alloc(rm);Hs.Buffer.from(r).copy(o);let i=r.length;n.forEach(e=>{const t=cl.struct([cl.u8("programIdIndex"),cl.blob(e.keyIndicesCount.length,"keyIndicesCount"),cl.seq(cl.u8("keyIndex"),e.keyIndices.length,"keyIndices"),cl.blob(e.dataLength.length,"dataLength"),cl.seq(cl.u8("userdatum"),e.data.length,"data")]).encode(e,o,i);i+=t}),o=o.slice(0,i);const s=cl.struct([cl.blob(1,"numRequiredSignatures"),cl.blob(1,"numReadonlySignedAccounts"),cl.blob(1,"numReadonlyUnsignedAccounts"),cl.blob(t.length,"keyCount"),cl.seq(cm("key"),e,"keys"),cm("recentBlockhash")]),a={numRequiredSignatures:Hs.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Hs.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Hs.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Hs.Buffer.from(t),keys:this.accountKeys.map(e=>Qg(e.toBytes())),recentBlockhash:Fu.decode(this.recentBlockhash)};let c=Hs.Buffer.alloc(2048);const u=s.encode(a,c);return o.copy(c,u),c.slice(0,u+o.length)}static from(e){let t=[...e];const n=mm(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=mm(t),o=mm(t),i=hm(t);let s=[];for(let e=0;e<i;e++){const e=ym(t,0,em);s.push(new nm(Hs.Buffer.from(e)))}const a=ym(t,0,em),c=hm(t);let u=[];for(let e=0;e<c;e++){const e=mm(t),n=ym(t,0,hm(t)),r=ym(t,0,hm(t)),o=Fu.encode(Hs.Buffer.from(r));u.push({programIdIndex:e,accounts:n,data:o})}const l={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:o},recentBlockhash:Fu.encode(Hs.Buffer.from(a)),accountKeys:s,instructions:u};return new wm(l)}}class bm{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.addressTableLookups=e.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let e=0;for(const t of this.addressTableLookups)e+=t.readonlyIndexes.length+t.writableIndexes.length;return e}getAccountKeys(e){let t;if(e&&"accountKeysFromLookups"in e&&e.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=e.accountKeysFromLookups.writable.length+e.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");t=e.accountKeysFromLookups}else if(e&&"addressLookupTableAccounts"in e&&e.addressLookupTableAccounts)t=this.resolveAddressTableLookups(e.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new am(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,n=this.staticAccountKeys.length;if(e>=n){return e-n<this.addressTableLookups.reduce((e,t)=>e+t.writableIndexes.length,0)}if(e>=this.header.numRequiredSignatures){return e-t<n-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}resolveAddressTableLookups(e){const t={writable:[],readonly:[]};for(const n of this.addressTableLookups){const r=e.find(e=>e.key.equals(n.accountKey));if(!r)throw new Error(`Failed to find address lookup table account for table key ${n.accountKey.toBase58()}`);for(const e of n.writableIndexes){if(!(e<r.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.writable.push(r.state.addresses[e])}for(const e of n.readonlyIndexes){if(!(e<r.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.readonly.push(r.state.addresses[e])}}return t}static compile(e){const t=pm.compile(e.instructions,e.payerKey),n=new Array,r={writable:new Array,readonly:new Array},o=e.addressLookupTableAccounts||[];for(const e of o){const o=t.extractTableLookup(e);if(void 0!==o){const[e,{writable:t,readonly:i}]=o;n.push(e),r.writable.push(...t),r.readonly.push(...i)}}const[i,s]=t.getMessageComponents(),a=new am(s,r).compileInstructions(e.instructions);return new bm({header:i,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();dm(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();dm(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),o=Array();dm(o,this.addressTableLookups.length);const i=cl.struct([cl.u8("prefix"),cl.struct([cl.u8("numRequiredSignatures"),cl.u8("numReadonlySignedAccounts"),cl.u8("numReadonlyUnsignedAccounts")],"header"),cl.blob(e.length,"staticAccountKeysLength"),cl.seq(cm(),this.staticAccountKeys.length,"staticAccountKeys"),cm("recentBlockhash"),cl.blob(n.length,"instructionsLength"),cl.blob(t.length,"serializedInstructions"),cl.blob(o.length,"addressTableLookupsLength"),cl.blob(r.length,"serializedAddressTableLookups")]),s=new Uint8Array(rm),a=i.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Fu.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(o),serializedAddressTableLookups:r},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(rm);for(const n of this.compiledInstructions){const r=Array();dm(r,n.accountKeyIndexes.length);const o=Array();dm(o,n.data.length);e+=cl.struct([cl.u8("programIdIndex"),cl.blob(r.length,"encodedAccountKeyIndexesLength"),cl.seq(cl.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),cl.blob(o.length,"encodedDataLength"),cl.blob(n.data.length,"data")]).encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(r),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(o),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(rm);for(const n of this.addressTableLookups){const r=Array();dm(r,n.writableIndexes.length);const o=Array();dm(o,n.readonlyIndexes.length);e+=cl.struct([cm("accountKey"),cl.blob(r.length,"encodedWritableIndexesLength"),cl.seq(cl.u8(),n.writableIndexes.length,"writableIndexes"),cl.blob(o.length,"encodedReadonlyIndexesLength"),cl.seq(cl.u8(),n.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(r),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(o),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=mm(t),r=127&n;fm(n!==r,"Expected versioned message but received legacy message");fm(0===r,`Expected versioned message with version 0 but found version ${r}`);const o={numRequiredSignatures:mm(t),numReadonlySignedAccounts:mm(t),numReadonlyUnsignedAccounts:mm(t)},i=[],s=hm(t);for(let e=0;e<s;e++)i.push(new nm(ym(t,0,em)));const a=Fu.encode(ym(t,0,em)),c=hm(t),u=[];for(let e=0;e<c;e++){const e=mm(t),n=ym(t,0,hm(t)),r=hm(t),o=new Uint8Array(ym(t,0,r));u.push({programIdIndex:e,accountKeyIndexes:n,data:o})}const l=hm(t),h=[];for(let e=0;e<l;e++){const e=new nm(ym(t,0,em)),n=ym(t,0,hm(t)),r=ym(t,0,hm(t));h.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new bm({header:o,staticAccountKeys:i,recentBlockhash:a,compiledInstructions:u,addressTableLookups:h})}}let km=function(e){return e[e.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",e[e.PROCESSED=1]="PROCESSED",e[e.TIMED_OUT=2]="TIMED_OUT",e[e.NONCE_INVALID=3]="NONCE_INVALID",e}({});const vm=Hs.Buffer.alloc(64).fill(0);class Em{constructor(e){this.keys=void 0,this.programId=void 0,this.data=Hs.Buffer.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:n})=>({pubkey:e.toJSON(),isSigner:t,isWritable:n})),programId:this.programId.toJSON(),data:[...this.data]}}}class Sm{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){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,e)if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){const{minContextSlot:t,nonceInfo:n}=e;this.minNonceContextSlot=t,this.nonceInfo=n}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:t,lastValidBlockHeight:n}=e;this.recentBlockhash=t,this.lastValidBlockHeight=n}else{const{recentBlockhash:t,nonceInfo:n}=e;n&&(this.nonceInfo=n),this.recentBlockhash=t}}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(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(0===e.length)throw new Error("No instructions");return e.forEach(e=>{"instructions"in e?this.instructions=this.instructions.concat(e.instructions):"data"in e&&"programId"in e&&"keys"in e?this.instructions.push(e):this.instructions.push(new Em(e))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t,n;if(this.nonceInfo?(e=this.nonceInfo.nonce,t=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");if(t.length,this.feePayer)n=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");n=this.signatures[0].publicKey}for(let e=0;e<t.length;e++)if(void 0===t[e].programId)throw new Error(`Transaction instruction index ${e} has undefined program id`);const r=[],o=[];t.forEach(e=>{e.keys.forEach(e=>{o.push({...e})});const t=e.programId.toString();r.includes(t)||r.push(t)}),r.forEach(e=>{o.push({pubkey:new nm(e),isSigner:!1,isWritable:!1})});const i=[];o.forEach(e=>{const t=e.pubkey.toString(),n=i.findIndex(e=>e.pubkey.toString()===t);n>-1?(i[n].isWritable=i[n].isWritable||e.isWritable,i[n].isSigner=i[n].isSigner||e.isSigner):i.push(e)}),i.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const s=i.findIndex(e=>e.pubkey.equals(n));if(s>-1){const[e]=i.splice(s,1);e.isSigner=!0,e.isWritable=!0,i.unshift(e)}else i.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=i.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);i[t].isSigner||(i[t].isSigner=!0)}let a=0,c=0,u=0;const l=[],h=[];i.forEach(({pubkey:e,isSigner:t,isWritable:n})=>{t?(l.push(e.toString()),a+=1,n||(c+=1)):(h.push(e.toString()),n||(u+=1))});const d=l.concat(h),f=t.map(e=>{const{data:t,programId:n}=e;return{programIdIndex:d.indexOf(n.toString()),accounts:e.keys.map(e=>d.indexOf(e.pubkey.toString())),data:Fu.encode(t)}});return f.forEach(e=>{fm(e.programIdIndex>=0),e.accounts.forEach(e=>fm(e>=0))}),new wm({header:{numRequiredSignatures:a,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:u},accountKeys:d,recentBlockhash:e,instructions:f})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);if(this.signatures.length===t.length){if(this.signatures.every((e,n)=>t[n].equals(e.publicKey)))return e}return this.signatures=t.map(e=>({signature:null,publicKey:e})),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(0===e.length)throw new Error("No signers");const t=new Set;this.signatures=e.filter(e=>{const n=e.toString();return!t.has(n)&&(t.add(n),!0)}).map(e=>({signature:null,publicKey:e}))}sign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}this.signatures=n.map(e=>({signature:null,publicKey:e.publicKey}));const r=this._compile();this._partialSign(r,...n)}partialSign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}const r=this._compile();this._partialSign(r,...n)}_partialSign(e,...t){const n=e.serialize();t.forEach(e=>{const t=((e,t)=>wu.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,Qg(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){fm(64===t.length);const n=this.signatures.findIndex(t=>e.equals(t.publicKey));if(n<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[n].signature=Hs.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:r,publicKey:o}of this.signatures)null===r?t&&(n.missing||=[]).push(o):Xg(r,e,o.toBytes())||(n.invalid||=[]).push(o);return n.invalid||n.missing?n:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:n}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),r=this.serializeMessage();if(n){const e=this._getMessageSignednessErrors(r,t);if(e){let t="Signature verification failed.";throw e.invalid&&(t+=`\nInvalid signature for public key${1===e.invalid.length?"":"(s)"} [\`${e.invalid.map(e=>e.toBase58()).join("`, `")}\`].`),e.missing&&(t+=`\nMissing signature for public key${1===e.missing.length?"":"(s)"} [\`${e.missing.map(e=>e.toBase58()).join("`, `")}\`].`),new Error(t)}}return this._serialize(r)}_serialize(e){const{signatures:t}=this,n=[];dm(n,t.length);const r=n.length+64*t.length+e.length,o=Hs.Buffer.alloc(r);return fm(t.length<256),Hs.Buffer.from(n).copy(o,0),t.forEach(({signature:e},t)=>{null!==e&&(fm(64===e.length,"signature has invalid length"),Hs.Buffer.from(e).copy(o,n.length+64*t))}),e.copy(o,n.length+64*t.length),fm(o.length<=rm,`Transaction too large: ${o.length} > 1232`),o}get keys(){return fm(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return fm(1===this.instructions.length),this.instructions[0].programId}get data(){return fm(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=hm(t);let r=[];for(let e=0;e<n;e++){const e=ym(t,0,64);r.push(Fu.encode(Hs.Buffer.from(e)))}return Sm.populate(wm.from(t),r)}static populate(e,t=[]){const n=new Sm;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const o={signature:t==Fu.encode(vm)?null:Fu.decode(t),publicKey:e.accountKeys[r]};n.signatures.push(o)}),e.instructions.forEach(t=>{const r=t.accounts.map(t=>{const r=e.accountKeys[t];return{pubkey:r,isSigner:n.signatures.some(e=>e.publicKey.toString()===r.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});n.instructions.push(new Em({keys:r,programId:e.accountKeys[t.programIdIndex],data:Fu.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new nm("SysvarC1ock11111111111111111111111111111111"),new nm("SysvarEpochSchedu1e111111111111111111111111"),new nm("Sysvar1nstructions1111111111111111111111111");const Am=new nm("SysvarRecentB1ockHashes11111111111111111111"),Tm=new nm("SysvarRent111111111111111111111111111111111");new nm("SysvarRewards111111111111111111111111111111"),new nm("SysvarS1otHashes111111111111111111111111111"),new nm("SysvarS1otHistory11111111111111111111111111"),new nm("SysvarStakeHistory1111111111111111111111111");class Im extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const o=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",i="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let s;switch(e){case"send":s=`Transaction ${t} resulted in an error. \n${n}. `+o+i;break;case"simulate":s=`Simulation failed. \nMessage: ${n}. \n`+o+i;break;default:s=`Unknown action '${e}'`}super(s),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=n,this.transactionLogs=r||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const e=this.transactionLogs;if(null==e||"object"!=typeof e||!("then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((t,n)=>{e.getTransaction(this.signature).then(e=>{if(e&&e.meta&&e.meta.logMessages){const n=e.meta.logMessages;this.transactionLogs=n,t(n)}else n(new Error("Log messages not found"))}).catch(n)})),await this.transactionLogs}}class Bm extends Error{constructor({code:e,message:t,data:n},r){super(null!=r?`${r}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=n,this.name="SolanaJSONRPCError"}}function xm(e){return new Promise(t=>setTimeout(t,e))}function Cm(e,t){const n=e.layout.span>=0?e.layout.span:lm(e,t),r=Hs.Buffer.alloc(n),o=Object.assign({instruction:e.index},t);return e.layout.encode(o,r),r}const Pm=cl.nu64("lamportsPerSignature"),Nm=cl.struct([cl.u32("version"),cl.u32("state"),cm("authorizedPubkey"),cm("nonce"),cl.struct([Pm],"feeCalculator")]),_m=Nm.span;class Um{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){const t=Nm.decode(Qg(e),0);return new Um({authorizedPubkey:new nm(t.authorizedPubkey),nonce:new nm(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function Dm(e){const t=cl.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),o=t,i=_p();return o.decode=(e,t)=>{const r=n(e,t);return i.decode(r)},o.encode=(e,t,n)=>{const o=i.encode(e);return r(o,t,n)},o}const Rm=Object.freeze({Create:{index:0,layout:cl.struct([cl.u32("instruction"),cl.ns64("lamports"),cl.ns64("space"),cm("programId")])},Assign:{index:1,layout:cl.struct([cl.u32("instruction"),cm("programId")])},Transfer:{index:2,layout:cl.struct([cl.u32("instruction"),Dm("lamports")])},CreateWithSeed:{index:3,layout:cl.struct([cl.u32("instruction"),cm("base"),um("seed"),cl.ns64("lamports"),cl.ns64("space"),cm("programId")])},AdvanceNonceAccount:{index:4,layout:cl.struct([cl.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:cl.struct([cl.u32("instruction"),cl.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:cl.struct([cl.u32("instruction"),cm("authorized")])},AuthorizeNonceAccount:{index:7,layout:cl.struct([cl.u32("instruction"),cm("authorized")])},Allocate:{index:8,layout:cl.struct([cl.u32("instruction"),cl.ns64("space")])},AllocateWithSeed:{index:9,layout:cl.struct([cl.u32("instruction"),cm("base"),um("seed"),cl.ns64("space"),cm("programId")])},AssignWithSeed:{index:10,layout:cl.struct([cl.u32("instruction"),cm("base"),um("seed"),cm("programId")])},TransferWithSeed:{index:11,layout:cl.struct([cl.u32("instruction"),Dm("lamports"),um("seed"),cm("programId")])},UpgradeNonceAccount:{index:12,layout:cl.struct([cl.u32("instruction")])}});class Fm{constructor(){}static createAccount(e){const t=Cm(Rm.Create,{lamports:e.lamports,space:e.space,programId:Qg(e.programId.toBuffer())});return new Em({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:t})}static transfer(e){let t,n;if("basePubkey"in e){t=Cm(Rm.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:Qg(e.programId.toBuffer())}),n=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{t=Cm(Rm.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new Em({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=Cm(Rm.AssignWithSeed,{base:Qg(e.basePubkey.toBuffer()),seed:e.seed,programId:Qg(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Cm(Rm.Assign,{programId:Qg(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Em({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=Cm(Rm.CreateWithSeed,{base:Qg(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:Qg(e.programId.toBuffer())});let n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey.equals(e.fromPubkey)||n.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new Em({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new Sm;"basePubkey"in e&&"seed"in e?t.add(Fm.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:_m,programId:this.programId})):t.add(Fm.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:_m,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=Cm(Rm.InitializeNonceAccount,{authorized:Qg(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Am,isSigner:!1,isWritable:!1},{pubkey:Tm,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new Em(n)}static nonceAdvance(e){const t=Cm(Rm.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Am,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new Em(n)}static nonceWithdraw(e){const t=Cm(Rm.WithdrawNonceAccount,{lamports:e.lamports});return new Em({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:Am,isSigner:!1,isWritable:!1},{pubkey:Tm,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=Cm(Rm.AuthorizeNonceAccount,{authorized:Qg(e.newAuthorizedPubkey.toBuffer())});return new Em({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static allocate(e){let t,n;if("basePubkey"in e){t=Cm(Rm.AllocateWithSeed,{base:Qg(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:Qg(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Cm(Rm.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Em({keys:n,programId:this.programId,data:t})}}function Lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Om,Mm;function $m(){if(Mm)return Om;Mm=1;var e=Object.prototype.toString,t=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};function n(r,o){var i,s,a,c,u,l,h;if(!0===r)return"true";if(!1===r)return"false";switch(typeof r){case"object":if(null===r)return null;if(r.toJSON&&"function"==typeof r.toJSON)return n(r.toJSON(),o);if("[object Array]"===(h=e.call(r))){for(a="[",s=r.length-1,i=0;i<s;i++)a+=n(r[i],!0)+",";return s>-1&&(a+=n(r[i],!0)),a+"]"}if("[object Object]"===h){for(s=(c=t(r).sort()).length,a="",i=0;i<s;)void 0!==(l=n(r[u=c[i]],!1))&&(a&&(a+=","),a+=JSON.stringify(u)+":"+l),i++;return"{"+a+"}"}return JSON.stringify(r);case"function":case"undefined":return o?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return Om=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Fm.programId=new nm("11111111111111111111111111111111"),new nm("BPFLoader2111111111111111111111111111111111");var qm=Lm($m());function Km(e){let t=0;for(;e>1;)e/=2,t++;return t}class Gm{constructor(e,t,n,r,o){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=n,this.firstNormalEpoch=r,this.firstNormalSlot=o}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=Km(0===(t=e+32+1)?1:(t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,1+(t|=t>>32)))-Km(32)-1;return[n,e-(this.getSlotsInEpoch(n)-32)]}{const t=e-this.firstNormalSlot,n=Math.floor(t/this.slotsPerEpoch);return[this.firstNormalEpoch+n,t%this.slotsPerEpoch]}var t}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?32*(Math.pow(2,e)-1):(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e<this.firstNormalEpoch?Math.pow(2,e+Km(32)):this.slotsPerEpoch}}var Wm=globalThis.fetch;class zm extends kg{constructor(e,t,n){super(e=>{const n=function(e,t){return new wg(e,t)}(e,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t});return this.underlyingSocket="socket"in n?n.socket:n,n},e,t,n),this.underlyingSocket=void 0}call(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}notify(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}}class jm{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const t=function(e,t){let n;try{n=e.layout.decode(t)}catch(e){throw new Error("invalid instruction; "+e)}if(n.typeIndex!==e.index)throw new Error(`invalid account data; account type mismatch ${n.typeIndex} != ${e.index}`);return n}(Hm,e),n=e.length-56;fm(n>=0,"lookup table is invalid"),fm(n%32==0,"lookup table is invalid");const r=n/32,{addresses:o}=cl.struct([cl.seq(cm(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new nm(t.authority[0]):void 0,addresses:o.map(e=>new nm(e))}}}const Hm={index:1,layout:cl.struct([cl.u32("typeIndex"),Dm("deactivationSlot"),cl.nu64("lastExtendedSlot"),cl.u8("lastExtendedStartIndex"),cl.u8(),cl.seq(cm(),cl.offset(cl.u8(),-1),"authority")])},Vm=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const Xm=og(Hp(nm),Jp(),e=>new nm(e)),Qm=eg([Jp(),Vp("base64")]),Zm=og(Hp(Hs.Buffer),Qm,e=>Hs.Buffer.from(e[0],"base64"));function Ym(e){let t,n;if("string"==typeof e)t=e;else if(e){const{commitment:r,...o}=e;t=r,n=o}return{commitment:t,config:n}}function Jm(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function ey(e){return ng([tg({jsonrpc:Vp("2.0"),id:Jp(),result:e}),tg({jsonrpc:Vp("2.0"),id:Jp(),error:tg({code:rg(),message:Jp(),data:Zp(Wp("any",()=>!0))})})])}const ty=ey(rg());function ny(e){return og(ey(e),ty,t=>"error"in t?t:{...t,result:qp(t.result,e)})}function ry(e){return ny(tg({context:tg({slot:Qp()}),value:e}))}function oy(e){return tg({context:tg({slot:Qp()}),value:e})}function iy(e,t){return 0===e?new bm({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new nm(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Fu.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new wm(t)}const sy=tg({foundation:Qp(),foundationTerm:Qp(),initial:Qp(),taper:Qp(),terminal:Qp()}),ay=ny(zp(Xp(tg({epoch:Qp(),effectiveSlot:Qp(),amount:Qp(),postBalance:Qp(),commission:Zp(Xp(Qp()))})))),cy=zp(tg({slot:Qp(),prioritizationFee:Qp()})),uy=tg({total:Qp(),validator:Qp(),foundation:Qp(),epoch:Qp()}),ly=tg({epoch:Qp(),slotIndex:Qp(),slotsInEpoch:Qp(),absoluteSlot:Qp(),blockHeight:Zp(Qp()),transactionCount:Zp(Qp())}),hy=tg({slotsPerEpoch:Qp(),leaderScheduleSlotOffset:Qp(),warmup:jp(),firstNormalEpoch:Qp(),firstNormalSlot:Qp()}),dy=Yp(Jp(),zp(Qp())),fy=Xp(ng([tg({}),Jp()])),py=tg({err:fy}),gy=Vp("receivedSignature"),my=tg({"solana-core":Jp(),"feature-set":Zp(Qp())}),yy=tg({program:Jp(),programId:Xm,parsed:rg()}),wy=tg({programId:Xm,accounts:zp(Xm),data:Jp()}),by=ry(tg({err:Xp(ng([tg({}),Jp()])),logs:Xp(zp(Jp())),accounts:Zp(Xp(zp(Xp(tg({executable:jp(),owner:Jp(),lamports:Qp(),data:zp(Jp()),rentEpoch:Zp(Qp())}))))),unitsConsumed:Zp(Qp()),returnData:Zp(Xp(tg({programId:Jp(),data:eg([Jp(),Vp("base64")])}))),innerInstructions:Zp(Xp(zp(tg({index:Qp(),instructions:zp(ng([yy,wy]))}))))})),ky=ry(tg({byIdentity:Yp(Jp(),zp(Qp())),range:tg({firstSlot:Qp(),lastSlot:Qp()})}));const vy=ny(sy),Ey=ny(uy),Sy=ny(cy),Ay=ny(ly),Ty=ny(hy),Iy=ny(dy),By=ny(Qp()),xy=ry(tg({total:Qp(),circulating:Qp(),nonCirculating:Qp(),nonCirculatingAccounts:zp(Xm)})),Cy=tg({amount:Jp(),uiAmount:Xp(Qp()),decimals:Qp(),uiAmountString:Zp(Jp())}),Py=ry(zp(tg({address:Xm,amount:Jp(),uiAmount:Xp(Qp()),decimals:Qp(),uiAmountString:Zp(Jp())}))),Ny=ry(zp(tg({pubkey:Xm,account:tg({executable:jp(),owner:Xm,lamports:Qp(),data:Zm,rentEpoch:Qp()})}))),_y=tg({program:Jp(),parsed:rg(),space:Qp()}),Uy=ry(zp(tg({pubkey:Xm,account:tg({executable:jp(),owner:Xm,lamports:Qp(),data:_y,rentEpoch:Qp()})}))),Dy=ry(zp(tg({lamports:Qp(),address:Xm}))),Ry=tg({executable:jp(),owner:Xm,lamports:Qp(),data:Zm,rentEpoch:Qp()}),Fy=tg({pubkey:Xm,account:Ry}),Ly=og(ng([Hp(Hs.Buffer),_y]),ng([Qm,_y]),e=>Array.isArray(e)?qp(e,Zm):e),Oy=tg({executable:jp(),owner:Xm,lamports:Qp(),data:Ly,rentEpoch:Qp()}),My=tg({pubkey:Xm,account:Oy}),$y=tg({state:ng([Vp("active"),Vp("inactive"),Vp("activating"),Vp("deactivating")]),active:Qp(),inactive:Qp()}),qy=ny(zp(tg({signature:Jp(),slot:Qp(),err:fy,memo:Xp(Jp()),blockTime:Zp(Xp(Qp()))}))),Ky=ny(zp(tg({signature:Jp(),slot:Qp(),err:fy,memo:Xp(Jp()),blockTime:Zp(Xp(Qp()))}))),Gy=tg({subscription:Qp(),result:oy(Ry)}),Wy=tg({pubkey:Xm,account:Ry}),zy=tg({subscription:Qp(),result:oy(Wy)}),jy=tg({parent:Qp(),slot:Qp(),root:Qp()}),Hy=tg({subscription:Qp(),result:jy}),Vy=ng([tg({type:ng([Vp("firstShredReceived"),Vp("completed"),Vp("optimisticConfirmation"),Vp("root")]),slot:Qp(),timestamp:Qp()}),tg({type:Vp("createdBank"),parent:Qp(),slot:Qp(),timestamp:Qp()}),tg({type:Vp("frozen"),slot:Qp(),timestamp:Qp(),stats:tg({numTransactionEntries:Qp(),numSuccessfulTransactions:Qp(),numFailedTransactions:Qp(),maxTransactionsPerEntry:Qp()})}),tg({type:Vp("dead"),slot:Qp(),timestamp:Qp(),err:Jp()})]),Xy=tg({subscription:Qp(),result:Vy}),Qy=tg({subscription:Qp(),result:oy(ng([py,gy]))}),Zy=tg({subscription:Qp(),result:Qp()}),Yy=tg({pubkey:Jp(),gossip:Xp(Jp()),tpu:Xp(Jp()),rpc:Xp(Jp()),version:Xp(Jp())}),Jy=tg({votePubkey:Jp(),nodePubkey:Jp(),activatedStake:Qp(),epochVoteAccount:jp(),epochCredits:zp(eg([Qp(),Qp(),Qp()])),commission:Qp(),lastVote:Qp(),rootSlot:Xp(Qp())}),ew=ny(tg({current:zp(Jy),delinquent:zp(Jy)})),tw=ng([Vp("processed"),Vp("confirmed"),Vp("finalized")]),nw=tg({slot:Qp(),confirmations:Xp(Qp()),err:fy,confirmationStatus:Zp(tw)}),rw=ry(zp(Xp(nw))),ow=ny(Qp()),iw=tg({accountKey:Xm,writableIndexes:zp(Qp()),readonlyIndexes:zp(Qp())}),sw=tg({signatures:zp(Jp()),message:tg({accountKeys:zp(Jp()),header:tg({numRequiredSignatures:Qp(),numReadonlySignedAccounts:Qp(),numReadonlyUnsignedAccounts:Qp()}),instructions:zp(tg({accounts:zp(Qp()),data:Jp(),programIdIndex:Qp()})),recentBlockhash:Jp(),addressTableLookups:Zp(zp(iw))})}),aw=tg({pubkey:Xm,signer:jp(),writable:jp(),source:Zp(ng([Vp("transaction"),Vp("lookupTable")]))}),cw=tg({accountKeys:zp(aw),signatures:zp(Jp())}),uw=tg({parsed:rg(),program:Jp(),programId:Xm}),lw=tg({accounts:zp(Xm),data:Jp(),programId:Xm}),hw=og(ng([lw,uw]),ng([tg({parsed:rg(),program:Jp(),programId:Jp()}),tg({accounts:zp(Jp()),data:Jp(),programId:Jp()})]),e=>qp(e,"accounts"in e?lw:uw)),dw=tg({signatures:zp(Jp()),message:tg({accountKeys:zp(aw),instructions:zp(hw),recentBlockhash:Jp(),addressTableLookups:Zp(Xp(zp(iw)))})}),fw=tg({accountIndex:Qp(),mint:Jp(),owner:Zp(Jp()),programId:Zp(Jp()),uiTokenAmount:Cy}),pw=tg({writable:zp(Xm),readonly:zp(Xm)}),gw=tg({err:fy,fee:Qp(),innerInstructions:Zp(Xp(zp(tg({index:Qp(),instructions:zp(tg({accounts:zp(Qp()),data:Jp(),programIdIndex:Qp()}))})))),preBalances:zp(Qp()),postBalances:zp(Qp()),logMessages:Zp(Xp(zp(Jp()))),preTokenBalances:Zp(Xp(zp(fw))),postTokenBalances:Zp(Xp(zp(fw))),loadedAddresses:Zp(pw),computeUnitsConsumed:Zp(Qp()),costUnits:Zp(Qp())}),mw=tg({err:fy,fee:Qp(),innerInstructions:Zp(Xp(zp(tg({index:Qp(),instructions:zp(hw)})))),preBalances:zp(Qp()),postBalances:zp(Qp()),logMessages:Zp(Xp(zp(Jp()))),preTokenBalances:Zp(Xp(zp(fw))),postTokenBalances:Zp(Xp(zp(fw))),loadedAddresses:Zp(pw),computeUnitsConsumed:Zp(Qp()),costUnits:Zp(Qp())}),yw=ng([Vp(0),Vp("legacy")]),ww=tg({pubkey:Jp(),lamports:Qp(),postBalance:Xp(Qp()),rewardType:Xp(Jp()),commission:Zp(Xp(Qp()))}),bw=ny(Xp(tg({blockhash:Jp(),previousBlockhash:Jp(),parentSlot:Qp(),transactions:zp(tg({transaction:sw,meta:Xp(gw),version:Zp(yw)})),rewards:Zp(zp(ww)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),kw=ny(Xp(tg({blockhash:Jp(),previousBlockhash:Jp(),parentSlot:Qp(),rewards:Zp(zp(ww)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),vw=ny(Xp(tg({blockhash:Jp(),previousBlockhash:Jp(),parentSlot:Qp(),transactions:zp(tg({transaction:cw,meta:Xp(gw),version:Zp(yw)})),rewards:Zp(zp(ww)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),Ew=ny(Xp(tg({blockhash:Jp(),previousBlockhash:Jp(),parentSlot:Qp(),transactions:zp(tg({transaction:dw,meta:Xp(mw),version:Zp(yw)})),rewards:Zp(zp(ww)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),Sw=ny(Xp(tg({blockhash:Jp(),previousBlockhash:Jp(),parentSlot:Qp(),transactions:zp(tg({transaction:cw,meta:Xp(mw),version:Zp(yw)})),rewards:Zp(zp(ww)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),Aw=ny(Xp(tg({blockhash:Jp(),previousBlockhash:Jp(),parentSlot:Qp(),rewards:Zp(zp(ww)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),Tw=ny(Xp(tg({blockhash:Jp(),previousBlockhash:Jp(),parentSlot:Qp(),transactions:zp(tg({transaction:sw,meta:Xp(gw)})),rewards:Zp(zp(ww)),blockTime:Xp(Qp())}))),Iw=ny(Xp(tg({blockhash:Jp(),previousBlockhash:Jp(),parentSlot:Qp(),signatures:zp(Jp()),blockTime:Xp(Qp())}))),Bw=ny(Xp(tg({slot:Qp(),meta:Xp(gw),blockTime:Zp(Xp(Qp())),transaction:sw,version:Zp(yw)}))),xw=ny(Xp(tg({slot:Qp(),transaction:dw,meta:Xp(mw),blockTime:Zp(Xp(Qp())),version:Zp(yw)}))),Cw=ry(tg({blockhash:Jp(),lastValidBlockHeight:Qp()})),Pw=ry(jp()),Nw=ny(zp(tg({slot:Qp(),numTransactions:Qp(),numSlots:Qp(),samplePeriodSecs:Qp()}))),_w=ry(Xp(tg({feeCalculator:tg({lamportsPerSignature:Qp()})}))),Uw=ny(Jp()),Dw=ny(Jp()),Rw=tg({err:fy,logs:zp(Jp()),signature:Jp()}),Fw=tg({result:oy(Rw),subscription:Qp()}),Lw={"solana-client":"js/1.0.0-maintenance"};class Ow{constructor(e,t){let n,r,o,i,s,a;var c;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const e={};return async t=>{const{commitment:n,config:r}=Ym(t),o=this._buildArgs([],n,void 0,r),i=qm(o);return e[i]=e[i]??(async()=>{try{const e=qp(await this._rpcRequest("getBlockHeight",o),ny(Qp()));if("error"in e)throw new Bm(e.error,"failed to get block height information");return e.result}finally{delete e[i]}})(),await e[i]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,r=t.httpHeaders,o=t.fetch,i=t.fetchMiddleware,s=t.disableRetryOnRateLimit,a=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=n||function(e){const t=e.match(Vm);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,o,i]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==o?null:parseInt(o.slice(1),10);return`${s}//${r}${null==a?"":`:${a+1}`}${i}`}(e),this._rpcClient=function(e,t,n,r,o){const i=n||Wm;let s;return r&&(s=async(e,t)=>{const n=await new Promise((n,o)=>{try{r(e,t,(e,t)=>n([e,t]))}catch(e){o(e)}});return await i(...n)}),new hg(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},Lw)};try{let t,n=5,c=500;for(;t=s?await s(e,a):await i(e,a),429===t.status&&!0!==o&&(n-=1,0!==n);)await xm(c),c*=2;const u=await t.text();t.ok?r(null,u):r(new Error(`${t.status} ${t.statusText}: ${u}`))}catch(e){e instanceof Error&&r(e)}},{})}(e,r,o,i,s),this._rpcRequest=(c=this._rpcClient,(e,t)=>new Promise((n,r)=>{c.request(e,t,(e,t)=>{e?r(e):n(t)})})),this._rpcBatchRequest=function(e){return t=>new Promise((n,r)=>{0===t.length&&n([]);const o=t.map(t=>e.request(t.methodName,t.args));e.request(o,(e,t)=>{e?r(e):n(t)})})}(this._rpcClient),this._rpcWebSocket=new zm(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){const{commitment:n,config:r}=Ym(t),o=this._buildArgs([e.toBase58()],n,void 0,r),i=qp(await this._rpcRequest("getBalance",o),ry(Qp()));if("error"in i)throw new Bm(i.error,`failed to get balance for ${e.toBase58()}`);return i.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=qp(await this._rpcRequest("getBlockTime",[e]),ny(Xp(Qp())));if("error"in t)throw new Bm(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=qp(await this._rpcRequest("minimumLedgerSlot",[]),ny(Qp()));if("error"in e)throw new Bm(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=qp(await this._rpcRequest("getFirstAvailableBlock",[]),By);if("error"in e)throw new Bm(e.error,"failed to get first available block");return e.result}async getSupply(e){let t={};t="string"==typeof e?{commitment:e}:e?{...e,commitment:e&&e.commitment||this.commitment}:{commitment:this.commitment};const n=qp(await this._rpcRequest("getSupply",[t]),xy);if("error"in n)throw new Bm(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=qp(await this._rpcRequest("getTokenSupply",n),ry(Cy));if("error"in r)throw new Bm(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=qp(await this._rpcRequest("getTokenAccountBalance",n),ry(Cy));if("error"in r)throw new Bm(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:o}=Ym(n);let i=[e.toBase58()];"mint"in t?i.push({mint:t.mint.toBase58()}):i.push({programId:t.programId.toBase58()});const s=this._buildArgs(i,r,"base64",o),a=qp(await this._rpcRequest("getTokenAccountsByOwner",s),Ny);if("error"in a)throw new Bm(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getParsedTokenAccountsByOwner(e,t,n){let r=[e.toBase58()];"mint"in t?r.push({mint:t.mint.toBase58()}):r.push({programId:t.programId.toBase58()});const o=this._buildArgs(r,n,"jsonParsed"),i=qp(await this._rpcRequest("getTokenAccountsByOwner",o),Uy);if("error"in i)throw new Bm(i.error,`failed to get token accounts owned by account ${e.toBase58()}`);return i.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=qp(await this._rpcRequest("getLargestAccounts",n),Dy);if("error"in r)throw new Bm(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=qp(await this._rpcRequest("getTokenLargestAccounts",n),Py);if("error"in r)throw new Bm(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=Ym(t),o=this._buildArgs([e.toBase58()],n,"base64",r),i=qp(await this._rpcRequest("getAccountInfo",o),ry(Xp(Ry)));if("error"in i)throw new Bm(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=Ym(t),o=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=qp(await this._rpcRequest("getAccountInfo",o),ry(Xp(Oy)));if("error"in i)throw new Bm(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(t){throw new Error("failed to get info about account "+e.toBase58()+": "+t)}}async getMultipleParsedAccounts(e,t){const{commitment:n,config:r}=Ym(t),o=e.map(e=>e.toBase58()),i=this._buildArgs([o],n,"jsonParsed",r),s=qp(await this._rpcRequest("getMultipleAccounts",i),ry(zp(Xp(Oy))));if("error"in s)throw new Bm(s.error,`failed to get info for accounts ${o}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=Ym(t),o=e.map(e=>e.toBase58()),i=this._buildArgs([o],n,"base64",r),s=qp(await this._rpcRequest("getMultipleAccounts",i),ry(zp(Xp(Ry))));if("error"in s)throw new Bm(s.error,`failed to get info for accounts ${o}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:o}=Ym(t),i=this._buildArgs([e.toBase58()],r,void 0,{...o,epoch:null!=n?n:o?.epoch}),s=qp(await this._rpcRequest("getStakeActivation",i),ny($y));if("error"in s)throw new Bm(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=Ym(t),{encoding:o,...i}=r||{},s=this._buildArgs([e.toBase58()],n,o||"base64",{...i,...i.filters?{filters:Jm(i.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=zp(Fy),u=!0===i.withContext?qp(a,ry(c)):qp(a,ny(c));if("error"in u)throw new Bm(u.error,`failed to get accounts owned by program ${e.toBase58()}`);return u.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=Ym(t),o=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=qp(await this._rpcRequest("getProgramAccounts",o),ny(zp(My)));if("error"in i)throw new Bm(i.error,`failed to get accounts owned by program ${e.toBase58()}`);return i.result}async confirmTransaction(e,t){let n,r;if("string"==typeof e)n=e;else{const t=e;if(t.abortSignal?.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{r=Fu.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return fm(64===r.length,"signature has invalid length"),"string"==typeof e?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,n)=>{null!=e&&(e.aborted?n(e.reason):e.addEventListener("abort",()=>{n(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let n,r,o=!1;return{abortConfirmation:()=>{r&&(r(),r=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:new Promise((i,s)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};i({__type:km.PROCESSED,response:r})},e);const a=new Promise(e=>{null==n?e():r=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,o)return;const n=await this.getSignatureStatus(t);if(o)return;if(null==n)return;const{context:r,value:c}=n;if(null!=c)if(c?.err)s(c.err);else{switch(e){case"confirmed":case"single":case"singleGossip":if("processed"===c.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===c.confirmationStatus||"confirmed"===c.confirmationStatus)return}o=!0,i({__type:km.PROCESSED,response:{context:r,value:c}})}})()}catch(e){s(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let o=!1;const i=new Promise(t=>{const r=async()=>{try{return await this.getBlockHeight(e)}catch(e){return-1}};(async()=>{let e=await r();if(!o){for(;e<=n;){if(await xm(1e3),o)return;if(e=await r(),o)return}t({__type:km.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:r}),c=this.getCancellationPromise(t);let u;try{const e=await Promise.race([c,a,i]);if(e.__type!==km.PROCESSED)throw new om(r);u=e.response}finally{o=!0,s()}return u}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:o,signature:i}}){let s=!1;const a=new Promise(t=>{let i=o,a=null;const c=async()=>{try{const{context:t,value:o}=await this.getNonceAndContext(r,{commitment:e,minContextSlot:n});return a=t.slot,o?.nonce}catch(e){return i}};(async()=>{if(i=await c(),!s)for(;;){if(o!==i)return void t({__type:km.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await xm(2e3),s)return;if(i=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:u}=this.getTransactionConfirmationPromise({commitment:e,signature:i}),l=this.getCancellationPromise(t);let h;try{const t=await Promise.race([l,u,a]);if(t.__type===km.PROCESSED)h=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(i);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await xm(400)}if(!r?.value)throw new sm(i);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new sm(i);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new sm(i);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new sm(i)}h={context:r.context,value:{err:r.value.err}}}}}finally{s=!0,c()}return h}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let n;const r=new Promise(t=>{let r=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":r=this._confirmTransactionInitialTimeout||3e4}n=setTimeout(()=>t({__type:km.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:o,confirmationPromise:i}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([i,r]);if(e.__type!==km.PROCESSED)throw new im(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(n),o()}return s}async getClusterNodes(){const e=qp(await this._rpcRequest("getClusterNodes",[]),ny(zp(Yy)));if("error"in e)throw new Bm(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=qp(await this._rpcRequest("getVoteAccounts",t),ew);if("error"in n)throw new Bm(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=Ym(e),r=this._buildArgs([],t,void 0,n),o=qp(await this._rpcRequest("getSlot",r),ny(Qp()));if("error"in o)throw new Bm(o.error,"failed to get slot");return o.result}async getSlotLeader(e){const{commitment:t,config:n}=Ym(e),r=this._buildArgs([],t,void 0,n),o=qp(await this._rpcRequest("getSlotLeader",r),ny(Jp()));if("error"in o)throw new Bm(o.error,"failed to get slot leader");return o.result}async getSlotLeaders(e,t){const n=[e,t],r=qp(await this._rpcRequest("getSlotLeaders",n),ny(zp(Xm)));if("error"in r)throw new Bm(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);fm(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=qp(await this._rpcRequest("getSignatureStatuses",n),rw);if("error"in r)throw new Bm(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=Ym(e),r=this._buildArgs([],t,void 0,n),o=qp(await this._rpcRequest("getTransactionCount",r),ny(Qp()));if("error"in o)throw new Bm(o.error,"failed to get transaction count");return o.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=qp(await this._rpcRequest("getInflationGovernor",t),vy);if("error"in n)throw new Bm(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:o}=Ym(n),i=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...o,epoch:null!=t?t:o?.epoch}),s=qp(await this._rpcRequest("getInflationReward",i),ay);if("error"in s)throw new Bm(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=qp(await this._rpcRequest("getInflationRate",[]),Ey);if("error"in e)throw new Bm(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=Ym(e),r=this._buildArgs([],t,void 0,n),o=qp(await this._rpcRequest("getEpochInfo",r),Ay);if("error"in o)throw new Bm(o.error,"failed to get epoch info");return o.result}async getEpochSchedule(){const e=qp(await this._rpcRequest("getEpochSchedule",[]),Ty);if("error"in e)throw new Bm(e.error,"failed to get epoch schedule");const t=e.result;return new Gm(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=qp(await this._rpcRequest("getLeaderSchedule",[]),Iy);if("error"in e)throw new Bm(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=qp(await this._rpcRequest("getMinimumBalanceForRentExemption",n),ow);return"error"in r?0:r.result}async getRecentBlockhashAndContext(e){const{context:t,value:{blockhash:n}}=await this.getLatestBlockhashAndContext(e);return{context:t,value:{blockhash:n,feeCalculator:{get lamportsPerSignature(){throw new Error("The capability to fetch `lamportsPerSignature` using the `getRecentBlockhash` API is no longer offered by the network. Use the `getFeeForMessage` API to obtain the fee for a given message.")},toJSON:()=>({})}}}}async getRecentPerformanceSamples(e){const t=qp(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),Nw);if("error"in t)throw new Bm(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=qp(await this._rpcRequest("getFeeCalculatorForBlockhash",n),_w);if("error"in r)throw new Bm(r.error,"failed to get fee calculator");const{context:o,value:i}=r.result;return{context:o,value:null!==i?i.feeCalculator:null}}async getFeeForMessage(e,t){const n=Qg(e.serialize()).toString("base64"),r=this._buildArgs([n],t),o=qp(await this._rpcRequest("getFeeForMessage",r),ry(Xp(Qp())));if("error"in o)throw new Bm(o.error,"failed to get fee for message");if(null===o.result)throw new Error("invalid blockhash");return o.result}async getRecentPrioritizationFees(e){const t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],r=qp(await this._rpcRequest("getRecentPrioritizationFees",n),Sy);if("error"in r)throw new Bm(r.error,"failed to get recent prioritization fees");return r.result}async getRecentBlockhash(e){try{return(await this.getRecentBlockhashAndContext(e)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhash(e){try{return(await this.getLatestBlockhashAndContext(e)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhashAndContext(e){const{commitment:t,config:n}=Ym(e),r=this._buildArgs([],t,void 0,n),o=qp(await this._rpcRequest("getLatestBlockhash",r),Cw);if("error"in o)throw new Bm(o.error,"failed to get latest blockhash");return o.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=Ym(t),o=this._buildArgs([e],n,void 0,r),i=qp(await this._rpcRequest("isBlockhashValid",o),Pw);if("error"in i)throw new Bm(i.error,"failed to determine if the blockhash `"+e+"`is valid");return i.result}async getVersion(){const e=qp(await this._rpcRequest("getVersion",[]),ny(my));if("error"in e)throw new Bm(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=qp(await this._rpcRequest("getGenesisHash",[]),ny(Jp()));if("error"in e)throw new Bm(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=Ym(t),o=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=await this._rpcRequest("getBlock",o);try{switch(r?.transactionDetails){case"accounts":{const e=qp(i,vw);if("error"in e)throw e.error;return e.result}case"none":{const e=qp(i,kw);if("error"in e)throw e.error;return e.result}default:{const e=qp(i,bw);if("error"in e)throw e.error;const{result:t}=e;return t?{...t,transactions:t.transactions.map(({transaction:e,meta:t,version:n})=>({meta:t,transaction:{...e,message:iy(n,e.message)},version:n}))}:null}}}catch(e){throw new Bm(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=Ym(t),o=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=await this._rpcRequest("getBlock",o);try{switch(r?.transactionDetails){case"accounts":{const e=qp(i,Sw);if("error"in e)throw e.error;return e.result}case"none":{const e=qp(i,Aw);if("error"in e)throw e.error;return e.result}default:{const e=qp(i,Ew);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Bm(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){const{commitment:r,...o}=e;n=r,t=o}const r=this._buildArgs([],n,"base64",t),o=qp(await this._rpcRequest("getBlockProduction",r),ky);if("error"in o)throw new Bm(o.error,"failed to get block production information");return o.result}async getTransaction(e,t){const{commitment:n,config:r}=Ym(t),o=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=qp(await this._rpcRequest("getTransaction",o),Bw);if("error"in i)throw new Bm(i.error,"failed to get transaction");const s=i.result;return s?{...s,transaction:{...s.transaction,message:iy(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:n,config:r}=Ym(t),o=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=qp(await this._rpcRequest("getTransaction",o),xw);if("error"in i)throw new Bm(i.error,"failed to get transaction");return i.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=Ym(t),o=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(o)).map(e=>{const t=qp(e,xw);if("error"in t)throw new Bm(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=Ym(t),o=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(o)).map(e=>{const t=qp(e,Bw);if("error"in t)throw new Bm(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:iy(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=qp(await this._rpcRequest("getBlock",n),Tw);if("error"in r)throw new Bm(r.error,"failed to get confirmed block");const o=r.result;if(!o)throw new Error("Confirmed block "+e+" not found");const i={...o,transactions:o.transactions.map(({transaction:e,meta:t})=>{const n=new wm(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...i,transactions:i.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:Sm.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),o=qp(await this._rpcRequest("getBlocks",r),ny(zp(Qp())));if("error"in o)throw new Bm(o.error,"failed to get blocks");return o.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=qp(await this._rpcRequest("getBlock",n),Iw);if("error"in r)throw new Bm(r.error,"failed to get block");const o=r.result;if(!o)throw new Error("Block "+e+" not found");return o}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=qp(await this._rpcRequest("getBlock",n),Iw);if("error"in r)throw new Bm(r.error,"failed to get confirmed block");const o=r.result;if(!o)throw new Error("Confirmed block "+e+" not found");return o}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=qp(await this._rpcRequest("getTransaction",n),Bw);if("error"in r)throw new Bm(r.error,"failed to get transaction");const o=r.result;if(!o)return o;const i=new wm(o.transaction.message),s=o.transaction.signatures;return{...o,transaction:Sm.populate(i,s)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=qp(await this._rpcRequest("getTransaction",n),xw);if("error"in r)throw new Bm(r.error,"failed to get confirmed transaction");return r.result}async getParsedConfirmedTransactions(e,t){const n=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],t,"jsonParsed")}));return(await this._rpcBatchRequest(n)).map(e=>{const t=qp(e,xw);if("error"in t)throw new Bm(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,n){let r={},o=await this.getFirstAvailableBlock();for(;!("until"in r)&&!(--t<=0||t<o);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(r.until=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}let i=await this.getSlot("finalized");for(;!("before"in r||++n>i);)try{const e=await this.getConfirmedBlockSignatures(n);e.signatures.length>0&&(r.before=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}return(await this.getConfirmedSignaturesForAddress2(e,r)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),o=qp(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),qy);if("error"in o)throw new Bm(o.error,"failed to get confirmed signatures for address");return o.result}async getSignaturesForAddress(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),o=qp(await this._rpcRequest("getSignaturesForAddress",r),Ky);if("error"in o)throw new Bm(o.error,"failed to get signatures for address");return o.result}async getAddressLookupTable(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let o=null;return null!==r&&(o=new jm({key:e,state:jm.deserialize(r.data)})),{context:n,value:o}}async getNonceAndContext(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let o=null;return null!==r&&(o=Um.fromAccountData(r.data)),{context:n,value:o}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+t)})}async requestAirdrop(e,t){const n=qp(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),Uw);if("error"in n)throw new Bm(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await xm(100);const e=Date.now()-this._blockhashInfo.lastFetch>=3e4;if(null!==this._blockhashInfo.latestBlockhash&&!e)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const e=Date.now(),t=this._blockhashInfo.latestBlockhash,n=t?t.blockhash:null;for(let e=0;e<50;e++){const e=await this.getLatestBlockhash("finalized");if(n!==e.blockhash)return this._blockhashInfo={latestBlockhash:e,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},e;await xm(200)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){const{commitment:t,config:n}=Ym(e),r=this._buildArgs([],t,"base64",n),o=qp(await this._rpcRequest("getStakeMinimumDelegation",r),ry(Qp()));if("error"in o)throw new Bm(o.error,"failed to get stake minimum delegation");return o.result}async simulateTransaction(e,t,n){if("message"in e){const r=e.serialize(),o=Hs.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const i=t||{};i.encoding="base64","commitment"in i||(i.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(i.innerInstructions=t.innerInstructions);const s=[o,i],a=qp(await this._rpcRequest("simulateTransaction",s),by);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof Sm){let t=e;r=new Sm,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=Sm.populate(e),r._message=r._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const o=t;if(r.nonceInfo&&o)r.sign(...o);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(r.lastValidBlockHeight=t.lastValidBlockHeight,r.recentBlockhash=t.blockhash,!o)break;if(r.sign(...o),!r.signature)throw new Error("!signature");const n=r.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(n)&&!this._blockhashInfo.transactionSignatures.includes(n)){this._blockhashInfo.simulatedSignatures.push(n);break}e=!0}}const i=r._compile(),s=i.serialize(),a=r._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:i.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}o&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const u=[a,c],l=qp(await this._rpcRequest("simulateTransaction",u),by);if("error"in l){let e;if("data"in l.error&&(e=l.error.data.logs,e&&Array.isArray(e))){const t="\n ";e.join(t)}throw new Im({action:"simulate",signature:"",transactionMessage:l.error.message,logs:e})}return l.result}async sendTransaction(e,t,n){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const n=e.serialize();return await this.sendRawTransaction(n,t)}if(void 0===t||!Array.isArray(t))throw new Error("Invalid arguments");const r=t;if(e.nonceInfo)e.sign(...r);else{let t=this._disableBlockhashCaching;for(;;){const n=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=n.lastValidBlockHeight,e.recentBlockhash=n.blockhash,e.sign(...r),!e.signature)throw new Error("!signature");const o=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(o)){this._blockhashInfo.transactionSignatures.push(o);break}t=!0}}const o=e.serialize();return await this.sendRawTransaction(o,n)}async sendRawTransaction(e,t){const n=Qg(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},r=t&&t.skipPreflight,o=!0===r?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(n.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(n.minContextSlot=t.minContextSlot),r&&(n.skipPreflight=r),o&&(n.preflightCommitment=o);const i=[e,n],s=qp(await this._rpcRequest("sendTransaction",i),Dw);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new Im({action:r?"send":"simulate",signature:"",transactionMessage:s.error.message,logs:e})}return s.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1}_wsOnClose(e){this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3!==e?(this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([e,t])=>{this._setSubscription(e,{...t,state:"pending"})})):this._updateSubscriptions()}_setSubscription(e,t){const n=this._subscriptionsByHash[e]?.state;if(this._subscriptionsByHash[e]=t,n!==t.state){const n=this._subscriptionStateChangeCallbacksByHash[e];n&&n.forEach(e=>{try{e(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){const n=this._subscriptionHashByClientSubscriptionId[e];if(null==n)return()=>{};const r=this._subscriptionStateChangeCallbacksByHash[n]||=new Set;return r.add(t),()=>{r.delete(t),0===r.size&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length)return void(this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(e){Error}},500)));if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected)return void this._rpcWebSocket.connect();const e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async e=>{const n=this._subscriptionsByHash[e];if(void 0!==n)switch(n.state){case"pending":case"unsubscribed":if(0===n.callbacks.size)return delete this._subscriptionsByHash[e],"unsubscribed"===n.state&&delete this._subscriptionCallbacksByServerSubscriptionId[n.serverSubscriptionId],void await this._updateSubscriptions();await(async()=>{const{args:r,method:o}=n;try{this._setSubscription(e,{...n,state:"subscribing"});const t=await this._rpcWebSocket.call(o,r);this._setSubscription(e,{...n,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=n.callbacks,await this._updateSubscriptions()}catch(r){if(!t())return;this._setSubscription(e,{...n,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===n.callbacks.size&&await(async()=>{const{serverSubscriptionId:r,unsubscribeMethod:o}=n;if(this._subscriptionsAutoDisposedByRpc.has(r))this._subscriptionsAutoDisposedByRpc.delete(r);else{this._setSubscription(e,{...n,state:"unsubscribing"}),this._setSubscription(e,{...n,state:"unsubscribing"});try{await this._rpcWebSocket.call(o,[r])}catch(r){if(Error,!t())return;return this._setSubscription(e,{...n,state:"subscribed"}),void await this._updateSubscriptions()}}this._setSubscription(e,{...n,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(e,t){const n=this._subscriptionCallbacksByServerSubscriptionId[e];void 0!==n&&n.forEach(e=>{try{e(...t)}catch(e){}})}_wsOnAccountNotification(e){const{result:t,subscription:n}=qp(e,Gy);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=qm([e.method,t]),o=this._subscriptionsByHash[r];return void 0===o?this._subscriptionsByHash[r]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:o.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[n]=r,this._subscriptionDisposeFunctionsByClientSubscriptionId[n]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[n],delete this._subscriptionHashByClientSubscriptionId[n];const t=this._subscriptionsByHash[r];fm(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${n}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),n}onAccountChange(e,t,n){const{commitment:r,config:o}=Ym(n),i=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",o);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},i)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=qp(e,zy);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:o,config:i}=Ym(n),s=this._buildArgs([e.toBase58()],o||this._commitment||"finalized","base64",i||(r?{filters:Jm(r)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},s)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,t,n){const r=this._buildArgs(["object"==typeof e?{mentions:[e.toString()]}:e],n||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},r)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:t,subscription:n}=qp(e,Fw);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=qp(e,Hy);this._handleServerNotification(n,[t])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:t,subscription:n}=qp(e,Xy);this._handleServerNotification(n,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){const n=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];n&&await n()}_buildArgs(e,t,n,r){const o=t||this._commitment;if(o||n||r){let t={};n&&(t.encoding=n),o&&(t.commitment=o),r&&(t=Object.assign(t,r)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,r){const o=t||this._commitment;if(o&&!["confirmed","finalized"].includes(o))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,n,r)}_wsOnSignatureNotification(e){const{result:t,subscription:n}=qp(e,Qy);"receivedSignature"!==t.value&&this._subscriptionsAutoDisposedByRpc.add(n),this._handleServerNotification(n,"receivedSignature"===t.value?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,n){const r=this._buildArgs([e],n||this._commitment||"finalized"),o=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(o)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},r);return o}onSignatureWithOptions(e,t,n){const{commitment:r,...o}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},i=this._buildArgs([e],r,void 0,o),s=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(s)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},i);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=qp(e,Zy);this._handleServerNotification(n,[t])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}class Mw{constructor(e){this._keypair=void 0,this._keypair=e??jg()}static generate(){return new Mw(jg())}static fromSecretKey(e,t){if(64!==e.byteLength)throw new Error("bad secret key size");const n=e.slice(32,64);if(!t||!t.skipValidation){const t=e.slice(0,32),r=Hg(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new Mw({publicKey:n,secretKey:e})}static fromSeed(e){const t=Hg(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new Mw({publicKey:t,secretKey:n})}get publicKey(){return new nm(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:cl.struct([cl.u32("instruction"),Dm("recentSlot"),cl.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:cl.struct([cl.u32("instruction")])},ExtendLookupTable:{index:2,layout:cl.struct([cl.u32("instruction"),Dm(),cl.seq(cm(),cl.offset(cl.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:cl.struct([cl.u32("instruction")])},CloseLookupTable:{index:4,layout:cl.struct([cl.u32("instruction")])}}),new nm("AddressLookupTab1e1111111111111111111111111");const $w=Object.freeze({RequestUnits:{index:0,layout:cl.struct([cl.u8("instruction"),cl.u32("units"),cl.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:cl.struct([cl.u8("instruction"),cl.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:cl.struct([cl.u8("instruction"),cl.u32("units")])},SetComputeUnitPrice:{index:3,layout:cl.struct([cl.u8("instruction"),Dm("microLamports")])}});class qw{constructor(){}static requestUnits(e){const t=Cm($w.RequestUnits,e);return new Em({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=Cm($w.RequestHeapFrame,e);return new Em({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=Cm($w.SetComputeUnitLimit,e);return new Em({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=Cm($w.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new Em({keys:[],programId:this.programId,data:t})}}var Kw;qw.programId=new nm("ComputeBudget111111111111111111111111111111"),cl.struct([cl.u8("numSignatures"),cl.u8("padding"),cl.u16("signatureOffset"),cl.u16("signatureInstructionIndex"),cl.u16("publicKeyOffset"),cl.u16("publicKeyInstructionIndex"),cl.u16("messageDataOffset"),cl.u16("messageDataSize"),cl.u16("messageInstructionIndex")]),new nm("Ed25519SigVerify111111111111111111111111111"),zg.utils.isValidPrivateKey,cl.struct([cl.u8("numSignatures"),cl.u16("signatureOffset"),cl.u8("signatureInstructionIndex"),cl.u16("ethAddressOffset"),cl.u8("ethAddressInstructionIndex"),cl.u16("messageDataOffset"),cl.u16("messageDataSize"),cl.u8("messageInstructionIndex"),cl.blob(20,"ethAddress"),cl.blob(64,"signature"),cl.u8("recoveryId")]),new nm("KeccakSecp256k11111111111111111111111111111"),new nm("StakeConfig11111111111111111111111111111111");class Gw{constructor(e,t,n){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=t,this.custodian=n}}Kw=Gw,Gw.default=new Kw(0,0,nm.default),Object.freeze({Initialize:{index:0,layout:cl.struct([cl.u32("instruction"),((e="authorized")=>cl.struct([cm("staker"),cm("withdrawer")],e))(),((e="lockup")=>cl.struct([cl.ns64("unixTimestamp"),cl.ns64("epoch"),cm("custodian")],e))()])},Authorize:{index:1,layout:cl.struct([cl.u32("instruction"),cm("newAuthorized"),cl.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:cl.struct([cl.u32("instruction")])},Split:{index:3,layout:cl.struct([cl.u32("instruction"),cl.ns64("lamports")])},Withdraw:{index:4,layout:cl.struct([cl.u32("instruction"),cl.ns64("lamports")])},Deactivate:{index:5,layout:cl.struct([cl.u32("instruction")])},Merge:{index:7,layout:cl.struct([cl.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:cl.struct([cl.u32("instruction"),cm("newAuthorized"),cl.u32("stakeAuthorizationType"),um("authoritySeed"),cm("authorityOwner")])}}),new nm("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:cl.struct([cl.u32("instruction"),((e="voteInit")=>cl.struct([cm("nodePubkey"),cm("authorizedVoter"),cm("authorizedWithdrawer"),cl.u8("commission")],e))()])},Authorize:{index:1,layout:cl.struct([cl.u32("instruction"),cm("newAuthorized"),cl.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:cl.struct([cl.u32("instruction"),cl.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:cl.struct([cl.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:cl.struct([cl.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>cl.struct([cl.u32("voteAuthorizationType"),cm("currentAuthorityDerivedKeyOwnerPubkey"),um("currentAuthorityDerivedKeySeed"),cm("newAuthorized")],e))()])}}),new nm("Vote111111111111111111111111111111111111111"),new nm("Va1idator1nfo111111111111111111111111111111"),tg({name:Jp(),website:Zp(Jp()),details:Zp(Jp()),iconUrl:Zp(Jp()),keybaseUsername:Zp(Jp())}),new nm("Vote111111111111111111111111111111111111111"),cl.struct([cm("nodePubkey"),cm("authorizedWithdrawer"),cl.u8("commission"),cl.nu64(),cl.seq(cl.struct([cl.nu64("slot"),cl.u32("confirmationCount")]),cl.offset(cl.u32(),-8),"votes"),cl.u8("rootSlotValid"),cl.nu64("rootSlot"),cl.nu64(),cl.seq(cl.struct([cl.nu64("epoch"),cm("authorizedVoter")]),cl.offset(cl.u32(),-8),"authorizedVoters"),cl.struct([cl.seq(cl.struct([cm("authorizedPubkey"),cl.nu64("epochOfLastAuthorizedSwitch"),cl.nu64("targetEpoch")]),32,"buf"),cl.nu64("idx"),cl.u8("isEmpty")],"priorVoters"),cl.nu64(),cl.seq(cl.struct([cl.nu64("epoch"),cl.nu64("credits"),cl.nu64("prevCredits")]),cl.offset(cl.u32(),-8),"epochCredits"),cl.struct([cl.nu64("slot"),cl.nu64("timestamp")],"lastTimestamp")]);const Ww=new nm("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new nm("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const zw=new nm("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new nm("So11111111111111111111111111111111111111112"),new nm("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const jw=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var Hw,Vw={};var Xw=(Hw||(Hw=1,Object.defineProperty(Vw,"__esModule",{value:!0}),Vw.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},Vw.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},Vw.toBufferLE=function(e,t){{const n=e.toString(16),r=Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex");return r.reverse(),r}},Vw.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}}),Vw);const Qw=(Zw=8,e=>{const t=cl.blob(Zw,e),{encode:n,decode:r}=jw(t),o=t;return o.decode=(e,t)=>{const n=r(e,t);return Xw.toBigIntLE(Buffer.from(n))},o.encode=(e,t,r)=>{const o=Xw.toBufferLE(e,Zw);return n(o,t,r)},o});var Zw;const Yw=e=>{const t=cl.u8(e),{encode:n,decode:r}=jw(t),o=t;return o.decode=(e,t)=>!!r(e,t),o.encode=(e,t,r)=>{const o=Number(e);return n(o,t,r)},o},Jw=e=>{const t=cl.blob(32,e),{encode:n,decode:r}=jw(t),o=t;return o.decode=(e,t)=>{const n=r(e,t);return new nm(n)},o.encode=(e,t,r)=>{const o=e.toBuffer();return n(o,t,r)},o};class eb extends Error{constructor(e){super(e)}}class tb extends eb{constructor(){super(...arguments),this.name="TokenAccountNotFoundError"}}class nb extends eb{constructor(){super(...arguments),this.name="TokenInvalidAccountError"}}class rb extends eb{constructor(){super(...arguments),this.name="TokenInvalidAccountOwnerError"}}class ob extends eb{constructor(){super(...arguments),this.name="TokenInvalidAccountSizeError"}}class ib extends eb{constructor(){super(...arguments),this.name="TokenOwnerOffCurveError"}}var sb;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Mint=1]="Mint",e[e.Account=2]="Account"}(sb||(sb={}));const ab=cl.struct([cl.u8("m"),cl.u8("n"),Yw("isInitialized"),Jw("signer1"),Jw("signer2"),Jw("signer3"),Jw("signer4"),Jw("signer5"),Jw("signer6"),Jw("signer7"),Jw("signer8"),Jw("signer9"),Jw("signer10"),Jw("signer11")]).span;var cb;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}(cb||(cb={}));const ub=cl.struct([Jw("mint"),Jw("owner"),Qw("amount"),cl.u32("delegateOption"),Jw("delegate"),cl.u8("state"),cl.u32("isNativeOption"),Qw("isNative"),Qw("delegatedAmount"),cl.u32("closeAuthorityOption"),Jw("closeAuthority")]),lb=ub.span;async function hb(e,t,n,r=Ww){return function(e,t,n=Ww){if(!t)throw new tb;if(!t.owner.equals(n))throw new rb;if(t.data.length<lb)throw new ob;const r=ub.decode(t.data.slice(0,lb));let o=Buffer.alloc(0);if(t.data.length>lb){if(t.data.length===ab)throw new ob;if(t.data[lb]!=sb.Account)throw new nb;o=t.data.slice(lb+1)}return{address:e,mint:r.mint,owner:r.owner,amount:r.amount,delegate:r.delegateOption?r.delegate:null,delegatedAmount:r.delegatedAmount,isInitialized:r.state!==cb.Uninitialized,isFrozen:r.state===cb.Frozen,isNative:!!r.isNativeOption,rentExemptReserve:r.isNativeOption?r.isNative:null,closeAuthority:r.closeAuthorityOption?r.closeAuthority:null,tlvData:o}}(t,await e.getAccountInfo(t,n),r)}function db(e,t,n=!1,r=Ww,o=zw){if(!n&&!nm.isOnCurve(t.toBuffer()))throw new ib;const[i]=nm.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],o);return i}cl.struct([cl.u32("mintAuthorityOption"),Jw("mintAuthority"),Qw("supply"),cl.u8("decimals"),Yw("isInitialized"),cl.u32("freezeAuthorityOption"),Jw("freezeAuthority")]).span;var fb=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");const t=new Uint8Array(256);for(let e=0;e<t.length;e++)t[e]=255;for(let n=0;n<e.length;n++){const r=e.charAt(n),o=r.charCodeAt(0);if(255!==t[o])throw new TypeError(r+" is ambiguous");t[o]=n}const n=e.length,r=e.charAt(0),o=Math.log(n)/Math.log(256),i=Math.log(256)/Math.log(n);function s(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;let i=0,s=0,a=0;for(;e[i]===r;)s++,i++;const c=(e.length-i)*o+1>>>0,u=new Uint8Array(c);for(;i<e.length;){const r=e.charCodeAt(i);if(r>255)return;let o=t[r];if(255===o)return;let s=0;for(let e=c-1;(0!==o||s<a)&&-1!==e;e--,s++)o+=n*u[e]>>>0,u[e]=o%256>>>0,o=o/256>>>0;if(0!==o)throw new Error("Non-zero carry");a=s,i++}let l=c-a;for(;l!==c&&0===u[l];)l++;const h=new Uint8Array(s+(c-l));let d=s;for(;l!==c;)h[d++]=u[l++];return h}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";let o=0,s=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,o++;const u=(c-a)*i+1>>>0,l=new Uint8Array(u);for(;a!==c;){let e=t[a],r=0;for(let t=u-1;(0!==e||r<s)&&-1!==t;t--,r++)e+=256*l[t]>>>0,l[t]=e%n>>>0,e=e/n>>>0;if(0!==e)throw new Error("Non-zero carry");s=r,a++}let h=u-s;for(;h!==u&&0===l[h];)h++;let d=r.repeat(o);for(;h<u;++h)d+=e.charAt(l[h]);return d},decodeUnsafe:s,decode:function(e){const t=s(e);if(t)return t;throw new Error("Non-base"+n+" character")}}}("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");class pb extends Ls{constructor(e){if(super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.tokenMetadataCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,!e.ethereumPrivateKey||!/^0x[a-fA-F0-9]{64}$/.test(e.ethereumPrivateKey))throw new Error("Invalid Ethereum private key format. Expected 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)");const t=new n("https://ethereum.publicnode.com");this.ethereumWallet=new r(e.ethereumPrivateKey,t);const o=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new Ow(o,"confirmed");try{i=fb.decode(e.solanaPrivateKeyBase58)}catch(e){throw new Error(`Invalid Solana private key format (expected base58-encoded string): ${e instanceof Error?e.message:"decode failed"}`)}if(64!==i.length)throw new Error(`Invalid Solana private key length: expected 64 bytes, got ${i.length} bytes`);this.solanaKeypair=Mw.fromSecretKey(i);const s=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new nm(s),[this.solanaBridgeTokenAuthority]=nm.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=nm.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=nm.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenConfigs=new Map;const a=e.tokenConfigs??$i;for(const e of a)this.tokenConfigs.set(e.symbol.toUpperCase(),e)}async estimateFee(e,t){const n=await this.getTokenMetadata(e),r=await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor});return{estimatedFeeInGala:r.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:r.estimatedTotalTxFeeInExternalToken,feeToken:r.bridgeToken,pricePerUnit:r.estimatedPricePerTxFeeUnit,estimatedGasUnits:r.estimatedTxFeeUnitsTotal,exchangeRate:r.galaExchangeRate?.exchangeRate??"0",timestamp:r.timestamp,raw:r}}async bridgeOut(e){const{amount:t,recipientAddress:n,tokenSymbol:r}=e;if(!r)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const o=r,i=parseFloat(t);if(isNaN(i)||i<=0)throw new Error(`Invalid bridge amount for ${o}: "${t}". Amount must be a positive number.`);try{new nm(n)}catch(e){throw new Error(`Invalid Solana recipient address: "${n}". ${e instanceof Error?e.message:"Expected valid base58 public key."}`)}const s=await this.getTokenMetadata(o),a=await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:s.descriptor}),c={destinationChainId:Ei.SOLANA,destinationChainTxFee:a,quantity:t,recipient:n,tokenInstance:{...s.descriptor,instance:"0"}},u=await this.buildBridgeOutPayload(c),l=await this.galaConnectClient.requestBridgeOut(u),h=this.extractBridgeRequestId(l);if(!h)throw new Error("Bridge request ID missing from RequestTokenBridgeOut response");const d=await this.galaConnectClient.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:h}),f=d.Hash??d.hash??"";if(!f)throw new Error("BridgeTokenOut response missing transaction hash");return{direction:"outbound",fromChain:"GalaChain",toChain:"Solana",transactionHash:f,tokenSymbol:o,amount:t,feePaid:a.estimatedTotalTxFeeInGala,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${f}`}}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:o}=e;if(!o)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const i=o,s=parseFloat(t);if(isNaN(s)||s<=0)throw new Error(`Invalid bridge amount for ${i}: "${t}". Amount must be a positive number.`);let a=this.solanaKeypair;if(n){let e;try{e=fb.decode(n)}catch(e){throw new Error(`Invalid sourcePrivateKey format (expected base58): ${e instanceof Error?e.message:"decode failed"}`)}if(64!==e.length)throw new Error(`Invalid sourcePrivateKey length: expected 64 bytes, got ${e.length} bytes`);a=Mw.fromSecretKey(e)}const c=this.tokenConfigs.get(i.toUpperCase());if(!c)throw new Error(`Token ${i} not supported for Solana bridge`);const u=await this.getTokenMetadata(i),l=ws(t,u.decimals),h=r??this.galaChainWalletAddress,d=await this.executeSolanaBridgeOut({keypair:a,tokenConfig:c,metadata:u,amountBaseUnits:l,recipient:h,amount:t});return{direction:"inbound",fromChain:"Solana",toChain:"GalaChain",transactionHash:d,tokenSymbol:i,amount:t,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${d}`}}async getStatus(e){const t=await this.galaConnectClient.getBridgeStatus(e),n=t.status;return{status:n,statusDescription:t.statusDescription,fromChain:t.fromChain,toChain:t.toChain,quantity:t.quantity,transactionHash:t.emitterTransactionHash,tokenInstance:t.tokenInstance,isComplete:5===n,isFailed:6===n||7===n}}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(e.toUpperCase())}isValidAddress(e){try{return new nm(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=this.tokenConfigs.get(e.toUpperCase());if(!n)throw new Error(`Token ${e} not supported for Solana. Supported: GALA (8 decimals), GSOL (9 decimals)`);if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58();let o;try{o=new nm(r)}catch{throw new Error(`Invalid Solana address: "${r}"`)}const i=db(new nm(n.mintAddress),o,!1,Ww,zw);try{const e=await hb(this.solanaConnection,i,"confirmed",Ww),t=n.decimals??8;return bs(e.amount,t)}catch(t){if(t instanceof Error&&t.message.includes("could not find")){return bs(0n,n.decimals??8)}throw new Error(`Failed to fetch ${e} balance for ${r}: ${t instanceof Error?t.message:"Unknown error"}`)}}async getSolanaNativeBalance(e){const t=e??this.solanaKeypair.publicKey.toBase58();let n;try{n=new nm(t)}catch{throw new Error(`Invalid Solana address: "${t}"`)}const r=await this.solanaConnection.getBalance(n,"confirmed");return bs(BigInt(r),9)}async requestDevnetAirdrop(e=1,t){if(e<=0||e>2)throw new Error(`Invalid airdrop amount: ${e} SOL. Devnet faucet limits: minimum >0 SOL, maximum 2 SOL per request.`);let n;if(t)try{n=new nm(t)}catch{throw new Error(`Invalid Solana address: "${t}"`)}else n=this.solanaKeypair.publicKey;const r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw new Error(`Solana devnet faucet only available on devnet. Current RPC: ${r}. Ensure SDK is configured with environment='STAGE' for devnet access.`);const o=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,o)}async getSolanaTransactionStatus(e){if(!e||"string"!=typeof e)throw new Error("Invalid signature: must be a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw new Error(`Invalid Solana signature format: "${e.slice(0,20)}...". Expected base58-encoded string (87-88 characters).`);const t=(await this.solanaConnection.getSignatureStatuses([e])).value[0];return t?t.err?{confirmed:!1,status:"failed",slot:t.slot,error:JSON.stringify(t.err)}:{confirmed:!0,status:t.confirmationStatus||"processed",slot:t.slot}:{confirmed:!1,status:"not_found"}}async getTokenMetadata(e){const t=this.tokenMetadataCache.get(e.toUpperCase());if(t)return t;const n=qi[e.toUpperCase()];if(n)return this.tokenMetadataCache.set(e.toUpperCase(),n),n;let r=e,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified);if(i||e.startsWith("G")||(r=`G${e}`,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified)),!i)throw new Error(`Unable to locate token metadata for ${e}`);const s={descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:i.decimals,...i.channel&&{channel:i.channel}};return this.tokenMetadataCache.set(e.toUpperCase(),s),s}async buildBridgeOutPayload(e){const t=e.uniqueKey??`galaconnect-operation-${O.randomUUID()}`,n="string"==typeof e.destinationChainId?Number(e.destinationChainId):e.destinationChainId,r=this.normalizeDestinationChainTxFee(e.destinationChainTxFee),o=Boolean(r.galaExchangeCrossRate),i=o?{...r,galaExchangeRate:void 0}:{...r,galaExchangeCrossRate:void 0},s={destinationChainId:n,destinationChainTxFee:this.sanitizeObject(i),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:t},a=ns(o),c=await this.ethereumWallet.signTypedData(Xi,a,s),u=`Ethereum Signed Message:\n${vi({domain:Xi,message:s,primaryType:"GalaTransaction",types:a}).length}`;return{...s,signature:c,prefix:u,types:a,domain:Xi}}async executeSolanaBridgeOut(e){const t=new nm(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),o=n?void 0:db(t,e.keypair.publicKey,!1,Ww,zw),i=Buffer.from(e.recipient,"utf8"),s=Buffer.alloc(8);s.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(i.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,s,a,i):this.buildTokenBridgeInstruction(e.keypair.publicKey,o,t,r,s,a,i),u=new Sm;u.add(qw.setComputeUnitPrice({microLamports:375e3}),qw.setComputeUnitLimit({units:2e5}),c),u.feePayer=e.keypair.publicKey;const l=await this.sendAndConfirmWithFallback(u,e.keypair),h={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:e.amount,tokenInstance:h,fromChain:"Solana",toChain:"GC",hash:l}),l}async sendAndConfirmWithFallback(e,t,n=3){let r=null;for(let o=1;o<=n;o++){try{const i=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=i.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const s=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:s,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed"),s}catch(e){const t=e instanceof Error?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const i=await this.solanaConnection.getSignatureStatuses([s]);if("confirmed"===i.value[0]?.confirmationStatus||"finalized"===i.value[0]?.confirmationStatus)return s;r=new Error(`Transaction ${s} not confirmed - block height exceeded (attempt ${o}/${n})`)}}catch(e){r=e instanceof Error?e:new Error(String(e));const t=r.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||o===n)throw r}const i=Math.min(1e3*Math.pow(2,o-1),5e3);await new Promise(e=>setTimeout(e,i))}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const o=Buffer.concat([Wi.BRIDGE_OUT_NATIVE,t,n,r]);return new Em({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!0},{pubkey:this.solanaNativeBridgePda,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:Fm.programId,isSigner:!1,isWritable:!1}],data:o})}buildTokenBridgeInstruction(e,t,n,r,o,i,s){const a=Buffer.concat([Wi.BRIDGE_OUT,o,i,s]);return new Em({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r.mintLookup,isSigner:!1,isWritable:!1},{pubkey:r.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:r.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:Fm.programId,isSigner:!1,isWritable:!1},{pubkey:Ww,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=nm.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),o=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!o)throw new Error(`Mint lookup account not found for ${r.toBase58()}`);if(!o.owner.equals(this.solanaBridgeProgramId))throw new Error("Mint lookup account owner mismatch for Solana bridge program");if(o.data.length<40)throw new Error("Mint lookup account data is unexpectedly short");const i={mintLookup:r,tokenBridge:new nm(o.data.slice(8,40)),bridgeTokenAccount:db(e,this.solanaBridgeTokenAuthority,!0,Ww,zw)};return this.solanaBridgeAccountCache.set(t,i),i}normalizeDestinationChainTxFee(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Number(e.galaDecimals):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Number(e.timestamp):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Number(e.galaExchangeRate.timestamp):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Number(n.timestamp):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Number(n.baseTokenCrossRate.timestamp):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Number(n.quoteTokenCrossRate.timestamp):n.quoteTokenCrossRate.timestamp})}return t}sanitizeObject(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=this.sanitizeObject(r):t[n]=r);return t}extractBridgeRequestId(e){if("string"==typeof e.Data)return e.Data;if(null!=e.data){if("string"==typeof e.data)return e.data;if("object"==typeof e.data){const t=e.data;if("string"==typeof t.Data)return t.Data}}}}const gb={PROD:{launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",galaChainBaseUrl:"https://gateway-mainnet.galachain.com",bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},STAGE:{launchpadBaseUrl:"https://lpad-backend-dev1.defi.gala.com",galaChainBaseUrl:"https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com",bundleBaseUrl:"https://bundle-backend-dev1.defi.gala.com",webSocketUrl:"https://bundle-backend-dev1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-dev1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function mb(e){return gb[e]}const yb={PROD:{ethereum:"https://ethereum.publicnode.com",solana:"https://api.mainnet-beta.solana.com"},STAGE:{ethereum:"https://ethereum-sepolia.publicnode.com",solana:"https://api.devnet.solana.com"}},wb={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class bb{static normalizeGalaChainAddress(e){let t;if(e.startsWith("eth|"))t=e.slice(4);else{if(e.startsWith("client|"))return e;t=e}(t.startsWith("0x")||t.startsWith("0X"))&&(t=t.slice(2));return`eth|${bb.checksumAddress(t)}`}static checksumAddress(e){const t=e.toLowerCase(),{keccak256:n,toUtf8Bytes:r}=require("ethers"),o=n(r(t)).slice(2);let i="";for(let e=0;e<t.length;e++){const n=t[e];parseInt(o[e],16)>=8?i+=n.toUpperCase():i+=n}return i}constructor(e){const t=bb.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"STAGE",r=gb[n],o=yb[n],i={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.galaChainBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??o.ethereum,solanaRpcUrl:e.solanaRpcUrl??o.solana,ethereumBridgeContract:e.ethereumBridgeContract??Oi(n),solanaBridgeProgram:e.solanaBridgeProgram??wb.solanaBridgeProgram,rateLimit:e.rateLimit??wb.rateLimit,pollInterval:e.pollInterval??wb.pollInterval,pollTimeout:e.pollTimeout??wb.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...i,solanaPrivateKey:e.solanaPrivateKey}:i,this.galaConnectClient=new Rs({baseUrl:this.config.galaConnectBaseUrl,galachainBaseUrl:this.config.galaChainApiBaseUrl,walletAddress:this.config.galaChainWalletAddress,requestsPerSecond:this.config.rateLimit}),e.bridgeableTokenService&&(this.bridgeableTokenService=e.bridgeableTokenService),this.strategies=new Map,this.initializeStrategies()}initializeStrategies(){const e=Li(this.config.environment),t={galaConnectClient:this.galaConnectClient,galaChainWalletAddress:this.config.galaChainWalletAddress,ethereumPrivateKey:this.config.ethereumPrivateKey,ethereumRpcUrl:this.config.ethereumRpcUrl,ethereumBridgeContract:this.config.ethereumBridgeContract,tokenConfigs:e};if(this.strategies.set("Ethereum",new Os(t)),this.config.solanaPrivateKey){const e={galaConnectClient:this.galaConnectClient,galaChainWalletAddress:this.config.galaChainWalletAddress,ethereumPrivateKey:this.config.ethereumPrivateKey,solanaPrivateKeyBase58:this.config.solanaPrivateKey,solanaRpcUrl:this.config.solanaRpcUrl,solanaBridgeProgram:this.config.solanaBridgeProgram,tokenConfigs:$i};this.strategies.set("Solana",new pb(e))}}async resolveTokenSymbol(e,t){if(!this.bridgeableTokenService)throw new Error("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.");const n=Bs(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",o=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!o){throw new Error([`Token "${n}" was not found in the list of tokens bridgeable to ${t}.`,"","Troubleshooting suggestions:",' 1. Verify the tokenId format is correct (e.g., "GALA|Unit|none|none")'," 2. Check if the token supports bridging to this network:",` - Use sdk.fetchAllBridgeableTokensByNetwork('${r}')`," - Or use sdk.isTokenBridgeableToNetwork({ tokenSymbol, network })"," 3. Common tokenId formats for bridge tokens:",' - GALA: "GALA|Unit|none|none"',' - GUSDC: "GUSDC|Unit|none|eth:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"'," 4. Use sdk.getSupportedBridgeTokens() to list all available tokens"].join("\n"))}return o.symbol}async estimateBridgeFee(e){const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return this.getStrategy(e.destinationChain).estimateFee(t,e.amount??"0")}async bridgeOut(e){const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw new Error(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`);if(!n.isTokenSupported(t))throw new Error(`Token ${t} is not supported for ${e.destinationChain} bridging`);return n.bridgeOut({...e,tokenSymbol:t})}async bridgeIn(e){const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw new Error(`Token ${t} is not supported for ${e.sourceChain} bridging`);return n.bridgeIn({...e,tokenSymbol:t})}async getBridgeStatus(e,t){if(t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let r;if(n)try{return await n.getStatus(e)}catch(e){r=e instanceof Error?e:new Error(String(e))}const o=this.strategies.get("Solana");if(o)try{return await o.getStatus(e)}catch(e){r=e instanceof Error?e:new Error(String(e))}const i=r?` (last error: ${r.message})`:"";throw new Error(`Unable to get status for transaction ${e}${i}`)}async waitForBridgeCompletion(e,t){const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},r=this.strategies.get("Ethereum");if(r)try{return await r.getStatus(e),r.waitForCompletion(e,n)}catch{}const o=this.strategies.get("Solana");if(o)return o.waitForCompletion(e,n);throw new Error(`Unable to wait for transaction ${e}: no suitable strategy found`)}getSupportedBridgeTokens(e){const t=[],n=Li(this.config.environment);if(!e||"Ethereum"===e)for(const e of n)t.push({symbol:e.symbol,decimals:e.decimals??18,verified:!0,supportedChains:["Ethereum"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{ethereum:e.contractAddress}});if(!e||"Solana"===e)for(const e of $i){const n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push("Solana"),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals??9,verified:!0,supportedChains:["Solana"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){if(t){const n=this.strategies.get(t);return n?.isTokenSupported(e)??!1}for(const t of this.strategies.values())if(t.isTokenSupported(e))return!0;return!1}isValidAddress(e,t){const n=this.strategies.get(t);return n?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){const n=this.strategies.get("Ethereum");if(!n)throw new Error("Ethereum bridge not configured");return n.getEthereumTokenBalance(e,t)}async getEthereumNativeBalance(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridge not configured");return t.getEthereumNativeBalance(e)}async getSolanaTokenBalance(e,t){const n=this.strategies.get("Solana");if(!n)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");return n.getSolanaTokenBalance(e,t)}async getSolanaNativeBalance(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");return t.getSolanaNativeBalance(e)}async fetchEthereumWalletTokenBalance(e,t){const n=this.strategies.get("Ethereum");if(!n)throw new Error("Ethereum bridging not configured. Provide ethereumPrivateKey in config.");const r=Li(this.config.environment),o=r.find(t=>t.symbol===e);if(!o){const t=r.map(e=>e.symbol).join(", ");throw new Error(`Unsupported Ethereum token: ${e}. Supported: ${t}`)}const i=n,s=t??i.getWalletAddress(),a=await i.getEthereumTokenBalance(e,s);return{symbol:o.symbol,quantity:a,decimals:o.decimals??18,contractAddress:o.contractAddress,isNative:!1}}async fetchEthereumWalletNativeBalance(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridging not configured. Provide ethereumPrivateKey in config.");const n=t,r=e??n.getWalletAddress();return{symbol:"ETH",quantity:await n.getEthereumNativeBalance(r),decimals:18,contractAddress:null,isNative:!0}}async fetchSolanaWalletTokenBalance(e,t){const n=this.strategies.get("Solana");if(!n)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");const r=$i.find(t=>t.symbol===e);if(!r){const t=$i.map(e=>e.symbol).join(", ");throw new Error(`Unsupported Solana token: ${e}. Supported: ${t}`)}const o=n,i=t??o.getWalletAddress(),s=await o.getSolanaTokenBalance(e,i);return{symbol:r.symbol,quantity:s,decimals:r.decimals??9,contractAddress:r.mintAddress,isNative:r.isNative??!1}}async fetchSolanaWalletNativeBalance(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");const n=t,r=e??n.getWalletAddress();return{symbol:"SOL",quantity:await n.getSolanaNativeBalance(r),decimals:9,contractAddress:null,isNative:!0}}async requestSolanaDevnetAirdrop(e,t){const n=this.strategies.get("Solana");if(!n)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");return n.requestDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridge strategy not configured. This method requires Solana wallet configuration. Initialize SDK with solanaPrivateKey to use Solana features.");const n=t;try{return await n.getSolanaTransactionStatus(e)}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw new Error(`Failed to query Solana transaction status: ${t}`)}}async getEthereumTransactionStatus(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridge strategy not configured. This method requires Ethereum wallet configuration. Initialize SDK with ethereumPrivateKey to use Ethereum features.");const n=t;try{return await n.getEthereumTransactionStatus(e)}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw new Error(`Failed to query Ethereum transaction status: ${t}`)}}async fetchEthereumWalletAllBalances(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridging not configured. Provide ethereumPrivateKey in config.");const n=t,r=e??n.getWalletAddress(),o=Li(this.config.environment),[i,...s]=await Promise.all([n.getEthereumNativeBalance(r),...o.map(async e=>{const t=await n.getEthereumTokenBalance(e.symbol,r);return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}})]);return{address:r,native:{symbol:"ETH",quantity:i,decimals:18,contractAddress:null,isNative:!0},tokens:s,timestamp:Date.now()}}async fetchSolanaWalletAllBalances(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");const n=t,r=e??n.getWalletAddress(),[o,...i]=await Promise.all([n.getSolanaNativeBalance(r),...$i.map(async e=>{const t=await n.getSolanaTokenBalance(e.symbol,r);return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}})]);return{address:r,native:{symbol:"SOL",quantity:o,decimals:9,contractAddress:null,isNative:!0},tokens:i,timestamp:Date.now()}}getStrategy(e){const t=this.strategies.get(e);if(!t)throw new Error(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."));return t}}class kb extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class vb extends kb{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Eb extends Error{constructor(e,t,n){super(`Transaction ${e} failed with status: ${t}${n?` - ${n}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function Sb(e,t){if(!e)throw new kb(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new kb(`Invalid WebSocket response received for transaction ${t}: expected object, got ${typeof e}`);if(!Object.prototype.hasOwnProperty.call(e,"status")&&!Object.prototype.hasOwnProperty.call(e,"Status"))throw new kb(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Ab(e,t,n,r){Sb(e,t);const o=e,i=o.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new kb(`Invalid trade data received for transaction ${t}`);const s={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:i.inputQuantity||r.amount,outputAmount:i.outputQuantity||r.expectedAmount||"0",totalFees:i.totalFees||"0",tokenName:r.tokenName,vaultAddress:i.vaultAddress||"",timestamp:Date.now()};return void 0!==o.blockHash&&(s.blockHash=o.blockHash),void 0!==o.gasUsed&&(s.gasUsed=o.gasUsed),void 0!==r.slippageToleranceFactor&&(s.slippageTolerance=r.slippageToleranceFactor),s}const Tb="4.0.22-beta.3";class Ib{constructor(e){this.logger=e||new H({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const n=[],r=new WeakSet,o=(e,i=0)=>{if(i>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(r.has(e))return;r.add(e);const s=this.extractLiquidityFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))o(t,i+1)}};return o(e,0),n}extractLiquidityFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const n=e.Data,r=n&&"object"==typeof n&&!Array.isArray(n)?n:e,o=this.extractPositionId(r),i=this.extractPoolHash(r),s=this.extractAmounts(r),a=this.extractUserAddress(r),c=this.extractPoolFee(r);if(!(o&&i&&s&&a&&null!==c))return null;const u=this.extractPoolAlias(r),l=this.extractUserBalanceDelta(r),h=this.extractTimestamp(r),d=l?.token0Balance?.collection,f=l?.token1Balance?.collection,p={transactionId:t,positionId:o,poolHash:i,poolFee:c,amounts:s,userAddress:a};return void 0!==d&&(p.token0=d),void 0!==f&&(p.token1=f),void 0!==h&&(p.timestamp=h),void 0!==u&&(p.poolAlias=u),void 0!==l&&(p.userBalanceDelta=l),p}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","poolId","pool"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}}extractAmounts(e){const t=e.amounts;if(Array.isArray(t)&&t.length>=2){const e=String(t[0]).trim(),n=String(t[1]).trim();if(e&&n)return[e,n]}const n=e.amount0||e.amount0Desired,r=e.amount1||e.amount1Desired;return void 0!==n&&void 0!==r?[String(n),String(r)]:null}extractUserAddress(e){const t=["userAddress","user","owner","from","sender","wallet","address"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPoolFee(e){const t=["poolFee","fee","feeTier","feeTierBps"];for(const n of t){const t=e[n];if("number"==typeof t)return this.normalizeFee(t);if("string"==typeof t){const e=Number(t);if(!Number.isNaN(e))return this.normalizeFee(e)}}return null}normalizeFee(e){return 1===e||1e4===e?1e4:.3===e||3e3===e?3e3:.05===e||500===e?500:Number.isInteger(e)?e:e<1?Math.round(1e4*e):e}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if("string"==typeof t){const e=new Date(t).getTime();if(!Number.isNaN(e))return e}}}extractUserBalanceDelta(e){const t=e.userBalanceDelta;if(!t||"object"!=typeof t)return;const n=t,r=this.extractBalanceObject(n.token0Balance),o=this.extractBalanceObject(n.token1Balance);if(!r&&!o)return;const i={};return void 0!==r&&(i.token0Balance=r),void 0!==o&&(i.token1Balance=o),i}extractBalanceObject(e){if(!e||"object"!=typeof e)return;const t=e,n=t.collection,r=t.category,o=t.type,i=t.additionalKey,s=t.quantity,a=t.owner;return"string"==typeof n&&"string"==typeof r&&"string"==typeof o&&"string"==typeof i&&"string"==typeof s&&"string"==typeof a?{collection:n,category:r,type:o,additionalKey:i,quantity:s,owner:a}:void 0}}class Bb{constructor(t){this.wallet=t.wallet;let n=null,r="STAGE";t.env?(r=t.env,n=mb(t.env)):t.baseUrl?.includes("prod")?(r="PROD",n=mb("PROD")):(r="STAGE",n=mb("STAGE")),this.environment=r,this.config={baseUrl:n.launchpadBaseUrl,galaChainBaseUrl:n.galaChainBaseUrl,bundleBaseUrl:n.bundleBaseUrl,webSocketUrl:n.webSocketUrl,dexApiBaseUrl:n.dexApiBaseUrl,dexBackendBaseUrl:n.dexBackendBaseUrl,launchpadFrontendUrl:n.launchpadFrontendUrl,timeout:3e4,debug:!1,...t},this.logger=new H({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===t.slippageToleranceFactor?Bb.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(t.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===t.maxAcceptableReverseBondingCurveFeeSlippageFactor?Bb.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(t.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=t.calculateAmountMode||Bb.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=t.pricingConcurrency||5,this.galaChainAddressOverride=t.galaChainAddress,this.auth=new j({wallet:t.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new X(this.auth,this.config),this.galaChainHttp=new X(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new X(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new X(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new X(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=e.create({baseURL:this.config.galaChainBaseUrl,timeout:this.config.timeout||3e4,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.cache=new Go(t.debug||!1),this.launchpadService=new dr(this.http),this.tokenResolverService=new xo(this.launchpadService.poolService),this.launchpadAPI=new ms(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new uo(this.galaChainHttp,t.wallet,this.tokenResolverService,t.debug||!1,this.galaChainPublicAxios),this.dexService=new lo(this.dexBackendHttp,this.cache,this.galaChainService,t.debug||!1),this.bundleService=new So(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,t.wallet,t.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Bo({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new No(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new jo(this.galaChainHttp,this.config.galaChainBaseUrl,t.debug||!1,t.dexQuoteNetworkTimeout||3e4),this.gswapService=new qo({privateKey:t.wallet?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,galaChainBaseUrl:this.config.galaChainBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new Wo(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,t.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw fe("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw fe('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new r(e),n={...this.config,wallet:t};return new Bb(n)}getAddress(){return this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw new Y("Wallet is required for this operation",void 0,"WALLET_REQUIRED");return this.wallet}setWallet(e){if(!e||"object"!=typeof e||!("address"in e))throw new Y("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}getWallet(){return this.wallet}hasWallet(){return void 0!==this.wallet}getConfig(){const{wallet:e,...t}=this.config;return{...t,environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:Ko.GAS_FEE}}getVersion(){return Tb}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw fe("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e||{});return await this.warmCacheFromPools(t.pools),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.pools),t}async fetchDexPools(e={}){return this.dexPoolService.fetchDexPools(e)}async fetchAllDexPools(e={}){return this.dexPoolService.fetchAllDexPools(e)}async fetchCompositePoolData(e){return this.dexQuoteService.fetchCompositePoolData(e)}async calculateDexPoolQuoteExactAmountLocal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountLocal(e)}async calculateDexPoolQuoteExactAmountExternal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountExternal(e)}async calculateDexPoolQuoteExactAmount(e,t="local"){return this.dexQuoteService.calculateDexPoolQuoteExactAmount(e,t)}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n,currentSupply:r,calculateAmountMode:o}=e;if(t&&!n){const e={tokenName:t};return r&&(e.currentSupply=r),o&&(e.calculateAmountMode=o),this.fetchLaunchpadTokenSpotPrice(e)}if(n&&!t)try{return await this.dexService.fetchTokenPrice({tokenId:n})}catch(e){const t=function(e){if(tr(e)&&e.response)return e.response.status}(e);if(400===t||404===t){this.logger.debug(`DEX spot price not available (HTTP ${t}) for tokenId, attempting launchpad fallback`);try{const t=(await this.fetchTokenDetails(n)).name.trim().toLowerCase();if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`);const i={tokenName:t};return r&&(i.currentSupply=r),o&&(i.calculateAmountMode=o),this.fetchLaunchpadTokenSpotPrice(i)}catch(t){throw this.logger.error(`Launchpad fallback failed: ${er(t)}`),e}}throw e}if(!t&&!n)throw le("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");throw new Y("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS")}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;return this.dexService.fetchLaunchpadTokenSpotPrice(t.tokenName,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchAllDexSeasons(){return this.dexService.fetchAllDexSeasons()}async fetchCurrentDexSeason(){return this.dexService.fetchCurrentDexSeason()}async fetchDexLeaderboardBySeasonId(e){return this.dexService.fetchDexLeaderboardBySeasonId(e)}async fetchCurrentDexLeaderboard(){return this.dexService.fetchCurrentDexLeaderboard()}async fetchDexAggregatedVolumeSummary(){return this.dexService.fetchDexAggregatedVolumeSummary()}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(!t)throw new Error(Z(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,r=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=r.currentSupply,n.reverseBondingCurveMaxFeeFactor=r.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=r.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=r.reverseBondingCurveNetFeeFactor,n.tokenName=e,n}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n=t(e)||this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=e?.solanaPrivateKey??process.env.SOLANA_PRIVATE_KEY;this._bridgeService=new bb({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:e?.ethereumPrivateKey??t.privateKey,...n&&{solanaPrivateKey:n},bridgeableTokenService:this.getBridgeableTokenService(),environment:this.environment,...this.config.ethereumRpcUrl&&{ethereumRpcUrl:this.config.ethereumRpcUrl},...this.config.solanaRpcUrl&&{solanaRpcUrl:this.config.solanaRpcUrl}})}return this._bridgeService}getBridgeableTokenService(){return this._bridgeableTokenService||(this._bridgeableTokenService=new si(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService||(this._wrappableTokenService=new li(this.dexApiHttp,this.config.debug??!1)),this._wrappableTokenService}getGalaConnectClient(){if(!this._galaConnectClient){const e=this.getAddress();if(!e)throw new Error("GalaConnectClient requires a wallet. Configure SDK with a wallet first.");if(!this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new Rs({baseUrl:this.config.dexApiBaseUrl,...this.config.galaChainBaseUrl&&{galachainBaseUrl:this.config.galaChainBaseUrl},walletAddress:e})}return this._galaConnectClient}getWrapService(){if(!this._wrapService){const e=this.getWallet();this._wrapService=new os({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService().fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService().fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService().fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService().fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService().requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService().getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService().getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService().fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService().fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService().isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService().isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService().isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService().fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService().fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService().getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService().getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService().isTokenWrappable(e)}async wrapToken(e){return this.getWrapService().wrapToken(e)}async unwrapToken(e){return this.getWrapService().unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService().estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService().estimateUnwrapFee(e,t)}async getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async estimateBridgeFee(e){return this.getBridgeService().estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService().bridgeOut(e)}async bridgeIn(e){return this.getBridgeService().bridgeIn(e)}async getBridgeStatus(e,t){return this.getBridgeService().getBridgeStatus(e,t)}async getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Fr}),r=t(e.tokenId),{collection:o,category:i,type:s,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:o,category:i,additionalKey:a,type:s,instance:"0"},e.withExpired??!1)}if(e.tokenName){const t=e.tokenName.toUpperCase();if("MUSIC"===t||"GMUSIC"===t){const r=`$${t}`;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:"Unit",additionalKey:"none",type:"none",instance:"0"},e.withExpired??!1)}}if(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...n&&{address:n}})).tokens[0];return t?{quantity:t.quantity,collection:t.collection||"Token",category:"Unit",tokenId:`${t.collection||"Token"}|Unit|${t.symbol}|none`,symbol:t.symbol,name:t.name}:null}throw le("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:o,calculateAmountMode:i,currentSupply:s}=e;let a=t;void 0===i&&void 0===s||(a={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==s&&{currentSupply:s}});const c=await this.calculateBuyAmountForGraduation(a),u={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(u.slippageToleranceFactor=n),void 0!==r&&(u.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==o&&(u.privateKey=o),await this.buy(u)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(!n)throw pe("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Ab(t,n,"buy",e))}async sell(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(!n)throw pe("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Ab(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.launchToken(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{Sb(n,t);const r=n?.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(r))throw new kb(`Invalid launch data received for transaction ${t}`);const o={transactionId:t,vaultAddress:r.vaultAddress||"",tokenStringKey:r.tokenStringKey||"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:r.creatorAddress||this.getAddress(),timestamp:Date.now(),...n.blockHash&&{blockHash:n.blockHash},...n.gasUsed&&{gasUsed:n.gasUsed}};return"string"==typeof e.tokenImage&&(o.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(o.preBuyQuantity=e.preBuyQuantity),o.vaultAddress&&this.tokenResolverService.set(e.tokenName,o.vaultAddress),o})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n=t(e)||this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(Ln,void 0,{"x-wallet-address":e})}async fetchReferrals(e){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return En}),r=n(e.address);if(!r)throw new Y(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=e?.page??1,r=e?.limit??10,o={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(On,o,{"x-wallet-address":t});if(!Array.isArray(i))throw new J("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=[];let n=1;let r=!0;for(;r&&n<=100;){const o=await this.fetchReferrals({...e,page:n,limit:100});t.push(...o.referrals),r=o.hasMore,n++}return{referrals:t,total:t.length}}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={...e,address:t(e.address)};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.updateProfile(r)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={...e,address:t(e.address)||this.getAddress()};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.uploadProfileImage(r)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n=t(e?.address)||this.getAddress(),r={page:e?.page||1,limit:e?.limit||10,address:n};return e?.tokenName&&(r.tokenName=e.tokenName),e?.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(n.tokenName=e.tokenName),e?.search&&(n.search=e.search),this.launchpadService.fetchTokenList(n)}async fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={...e,recipientAddress:t(e.recipientAddress)};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferGala(r)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={...e,to:t(e.to)};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferToken(r)}return this.validateWallet(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.validateWallet(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.validateWallet(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.validateWallet(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),e||(this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){if(("number"!=typeof this.config.timeout||this.config.timeout<=0||this.config.timeout>3e5)&&(this.logger.warn(`Invalid timeout value: ${this.config.timeout}. Using default 30000ms.`),this.config.timeout=3e4),!this.config.baseUrl)throw fe("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw fe("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw fe(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw fe(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw fe(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw fe(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw fe(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=parseFloat(String(e));return isNaN(t)||t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${e}, using default: ${Bb.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Bb.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=parseFloat(String(e));return isNaN(t)||t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${e}, using default: ${Bb.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Bb.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if("completed"!==n.status)throw new Eb(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof kb)throw t;throw new kb(`Failed to transform WebSocket response for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Eb||t instanceof kb)throw t;throw new kb(`WebSocket confirmation failed for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}}async warmCacheFromPools(e){if(!e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Jb});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}async getSwapQuoteExactInput(e,t,n){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:n})}async getSwapQuoteExactOutput(e,t,n){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:n})}async executeSwap(e,t,n,r,o,i=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:r,feeTier:o,slippageTolerance:i})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async fetchAvailableDexTokens(e={}){return this.gswapService.fetchAvailableDexTokens(e)}async fetchAllAvailableDexTokens(e={}){return this.gswapService.fetchAllAvailableDexTokens(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,n){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:n})}async getSwapUserLiquidityPositions(e,t,n,r){let o,i;"string"==typeof n?(o=n,i=r):"object"==typeof n?i=n:r&&(i=r);return await this.gswapService.getUserLiquidityPositions(e,t,o,i)}async getAllSwapUserLiquidityPositions(e,t){const n=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(n))return n;if(n&&"items"in n)return n.items}return n}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t,n,r,o,i,s){return this.gswapService.getLiquidityPositionById(e,t,n,r,o,i,s)}async fetchSwapPositionDirect(e){return this.gswapService.fetchSwapPositionDirect(e)}async getSwapEstimateRemoveLiquidity(e){return this.gswapService.estimateRemoveLiquidity(e)}async addSwapLiquidityByPrice(e){return this.gswapService.addLiquidityByPrice(e)}async addSwapLiquidityByTicks(e){this.validateWallet();const t={token0:e.token0,token1:e.token1,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired};return void 0!==e.amount0Min&&(t.amount0Min=e.amount0Min),void 0!==e.amount1Min&&(t.amount1Min=e.amount1Min),this.gswapService.addSwapLiquidityByTicks(t)}async removeSwapLiquidity(e){return this.validateWallet(),this.gswapService.removeLiquidity(e)}async collectSwapPositionFees(e){return this.validateWallet(),this.gswapService.collectPositionFees(e)}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onDexPoolCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const o=t?.minTVL,i=t?.tokens,s=new Map;let a=!0,c=null;let u=0;const l=async()=>{if(a){try{const t=await this.fetchDexPools({limit:20});u>0&&(this.logger.debug("Successfully recovered from polling errors"),u=0),t.pools.forEach(t=>{const n=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!s.has(n)){if((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(n),o){if((t.token0Tvl+t.token1Tvl)/2<o)return}if(i&&i.length>0){if(!(i.includes(t.token0)||i.includes(t.token1)))return}e(t)}})}catch(e){u++;const t=e instanceof Error?e.message:String(e);u>=5?this.logger.error(`Polling for new DEX pools failed ${u} consecutive times. Last error: ${t}. Continuing to retry...`):u>1?this.logger.warn(`Error polling for new DEX pools (attempt ${u}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(a){const e=Math.min(Math.max(u-1,0),2),t=r*Math.pow(2,e);c=setTimeout(l,t)}}};return l(),()=>{a=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const o=t?.creatorAddress,i=new Map;let s=!0,a=null;let c=0;const u=async()=>{if(s){try{const t=await this.fetchPools({type:"recent",limit:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.pools.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),o&&t.creatorAddress!==o||e(t))})}catch(e){c++;const t=e instanceof Error?e.message:String(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(s){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(u,t)}}};return u(),()=>{s=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}normalizeFee(e){if(null==e)return null;const t="number"==typeof e?e:Number.parseFloat(String(e).replace("%","").trim());return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:!Number.isInteger(t)||500!==t&&3e3!==t&&1e4!==t?null:t}extractField(e,...t){if("object"!=typeof e||null===e)return"";const n=e;for(const e of t)if(n[e])return String(n[e]);return""}looksLikePoolPair(e){if("string"!=typeof e)return null;const t=e.trim();if(!t.includes("/"))return null;const n=t.split("/");return 3!==n.length?null:n[0]&&n[1]&&n[2]?t:null}buildPoolPairFromObject(e){if("object"!=typeof e||null===e)return null;const t=e,n=this.extractField(t,"token0ClassKey","token0Class","token0","token0Symbol")||"",r=this.extractField(t,"token1ClassKey","token1Class","token1","token1Symbol")||"",o=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return n&&r&&null!==o?`${n}/${r}/${o}`:null}parsePoolPairString(e){const t=e.split("/");if(3!==t.length)return null;const n=t[0].split("|")[0],r=t[1].split("|")[0],o=t[2];return n&&r&&o?{token0:n,token1:r,fee:o,poolPair:e}:null}serializeBalanceToken(e){if(!e||"object"!=typeof e)return"";const t=e;return[(t.collection??t.token??"")||"",(t.category??"")||"none",(t.type??"")||"none",(t.additionalKey??"none")||"none"].join("|")}buildPoolPairFromBalances(e){if("object"!=typeof e||null===e)return null;const t=e,n=t.userBalanceDelta??t.balanceDelta??t.delta;if(!n||"object"!=typeof n||null===n)return null;const r=n,o=r.token0Balance??r.token0??r.baseBalance??r.primaryBalance,i=r.token1Balance??r.token1??r.quoteBalance??r.secondaryBalance,s=this.serializeBalanceToken(o),a=this.serializeBalanceToken(i),c=this.normalizeFee(t.poolFee??t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps);return s&&a&&null!==c?`${s}/${a}/${c}`:null}extractPoolDataFromPayload(e){if("string"==typeof e){const t=this.looksLikePoolPair(e);return t?this.parsePoolPairString(t):null}if("object"!=typeof e||null===e)return null;const t=e,n=this.looksLikePoolPair(t.poolPair);if(n)return this.parsePoolPairString(n);const r=this.buildPoolPairFromBalances(t);if(r)return this.parsePoolPairString(r);const o=this.buildPoolPairFromObject(t);if(o)return this.parsePoolPairString(o);if(t.pool&&"object"==typeof t.pool&&null!==t.pool){const e=this.extractPoolDataFromPayload(t.pool);if(e)return e}return null}matchesPoolFilter(e,t){if(t?.tokenFilter){if(!(e.token0===t.tokenFilter||e.token1===t.tokenFilter))return!1}if(t?.pairTokens){const[n,r]=t.pairTokens,o=e.token0===n||e.token1===n,i=e.token0===r||e.token1===r;if(!o||!i||n===r)return!1}if(void 0!==t?.feeTierFilter){if(this.normalizeFee(t.feeTierFilter)!==this.normalizeFee(e.fee))return!1}return!0}matchesCreatorFilter(e,t){return!t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(t?.creatorFilter?` (filter: ${t.creatorFilter})`:"")),!this.websocketService)throw new Error("WebSocket service not initialized");let n=!1,r=null;const o=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(n&&n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n={tokenName:r.tokenName||"",symbol:r.symbol||"",creatorAddress:r.creatorAddress||"",description:r.description||"",image:r.image||"",vaultAddress:r.vaultAddress||"",tokenStringKey:r.tokenStringKey||"",preBuyQuantity:r.initialBuyQuantity||"0",websiteUrl:r.websiteUrl||"",telegramUrl:r.telegramUrl||"",twitterUrl:r.twitterUrl||"",isFinalized:r.isFinalized||!1};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${e instanceof Error?e.message:String(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(o),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const s=()=>{if(i=this.websocketService.getSocket(),!i&&e<Bb.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>s(),Bb.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=Bb.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Bb.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Bb.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(o),n=!0,this.logger.debug("Token creation broadcast listener registered"))};s()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(o),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}walkPayloadForPools(e,t,n=new WeakSet){const r=[];if("string"==typeof e){const n=this.looksLikePoolPair(e);if(n){const e=this.parsePoolPairString(n);e&&!t.has(e.poolPair)&&(t.add(e.poolPair),r.push(e))}return r}if("object"!=typeof e||null===e)return r;if(n.has(e))return r;n.add(e);const o=this.extractPoolDataFromPayload(e);o&&!t.has(o.poolPair)&&(t.add(o.poolPair),r.push(o));for(const o of Object.values(e)){const e=this.walkPayloadForPools(o,t,n);r.push(...e)}return r}subscribeToDexPoolAdded(e,t){if(this.logger.debug("Subscribing to DEX pool creation broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw new Error("WebSocket service not initialized");let n=!1,r=null;const o=new Set,i=(n,...r)=>{try{for(const n of r){const r=this.walkPayloadForPools(n,o);for(const n of r)this.matchesPoolFilter(n,t)&&e(n)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${e instanceof Error?e.message:String(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(i),n=!0,this.logger.debug("DEX pool broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(s=this.websocketService.getSocket(),!s&&e<Bb.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),Bb.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=Bb.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Bb.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Bb.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX pool subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(i),n=!0,this.logger.debug("DEX pool broadcast listener registered"))};o()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX pool polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(i),n=!1,this.logger.debug("Stopped listening to DEX pool broadcasts"))}catch(e){this.logger.warn("Error removing DEX pool listener:",e)}}}subscribeToDexSwapExecuted(e,t){if(this.logger.debug("Subscribing to DEX swap execution broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw new Error("WebSocket service not initialized");let n=null,r=null,o=null,i=!1;const s=async e=>{const t=Vo.parsePoolKey(e);if(!t)throw new Error(`Invalid pool key format: ${e}`);return await this.dexQuoteService.fetchCompositePoolData({token0:t.token0,token1:t.token1,fee:t.feeTier})},a=()=>{const c=this.websocketService.getSocket();if(!c)return this.logger.debug("WebSocket not yet ready for swap monitoring, polling..."),void(n=setTimeout(()=>a(),100));i=!0,r=new ti(c,s,this.dexQuoteService,t||{},this.logger),o=r.subscribe(t||{},e),this.logger.debug("DEX swap monitoring subscription established")};return this.websocketService.getSocket()||(this.logger.debug("WebSocket not yet connected, initiating connection for swap monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed for swap monitoring: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)})),a(),()=>{try{n&&clearTimeout(n),o&&i&&o(),r&&r.shutdown().catch(e=>{this.logger.warn("Error shutting down swap monitor:",e)})}catch(e){this.logger.warn("Error cleaning up swap monitor:",e)}}}subscribeToDexLiquidityAdded(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityRemoved(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityChanged(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityEvents(e,t){if(this.logger.debug("Subscribing to DEX liquidity broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw new Error("WebSocket service not initialized");let n=!1,r=null;const o=new Set,i=new Ib(this.logger),s=(n,...r)=>{try{for(const n of r){const r=i.walkPayloadForLiquidityEvents(n,o);for(const n of r)if(this.matchesLiquidityFilter(n,t))try{const t=e(n);t instanceof Promise&&t.catch(e=>{this.logger.warn(`Error in liquidity event callback: ${e instanceof Error?e.message:String(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${e instanceof Error?e.message:String(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${e instanceof Error?e.message:String(e)}`)}};let a=this.websocketService.getSocket();if(a)a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection for liquidity monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(a=this.websocketService.getSocket(),!a&&e<Bb.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),Bb.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=Bb.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Bb.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Bb.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX liquidity subscription timeout:",e.message),void(t?.onError&&t.onError(e))}a&&(a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered"))};o()}return async()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX liquidity polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to DEX liquidity broadcasts"))}catch(e){this.logger.warn("Error removing DEX liquidity listener:",e)}}}matchesLiquidityFilter(e,t){if(!t)return!0;if(t.positionId&&e.positionId!==t.positionId)return!1;if(t.poolHash&&e.poolHash!==t.poolHash)return!1;if(void 0!==t.feeTierFilter){const n=this.normalizeFeeTier(t.feeTierFilter);if(e.poolFee!==n)return!1}if(t.userFilter&&e.userAddress!==t.userFilter)return!1;if(t.tokenFilter){const n=e.token0?.toLowerCase().includes(t.tokenFilter.toLowerCase()),r=e.token1?.toLowerCase().includes(t.tokenFilter.toLowerCase());if(!n&&!r)return!1}if(t.pairTokens){const[n,r]=t.pairTokens.map(e=>e.toLowerCase()),o=e.token0?.toLowerCase()||"",i=e.token1?.toLowerCase()||"",s=o.includes(n)&&i.includes(r),a=o.includes(r)&&i.includes(n);if(!s&&!a)return!1}if(t.minAmount){const n=parseFloat(t.minAmount),r=parseFloat(e.amounts[0])||0,o=parseFloat(e.amounts[1])||0;if(Math.abs(r)<n&&Math.abs(o)<n)return!1}return!0}normalizeFeeTier(e){if("number"==typeof e)return e>=100?e:Math.round(1e4*e);const t=e.replace("%","").trim(),n=parseFloat(t);return n>=100?n:Math.round(1e4*n)}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),this.websocketService&&this.websocketService.disconnect(),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new H({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:n}=require("./services/WebSocketService");n.cleanupAll(e),t.debug("Global cleanup completed")}}Bb.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Bb.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Bb.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=Ko.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Bb.DEFAULT_CALCULATE_AMOUNT_MODE=ps.LOCAL,Bb.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Bb.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,Bb.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,Bb.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class xb{static generateWallet(){try{const e=r.createRandom();if(!e.mnemonic?.phrase)throw new Error("Failed to generate wallet with mnemonic phrase");const t=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:t,mnemonic:e.mnemonic.phrase,wallet:new r(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,t="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),n=new r(t),o=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:o,mnemonic:"test test test test test test test test test test test junk",wallet:n}}throw e}}static fromPrivateKey(e){const t=new r(e),n=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:n,mnemonic:"",wallet:t}}static fromMnemonic(e,t=0){try{const n=c.fromPhrase(e),o=u.fromMnemonic(n,`m/44'/60'/0'/0/${t}`),i=new r(o.privateKey),s=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:s,mnemonic:e,wallet:i}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${t}-${e}`,o="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),i=new r(o),s=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:s,mnemonic:e,wallet:i}}throw n}}static toGalaAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid Ethereum address format: ${e}`);return`eth|${t}`}static toEthereumAddress(e){if(!e.startsWith("eth|"))throw new Error(`Invalid Gala address format: ${e}. Must start with 'eth|'`);const t=e.slice(4);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid address in Gala format: ${e}`);return`0x${t}`}static isValidEthereumAddress(e){try{const t=e.replace(/^0x/i,"");return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){try{if(!e.startsWith("eth|"))return!1;const t=e.slice(4);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static generateMultipleWallets(e=1){if(e<1||e>100)throw new Error("Count must be between 1 and 100");const t=[];if("undefined"!=typeof process&&"test"===process.env.NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++this.testCounter}`,r="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(r))}else for(let n=0;n<e;n++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${e.mnemonic||"Not available"}`];return t?n.splice(3,0,`🔑 Private Key: ${e.privateKey}`):n.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),n.push("═".repeat(50)),n.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),n.push("This is your backup to recover the wallet."),n.join("\n")}}function Cb(e){if(void 0===e)return xb.generateWallet();const t=e.trim();if(!t)throw new Error("Input cannot be empty string");if(function(e){const t=e.replace(/^0x/i,"");return/^[a-fA-F0-9]{64}$/.test(t)}(t))return xb.fromPrivateKey(t);if(function(e){const t=e.split(/\s+/).filter(e=>e.length>0);if(12!==t.length&&24!==t.length)return!1;return t.every(e=>/^[a-zA-Z]+$/.test(e))}(t))return xb.fromMnemonic(t);throw new Error(`Unable to detect input format. Expected:\n- Private key: 64 hexadecimal characters (with or without 0x prefix)\n- Mnemonic: 12 or 24 space-separated words\nReceived: "${t.slice(0,50)}${t.length>50?"...":""}"`)}function Pb(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw new Error("Invalid private key format. Expected 0x-prefixed 64 hex characters.");const t=new l(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}}function Nb(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw new Error("Invalid private key format. Expected 0x-prefixed 64 hex characters.");return a(h(e))}function _b(){const e=Mw.generate();return{privateKey:fb.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}}function Ub(e){e||(e={});const{wallet:t,env:n,config:o={},...i}=e,s={...i,...o},{wallet:a,env:c,config:u,...l}=s;let h;if(t)if("string"==typeof t){h=Cb(t).wallet}else{if(!(t instanceof r))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");h=t}else{h=Cb().wallet}const d={wallet:h,...n&&{env:n},debug:!1,timeout:3e4,...l};return new Bb(d)}function Db(){const e=M.join(process.cwd(),"..","..",".env");$.existsSync(e)&&q.config({path:e});const t=M.join(process.cwd(),".env");$.existsSync(t)&&q.config({path:t})}function Rb(e,t){const n=process.env[e];if(!n){throw new Error(t?`${e} not set in root or local .env (${t})`:`${e} not set in root or local .env`)}return n}function Fb(e,t){return process.env[e]??t}xb.testCounter=0;class Lb{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=e.galaChainAddress||process.env.WALLET_ADDRESS,o={wallet:n.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{},...r?{galaChainAddress:r}:{}},i=new Bb(o),s={sdk:i,wallet:n,config:o};if(!1!==e.autoValidate){const e=await this.validateSetup(i,n);return{...s,validation:e}}return s}static async readOnlySetup(e={}){const t=e.environment||this.detectEnvironment(),n=e.galaChainAddress||process.env.WALLET_ADDRESS,r={wallet:void 0,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{},...n?{galaChainAddress:n}:{}};return{sdk:new Bb(r),config:r}}static async validateSetup(e,t){const n=[],r=[],o={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(o.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);o.hasBalance=e>0,o.canTrade=e>=.1,o.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${e instanceof Error?e.message:String(e)}`)}try{const t=await e.fetchPools({type:"recent",page:1,limit:1});t.pools&&0!==t.pools.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${e instanceof Error?e.message:String(e)}`)}return{ready:0===n.length&&o.connectionHealthy,sdk:e,wallet:t||xb.generateWallet(),issues:n,warnings:r,capabilities:o}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(n,{debug:!1,timeout:3e4});break;case"development":Object.assign(n,{debug:!0,timeout:45e3});break;case"testing":Object.assign(n,{debug:!0,timeout:6e4})}switch(t){case"trading":n.timeout=1.5*(n.timeout||3e4);break;case"creation":n.timeout=2*(n.timeout||3e4);break;case"monitoring":n.timeout=.5*(n.timeout||3e4)}return n}static async multiWalletSetup(e,t="development"){const n={};for(const[r,o]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:o,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){const e=process.env.NODE_ENV?.toLowerCase();return"development"===e?"development":"test"===e||"testing"===e?"testing":"production"}static setupWallet(e){if(!e){const e=process.env.PRIVATE_KEY;return e?xb.fromPrivateKey(e):xb.generateWallet()}return"generate"===e?xb.generateWallet():xb.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}}function Ob(e){return e.filter(e=>new y(e.liquidity).isGreaterThan(0))}function Mb(e,t){const n=new y(t);return e.filter(e=>new y(e.liquidity).isGreaterThanOrEqualTo(n))}function $b(e,t="desc"){return[...e].sort((e,n)=>{const r=new y(e.liquidity),o=new y(n.liquidity);return"desc"===t?o.minus(r).toNumber():r.minus(o).toNumber()})}function qb(e,t,n){const r=t.toUpperCase(),o=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return t===r&&n===o||t===o&&n===r})}function Kb(e,t){const n=t.toUpperCase();return e.filter(e=>e.token0.toUpperCase()===n||e.token1.toUpperCase()===n)}function Gb(e,t){return e.filter(e=>e.feeTier===t)}function Wb(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t}function zb(e){const t=new Map;return e.forEach(e=>{t.has(e.feeTier)||t.set(e.feeTier,[]),t.get(e.feeTier).push(e)}),t}function jb(e,t,n,r){const o=t.toUpperCase(),i=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return(t===o&&n===i||t===i&&n===o)&&e.feeTier===r})}function Hb(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t}const Vb={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"};class Xb{static fastValidation(e,t,n,r=Xb.DEFAULT_CONFIG){const o=Date.now();let i=!0;try{const s=new y(e.sqrtPrice),a=new y(t.sqrtPrice);n.zeroForOne?a.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),i=!1):a.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),i=!1);const c=new y(e.liquidity),u=new y(t.liquidity);if(!c.isZero()){const e=u.minus(c).abs().div(c);e.gt(r.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:c.toString(),updatedLiquidity:u.toString(),changePct:e.times(100).toFixed(2)})}const l=new y(e.feeGrowthGlobal0),h=new y(t.feeGrowthGlobal0),d=new y(e.feeGrowthGlobal1),f=new y(t.feeGrowthGlobal1);n.zeroForOne?f.lt(d)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:d.toString(),updatedFeeGrowth1:f.toString()}),i=!1):h.lt(l)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:l.toString(),updatedFeeGrowth0:h.toString()}),i=!1);const p=new y(e.protocolFeesToken0),g=new y(t.protocolFeesToken0),m=new y(e.protocolFeesToken1),w=new y(t.protocolFeesToken1);g.lt(p)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:p.toString(),updatedProtocolFees0:g.toString()}),i=!1),w.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:m.toString(),updatedProtocolFees1:w.toString()}),i=!1);const b=Date.now()-o;return this.logger.debug("Fast validation completed",{passed:i,elapsedMs:b}),i}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=Xb.DEFAULT_CONFIG){const r=Date.now(),o=[];let i=0;try{if(t.actualSqrtPrice){const r=new y(e.sqrtPrice),s=new y(t.actualSqrtPrice),a=this.calculateDriftPercentage(r,s);i=a,a>100*n.maxDriftThreshold&&o.push(`Price drift detected: ${a.toFixed(4)}% (threshold: ${(100*n.maxDriftThreshold).toFixed(4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:r.toString(),actualSqrtPrice:s.toString(),driftPct:a.toFixed(4)})}const s=new y(e.sqrtPrice),a=new y(2).pow(96),c=s.dividedBy(a),u=N(c),l=e.tick??0,h=Math.abs(u-l);h>n.maxTickDrift&&o.push(`Tick/price mismatch: tick=${l}, calculated=${u}, drift=${h}`);const d=new y(e.feeGrowthGlobal0),f=new y(e.feeGrowthGlobal1),p=new y(e.liquidity);try{vr(d,f,p)}catch(e){o.push(e.message)}const g=0===o.length,m=!g||i>100*n.maxDriftThreshold,w=Date.now()-r;return this.logger.debug("Moderate validation completed",{isValid:g,shouldRefetch:m,driftPercentage:i,errorCount:o.length,elapsedMs:w}),this.buildValidationResult(g,i,m,o)}catch(e){this.logger.error("Moderate validation exception",e);const t=e instanceof Error?e.message:String(e);return this.buildValidationResult(!1,0,!0,[`Exception during validation: ${t}`])}}static async fullValidation(e,t,n){const r=Date.now(),o=[];let i=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await n(),a=new y(t.pool.sqrtPrice),c=new y(s.pool.sqrtPrice),u=this.calculateDriftPercentage(a,c);i=Math.max(i,u),u>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&o.push(`Price drift: ${u.toFixed(4)}% (cached: ${a.toString()}, fresh: ${c.toString()})`);const l=new y(t.pool.liquidity),h=new y(s.pool.liquidity),d=this.calculateDriftPercentage(l,h);i=Math.max(i,d),d>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&o.push(`Liquidity drift: ${d.toFixed(4)}% (cached: ${l.toString()}, fresh: ${h.toString()})`);const f=Object.keys(t.tickDataMap).length,p=Object.keys(s.tickDataMap).length;if(p>0){const e=Math.abs(p-f)/p;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&o.push(`Tick data incomplete: cached has ${f} ticks, fresh has ${p} ticks (${(100*e).toFixed(2)}% difference)`)}const g=0===o.length,m=!g,w=Date.now()-r;return this.logger.debug("Full validation completed",{poolKey:e,isValid:g,shouldRefetch:m,maxDriftPercentage:i,priceDrift:u,liquidityDrift:d,cachedTickCount:f,freshTickCount:p,errorCount:o.length,elapsedMs:w}),this.buildValidationResult(g,i,m,o)}catch(t){this.logger.error("Full validation exception",{poolKey:e,error:t});const n=t instanceof Error?t.message:String(t);return this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${n}`])}}static calculateDriftPercentage(e,t){if(t.isZero())return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return t.minus(e).abs().div(t).times(100).toNumber()}static buildValidationResult(e,t,n,r=[]){let o;if(n&&r.length>0){const e=r.join(" ").toLowerCase();o=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const i={isValid:e,driftPercentage:t,shouldRefetch:n,validationErrors:r};return void 0!==o&&(i.refetchReason=o),i}}Xb.logger=new H({debug:!1,context:"PoolStateValidator"}),Xb.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class Qb{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return K.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){this.logger=new H({debug:t?.debug??!1,context:"PoolStateManager"});const n={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??y.ROUND_DOWN,debug:t?.debug??!1,maxSwapsSinceRefetch:t?.maxSwapsSinceRefetch??50,maxCumulativeDrift:t?.maxCumulativeDrift??5,strictValidation:t?.strictValidation??!1,enablePerformanceWarnings:t?.enablePerformanceWarnings??!0,performanceWarningThreshold:t?.performanceWarningThreshold??100};this.config={...n,...t?.onRefetchNeeded?{onRefetchNeeded:t.onRefetchNeeded}:{}},this.validationConfig=Xb.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:Qb.calculatePoolStateHash(this.pool)};if(!Xb.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new Error("Initial pool state validation failed");this.logger.info("PoolStateManager initialized",{pool:{sqrtPrice:this.pool.sqrtPrice.toString(),liquidity:this.pool.liquidity.toString(),tick:this.pool.tick},config:this.config})}async applySwapDelta(e){const t=Date.now();if(this.metadata.processedTransactions.includes(e.transactionId))throw this.logger.warn("Duplicate swap transaction",{transactionId:e.transactionId}),new Error(`Duplicate transaction ID: ${e.transactionId}`);try{const t={pool:this.pool,tickDataMap:this.tickDataMap},n={maxIterations:this.config.maxIterations,enableBigNumberCache:this.config.enableBigNumberCache,roundingMode:this.config.roundingMode,debugLogging:this.config.debug},r=Yo.calculateSwapDelta(t,e,n);this.lastSwapMetrics={calculationTimeMs:r.metadata.calculationTimeMs,swapSteps:r.metadata.swapSteps,timestamp:Date.now()},this.config.enablePerformanceWarnings&&r.metadata.calculationTimeMs>this.config.performanceWarningThreshold&&this.logger.warn("Slow swap calculation",{calculationTimeMs:r.metadata.calculationTimeMs,swapSteps:r.metadata.swapSteps,threshold:this.config.performanceWarningThreshold});if(!Xb.fastValidation(t.pool,r.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new Error("Swap validation failed");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=new y(e.actualAmount0),n=new y(e.actualAmount1),o=r.amount0.minus(t).abs(),i=r.amount1.minus(n).abs(),s=t.isZero()?0:o.div(t.abs()).times(100).toNumber(),a=n.isZero()?0:i.div(n.abs()).times(100).toNumber(),c=Math.max(s,a);c>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:c.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=c)}if((this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift)&&(this.logger.info("Triggering full refetch due to drift accumulation",{swapsSinceRefetch:this.metadata.swapsSinceRefetch,cumulativeDrift:this.metadata.cumulativeDrift.toFixed(2)}),this.config.onRefetchNeeded)){const e=await this.config.onRefetchNeeded(this.pool,this.tickDataMap);this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.metadata.stateHash=Qb.calculatePoolStateHash(this.pool),this.logger.info("Full refetch completed",{sqrtPrice:this.pool.sqrtPrice.toString()})}return this.pool=r.updatedPool,Object.assign(this.tickDataMap,r.updatedTicks),this.metadata.swapsSinceRefetch++,this.metadata.stateHash=Qb.calculatePoolStateHash(this.pool),this.metadata.processedTransactions.push(e.transactionId),this.metadata.processedTransactions.length>1e3&&(this.metadata.processedTransactions=this.metadata.processedTransactions.slice(-1e3)),this.logger.debug("Swap delta applied",{transactionId:e.transactionId,amount0:r.amount0.toString(),amount1:r.amount1.toString(),sqrtPriceNew:this.pool.sqrtPrice.toString()}),r}catch(n){const r=n instanceof Error?n.message:String(n);if(this.logger.error("Failed to apply swap delta",{transactionId:e.transactionId,error:r}),this.config.strictValidation)throw n;return{updatedPool:this.pool,updatedTicks:{},amount0:new y(0),amount1:new y(0),feeAmount0:new y(0),feeAmount1:new y(0),ticksCrossed:[],metadata:{calculationTimeMs:Date.now()-t,swapSteps:0,priceHitLimit:!1}}}}forceFullRefetch(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.logger.info("Full refetch forced",{sqrtPrice:this.pool.sqrtPrice.toString()})}getPoolState(){return this.pool}getTickDataMap(){return{...this.tickDataMap}}getMetadata(){return{...this.metadata}}getLastSwapMetrics(){if(this.lastSwapMetrics)return{...this.lastSwapMetrics}}isRefetchRecommended(){return this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift}reset(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:Qb.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}function Zb(e,t){return new Qb(e,t)}class Yb extends Gn{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}async resolveTokenMetadata(e){const t=this.getCacheKey(e),n=this.cache[t];if(n&&!this.isCacheExpired(n.timestamp))return this.logger.debug(`Using cached metadata for token: ${t}`),n.data;const r=this.extractMetadata(e);return this.cache[t]={data:r,timestamp:Date.now()},r}async getTokenSymbol(e){return(await this.resolveTokenMetadata(e)).symbol}async getTokenDecimals(e){return(await this.resolveTokenMetadata(e)).decimals}clearCache(e){e?(delete this.cache[e],this.logger.debug(`Cleared cache for token: ${e}`)):(this.cache={},this.logger.debug("Cleared all token metadata cache"))}getCacheStats(){const e=Object.keys(this.cache);return{size:e.length,entries:e}}getCacheKey(e){if("string"==typeof e)return e.toLowerCase();return`${e.type||e.symbol||"unknown"}|${e.additionalKey||"none"}`.toLowerCase()}extractMetadata(e){let t,n,r="Token",o="Unit",i="none";if("string"==typeof e)if(e.includes("|")){const s=e.split("|");"Token"===s[0]&&s[2]?(r=s[0],o=s[1]||"Unit",t=s[2],i=s[3]||"none",n=t):(t=s[0],n=t,o=s[1]||"Unit",i=s[3]||"none")}else t=e,n=e;else t=e.type||"unknown",r=e.collection||"Token",o=e.category||"Unit",i=e.additionalKey||"none",n=e.symbol||("Token"===r?t:r)||"unknown";const s=this.getDecimalsForToken(n);return{symbol:n.toUpperCase(),decimals:s,collection:r,category:o,type:t.toUpperCase(),additionalKey:i,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return Date.now()-e>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}}"undefined"!=typeof process&&process.env&&(process.env.CORE_CHAINCODE_LOGGING_LEVEL=process.env.CORE_CHAINCODE_LOGGING_LEVEL||"ERROR");var Jb=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=parseFloat(e.reverseBondingCurveMinFeePortion);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=r}if(void 0!==e.reverseBondingCurveMaxFeePortion){const r=parseFloat(e.reverseBondingCurveMaxFeePortion);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{Lb as AgentConfig,Gi as BRIDGE_CONTRACT_ABI,qi as BRIDGE_TOKEN_METADATA,Ls as BaseBridgeStrategy,ys as BridgeRateLimiter,Fs as BridgeStatusCode,Yr as BurnError,Zr as BurnErrorType,ps as CALCULATION_MODES,Ei as CHAIN_IDS,zo as COMPOSITE_POOL_FETCH_CONCURRENCY,ts as CROSS_RATE_TYPED_DATA_TYPES,ee as ConfigurationError,Ni as DEFAULT_ETHEREUM_BRIDGE_CONTRACT,Ci as DEFAULT_ETHEREUM_RPC_URL,Mi as DEFAULT_ETHEREUM_TOKENS,Ii as DEFAULT_POLL_INTERVAL_MS,Bi as DEFAULT_POLL_TIMEOUT_MS,Ti as DEFAULT_RATE_LIMIT_RPS,Ui as DEFAULT_SOLANA_BRIDGE_PROGRAM,Pi as DEFAULT_SOLANA_RPC_URL,$i as DEFAULT_SOLANA_TOKENS,ce as DexPoolNotFoundError,ae as DexQuoteError,Ki as ERC20_ABI,_i as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,Ri as ETHEREUM_TOKENS_PROD,Fi as ETHEREUM_TOKENS_STAGE,Os as EthereumBridgeStrategy,cr as FileValidationError,Si as GALACHAIN_CHANNELS,Di as GALACONNECT_PRODUCTION_URL,Xi as GALA_BRIDGE_TYPED_DATA_DOMAIN,ho as GALA_DECIMALS,po as GALA_TOKEN_CLASS_KEY,ie as GSwapAssetError,oe as GSwapPoolError,ne as GSwapQuoteError,re as GSwapSwapError,Rs as GalaConnectClient,xs as GalaConnectHttpError,it as IMAGE_EXTENSIONS,fo as LAUNCHPAD_TOKEN_DECIMALS,es as LEGACY_TYPED_DATA_TYPES,Gr as LOCK_CONSTRAINTS,Bb as LaunchpadSDK,zr as LockError,Wr as LockErrorType,Qr as MAX_BURN_BATCH_SIZE,Mn as MAX_CONCURRENT_POOL_FETCHES,qr as MAX_LOCK_BATCH_SIZE,Kr as MAX_UNLOCK_BATCH_SIZE,J as NetworkError,$n as PAGINATION_DEFAULTS,qn as POOL_FETCH_CONFIG,fs as POOL_TYPES,Qb as PoolStateManager,Vb as QUERY_FIELD_NAMES,To as SDKTransactionStatus,Tb as SDK_VERSION,xi as SOLANA_COMPUTE,Wi as SOLANA_DISCRIMINATORS,pb as SolanaBridgeStrategy,ds as TRADING_TYPES,Yb as TokenMetadataService,te as TransactionError,Eb as TransactionFailedError,Y as ValidationError,kb as WebSocketError,vb as WebSocketTimeoutError,Ie as addressFormatSchema,nt as amountMethodSchema,tt as amountTypeSchema,at as browserFileSchema,ct as bufferFileSchema,Pt as buyTokensDataSchema,Lt as calculatePreMintDataSchema,et as checkPoolOptionsSchema,vs as compareAmounts,Ub as createLaunchpadSDK,Re as createLimitSchema,bt as createPaginatedResultSchema,Zb as createPoolStateManager,_b as createSolanaWallet,Ct as createTradeDataSchema,Cb as createWallet,Be as ethereumAddressSchema,Et as fetchGalaBalanceOptionsSchema,Ot as fetchPoolDetailsDataSchema,It as fetchTokenBalanceOptionsSchema,Me as fileSizeSchema,st as fileUploadSchema,$e as filenameSchema,Gb as filterByFeeTier,Ob as filterByLiquidity,Mb as filterByMinLiquidity,jb as filterByPoolKey,Kb as filterByToken,qb as filterByTokenPair,xe as flexibleAddressSchema,ut as flexibleFileSchema,mo as formatGalaForDTO,yo as formatLaunchpadTokenForDTO,ks as formatTokenAmount,Vi as formatTokenDescriptor,bs as fromBaseUnits,Te as fullNameSchema,Ft as getAmountOptionsSchema,Fb as getEnv,Rb as getEnvOrThrow,Nb as getEthereumAddressFromPrivateKey,Oi as getEthereumBridgeContractByEnvironment,ji as getEthereumTokenConfig,Li as getEthereumTokensByEnvironment,ns as getGalaBridgeTypedDataTypes,Pb as getPublicKeyFromPrivateKey,Hi as getSolanaTokenConfig,zi as getStaticTokenMetadata,_t as getTradeOptionsSchema,ot as graduateTokenOptionsSchema,rt as graphDataOptionsSchema,zb as groupByFeeTier,Hb as groupByPoolKey,Wb as groupByTokenPair,lt as imageExtensionSchema,ht as imageFilenameSchema,qe as imageMimeTypeSchema,Ye as imageUploadOptionsSchema,Vr as isBurnTokenEntry,Xr as isBurnTokensData,jr as isLockTokenData,Lr as isLockTokenEntry,Mr as isLockTokensData,Hr as isUnlockTokenData,Or as isUnlockTokenEntry,$r as isUnlockTokensData,Ai as isValidGalaChainChannel,Ke as isoDateStringSchema,Ze as launchTokenDataSchema,Db as loadEnvWithFallback,Ne as nonNegativeDecimalStringSchema,Ue as optionalUrlSchema,De as pageNumberSchema,wt as paginationResultMetaSchema,Je as poolFetchTypeSchema,gt as poolPaginationSchema,Pe as positiveDecimalStringSchema,We as privateKeySchema,vr as requireNonNegative,kr as requirePositive,Er as requirePositiveWithContext,Qe as reverseBondingCurveConfigSchema,Mt as reverseBondingCurveConfigurationSchema,Ae as searchQuerySchema,Nt as sellTokensDataSchema,$b as sortByLiquidity,Fe as standardLimitSchema,dt as standardPaginationSchema,Ge as timestampSchema,ws as toBaseUnits,Ve as tokenCategorySchema,Xe as tokenCollectionSchema,Ee as tokenDescriptionSchema,Tt as tokenHoldSchema,vt as tokenListOptionsSchema,ke as tokenNameSchema,ve as tokenSymbolSchema,He as tokenUrlsSchema,Rt as tradeCalculationMethodSchema,Dt as tradeCalculationTypeSchema,Oe as tradeLimitSchema,Ut as tradeListParamsSchema,pt as tradePaginationSchema,yt as tradePaginationWithFiltersSchema,xt as tradeTypeBackendSchema,Bt as tradeTypeSchema,ze as transactionIdSchema,je as uniqueKeySchema,St as updateProfileDataSchema,At as uploadProfileImageOptionsSchema,_e as urlSchema,Le as userLimitSchema,ft as userPaginationSchema,Se as userTokenNameSchema,kt as userTokenTypeSchema,mt as userTokensPaginationSchema,Wt as validateAddress,jt as validateAmountString,an as validateBuyTokensData,dn as validateCalculatePreMintData,Jt as validateCheckPoolOptions,sn as validateCreateTradeData,tn as validateFetchGalaBalanceOptions,fn as validateFetchPoolDetailsData,on as validateFetchTokenBalanceOptions,Ht as validateFullName,hn as validateGetAmountOptions,un as validateGetTradeOptions,Yt as validateImageUploadOptions,Qt as validateLaunchTokenData,Vt as validateSearchQuery,cn as validateSellTokensData,Gt as validateTokenDescription,en as validateTokenListOptions,qt as validateTokenName,Kt as validateTokenSymbol,Zt as validateTokenUrls,ln as validateTradeListParams,nn as validateUpdateProfileData,rn as validateUploadProfileImageOptions,Xt as validateUserTokenName,zt as validateVaultAddress,Ce as vaultAddressSchema};
|
|
1
|
+
import e from"axios";import{ethers as t,JsonRpcProvider as n,Wallet as r,isAddress as o,Contract as i,Signature as s,getAddress as a,Mnemonic as c,HDNodeWallet as u,SigningKey as l,computeAddress as h}from"ethers";import{SigningType as d,SigningClient as f,ChainCallDTO as p,calculatePersonalSignPrefix as g}from"@gala-chain/connect";import{z as m}from"zod";import y from"bignumber.js";import{tickToSqrtPrice as w,getLiquidityForAmounts as b,getAmountsForLiquidity as k,liquidity0 as v,liquidity1 as E,getAmount0Delta as S,getAmount1Delta as A,Pool as T,TickData as I,CompositePoolDto as x,GetCompositePoolDto as B,QuoteExactAmountDto as C,quoteExactAmount as P,sqrtPriceToTick as N,computeSwapStep as _}from"@gala-chain/dex";import{TokenClassKey as U,TokenBalance as D}from"@gala-chain/api";import R,{v4 as F}from"uuid";import{io as L}from"socket.io-client";import O from"node:crypto";import*as M from"path";import*as $ from"fs";import*as q from"dotenv";import K from"crypto";if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}var G,W;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(G||(G={}));class z extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class j{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new z(G.SIGNATURE_FAILED,"Message prefix cannot be empty")}hasWallet(){return void 0!==this.wallet}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new z(G.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new z(G.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.wallet.signMessage(t);return{message:t,signature:n,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof z)throw e;throw new z(G.SIGNATURE_FAILED,"Failed to generate signature for authentication",e instanceof Error?e:new Error(String(e)))}}getAddress(){return this.validateWallet(),this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.validateWallet(),this.wallet.address}getPrivateKey(){if(this.validateWallet(),!this.wallet.privateKey)throw new z(G.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new z(G.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`);return`eth|${t}`}async signMessage(e){this.validateWallet();try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){if(e instanceof z)throw e;const t=e instanceof Error?e.message:String(e);throw new z(G.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,o=await this.wallet.signMessage(r);return{"x-signature":o,"x-address":this.formatAddress(this.wallet.address),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof z)throw e;throw new z(G.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(e)))}}async signTypedData(e,t,n){this.validateWallet();try{return await this.wallet.signTypedData(e,t,n)}catch(e){if(e instanceof z)throw e;throw new z(G.SIGNATURE_FAILED,"Failed to sign typed data",e instanceof Error?e:new Error(String(e)))}}async generateCustomSignature(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new z(G.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){if(e instanceof z)throw e;throw new z(G.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new z(G.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new z(G.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new z(G.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(W||(W={}));class H{constructor(e){this.levelPriority={[W.DEBUG]:0,[W.INFO]:1,[W.WARN]:2,[W.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?W.DEBUG:W.INFO)}debug(e,t){this.log(W.DEBUG,e,t)}info(e,t){this.log(W.INFO,e,t)}warn(e,t){this.log(W.WARN,e,t)}error(e,t){this.log(W.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===W.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,o=this.getConsoleMethod(e);void 0!==n?n instanceof Error?o(`${r} ${t}`,n.message,n.stack):o(`${r} ${t}`,n):o(`${r} ${t}`)}getConsoleMethod(e){switch(e){case W.DEBUG:return console.debug;case W.INFO:return console.info;case W.WARN:return console.warn;case W.ERROR:return console.error;default:return console.log}}child(e){return new H({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[W.DEBUG]>=this.levelPriority[this.minLevel]}}function V(e){if(!e||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))null!=r&&("string"==typeof r?t[n]=r:"number"==typeof r||"boolean"==typeof r?t[n]=r.toString():Array.isArray(r)?t[n]=r.join(","):t[n]="object"==typeof r?JSON.stringify(r):String(r));return t}class X{constructor(t,n={}){this.auth=t,this.debug=n.debug??!1,this.logger=new H({debug:this.debug,context:"HttpClient"}),this.axios=e.create({baseURL:n.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:n.timeout||3e4,headers:{Accept:"application/json",...n.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:V(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};e.headers&&this.logger.debug("Custom headers provided:",e.headers),e.data instanceof FormData&&(t.headers&&t.headers["Content-Type"]&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload"));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const r=await this.axios.request(t);return this.logger.debug("Response:",{status:r.status,data:r.data}),r.data}catch(e){throw this.logger.error("Error:",e),e}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){try{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}}catch(e){throw this.logger.error("Custom signature generation failed:",e),new Error(`Failed to generate custom signature for message: ${e instanceof Error?e.message:"Unknown error"}`)}}async signWithGalaChain(e,t,n=d.SIGN_TYPED_DATA){const r=this.auth.getPrivateKey(),o=new f(r);return await o.sign(e,t,n)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{try{if(e.headers||(e.headers={}),this.auth.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request headers being sent:",e.headers),e}catch(e){throw this.logger.error("Failed to add signature:",e),e}},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{if(e.response){const t={message:e.response.data?.message||e.message,error:e.response.data?.error,statusCode:e.response.status,details:e.response.data?.details,timestamp:e.response.data?.timestamp,path:e.response.data?.path};e.launchpadError=t,this.logger.error("Backend error:",t)}else e.request?this.logger.error("Network error:",e.message):this.logger.error("Request setup error:",e.message);return Promise.reject(e)})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}const Q="Token name is required and must be a string",Z=e=>`Could not find vault address for token: ${e}`;class Y extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class J extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class ee extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class te extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class ne extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class re extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.transactionHash=n,this.code=r,this.name="GSwapSwapError"}}class oe extends Error{constructor(e,t,n,r,o){super(e),this.originalError=t,this.tokenA=n,this.tokenB=r,this.code=o,this.name="GSwapPoolError"}}class ie extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.walletAddress=n,this.code=r,this.name="GSwapAssetError"}}class se extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class ae extends Y{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class ce extends Y{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function ue(e,t){return new Y(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function le(e,t){const n=t||e.charAt(0).toUpperCase()+e.slice(1);return new Y(`${n} is required`,e,"REQUIRED_FIELD")}function he(e,t,n){const r=n||e.charAt(0).toUpperCase()+e.slice(1);return new Y(`${r} must be ${t}`,e,"INVALID_FORMAT")}function de(e,t,n){return new J(e,t,n)}function fe(e,t){return new ee(e,t)}function pe(e,t,n){return new te(e,t,n)}function ge(e,t,n){const{MIN_PAGE:r,MAX_PAGE:o,MIN_LIMIT:i,MAX_LIMIT:s}=n.PAGINATION;if("number"!=typeof e||e<r||e>o)throw new Y(`Page must be a number between ${r} and ${o}`,"page","INVALID_PAGE");if("number"!=typeof t||t<i||t>s)throw new Y(`Limit must be a number between ${i} and ${s}`,"limit","INVALID_LIMIT")}const me={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9]+$/};function ye(e){return"string"==typeof e&&e.trim().length>0}function we(e){return!(!e||"string"!=typeof e)&&(me.ETH_ADDRESS.test(e)||me.BACKEND_ADDRESS.test(e)||me.CLIENT_ADDRESS.test(e))}function be(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const ke=m.string().min(3,"Token name must be at least 3 characters").max(20,"Token name must be at most 20 characters").regex(/^[a-zA-Z0-9]{3,20}$/,"Token name can only contain letters and numbers"),ve=m.string().min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),Ee=m.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Se=m.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Ae=m.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Te=m.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),Ie=m.string().regex(me.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),xe=m.string().regex(me.ETH_ADDRESS,"Invalid Ethereum address format"),Be=m.string().refine(e=>me.BACKEND_ADDRESS.test(e)||me.ETH_ADDRESS.test(e),"Address must be either eth|[40-hex-chars] or 0x[40-hex-chars] format").transform(e=>e.startsWith("0x")?`eth|${e.slice(2)}`:e),Ce=m.string().refine(e=>me.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Pe=m.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),Ne=m.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),_e=m.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Ue=m.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),De=m.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function Re(e=100){return m.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const Fe=Re(100),Le=Re(20),Oe=Re(20),Me=m.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),$e=m.string().max(255,"Filename must be at most 255 characters"),qe=m.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Ke=m.string().datetime("Must be a valid ISO 8601 date string"),Ge=m.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),We=m.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),ze=m.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),je=m.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),He=m.object({websiteUrl:Ue,telegramUrl:Ue,twitterUrl:Ue}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),Ve=m.string().min(1,"Token category must not be empty").default("Unit"),Xe=m.string().min(1,"Token collection must not be empty").default("Token"),Qe=m.object({minFeePortion:m.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>parseFloat(e)>=.1,"Minimum fee must be >= 0.1").refine(e=>parseFloat(e)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:m.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>parseFloat(e)>=.1,"Maximum fee must be >= 0.1").refine(e=>parseFloat(e)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>parseFloat(e.maxFeePortion)>=parseFloat(e.minFeePortion),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Ze=m.object({tokenName:ke,tokenSymbol:ve,tokenDescription:Ee,tokenImage:m.union([m.instanceof(File),m.instanceof(Buffer),m.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Ne.default("0"),websiteUrl:Ue,telegramUrl:Ue,twitterUrl:Ue,tokenCategory:Ve,tokenCollection:Xe,reverseBondingCurveConfiguration:Qe.optional(),privateKey:We.optional()}),Ye=m.object({file:m.union([m.instanceof(File),m.instanceof(Buffer)]),tokenName:ke}),Je=m.enum(["recent","popular"]),et=m.object({tokenName:ke.optional(),symbol:ve.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),tt=m.enum(["NATIVE","MEME"]),nt=m.enum(["IN","OUT"]),rt=m.object({from:m.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:m.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:m.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:ke}),ot=m.object({tokenName:ke,slippageToleranceFactor:m.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:m.number().min(0).max(1).optional(),privateKey:We.optional()}),it=[".png",".jpg",".jpeg",".gif",".webp",".svg"],st=m.object({file:m.union([m.instanceof(File),m.instanceof(Buffer)]),name:$e,size:Me,type:qe}),at=m.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),ct=m.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),ut=m.union([at,ct]),lt=m.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),ht=$e.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return it.includes(t)},`Filename must end with one of: ${it.join(", ")}`),dt=m.object({page:De,limit:Fe}),ft=m.object({page:De,limit:Le}),pt=m.object({page:De,limit:Oe}),gt=dt.extend({type:m.enum(["recent","popular"]).optional(),tokenName:m.string().min(1).max(50).optional(),search:m.string().min(1).max(100).optional()}),mt=ft.extend({tokenName:m.string().min(1).max(50).optional(),search:m.string().min(1).max(100).optional()}),yt=pt.extend({tradeType:m.enum(["BUY","SELL"]).optional(),tokenName:m.string().min(1).max(50).optional(),userAddress:m.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:m.string().datetime().optional(),endDate:m.string().datetime().optional(),sortOrder:m.enum(["ASC","DESC"]).default("DESC")}),wt=m.object({page:m.number().int().min(1),limit:m.number().int().min(1),total:m.number().int().min(0),totalPages:m.number().int().min(0),hasNext:m.boolean(),hasPrevious:m.boolean()});function bt(e){return m.object({data:m.array(e),page:m.number().int().min(1),limit:m.number().int().min(1),total:m.number().int().min(0),totalPages:m.number().int().min(0),hasNext:m.boolean(),hasPrevious:m.boolean()})}const kt=m.enum(["all","DEFI","ASSET"]),vt=ft.extend({type:kt.optional(),address:Be.optional(),search:Ae.optional(),tokenName:Se.optional()}),Et=m.object({address:Be.optional(),refresh:m.boolean().optional()}),St=m.object({profileImage:m.string(),fullName:Te,address:Be,privateKey:We.optional()}),At=m.object({file:m.union([m.instanceof(File),m.instanceof(Buffer)]),address:Be.optional(),privateKey:We.optional()}),Tt=m.object({created:m.number(),createdBy:m.string(),expires:m.number(),instanceId:m.string(),lockAuthority:m.string(),name:m.string(),quantity:m.string(),vestingPeriodStart:m.number()}),It=m.object({address:Be,tokenId:m.union([m.string(),m.object({collection:m.string(),category:m.string(),type:m.string(),additionalKey:m.string()}),m.object({collection:m.string(),category:m.string(),type:m.string(),additionalKey:m.string(),instance:m.string()})]).optional(),tokenName:Se.optional(),withExpired:m.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),xt=m.enum(["buy","sell"]),Bt=m.enum(["BUY","SELL"]),Ct=m.object({tradeType:xt,tokenAmount:Pe,vaultAddress:Ce,userAddress:Be,slippageTolerance:Pe.optional(),deadline:m.number().int().positive().optional()}),Pt=m.object({tokenSymbol:ve,nativeTokenQuantity:Pe,expectedToken:Pe,maxAcceptableReverseBondingCurveFee:Ne.default("0").optional()}),Nt=m.object({tokenSymbol:ve,tokenQuantity:Pe,expectedNativeToken:Pe,maxAcceptableReverseBondingCurveFee:Ne.default("0").optional()}),_t=pt.extend({tokenName:Se.optional()}),Ut=m.object({page:m.number().int().min(1).max(1e3).default(1).optional(),limit:m.number().int().min(1).max(20).default(10).optional()}),Dt=m.enum(["NATIVE","MEME"]),Rt=m.enum(["IN","OUT"]),Ft=m.object({type:Dt,method:Rt,vaultAddress:Ce,amount:Pe}),Lt=m.object({nativeTokenQuantity:Pe}),Ot=m.object({vaultAddress:Ce}),Mt=m.object({minFeePortion:Pe,maxFeePortion:Pe});function $t(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.errors.map(e=>e.message)}}}const qt=$t(ke),Kt=$t(ve),Gt=$t(Ee),Wt=$t(Be),zt=$t(Ce),jt=$t(Pe),Ht=$t(Te),Vt=$t(Ae),Xt=$t(Se),Qt=$t(Ze),Zt=$t(He),Yt=$t(Ye),Jt=$t(et),en=$t(vt),tn=$t(Et),nn=$t(St),rn=$t(At),on=$t(It),sn=$t(Ct),an=$t(Pt),cn=$t(Nt),un=$t(_t),ln=$t(Ut),hn=$t(Ft),dn=$t(Lt),fn=$t(Ot);function pn(e,t){throw new Y(e.join("; "),t,"VALIDATION_ERROR")}function gn(e){const t=qt(e);!t.success&&t.errors&&pn(t.errors,"tokenName")}function mn(e){const t=gt.safeParse(e);t.success||pn(t.error.errors.map(e=>e.message),"pagination")}function yn(e){const t=Jt(e);!t.success&&t.errors&&pn(t.errors,"options")}function wn(e){const t=hn(e);!t.success&&t.errors&&pn(t.errors,"options")}function bn(e){const t=rt.safeParse(e);t.success||pn(t.error.errors.map(e=>e.message),"options")}function kn(e){const t=Be.safeParse(e);if(!t.success)throw new Y("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function vn(e,t,n=!0){if(!e||""===e.trim())throw new Y(`${t} cannot be empty or whitespace-only. Provide a valid numeric string or omit the parameter to auto-fetch.`,t,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Y(`${t} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,t,"INVALID_NUMERIC_STRING");const r=parseFloat(e);if(isNaN(r))throw new Y(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(r))throw new Y(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(r<0)throw new Y(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!n&&0===r)throw new Y(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var En=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=Be.safeParse(e);if(!t.success)throw new Y(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:kn,validateCheckPoolOptions:yn,validateGetAmountOptions:wn,validateGetGraphOptions:bn,validateNumericString:vn,validatePagination:mn,validateTokenName:gn});function Sn(e,t){const n=e,r=Number(n.page)||t.page,o=Number(n.limit)||t.limit,i=n.data,s=Number(n.total)||Number(i?.count)||0;return{page:r,limit:o,total:s,totalPages:Math.ceil(s/o)}}function An(e,t){return{hasNext:e<t,hasPrevious:e>1}}function Tn(e,t,n=!1){const r=!0===e.error||200!==e.status,o=n&&!e.data;if(r||o)throw new Error(e.message||t)}const In="/launchpad/upload-image",xn="/launchpad/fetch-pool",Bn="/launchpad/check-pool",Cn="/launchpad/get-graph-data",Pn="/holders",Nn="/launchpad/get-badge/",_n="/trade/",Un="/user/profile",Dn="/user/profile",Rn="/user/token-list",Fn="/user/token-hold",Ln="/v1/users/referrals/url",On="/v1/users/referrals",Mn="/v1/users/referrals/summary",$n="/v1/registered",qn=5,Kn={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100},Gn={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20};class Wn{constructor(e,t=!1){this.http=e,this.logger=new H({debug:t,context:this.constructor.name})}}class zn{constructor(e=!1){this.logger=new H({debug:e,context:this.constructor.name})}}function jn(e,t){return"string"==typeof e[t]}function Hn(e,t){return void 0===e[t]||"string"==typeof e[t]}function Vn(e,t){return void 0===e[t]||"number"==typeof e[t]}function Xn(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function Qn(e){if(!e||"object"!=typeof e)return!1;const t=e;return jn(t,"tokenName")&&Vn(t,"from")&&Vn(t,"to")&&Vn(t,"resolution")}class Zn extends Wn{constructor(e,t=!1){super(e,t)}async fetchSinglePage(e){const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const n=V(t),r=await this.http.get(xn,n);if(!r)throw de("No response from pool service",500);Tn(r,"Failed to fetch pools",!0);const o=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at||e.createdAt||""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at||n.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(r.data),i=r.data.count??r.data.total??0;return{pools:o,total:i,totalPages:e.limit>0?Math.ceil(i/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:n,pageSize:r,...o}=e,i=[];if(n&&n>=t){const e=[];for(let r=t;r<=n;r++)e.push(r);for(let t=0;t<e.length;t+=5){const n=e.slice(t,t+5).map(e=>this.fetchSinglePage({...o,page:e,limit:r}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e}));(await Promise.all(n)).forEach(e=>{i.push(...e.pools)})}return i}let s=t,a=!0;for(;a;){const e=[];for(let t=0;t<5&&a;t++)e.push(s+t);const t=e.map(e=>this.fetchSinglePage({...o,page:e,limit:r}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e})),n=await Promise.all(t);for(const e of n){if(0===e.pools.length){a=!1;break}i.push(...e.pools)}s+=e.length,s>Kn.SAFETY_MAX_PAGES&&(a=!1)}return i}async fetchPools(e={}){const t=e.page||Kn.DEFAULT_PAGE,n=e.limit??Kn.DEFAULT_LIMIT;let r;if(0!==n&&mn({page:t,limit:n}),e.tokenName&&gn(e.tokenName),"recent"===e.type?r="RECENT":"popular"===e.type&&(r="POPULAR"),n>0&&n<=20){const o=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},page:t,limit:n});return{pools:o.pools,page:t,limit:n,total:o.total,totalPages:o.totalPages,hasNext:t<o.totalPages,hasPrevious:t>1}}if(0===n){const t=Kn.BACKEND_MAX_PAGE_SIZE,n=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},page:1,limit:t}),o=[...n.pools];if(n.pools.length<t)return{pools:o,page:1,limit:o.length,total:o.length,totalPages:1,hasNext:!1,hasPrevious:!1};if(n.pools.length>0){const i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},startPage:2,totalPages:n.totalPages>1?n.totalPages:null,pageSize:t});o.push(...i)}return{pools:o,page:1,limit:o.length,total:n.total||o.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const o=Kn.BACKEND_MAX_PAGE_SIZE,i=Math.ceil(n/o),s=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},page:t,limit:o}),a=[...s.pools],c=Math.min(i,s.totalPages-t+1);if(c>1){const n=t+c-1,i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...r&&{type:r},startPage:t+1,totalPages:n,pageSize:o});a.push(...i)}const u=a.slice(0,n);return{pools:u,page:t,limit:n,total:s.total,totalPages:s.totalPages,hasNext:t<s.totalPages&&u.length<s.total,hasPrevious:t>1}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){yn(e),e.tokenName&&gn(e.tokenName);const t=V(e),n=await this.http.get(Bn,t);if(!n)throw de("No response from pool service",500);Tn(n,"Failed to check pool");const r=n.data;return e.symbol?r?.isSymbolExist??!1:e.tokenName?r?.isNameExist??!1:r?.exists??!1}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!Qn(e))throw new Y("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:o}=e;if(gn(t),!n||!r||!o)throw new Y("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:o};bn(i);const s=V(i),a=await this.http.get(Cn,s);if(!a)throw de("No response from pool service",500);return Tn(a,"Failed to fetch graph data",!0),{dataPoints:a.data}}async fetchTokenDistribution(e){if(!e)throw le("tokenName","Token name");gn(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw ue(e);const n=encodeURIComponent(t);let r;try{r=await this.http.get(`${Pn}/${n}`)}catch(t){if(t&&"object"==typeof t&&"response"in t){const n=t;if(500===n.response?.status)throw de(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500)}throw t}if(!r)throw de("No response from pool service",500);Tn(r,"Failed to fetch token distribution",!0);const o=r.data;if(!Array.isArray(o))throw de("Invalid API response: expected array of holders",r.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw de("Invalid holder data: missing or invalid owner field",r.status);if(!e.quantity||"string"!=typeof e.quantity)throw de("Invalid holder data: missing or invalid quantity field",r.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw de(`Invalid holder quantity: "${e.quantity}"`,r.status)}const i=o.reduce((e,t)=>e.plus(t.quantity),new y(0));return{holders:o.map(e=>{const t=new y(e.quantity),n=i.isZero()?0:t.dividedBy(i).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:i.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw le("tokenName","Token name");gn(e);const t=await this.http.get(Nn,{tokenName:e});if(!t)throw de("No response from pool service",500);return Tn(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const o=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return o?.isActive||!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(t.pools&&Array.isArray(t.pools)&&t.pools.length>0)return t.pools[0].vaultAddress||null;if(t.pools&&"object"==typeof t.pools){const e=t.pools.tokens;return e?.vaultAddress||null}return null}catch{return null}}}function Yn(e,t={}){const{stringifyFields:n=[],optionalFields:r=[],fieldMappings:o={}}=t,i={};for(const[t,s]of Object.entries(e)){const e=t;if(r.includes(e)&&void 0===s)continue;if(r.includes(e)&&"string"==typeof s&&0===s.trim().length)continue;const a=o[e],c=a?String(a):t;n.includes(e)?i[c]=String(s):i[c]=s}return V(i)}const Jn={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class er extends Wn{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return jn(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Hn(t,"userAddress")&&Vn(t,"page")&&Vn(t,"limit")}(e))throw new Y("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, page?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:n,userAddress:r,page:o=Kn.DEFAULT_PAGE,limit:i=Kn.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!ye(t))throw new Y("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");ge(o,i,Jn);const u=function(e,t,n){return Yn({tokenName:e,page:t,limit:n},{stringifyFields:["page","limit"]})}(t,o,i),l=await this.http.get(_n,u);if(!l)throw new Y("No response from trade service","response","NO_RESPONSE");const h=(d=l.data)?Array.isArray(d)?d:d.trades:[];var d;const f=Sn(l,{page:o,limit:i}),p=An(f.page,f.totalPages);return{trades:h,...f,...p}}}function tr(e){return e instanceof Error}function nr(e){return tr(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function rr(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function or(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw he("file","a File object (browser) or Buffer (Node.js)");{const o=new Blob([e],{type:"image/png"});r.append(t,o,n)}}return r}const ir={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20},USER_ADDRESS:{PATTERN:/^eth\|[0-9a-fA-F]{40}$/},TOKEN_NAME:{MIN_LENGTH:1,MAX_LENGTH:50},SEARCH:{MIN_LENGTH:1,MAX_LENGTH:100},PROFILE:{FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}}};function sr(e){return!(!e||"string"!=typeof e)&&ir.USER_ADDRESS.PATTERN.test(e)}const ar="Update profile",cr="Upload profile image";class ur extends Wn{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!sr(t))throw new Y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const n={userAddress:t},r=await this.http.get(Un,n);if(!r)throw new Y("No response from user service","response","NO_RESPONSE");return r}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!t||""===t.trim())try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage||""}catch{t=""}const n={profileImage:t,fullName:e.fullName,userAddress:e.address},r=await this.http.signCustomMessage(ar);if(!r)throw new Y("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const o={address:r.address,message:ar,publickey:r.ethereumAddress,sign:r.signature},i=await this.http.put(Dn,n,o);if(!i)throw new Y("No response from user service","response","NO_RESPONSE");Tn(i,"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new Y("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=or(e.file,"image",n),o=await this.http.signCustomMessage(cr);if(!o)throw new Y("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const i={address:o.address,message:cr,publickey:o.ethereumAddress,sign:o.signature},s=await this.http.request({method:"POST",url:`${In}?tokenName=${encodeURIComponent(t)}`,data:r,headers:i});if(!s)throw new Y("No response from user service","response","NO_RESPONSE");return Tn(s,"Image upload failed"),"string"==typeof s.data?s.data:""}catch(e){if(e instanceof Y)throw e;throw new Y(`Profile image upload failed: ${nr(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(Rn,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(Fn,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=Kn.DEFAULT_PAGE,limit:n=Kn.DEFAULT_LIMIT,search:r,tokenName:o}=e,i=this.http.getAddress();if(!i)throw new Y("Wallet address not available - wallet not configured","address","NO_WALLET");const s={type:"DEFI",address:i,page:t,limit:n};return void 0!==r&&(s.search=r),void 0!==o&&(s.tokenName=o),this.fetchTokenList(s)}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},o=Yn(n.includeType?{...r,type:"all"!==t.type&&t.type?t.type:"DEFI"}:r,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),i=await this.http.get(e,o);if(!i)throw new Y("No response from user service","response","NO_RESPONSE");Tn(i,n.errorMessage,!0);const s=(a=i.data)?Array.isArray(a)?a:a.token:[];var a;const c=Sn(i,{page:t.page||Kn.DEFAULT_PAGE,limit:t.limit||Kn.DEFAULT_LIMIT}),u=An(c.page,c.totalPages);return{tokens:s,...c,...u}}validateGetTokenListOptions(e){if(ge(e.page,e.limit,ir),void 0!==e.address&&!sr(e.address))throw new Y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(void 0!==e.search&&e.search.trim().length>0&&!((t=e.search)&&"string"==typeof t&&t.length>=ir.SEARCH.MIN_LENGTH&&t.length<=ir.SEARCH.MAX_LENGTH))throw new Y(`Search query must be between ${ir.SEARCH.MIN_LENGTH} and ${ir.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,n;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((n=e.tokenName)&&"string"==typeof n&&n.length>=ir.TOKEN_NAME.MIN_LENGTH&&n.length<=ir.TOKEN_NAME.MAX_LENGTH))throw new Y(`Token name must be between ${ir.TOKEN_NAME.MIN_LENGTH} and ${ir.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!sr(e.address))throw new Y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=ir.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=ir.PROFILE.FULL_NAME.MAX_LENGTH&&ir.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new Y(`Full name must be between ${ir.PROFILE.FULL_NAME.MIN_LENGTH} and ${ir.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!sr(e.address))throw new Y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class lr extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function hr(e,t,n){if(!e)throw new lr("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=at.safeParse(e);if(!t.success){const n=t.error.errors.map(e=>e.message).join("; ");throw new lr(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new lr("Filename is required when uploading Buffer objects",t,n);const r=ct.safeParse(e);if(!r.success){const e=r.error.errors.map(e=>e.message).join("; ");throw new lr(e,t,n)}if(t.length>255)throw new lr(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,n);const o=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!o.includes(n))throw new lr(`Invalid file type "${n}" is not allowed. Allowed types: ${o.join(", ")}`,t,n);const i=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),s=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!s.includes(i))throw new lr(`File extension "${i}" is not allowed. Allowed extensions: ${s.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(a!==n&&"application/octet-stream"!==a)throw new lr(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new lr("File must be a File object (browser) or Buffer (Node.js)",t,n)}const dr="Upload token image";class fr extends Wn{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;gn(t);const r=`${t}.png`;hr(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=or(n.file,"image",e),o=await this.http.signCustomMessage(dr);if(!o)throw fe("Failed to generate signature - wallet not configured","signature");const i={address:o.address,message:dr,publickey:o.ethereumAddress,sign:o.signature},s=await this.http.request({method:"POST",url:`${In}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:i});if(!s)throw fe("No response from image upload service","response");return Tn(s,"Image upload failed"),"string"==typeof s.data?s.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw fe("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class pr{constructor(e,t=!1){this.http=e,this.poolService=new Zn(e,t),this.tradeService=new er(e,t),this.userService=new ur(e,t),this.imageService=new fr(e,t)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async fetchProfile(e){return this.userService.fetchProfile(e)}async updateProfile(e){return this.userService.updateProfile(e)}async uploadProfileImage(e){return this.userService.uploadProfileImage(e)}async fetchTokenList(e){return this.userService.fetchTokenList(e)}async fetchTokensHeld(e){return this.userService.fetchTokensHeld(e)}async fetchTokensCreated(e={}){return this.userService.fetchTokensCreated(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return gn(e)}}const gr={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var mr;!function(e){e.INVALID_RECIPIENT="INVALID_RECIPIENT",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.DUPLICATE_TRANSFER="DUPLICATE_TRANSFER",e.TRANSFER_LIMIT_EXCEEDED="TRANSFER_LIMIT_EXCEEDED",e.WALLET_REQUIRED="WALLET_REQUIRED"}(mr||(mr={}));class yr extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function wr(e,t="0"){return new y(null==e||""===e?t:e)}function br(e){return w(e)}function kr(e){const t=wr(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function vr(e,t=!1){const n=wr(e),r=new y(1).dividedBy(n);return t?r.toFixed():r}function Er(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThanOrEqualTo(0))throw new Error(`Value at index ${t} must be positive, got: ${e.toString()}`)})}function Sr(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThan(0))throw new Error(`Value at index ${t} must be non-negative, got: ${e.toString()}`)})}function Ar(e,t,n){if(e.isNaN())throw new Error(`${t} must be a valid number, got: NaN`);if(!e.isFinite()){const r=n?`${t} must be finite ${n}, got: ${e.toString()}`:`${t} must be finite, got: ${e.toString()}`;throw new Error(r)}if(e.isLessThanOrEqualTo(0)){const r=n?`${t} must be positive ${n}, got: ${e.toString()}`:`${t} must be positive, got: ${e.toString()}`;throw new Error(r)}}class Tr{static validateAmount(e){const t=new y(e);try{Ar(t,"amount","for transfer")}catch(t){throw new yr(t.message,mr.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(e){if(e.length>gr.MAX_UNIQUE_KEY_LENGTH)throw new Y(`Unique key too long. Maximum length: ${gr.MAX_UNIQUE_KEY_LENGTH}`);if(!gr.UNIQUE_KEY_PATTERN.test(e))throw new yr('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',mr.INVALID_AMOUNT,{uniqueKey:e})}}}class Ir{toLaunchpadFormat(e){if(!e)return"unknown|Unit|none|none";if("string"==typeof e)return e.includes("|")?e:`${e}|Unit|none|none`;return`${e.collection||e.symbol||"unknown"}|${e.category||"Unit"}|${e.type||"none"}|${e.additionalKey||"none"}`}toTokenClass(e){if("object"==typeof e&&null!==e)return{collection:e.collection||"Token",category:e.category||"Unit",type:e.type||e.symbol||"unknown",additionalKey:e.additionalKey||"none"};if("string"!=typeof e)throw new Error("Invalid token format: expected string or object, got "+typeof e);const t=e.split("|");if(t.length<3)throw new Error(`Invalid token format: ${e}`);return{collection:t[0]||"Token",category:t[1]||"Unit",type:t[2]||"none",additionalKey:t[3]||"none"}}isGSwapFormat(e){return"string"==typeof e&&e.includes("|")}normalize(e){return"string"==typeof e&&this.isGSwapFormat(e)?e:this.toLaunchpadFormat(e)}}function xr(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function Br(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected at least 4 parts separated by $, got ${t.length}`);const[n,r,o,...i]=t;if(!n||!r||!o)throw new Error("Collection, category, and type must be non-empty");const s=i.join("$");if(!s)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:r,type:o,additionalKey:s}}catch(t){throw new Y(`Invalid dollar-delimited token: "${e}". Expected format: "Token$Unit$SYMBOL$additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"dollarToken","INVALID_DOLLAR_DELIMITED_TOKEN_FORMAT")}}class Cr extends p{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,o){let i;if("string"==typeof r){i={...Br(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new Cr({from:e,to:t,quantity:n,tokenInstance:i,uniqueKey:o||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n,r){return new Cr({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){return`${this.tokenInstance.collection}$${this.tokenInstance.category}$${this.tokenInstance.type}$${this.tokenInstance.additionalKey}`}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}class Pr extends p{constructor(e){super(),this.lockAuthority=e.lockAuthority,this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.expires&&(this.expires=e.expires),void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,o){let i;if("string"==typeof r){i={...Br(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new Pr({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:i}],...void 0!==o?.expires&&{expires:o.expires},...void 0!==o?.name&&{name:o.name},uniqueKey:o?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n,r){return new Pr({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==r?.expires&&{expires:r.expires},...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0].tokenInstanceKey;return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}toSigningPayload(){return{lockAuthority:this.lockAuthority,tokenInstances:this.tokenInstances,...void 0!==this.expires&&{expires:this.expires},...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class Nr extends p{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r){let o;if("string"==typeof n){o={...Br(n),instance:"0"}}else o={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new Nr({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:o}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n){return new Nr({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==n?.name&&{name:n.name},uniqueKey:n?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0].tokenInstanceKey;return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class _r extends p{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokens(e,t){const n=e.map(e=>{let t;if("string"==typeof e.tokenClassKey){t={...Br(e.tokenClassKey),instance:"0"}}else t={collection:e.tokenClassKey.collection,category:e.tokenClassKey.category,type:e.tokenClassKey.type,additionalKey:e.tokenClassKey.additionalKey,instance:"0"};return{quantity:e.quantity,tokenInstanceKey:t}});return new _r({tokenInstances:n,uniqueKey:t?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static fromTokenClassKey(e,t,n){return _r.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new _r({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0].tokenInstanceKey;return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class Ur{constructor(e){this.wallet=e}static generateUniqueKey(){return`${Date.now()}_${Math.random().toString(36).substring(2,8)}`}async signTransferToken(e){const t={name:"GalaChain",chainId:1},n={TransferToken:[{name:"from",type:"string"},{name:"to",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstance",type:"TokenInstance"},{name:"uniqueKey",type:"string"}],TokenInstance:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]};return{signature:await this.wallet.signTypedData(t,n,e),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signLockToken(e){const t={name:"GalaChain",chainId:1},n={LockToken:[{name:"lockAuthority",type:"string"},{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.expires?[{name:"expires",type:"uint256"}]:[],...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={lockAuthority:e.lockAuthority,tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.expires&&(r.expires=e.expires),void 0!==e.name&&(r.name=e.name);return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signBurnTokens(e){const t={name:"GalaChain",chainId:1},n={BurnTokens:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"}],TokenInstanceQuantity:[{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signUnlockToken(e){const t={name:"GalaChain",chainId:1},n={UnlockToken:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},r={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.name&&(r.name=e.name);return{signature:await this.wallet.signTypedData(t,n,r),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const n=e.replace("0x","");return`eth|${t.getAddress(`0x${n}`).replace("0x","")}`}static fromGalaChainAddress(e){return e.startsWith("eth|")?e.substring(4):e}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...Br(e),instance:"0"}}}function Dr(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new Y(`Invalid tokenId string format: "${e}". Expected format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");if(!(t[0]&&t[1]&&t[2]&&t[3]))throw new Y(`Invalid tokenId string format: "${e}". All components (collection, category, type, additionalKey) must be non-empty`,"tokenId","INVALID_TOKEN_ID_FORMAT");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3],instance:t[4]||"0"}}if("object"==typeof e&&null!==e){if(!(e.collection&&e.category&&e.type&&e.additionalKey))throw new Y("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return"instance"in e&&void 0!==e.instance?e:{...e,instance:"0"}}throw new Y(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Rr(e){try{const[t,n]=e.split("|");if(!n)throw new Error("Missing token part after service");const r=n.split("$");if(r.length<4)throw new Error(`Invalid vault address format. Expected at least 4 parts separated by $, got ${r.length}`);if(!(r[0]&&r[1]&&r[2]&&r[3]))throw new Error("All vault address components (collection, category, type, additionalKey) must be non-empty");const o=r.slice(3,-1),i=o.length>0?o.join("$"):r[3];return{collection:r[0],category:r[1],type:r[2],additionalKey:i}}catch(t){throw new Y(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${t instanceof Error?t.message:String(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}function Fr(e){return{...Rr(e),instance:"0"}}function Lr(e){return Rr(e).type}var Or=Object.freeze({__proto__:null,extractTokenSymbolFromVault:Lr,normalizeToTokenInstanceKey:Dr,parseVaultAddressToTokenClassKey:Rr,parseVaultAddressToTokenInstance:Fr});function Mr(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.lockAuthority||"string"==typeof t.lockAuthority)&&(void 0===t.expires||"number"==typeof t.expires)&&(void 0===t.name||"string"==typeof t.name)}function $r(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.name||"string"==typeof t.name)}function qr(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Mr)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function Kr(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every($r)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Gr=100,Wr=100,zr={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/,ETH_ADDRESS_PATTERN:me.ETH_ADDRESS,BACKEND_ADDRESS_PATTERN:me.BACKEND_ADDRESS,MAX_LOCK_BATCH_SIZE:100,MAX_UNLOCK_BATCH_SIZE:100};var jr;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(jr||(jr={}));class Hr extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="LockError"}}function Vr(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(!("string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0))||void 0!==t.lockAuthority&&"string"!=typeof t.lockAuthority||void 0!==t.expires&&"number"!=typeof t.expires||void 0!==t.name&&"string"!=typeof t.name||void 0!==t.uniqueKey&&"string"!=typeof t.uniqueKey)}function Xr(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.name||"string"==typeof t.name)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}function Qr(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)}function Zr(e){if(!e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Qr)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const Yr=50;var Jr;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(Jr||(Jr={}));class eo extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const to="gala-transfer-successful",no="token-transfer-successful",ro="token-locked-successfully",oo="token-unlocked-successfully",io="transfer-successful-no-id",so=50,ao=100,co=100;function uo(e){return e&&0!==e.length?e.reduce((e,t)=>y(e).plus(t.quantity).toString(),"0"):"0"}function lo(e,t){if(!e||0===e.length)return[];if(t)return e;const n=Date.now();return e.filter(e=>0===e.expires||e.expires>n)}class ho extends Wn{constructor(e,t,n,r=!1,o){super(e,r),this.wallet=t,this.tokenResolver=n,this.publicAxios=o,this.signatureHelper=t?new Ur(t):void 0}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw de("No response from GalaChain service",500);if(1!==t.Status)throw de(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",o=n?.maxFeePortion??"0",i=(await import("bignumber.js")).default,s=!new i(r).isZero()||!new i(o).isZero(),a=t.Data;return a.reverseBondingCurveMinFeePortion=r,a.reverseBondingCurveMaxFeePortion=o,a.hasReverseBondingCurveFee=s,a.isGraduated="Finished"===t.Data.saleStatus,delete a.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(!e)throw de("No response from GalaChain service",500);if(1!==e.Status)throw de(`Failed to fetch launch token fee: Status ${e.Status}`,e.Status);return e.Data.feeAmount}getChannelForCollection(e){return"MUSIC"===(e.startsWith("$")?e.slice(1).toUpperCase():e.toUpperCase())?"music":"asset"}validateFetchPoolDetailsData(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.vaultAddress)throw new Y("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new Y("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new Y("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const n=`/api/${this.getChannelForCollection(e.collection)}/token-contract/FetchBalances`,r=await this.http.post(n,e);if(!r)return null;if(1!==r.Status||!r.Data||0===r.Data.length)return null;const o=r.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!o||"0"===o.quantity)return null;const i=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`,s={quantity:o.quantity,collection:o.collection,category:o.category,tokenId:i};if(o.inUseHolds?.length){const e=lo(o.inUseHolds??[],t);e.length>0&&(s.inUseHolds=e,s.inUseQuantity=uo(e))}if(o.lockedHolds?.length){const e=lo(o.lockedHolds??[],t);e.length>0&&(s.lockedHolds=e,s.lockedQuantity=uo(e))}return(s.lockedQuantity||s.inUseQuantity)&&(s.availableQuantity=function(e,t="0",n="0"){return y(e).minus(t).minus(n).toString()}(s.quantity,s.lockedQuantity,s.inUseQuantity)),s}catch(e){throw de(`Failed to fetch token balance from GalaChain: ${nr(e)}`,void 0,tr(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Dr(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]},r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(1!==r.Status)throw de(`Failed to fetch token class from GalaChain: Status ${r.Status}${r.Message?` - ${r.Message}`:""}`,r.Status);if(!r.Data||0===r.Data.length)throw de(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return r.Data[0]}catch(e){if(rr(e)&&404===e.response?.status)throw de("Token not found on GalaChain",404,tr(e)?e:void 0);const t=nr(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw de(`Failed to fetch token class from GalaChain: ${t}`,void 0,tr(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw new Y("tokenClasses array must not be empty");const t={tokenClasses:e},n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(1!==n.Status)throw de(`Failed to fetch token classes with supply from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw de("No token supply data found for requested token classes",404);return n.Data}catch(e){if(rr(e)&&404===e.response?.status)throw de("Token supply data not found on GalaChain",404,tr(e)?e:void 0);const t=nr(e);if(t.includes("Token")||t.includes("Status")||t.includes("tokenClasses"))throw e;throw de(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,tr(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new yr("Wallet required for GALA transfer operations",mr.WALLET_REQUIRED);try{const t=be(e.recipientAddress),n=be(this.wallet.address),r=Cr.forGALA(n,t,e.amount,e.uniqueKey),o=await this.signatureHelper.signTransferToken(r.toSigningPayload()),i=new Cr({...r.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(i,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",i);if(!s)throw new yr("No response from GalaChain transfer service",mr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new yr("Wallet required for token transfer operations",mr.WALLET_REQUIRED);try{const t=be(e.to),n=be(this.wallet.address);let r;if(e.tokenId)r=Dr(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",JSON.stringify(r,null,2));else{if(!e.tokenName)throw new yr("Must provide either tokenId or tokenName for token identification",mr.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const o=new Cr({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),i=await this.signatureHelper.signTransferToken(o.toSigningPayload()),s=new Cr({...o.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(s,null,2));const a=await this.http.post("/api/asset/token-contract/TransferToken",s);if(!a)throw new yr("No response from GalaChain transfer service",mr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(a,null,2)),this.extractTransactionIdFromResponse(a,"token")}catch(t){throw this.handleTransferError(t,"Token transfer failed",e)}}async resolveTokenClassKey(e){try{const t=await this.tokenResolver.resolveTokenClassKey(e);return this.logger.debug(`[DEBUG] Token class key resolution for '${e}':`,JSON.stringify(t,null,2)),t}catch(t){if(t instanceof yr)throw t;throw new yr(`Failed to resolve token class key for '${e}': ${nr(t)}`,mr.TOKEN_NOT_FOUND,{tokenName:e})}}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.signatureHelper)throw new Hr("Wallet required for token lock operations",jr.WALLET_REQUIRED);try{const t=be(this.wallet.address),n=[],r=[];let o=t;const i=e.tokens.find(e=>e.lockAuthority);i?.lockAuthority&&(o=be(i.lockAuthority));const s=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const i of e.tokens){let e;if(i.tokenId)e=Dr(i.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",i.tokenId);else{if(!i.tokenName)throw new Hr("Must provide either tokenId or tokenName for token identification",jr.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(i.tokenName)}n.push({owner:t,quantity:i.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:i.amount,lockAuthority:i.lockAuthority?be(i.lockAuthority):o})}const c=new Pr({lockAuthority:o,tokenInstances:n,...void 0!==s?.expires&&{expires:s.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),u=await this.signatureHelper.signLockToken(c.toSigningPayload()),l=new Pr({...c.toSigningPayload(),signedPayload:u});this.logger.debug("[DEBUG] Full Lock Request Payload:",JSON.stringify(l,null,2));const h=await this.http.post("/api/asset/token-contract/LockTokens",l);if(!h)throw new Hr("No response from GalaChain lock service",jr.NETWORK_ERROR);if(1!==h.Status)throw new Hr(`Token lock failed: ${h.Message||`Status ${h.Status}`}`,jr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token lock response:",JSON.stringify(h,null,2)),this.extractLockResult(h,r)}catch(t){throw this.handleLockError(t,"Token lock failed",e)}}async unlockTokens(e){if(this.validateUnlockTokensData(e),!this.wallet||!this.signatureHelper)throw new Hr("Wallet required for token unlock operations",jr.WALLET_REQUIRED);try{const t=be(this.wallet.address),n=[],r=[],o=e.tokens.find(e=>void 0!==e.name);for(const o of e.tokens){let e;if(o.tokenId)e=Dr(o.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",o.tokenId);else{if(!o.tokenName)throw new Hr("Must provide either tokenId or tokenName for token identification",jr.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(o.tokenName)}n.push({owner:t,quantity:o.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:o.amount})}const i=new Nr({tokenInstances:n,...void 0!==o?.name&&{name:o.name},uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),s=await this.signatureHelper.signUnlockToken(i.toSigningPayload()),a=new Nr({...i.toSigningPayload(),signedPayload:s});this.logger.debug("[DEBUG] Full Unlock Request Payload:",JSON.stringify(a,null,2));const c=await this.http.post("/api/asset/token-contract/UnlockTokens",a);if(!c)throw new Hr("No response from GalaChain unlock service",jr.NETWORK_ERROR);if(1!==c.Status)throw new Hr(`Token unlock failed: ${c.Message||`Status ${c.Status}`}`,jr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token unlock response:",JSON.stringify(c,null,2)),this.extractUnlockResult(c,r)}catch(t){throw this.handleLockError(t,"Token unlock failed",e)}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.signatureHelper)throw new eo("Wallet required for token burn operations",Jr.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(n.tokenId)e=Dr(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(!n.tokenName)throw new eo("Must provide either tokenId or tokenName for token identification",Jr.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new _r({tokenInstances:t,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),r=await this.signatureHelper.signBurnTokens(n.toSigningPayload()),o=new _r({...n.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full Burn Request Payload:",JSON.stringify(o,null,2));const i=await this.http.post("/api/asset/token-contract/BurnTokens",o);if(!i)throw new eo("No response from GalaChain burn service",Jr.NETWORK_ERROR);if(1!==i.Status)throw new eo(`Token burn failed: ${i.Message||`Status ${i.Status}`}`,Jr.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token burn response:",JSON.stringify(i,null,2)),this.extractBurnResult(i)}catch(t){throw this.handleBurnError(t,"Token burn failed",e)}}extractBurnResult(e){const t=[];if(e.Data&&Array.isArray(e.Data))for(const n of e.Data)t.push({collection:n.collection||"",category:n.category||"",type:n.type||"",additionalKey:n.additionalKey||"",instance:n.instance||"0",quantity:n.quantity||"0",burnedBy:n.burnedBy||""});let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},burned:t}}validateBurnTokensData(e){if(!Zr(e))throw new eo("Invalid burn data: missing required fields",Jr.VALIDATION_ERROR);if(e.tokens.length>so)throw new eo(`Batch size exceeds maximum limit of ${so} tokens per burn operation`,Jr.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new eo("Must provide either tokenId or tokenName for token identification",Jr.TOKEN_NOT_FOUND);const e=new y(t.amount);if(e.isNaN()||e.lte(0))throw new eo("Burn amount must be a positive number",Jr.INVALID_AMOUNT,{amount:t.amount})}}handleBurnError(e,t,n){if(e instanceof eo)return e;let r=t,o=Jr.NETWORK_ERROR;if(rr(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n;e.Message&&"string"==typeof e.Message&&(r=`${t}: ${e.Message}`);const i=String(e.Message||"").toLowerCase();i.includes("insufficient")||i.includes("balance")?o=Jr.INSUFFICIENT_BALANCE:(i.includes("not found")||i.includes("token"))&&(o=Jr.TOKEN_NOT_FOUND)}}else tr(e)&&(r=`${t}: ${e.message}`);const i={};return void 0!==n?.tokens?.[0]?.tokenName&&(i.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(i.amount=n.tokens[0].amount),new eo(r,o,Object.keys(i).length>0?i:void 0)}validateLockTokensData(e){if(!qr(e))throw new Hr("Invalid lock data: missing required fields",jr.VALIDATION_ERROR);if(e.tokens.length>ao)throw new Hr(`Batch size exceeds maximum limit of ${ao} tokens per lock operation`,jr.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new Hr("Must provide either tokenId or tokenName for token identification",jr.TOKEN_NOT_FOUND);if(t.tokenName&&!gr.TOKEN_NAME_PATTERN.test(t.tokenName))throw new Hr("Invalid token name format",jr.TOKEN_NOT_FOUND,{tokenName:t.tokenName});const e=new y(t.amount);if(e.isNaN()||e.lte(0))throw new Hr("Lock amount must be a positive number",jr.INVALID_AMOUNT,{amount:t.amount});if(t.lockAuthority&&!we(t.lockAuthority))throw new Hr("Invalid lock authority address format",jr.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires&&(t.expires<=0||!Number.isInteger(t.expires)))throw new Hr("Expires must be a positive integer (epoch milliseconds)",jr.VALIDATION_ERROR)}}validateUnlockTokensData(e){if(!Kr(e))throw new Hr("Invalid unlock data: missing required fields",jr.VALIDATION_ERROR);if(e.tokens.length>co)throw new Hr(`Batch size exceeds maximum limit of ${co} tokens per unlock operation`,jr.VALIDATION_ERROR);for(const t of e.tokens){if(!t.tokenId&&!t.tokenName)throw new Hr("Must provide either tokenId or tokenName for token identification",jr.TOKEN_NOT_FOUND);if(t.tokenName&&!gr.TOKEN_NAME_PATTERN.test(t.tokenName))throw new Hr("Invalid token name format",jr.TOKEN_NOT_FOUND,{tokenName:t.tokenName});const e=new y(t.amount);if(e.isNaN()||e.lte(0))throw new Hr("Unlock amount must be a positive number",jr.INVALID_AMOUNT,{amount:t.amount})}}extractLockResult(e,t){let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},locked:t}}extractUnlockResult(e,t){let n;if(e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId||t.txnId||t.TxnId||t.id||void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof Hr)return e;let r=t,o=jr.NETWORK_ERROR;if(rr(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n;e.Message&&"string"==typeof e.Message&&(r=`${t}: ${e.Message}`);const i=String(e.Message||"").toLowerCase();i.includes("insufficient")||i.includes("balance")?o=jr.INSUFFICIENT_BALANCE:i.includes("lock")&&i.includes("not found")?o=jr.LOCK_NOT_FOUND:i.includes("not found")||i.includes("token")?o=jr.TOKEN_NOT_FOUND:i.includes("authority")?o=jr.NOT_LOCK_AUTHORITY:i.includes("expired")&&(o=jr.LOCK_EXPIRED)}}else tr(e)&&(r=`${t}: ${e.message}`);const i={};return void 0!==n?.tokens?.[0]?.tokenName&&(i.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(i.amount=n.tokens[0].amount),new Hr(r,o,Object.keys(i).length>0?i:void 0)}validateTransferGalaData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.recipientAddress&&t.recipientAddress.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Y("Invalid GALA transfer data: missing required fields");if(!we(e.recipientAddress))throw new yr("Invalid recipient address format",mr.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Tr.validateAmount(e.amount),Tr.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.to&&t.to.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Y("Invalid token transfer data: missing required fields");if(!we(e.to))throw new yr("Invalid recipient address format",mr.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new yr("Must provide either tokenId or tokenName for token identification",mr.TOKEN_NOT_FOUND);if(e.tokenName&&!gr.TOKEN_NAME_PATTERN.test(e.tokenName))throw new yr("Invalid token name format",mr.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Tr.validateAmount(e.amount),Tr.validateUniqueKey(e.uniqueKey)}validateLockTokenData(e){if(!Vr(e))throw new Y("Invalid lock token data: missing required fields");if(e.lockAuthority&&!we(e.lockAuthority))throw new yr("Invalid lock authority address format",mr.INVALID_RECIPIENT,{recipientAddress:e.lockAuthority});if(!e.tokenId&&!e.tokenName)throw new yr("Must provide either tokenId or tokenName for token identification",mr.TOKEN_NOT_FOUND);if(e.tokenName&&!gr.TOKEN_NAME_PATTERN.test(e.tokenName))throw new yr("Invalid token name format",mr.TOKEN_NOT_FOUND,{tokenName:e.tokenName});if(void 0!==e.expires&&(e.expires<=0||!Number.isInteger(e.expires)))throw new Y("Expires must be a positive integer (epoch milliseconds)");Tr.validateAmount(e.amount),Tr.validateUniqueKey(e.uniqueKey)}validateUnlockTokenData(e){if(!Xr(e))throw new Y("Invalid unlock token data: missing required fields");if(!e.tokenId&&!e.tokenName)throw new yr("Must provide either tokenId or tokenName for token identification",mr.TOKEN_NOT_FOUND);if(e.tokenName&&!gr.TOKEN_NAME_PATTERN.test(e.tokenName))throw new yr("Invalid token name format",mr.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Tr.validateAmount(e.amount),Tr.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(t){const n=this.resolveTokenInstanceFromVaultAddress(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}const n={collection:e.trim().toUpperCase(),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug(`[DEBUG] Token resolution for '${e}' (standard format):\n Token Instance: ${JSON.stringify(n,null,2)}`),n}catch(t){if(t instanceof yr)throw t;throw new yr(`Failed to resolve token '${e}': ${nr(t)}`,mr.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){try{return Fr(e)}catch(e){if(e instanceof Y)throw new yr(`Invalid vault address format: ${e.message}`,mr.TOKEN_NOT_FOUND);throw new yr(`Failed to parse vault address: ${e instanceof Error?e.message:String(e)}`,mr.TOKEN_NOT_FOUND)}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const n=e;if(Array.isArray(n.Data)&&n.Data.length>0)switch(t){case"gala":return to;case"token":return no;case"lock":return ro;case"unlock":return oo}return io}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new yr("Operation succeeded but transaction ID could not be extracted",mr.NETWORK_ERROR)}handleTransferError(e,t,n){if(e instanceof yr)return e;if(e instanceof Y)return new yr(e.message,mr.INVALID_AMOUNT);if(rr(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t)return new yr(("string"==typeof r?.message?r.message:void 0)||"Invalid transfer request",mr.INVALID_AMOUNT);if(403===t)return new yr("Insufficient balance for transfer",mr.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new yr("Token not found",mr.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new yr("Transfer request timed out",mr.NETWORK_ERROR);const r=nr(e);return new yr(r||t,mr.NETWORK_ERROR)}}class fo{constructor(e,t,n,r=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=n,this.logger=new H({debug:r,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e;if(!t&&!n)throw le("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&n)throw new Y("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS");if(n)return this.logger.debug(`Fetching spot price by tokenId: ${n}`),this._fetchDexTokenSpotPrice(n);throw new Y("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw le("tokenId","Token ID");try{const t=Dr(e),n=xr(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${n}`),!this.dexBackendHttp)throw de("DEX Backend API client not configured");const r=await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:n}});if(!r.data||"string"!=typeof r.data)throw new Y("Invalid price response: data must be a string, got "+typeof r.data,"data","INVALID_RESPONSE");const o=parseFloat(r.data);if(isNaN(o))throw new Y(`Invalid price value: could not parse "${r.data}" as number`,"data","INVALID_CALCULATION");const i=`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`;let s;try{if(this.cache){const e=this.cache.getByTokenId(i);if(e?.symbol)return s=e.symbol,this.logger.debug(`DEX spot price for ${s} (cached): $${o}`),{symbol:s,price:o}}this.logger.debug(`Symbol cache miss for ${i}, fetching from API`);s=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(i,{symbol:s}),this.logger.debug(`Cached symbol for ${i}: ${s}`)),this.logger.debug(`DEX spot price for ${s}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${e instanceof Error?e.message:String(e)}`),s=("Token"===t.collection?t.type:t.collection).toUpperCase(),this.logger.debug(`DEX spot price for ${s} (fallback): $${o}`)}return{symbol:s,price:o}}catch(e){if(e instanceof Y)throw e;throw de(`Failed to fetch DEX spot price: ${nr(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!e||"string"!=typeof e)throw new Error(Q);try{if(n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const n=`${t.sellingToken.collection}|${t.sellingToken.category}|${t.sellingToken.type}|${t.sellingToken.additionalKey}`;return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${nr(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const r=await t({tokenName:e,amount:"1",type:"native"}),o=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(!o)throw de("GALA price not available");const i=Number(r.amount)/1e18;if(i<=0)throw new Y(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const s=o.price/i;return{symbol:e.toUpperCase(),price:s}}catch(t){if(t instanceof Error)throw de(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw de(`Failed to calculate launchpad token spot price for ${e}: ${nr(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw de("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),n={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey,symbol:t.symbol,decimals:t.decimals,name:t.name,image:t.image,description:t.description,network:t.network,...void 0!==t.contractAddress&&{contractAddress:t.contractAddress}};return this.logger.debug(`Fetched token details for ${t.symbol} from GalaChain`),n}catch(t){if((t instanceof Y||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw de(`Failed to fetch token details from GalaChain for ${e}: ${nr(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw de("DEX Backend API client not configured");const e=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard/seasons"});let t;if(Array.isArray(e))t=e;else{if(!e||"object"!=typeof e)return this.logger.warn("Seasons endpoint returned invalid data:",e),[];if(Array.isArray(e.data))t=e.data;else if(e.data&&Array.isArray(e.data.seasons))t=e.data.seasons;else{if(!Array.isArray(e.seasons))return this.logger.warn("Seasons endpoint returned unexpected structure:",e),[];t=e.seasons}}const n=t.map(e=>({id:e?.id??0,name:e?.name??"",start:e?.start?new Date(e.start):new Date,end:e?.end?new Date(e.end):new Date,rulesId:e?.rules_id??0}));return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(e instanceof Error&&e.message.includes("not configured"))throw e;if(e&&"object"==typeof e&&"response"in e){const t=e;if(404===t.response?.status)return this.logger.warn("Seasons endpoint not available"),[]}throw de(`Failed to fetch DEX seasons: ${nr(e)}`)}}async fetchCurrentDexSeason(){const e=await this.fetchAllDexSeasons(),t=new Date,n=e.find(e=>t>=e.start&&t<=e.end);return n?this.logger.debug(`Current DEX season: ${n.name} (ID: ${n.id})`):this.logger.debug("No active DEX season found"),n||null}async fetchDexLeaderboardBySeasonId(e){if(!e||"number"!=typeof e||e<1)throw le("seasonId","Season ID must be a positive number");try{if(!this.dexBackendHttp)throw de("DEX Backend API client not configured");const t=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard",params:{seasonId:e.toString()}});let n;if(Array.isArray(t))n=t;else{if(!t||"object"!=typeof t)return this.logger.warn("Leaderboard endpoint returned invalid data:",t),{entries:[],seasonId:e,totalEntries:0};if(t.data&&Array.isArray(t.data.leaderboard))n=t.data.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!t.data||!Array.isArray(t.data))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=t.data}}const r=n.map(e=>({wallet:e?.wallet??"",rank:e?.rank??0,totalXp:e?.total_xp??0,distributionPercent:e?.distribution_percent??0,liquidityXp:e?.liquidity_xp??0,tradingXp:e?.trading_xp??0,masteryTitles:(e?.mastery_titles??[]).map(e=>({name:e?.name??"",type:e?.type??"trade",order:e?.order??0}))}));return this.logger.debug(`Fetched leaderboard for season ${e} with ${r.length} entries`),{entries:r,seasonId:e,totalEntries:r.length}}catch(t){if(t instanceof Error&&t.message.includes("must be a positive number"))throw t;throw de(`Failed to fetch DEX leaderboard for season ${e}: ${nr(t)}`)}}async fetchCurrentDexLeaderboard(){const e=await this.fetchCurrentDexSeason();return e?this.fetchDexLeaderboardBySeasonId(e.id):(this.logger.debug("Cannot fetch current leaderboard - no active season"),null)}async fetchDexAggregatedVolumeSummary(){try{if(!this.dexBackendHttp)throw de("DEX Backend API client not configured");const e=await this.dexBackendHttp.request({method:"GET",url:"/explore/volume"}),t={volume1d:e.data.volume1d,volume1dDelta:e.data.volume1dDelta,volume7d:e.data.volume7d,volume7dDelta:e.data.volume7dDelta,volume30d:e.data.volume30d,volume30dDelta:e.data.volume30dDelta};return this.logger.debug(`Fetched DEX volume summary: $${t.volume1d.toFixed(2)} (1d)`),t}catch(e){throw de(`Failed to fetch DEX volume summary: ${nr(e)}`)}}}const po=8,go=18,mo={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"};function yo(e,t=18){const n=parseFloat(e);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function wo(e){return yo(e,8)}function bo(e){return yo(e,18)}function ko(e){return{maxAcceptableReverseBondingCurveFee:wo(e.maxAcceptableReverseBondingCurveFee)}}new H({debug:!1,context:"NumberUtils"});const vo={BuyNativeDto:class extends p{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=wo(t),this.expectedToken=bo(n),this.extraFees=ko(r)}},BuyExactDto:class extends p{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=bo(t),this.expectedNativeToken=wo(n),this.extraFees=ko(r)}},SellExactDto:class extends p{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=bo(t),this.expectedNativeToken=wo(n),this.extraFees=ko(r)}},SellNativeDto:class extends p{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=wo(t),this.expectedToken=bo(n),this.extraFees=ko(r)}}};class Eo extends zn{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,n){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const n=this.generateEIP712Types(t,e),r=g(e),o={...e,prefix:r},{signature:i,domain:s}=await this.signWithEthersWallet(n,o),a={...e,signature:i,types:n,domain:s};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(a),signatureLength:i.length}),a}catch(e){this.logger.error("❌ Signature generation failed:",e);throw pe(`Failed to sign DTO: ${nr(e)}`)}}async signWithEthersWallet(e,t){try{let n,r;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)n={name:"ethereum",chainId:1},r=await this.walletProvider.signTypedData(n,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw fe("Wallet provider does not support typed data signing","walletProvider");{const o=await this.walletProvider.getNetwork();n={name:o.name,chainId:Number(o.chainId)},r=await this.walletProvider.signTypedData(n,e,t)}}return{signature:r,domain:n}}catch(e){throw pe(`Ethers.js signing failed: ${nr(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const r=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),o=(e,t,r,i=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const s=o(e,t[0],r,!0);return i||n[r].push({name:e,type:(s??e)+"[]"}),s?s+"[]":void 0}if("object"==typeof t&&null!==t){if(n[e])throw new Y(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).forEach(([t,n])=>{o(t,n,e)}),i||n[r].push({name:e,type:e}),e}{let o;switch(typeof t){case"string":o="string";break;case"number":o="uint256";break;case"boolean":o="bool";break;default:throw new Y(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return i||n[r].push({name:e,type:o}),o}}};return Object.entries(r).forEach(([t,n])=>{o(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class So extends zn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),r=this.createGalaInstance(),o=`$service$${n.toStringKey()}$launchpad`,i=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${r.toStringKey()}$${e}`,c=[o,i,s,a,`$tokenBalance$${r.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=nr(e);throw new Y(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new U;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new U;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!e||"string"!=typeof e)throw le("vaultAddress","Vault address");try{const t=Lr(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof Y)throw he("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!e||"string"!=typeof e)throw le("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw he("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw he("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw he("vaultAddress",'having at least 5 parts separated by "$"');const n=t[2];if(!n||!/^[A-Za-z]{1,10}$/.test(n))throw he("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return Br(e)}catch(e){if(e instanceof Y)throw he("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Ao(e,t,n){if(t<0||t>1)throw new Error(`Invalid slippage tolerance factor: ${t}. Must be between 0 and 1 (e.g., 0.05 for 5%)`);const r=new y(e);if(r.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const o=r.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=r.minus(o);break;case"buy-exact":case"sell-native":i=r.plus(o);break;default:throw new Error(`Unknown operation type: ${n}`)}return i.isLessThan(0)&&(i=new y(0)),i.toFixed()}class To extends Wn{constructor(e,t,n=!1,r,o,i=.05,s=.01){super(e,n),this.tokenResolver=t,this.walletProvider=r,this.userAddress=o,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=s,this.bundleEndpoint="/bundle",r&&o&&(this.signatureService=new Eo(r,n),this.tokenKeyService=new So(n))}async submitTransaction(e){try{this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)}),this.validateBundleData(e);const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});const n=await this.http.post(this.bundleEndpoint,t);return n?(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:!!n.data,error:n.error}),this.handleBundleResponse(n)):{success:!1,error:"No response from bundle API"}}catch(e){return this.logger.error("❌ Bundle transaction submission failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}validateBundleData(e){if(!e)throw le("bundleData","Bundle data");if(!e.signedDto)throw le("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw le("method","Method name");if(!Array.isArray(e.stringsInstructions))throw he("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Y("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw he("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new Y(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new Y(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT")}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){if(e.data&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",e.data),{success:!0,data:e.data};const t=e.error||e.message||"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",t),{success:!1,error:t}}formatErrorMessage(e){if("string"==typeof e)return e;if(rr(e)&&e.response){const t=e.response.data;if(t&&"object"==typeof t){const e=t;if(e.error)return String(e.error);if(e.message)return String(e.message)}}return nr(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw le("transactionId","Transaction ID");this.logger.debug("🔍 Checking bundler transaction result:",e);const t=await this.http.get(`${this.bundleEndpoint}?id=${e}`);return t?(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t}):{success:!1,error:"No response from bundler transaction query"}}catch(e){return this.logger.error("❌ Failed to get bundler transaction result:",e),{success:!1,error:this.formatErrorMessage(e)}}}async cancelTransaction(e){try{if(!e||"string"!=typeof e)throw le("transactionId","Transaction ID");this.logger.debug("🚫 Cancelling transaction:",e);const t=await this.http.delete(`${this.bundleEndpoint}/${e}`);return t?(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t}):{success:!1,error:"No response from transaction cancellation"}}catch(e){return this.logger.error("❌ Failed to cancel transaction:",e),{success:!1,error:this.formatErrorMessage(e)}}}async getHealthStatus(){try{this.logger.debug("🏥 Checking bundle service health");const e=await this.http.get(`${this.bundleEndpoint}/health`);return e?(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e}):{success:!1,error:"No response from bundle service health check"}}catch(e){return this.logger.error("❌ Bundle service health check failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:o}=e,{effectiveSlippageFactor:i,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(!o)throw new Y("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ao(o,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:o,slippageFactor:i,adjustedMinTokens:e});const t=new vo.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(!o)throw new Y("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ao(o,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:o,slippageFactor:i,adjustedMaxGalaCost:e});const t=new vo.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:o}=e,{effectiveSlippageFactor:i,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(!o)throw new Y("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ao(o,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:o,slippageFactor:i,adjustedMinGala:e});const t=new vo.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(!o)throw new Y("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ao(o,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:o,slippageFactor:i,adjustedMaxTokensToSell:e});const t=new vo.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:o,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,r),s=await this.resolveTokenNameToVault(e);if(!s)throw ue(e);return{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:s}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,o=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e||"0";return e&&(i=Ao(e,o,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:o,adjustedMaxFee:i})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:o,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw fe("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw le("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${F()}-${Date.now()}-${this.userAddress}`;const r=await this.signatureService.signDTO(e,t,this.userAddress),o=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:o,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:o,dtoKeys:Object.keys(r)});const s=await this.submitTransaction(i);if(s.success&&s.data)return this.logger.debug("✅ Bundle transaction submitted:",s.data),{success:!0,data:{transactionId:s.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(s.error||"Bundle transaction failed"))}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}var Io,xo;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Io||(Io={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(xo||(xo={}));const Bo={[Io.PROCESSED]:xo.COMPLETED,[Io.COMPLETED]:xo.COMPLETED,[Io.SUCCESS]:xo.COMPLETED,[Io.FAILED]:xo.FAILED,[Io.ERROR]:xo.FAILED,[Io.PROCESSING]:xo.PROCESSING,[Io.PENDING]:xo.PENDING};class Co extends zn{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.reconnectCount=0,this.hasOnAnyListener=!1,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof L||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{try{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');return this.logger.error("❌ Socket.IO connection failed:",e.message),void t(e)}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=L(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts||5,reconnectionDelay:this.config.reconnectDelay||2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectCount=0,e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status||n.Status;if(r&&"string"==typeof r){if(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE){const e=this.eventBuffer.keys().next().value;if(e){const t=this.eventBufferTimeouts.get(e);t&&(clearTimeout(t),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e),this.logger.warn(`📡 [Event Buffer] Buffer full (${this.MAX_BUFFER_SIZE}), dropped oldest: ${e}`)}}this.eventBuffer.set(e,n);const t=this.eventBufferTimeouts.get(e);t&&clearTimeout(t);const o=setTimeout(()=>{this.eventBuffer.has(e)&&(this.logger.debug(`📡 [Event Buffer] Cleaning up orphaned event for ${e}`),this.eventBuffer.delete(e),this.eventBufferTimeouts.delete(e))},3e4);this.eventBufferTimeouts.set(e,o)}}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0}catch(e){t(e)}})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=this.eventBuffer.get(e);if(n){this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)});const r=this.eventBufferTimeouts.get(e);r&&(clearTimeout(r),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e)}const r=this.config.timeout||3e5,o=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),o={transactionId:e,status:xo.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(o),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,o),this.socket&&this.socket.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:xo.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,o=r?.data,i=r?.status||r?.Status||o?.status||o?.Status;let s=r?.message||r?.Message||o?.message||o?.Message||r?.error||o?.error;s&&"string"==typeof s||(s=i===Io.FAILED||i===Io.ERROR?"Transaction failed - check transaction details":i===Io.COMPLETED||i===Io.PROCESSED||i===Io.SUCCESS?"Transaction completed successfully":i?`Transaction status: ${i}`:"Unknown transaction status");const a=r?.blockHash||o?.blockHash,c=r?.gasUsed||o?.gasUsed,u=r?.Data||o?.Data,l={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...a&&{blockHash:a},...c&&{gasUsed:c},...u&&{data:u}};if(this.logger.debug(`📡 Mapped status for ${e}: ${i} -> ${l.status}`),this.logger.debug(`📡 Final message: "${s}"`),n(l),l.status===xo.COMPLETED||l.status===xo.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${l.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===xo.COMPLETED?t(e):e.status!==xo.FAILED&&e.status!==xo.TIMEOUT||n(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Bo[t]||xo.PENDING}async handleReconnect(){this.reconnectCount<this.config.reconnectAttempts?(this.reconnectCount++,this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectCount}/${this.config.reconnectAttempts}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.config.reconnectDelay)):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.eventBufferTimeouts.forEach(e=>{clearTimeout(e)}),this.eventBufferTimeouts.clear(),this.logger.debug("🧹 Cleared event buffer and timeouts"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected"))}isConnected(){return this.socket?.connected||!1}getSocket(){return this.socket}}class Po extends zn{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!ye(e))throw new Y("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");const t=e.trim().toLowerCase(),n=this.get(t);if(n)return n;try{const n=await this.poolService.resolveTokenNameToVault(e);return n&&this.set(t,n),n}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw ue(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(e.toLowerCase())||null}set(e,t){this.cache.set(e.toLowerCase(),t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}parseVaultAddressToTokenClassKey(e){try{return Rr(e)}catch(e){if(e instanceof Y)throw he("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}async function No(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:o=20}=t,i=[];let s=1,a=!0,c=0;for(;a&&s<=n;){r&&r.debug(`Auto-pagination: fetching page ${s} with limit ${o}`);const t=await e(s,o);if(!t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(i.push(...t.items),c=t.total,r&&r.debug(`Auto-pagination: page ${s} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${s}, exiting loop`);break}a=t.hasNext,s++}return s>n&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n}, stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${i.length}, total count: ${c}`),{items:i,total:c}}function _o(e,t=e.length,n="items"){return{...{page:1,limit:e.length||0,total:t,totalPages:Math.ceil(t/(e.length||1))||1,hasNext:!1,hasPrevious:!1},[n]:e}}class Uo extends Wn{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw fe("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");if(!e||"string"!=typeof e||e.length<3||e.length>20)throw fe("Token name must be a string between 3 and 20 characters","tokenName");this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(!t)throw fe(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Rr(t),r=`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`;return this.logger.debug(`Extracted token class key: ${r}`),r}catch(t){if(t instanceof Error&&t.message.includes("ConfigurationError"))throw t;throw de(`Failed to resolve token name '${e}': ${nr(t)}`,500)}}async fetchPriceHistory(e){this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e);try{let t=e.tokenId;if(e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const n=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=n,this.logger.debug(`Resolved to token ID: ${n}`)}if(!t)throw fe("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return Or}),r=n(t),o=xr(`${r.collection}|${r.category}|${r.type}|${r.additionalKey}`),{from:i,to:s,sortOrder:a="DESC",page:c=1,limit:u=10}=e,l={token:o,page:String(c),limit:String(u)};i&&(l.from=i.toISOString()),s&&(l.to=s.toISOString());const h=function(e){if(e)return e.toLowerCase()}(a);h&&(l.order=h),this.logger.debug(`Querying price snapshots for token ${o}, page ${c}, limit ${u}`);const d=await this.http.get("/price-oracle/fetch-price",l);if(!d)throw de("No response from price history service",500);const f=this.transformApiResponseToPriceHistory(d);return this.logger.debug(`Found ${f.snapshots.length} price snapshots, total ${f.total}`),f}catch(e){if(e instanceof Error&&(e.message.includes("ConfigurationError")||e.message.includes("NetworkError")))throw e;throw de(`Failed to fetch price history: ${nr(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw de("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw de("Invalid API response: missing data.meta pagination info",500);const t=e.data.data.map(e=>({price:e.price,timestamp:new Date(e.createdAt),tokenId:`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`})),n=e.data.meta,r=n.currentPage??1,o=n.totalPages??1;return{snapshots:t,page:r,limit:n.pageSize??50,total:n.totalItems??0,totalPages:o,hasNext:r<o,hasPrevious:r>1}}async fetchAllPriceHistory(e){this.logger.debug("Fetching all price history with options:",e);const t=await No((t,n)=>this.fetchPriceHistory({...e,page:t,limit:n}).then(e=>({items:e.snapshots,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:50});return _o(t.items,t.total,"snapshots")}validateOptions(e){const{from:t,to:n,sortOrder:r,page:o=1,limit:i=10}=e;if(function(e,t,n,r={}){const{description:o="parameter",treatEmptyAsNull:i=!0}=r,s=e[t],a=e[n],c=null!=s&&(!i||""!==s),u=null!=a&&(!i||""!==a);if(!c&&!u)throw fe(`Either ${t} or ${n} must be provided (${o})`,n);if(c&&u)throw fe(`Cannot provide both ${t} and ${n}. Provide exactly one (${o}).`,n)}(e,"tokenName","tokenId",{description:"token identifier"}),t&&!(t instanceof Date)&&isNaN(new Date(t).getTime()))throw fe("from must be a valid Date","from");if(n&&!(n instanceof Date)&&isNaN(new Date(n).getTime()))throw fe("to must be a valid Date","to");if(r&&"ASC"!==r&&"DESC"!==r)throw fe('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(o)||o<1)throw fe("page must be a positive integer","page");if(!Number.isInteger(i)||i<1||i>50)throw fe("limit must be between 1 and 50","limit")}}function Do(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new Y("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:r,additionalKey:o}=e;if(!t||"string"!=typeof t)throw new Y("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!n||"string"!=typeof n)throw new Y("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!r||"string"!=typeof r)throw new Y("Token.type must be a non-empty string, got "+typeof r,"token.type","MISSING_OR_INVALID_TYPE");if(!o||"string"!=typeof o)throw new Y("Token.additionalKey must be a non-empty string, got "+typeof o,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:r,additionalKey:o}}(e);if(!e)throw new Y(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new Y("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(e.includes("|"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected 4+ parts separated by |, got ${t.length}`);const[n,r,o,...i]=t;if(!n||!r||!o)throw new Error("Collection, category, and type must be non-empty");const s=i.join("|");if(!s)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:r,type:o,additionalKey:s}}catch(t){const n=e.split("|");throw new Y(`Invalid pipe-delimited token: "${e}" (${n.length} parts). Expected format: "collection|category|type|additionalKey" (4 parts minimum). Received: [${n.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_PIPE_DELIMITED_TOKEN")}}(e);if(e.includes("$"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected 4+ parts separated by $, got ${t.length}`);const n=t[t.length-1],r=t[t.length-2],o=t[t.length-3],i=t.slice(0,t.length-3).join("$");if(!(i&&o&&r&&n))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:o,type:r,additionalKey:n}}catch(t){const n=e.split("$");throw new Y(`Invalid dollar-delimited token: "${e}" (${n.length} parts). Expected format: "collection$category$type$additionalKey" (4 parts minimum). Received: [${n.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e);throw new Y(`Plain token string "${e}" (length: ${e.length}) is not allowed - tokens must be delimited with | or $. Expected format: "GALA|Unit|none|none" or "GALA$Unit$none$none". Input: "${e}"`,"token","PLAIN_STRING_NOT_ALLOWED")}class Ro extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function Fo(e){return"object"==typeof e&&null!==e&&"collection"in e&&"category"in e&&"type"in e&&"additionalKey"in e&&"string"==typeof e.collection&&"string"==typeof e.category&&"string"==typeof e.type&&"string"==typeof e.additionalKey}function Lo(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&Fo(t.token0ClassKey)&&Fo(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickLower&&"number"==typeof t.tickUpper&&"string"==typeof t.liquidity&&"string"==typeof t.feeGrowthInside0Last&&"string"==typeof t.feeGrowthInside1Last&&"string"==typeof t.tokensOwed0&&"string"==typeof t.tokensOwed1}class Oo{constructor(t){this.client=e.create({baseURL:t.baseUrl,timeout:t.timeout??3e4})}async getPoolData(e){try{if("string"==typeof e.token0||"string"==typeof e.token1)throw new Error(`GalaChain API getPoolData requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getPoolData(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`);const t=await this.client.post("/api/asset/dexv3-contract/GetPoolData",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.token0&&"string"==typeof t.token1&&Fo(t.token0ClassKey)&&Fo(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickSpacing&&"string"==typeof t.liquidity&&"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.feeGrowthGlobal0&&"string"==typeof t.feeGrowthGlobal1}(n))throw new Ro(t.status,"Invalid pool data response format",n);return n}catch(e){throw this.handleError(e,"getPoolData")}}async getPositions(e){try{const t=await this.client.post("/api/asset/dexv3-contract/GetPositions",e);this.validateResponse(t.data);const n=t.data.Data;let r;r=n&&"object"==typeof n&&"positions"in n&&Array.isArray(n.positions)?n.positions:n&&"object"==typeof n&&"positionId"in n?[n]:Array.isArray(n)?n:[];for(const e of r)if(!Lo(e))throw new Ro(t.status,"Invalid position in response",e);return{positions:r,count:r.length}}catch(e){throw this.handleError(e,"getPositions")}}async getPositionById(e,t,n,r,o,i,s){try{let a,c;if(void 0!==t&&void 0!==n&&void 0!==r&&void 0!==o&&void 0!==i){a={owner:e,token0:"string"==typeof t?{collection:t,category:"Unit",type:"none",additionalKey:"none"}:t,token1:"string"==typeof n?{collection:n,category:"Unit",type:"none",additionalKey:"none"}:n,fee:r,tickLower:o,tickUpper:i},s&&(a.positionId=s),c=`${e}/${t}/${n}/${r}`}else a={positionId:e},c=e;const u=await this.client.post("/api/asset/dexv3-contract/GetPositions",a);this.validateResponse(u.data);const l=u.data.Data;let h;if(l&&"object"==typeof l&&"positionId"in l&&!("positions"in l))h=l;else{if(!(l&&Array.isArray(l.positions)&&l.positions.length>0))throw new Ro(404,`Position not found: ${c}`);h=l.positions[0]}const d={Data:h,Status:u.status};return void 0!==u.data.Message&&(d.Message=u.data.Message),d}catch(t){throw this.handleError(t,`getPositionById(${e})`)}}async getRemoveLiquidityEstimation(e){try{const t=await this.client.post("/api/asset/dexv3-contract/GetRemoveLiquidityEstimation",e);this.validateResponse(t.data);const n=t.data.Data;if("string"!=typeof n.amount0||"string"!=typeof n.amount1)throw new Ro(t.status,"Invalid removal estimation response format",n);return n}catch(e){throw this.handleError(e,"getRemoveLiquidityEstimation")}}validateResponse(e){if(!e||"object"!=typeof e)throw new Ro(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new Ro(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new Ro(e.Status,e.Message??"Gateway error",e.Data)}handleError(t,n){if(t instanceof Ro)return t;if(e.isAxiosError(t)){const e=t.response?.status??500,r=t.response?.data?.Message??t.message,o=t.response?.data?.Data??void 0;return new Ro(e,`${n}: ${r}`,o)}return new Ro(500,`${n}: ${t instanceof Error?t.message:String(t)}`)}}class Mo{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){try{if(!e||"string"!=typeof e)throw new Ro(400,"Invalid wallet address");const r=Math.max(1,Math.floor(n/t)+1),o={};o.address=e,o.page=r,o.limit=t;const i=await this.http.get("/user/assets",o);if(!i||"object"!=typeof i)throw new Ro(500,"Invalid response format: not an object");const s=i.data;if(!s||"object"!=typeof s)throw new Ro(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new Ro(500,"Invalid response format: token array must be an array");const c=[];for(const e of a){if("object"!=typeof e||null===e)throw new Ro(500,"Invalid asset in response: asset must be an object");const t=e;if("string"!=typeof t.symbol||"string"!=typeof t.name)throw new Ro(500,"Invalid asset in response: missing symbol or name",t);const n="number"==typeof t.decimals?t.decimals:"string"==typeof t.decimals?parseInt(t.decimals,10):void 0;if("number"!=typeof n||isNaN(n))throw new Ro(500,"Invalid asset in response: decimals must be a number",t);const r={tokenId:t.compositeKey||`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:n,balance:t.quantity||"0"};t.image&&(r.imageUrl=t.image),t.verify&&(r.verified=t.verify),c.push(r)}const u={tokens:c,count:s.count??c.length};return void 0!==s.totalValue&&(u.totalValue=s.totalValue),u}catch(t){throw this.handleError(t,`getUserAssets(${e})`)}}async fetchTokenList(e={}){try{const{address:t,search:n,page:r=1,limit:o=20}=e,i={page:r,limit:Math.min(o,20)};t&&(i.address=t),n&&(i.search=n);const s=await this.http.get("/user/token-list",i);if(!s||"object"!=typeof s)throw new Ro(500,"Invalid response format: not an object");const a=s.data;if(!a||"object"!=typeof a)throw new Ro(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new Ro(500,"Invalid response format: token array must be an array");const u=[];for(const e of c){if("object"!=typeof e||null===e)throw new Ro(500,"Invalid token in response: must be an object");const t=e;if("string"!=typeof t.symbol||""===t.symbol.trim())throw new Ro(500,'Invalid token in response: missing required field "symbol"',{token:t});if("string"!=typeof t.name)throw new Ro(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new Ro(500,'Invalid token in response: missing required field "decimals"',{token:t});if("string"!=typeof t.compositeKey||""===t.compositeKey.trim())throw new Ro(500,'Invalid token in response: missing required field "compositeKey"',{token:t});u.push({image:"string"==typeof t.image?t.image:"",name:t.name,symbol:t.symbol,decimals:String(n),description:"string"==typeof t.description?t.description:"",verify:"boolean"==typeof t.verify&&t.verify,compositeKey:t.compositeKey,additionalKey:"string"==typeof t.additionalKey?t.additionalKey:"",category:"string"==typeof t.category?t.category:"",type:"string"==typeof t.type?t.type:"",collection:"string"==typeof t.collection?t.collection:"",subscribePrice:"boolean"==typeof t.subscribePrice&&t.subscribePrice,quantity:"string"==typeof t.quantity?t.quantity:"0"})}return{token:u,count:"number"==typeof a.count?a.count:u.length}}catch(e){throw this.handleError(e,"fetchTokenList")}}handleError(e,t){if(e instanceof Ro)return e;if(e instanceof Error&&e instanceof Error&&"response"in e){const n=e,r=n.response?.status??500,o=n.response?.data?.message??n.response?.data?.Message??n.message,i=n.response?.data?.Data??n.response?.data?.data??void 0;return n.response,new Ro(r,`${t}: ${o}`,i)}return new Ro(500,`${t}: ${e instanceof Error?e.message:String(e)}`)}}function $o(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected at least 4 parts separated by |, got ${t.length}`);const[n,r,o,...i]=t;if(!n||!r||!o)throw new Error("Collection, category, and type must be non-empty");const s=i.join("|");if(!s)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:r,type:o,additionalKey:s}}catch(t){throw new Y(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}const qo=20,Ko=10;class Go extends zn{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new Ir,this.webSocketService=t,this.dexQuoteService=n,this.getWalletAddress=e.getWalletAddress,this.galaChainBaseUrl=e.galaChainBaseUrl,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.privateKey=e.privateKey,!(e.gatewayBaseUrl&&e.bundlerBaseUrl&&e.dexBackendBaseUrl&&e.dexBackendHttp))throw new Error("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.");try{this.gatewayClient=new Oo({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new Mo(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{gatewayUrl:e.gatewayBaseUrl,dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new Error("Failed to initialize GSwapService HTTP clients")}}setPricingConcurrency(e){if(e<1)throw new Error("Pricing concurrency must be at least 1");e>100&&this.logger.warn("Pricing concurrency > 100 may cause performance issues",{concurrency:e}),this.pricingConcurrency=e,this.logger.debug("Updated pricing concurrency",{concurrency:this.pricingConcurrency})}async getSwapQuoteExactInput(e){try{if(new y(e.amount).isLessThanOrEqualTo(0))throw new ne("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new ne("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,o]=t<n?[t,n]:[n,t],i=[3e3,500,1e4];let s;for(const a of i)try{const i=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:o,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:i,fromToken:t,toToken:n,amount:e.amount}),c=new y(s.currentSqrtPrice),u=new y(s.newSqrtPrice),l=c.gt(u)?c.minus(u).dividedBy(c):new y(0),h=new y(s.amount0),d=new y(s.amount1),f=h.isNegative(),p=d.isNegative();this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":s.amount0,"quoteResult.amount1":s.amount1,"amount0BN.isNegative()":f,"amount1BN.isNegative()":p});const g=f?h:d;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:f,selectedAmount:g.toFixed(),selectedAmountAbs:g.absoluteValue().toFixed()});const m=g.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:m,feeTier:a,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,m),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e instanceof Error?e.message:"Unknown error"})}throw s||new ne("No available fee tiers for quote",{feeTiers:i,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",ne,e)}}async getSwapQuoteExactOutput(e){try{if(new y(e.amount).isLessThanOrEqualTo(0))throw new ne("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new ne("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact output",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,o]=t<n?[t,n]:[n,t],i=[3e3,500,1e4];let s;for(const a of i)try{const i=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:o,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:i,fromToken:t,toToken:n,amount:e.amount}),c=new y(s.currentSqrtPrice),u=new y(s.newSqrtPrice),l=c.gt(u)?c.minus(u).dividedBy(c):new y(0),h=i.pool.token0,d="string"==typeof h?h.split("|")[0]:"object"==typeof h&&null!==h&&"tokenName"in h?h.tokenName:String(h),f=n.split("|")[0]===d?s.amount1:s.amount0;return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:f,estimatedOutput:e.amount,feeTier:a,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(f,e.amount),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e instanceof Error?e.message:"Unknown error"})}throw s||new ne("No available fee tiers for quote",{feeTiers:i,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",ne,e)}}async executeSwap(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");this.logger.debug("Executing swap",{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),r=function(e,t=.01){const n=wr(e),r=new y(1).minus(t);return n.multipliedBy(r)}(e.estimatedOutput,e.slippageTolerance||.01),o=this.getWalletAddress();if(!o)throw new Error("Wallet address required for swap execution");let i;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});i=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:i,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:t instanceof Error?t.message:String(t)})}const s={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:r.toFixed(),feeTier:e.feeTier,walletAddress:o,slippageTolerance:e.slippageTolerance||.01};void 0!==i&&(s.currentSqrtPrice=i);const a=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:a,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const c=await this.webSocketService.waitForTransaction(a);return{transactionId:c.transactionId,status:c.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(c.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",re,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){try{if(!we(e))throw new ie(`Invalid wallet address format: "${e}". Expected format: "0x...", "eth|...", or "client|..."`,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching user assets",{walletAddress:e,page:t,limit:n});return(await this.dexBackendClient.fetchTokenList({address:e,page:t,limit:n})).token.filter(e=>"0"!==e.quantity).map(e=>this.transformRawTokenToUserAsset(e)).filter(e=>null!==e)}catch(r){this.handleGSwapError("Failed to fetch user assets",ie,r,{walletAddress:e,page:t,limit:n})}}async getAllUserAssets(e){try{if(!we(e))throw new ie(`Invalid wallet address format: "${e}". Expected format: "0x...", "eth|...", or "client|..."`,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching all user assets (auto-paginated with optimization)",{walletAddress:e});const t=[];let n=1;const r=20;let o=!0;for(;o&&n<=qo;){const i=await this.dexBackendClient.fetchTokenList({address:e,page:n,limit:r});let s=!1;for(const e of i.token){if("0"===e.quantity){s=!0;break}const n=this.transformRawTokenToUserAsset(e);n&&t.push(n)}o=!s&&i.token.length===r,n++}return n>qo&&this.logger.warn("Reached maximum page limit (20) while fetching user assets",{walletAddress:e,totalAssets:t.length}),this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:t.length}),t}catch(t){this.handleGSwapError("Failed to fetch all user assets",ie,t,{walletAddress:e})}}async fetchAvailableDexTokens(e={}){try{const{search:t,page:n=1,limit:r=20}=e;this.logger.debug("Fetching available DEX tokens",{search:t,page:n,limit:r});const o=await this.dexBackendClient.fetchTokenList({...void 0!==t&&{search:t},page:n,limit:r});return{tokens:o.token.map(e=>this.transformRawTokenToDexToken(e)),count:o.count,page:n,limit:r,hasMore:n*r<o.count}}catch(t){this.handleGSwapError("Failed to fetch available DEX tokens",ie,t,{...e})}}async fetchAllAvailableDexTokens(e={}){try{const{search:t}=e;this.logger.debug("Fetching all available DEX tokens (auto-paginated)",{search:t});const n=[];let r=1;const o=20;let i=!0;for(;i&&r<=qo;){const e=await this.dexBackendClient.fetchTokenList({...void 0!==t&&{search:t},page:r,limit:o});for(const t of e.token)n.push(this.transformRawTokenToDexToken(t));i=e.token.length===o,r++}return r>qo&&this.logger.warn("Reached maximum page limit (20) while fetching available DEX tokens",{search:t,totalTokens:n.length}),this.logger.debug("Fetched all available DEX tokens",{search:t,totalTokens:n.length}),n}catch(t){this.handleGSwapError("Failed to fetch all available DEX tokens",ie,t,e)}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),o=[500,3e3,1e4];let i=new y(0),s=0;for(const a of o)try{const e="string"==typeof n?Do(n):n,t="string"==typeof r?Do(r):r,o=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});o&&(i=i.plus(new y(o.liquidity||0)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:i.toFixed(),feeTiers:o,swapCount:s}}catch(n){this.logger.warn("Failed to fetch pool info",n);const r=n;return this.logger.debug("Pool error details",{error:new oe(`Failed to fetch pool info: ${r?.message||String(n)}`,n,e,t,this.extractGSwapErrorCode(n))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const n=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;n.has(e)||n.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const r=Array.from(n.values()),o=this.chunkArray(r,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:o.length,concurrency:t});const i=new Map;for(let e=0;e<o.length;e++){const t=o[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?i.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return i}normalizePositionResponse(e,t){const n=e=>{if(!e)return"";if("string"==typeof e)return e;if("object"==typeof e){if(e.type&&"none"!==e.type)return e.type;if(e.collection)return e.collection;if(e.symbol)return e.symbol;if(e.tokenSymbol)return e.tokenSymbol;if(e.name)return e.name}return""},r=e.token0Symbol||n(e.token0)||n(e.tokenA)||e.tokenSymbol0||"",o=e.token1Symbol||n(e.token1)||n(e.tokenB)||e.tokenSymbol1||"",i=r?this.tokenConverter.toLaunchpadFormat(r):"",s=o?this.tokenConverter.toLaunchpadFormat(o):"";return{positionId:e.positionId||e.id||"",ownerAddress:t||e.ownerAddress||e.owner||"",token0:i,token1:s,feeTier:e.feeTier||e.fee||e.feeAmount||0,tickLower:e.tickLower||e.lowerTick||0,tickUpper:e.tickUpper||e.upperTick||0,liquidity:String(e.liquidity||e.liquidityAmount||"0"),amount0:String(e.amount0||e.amountA||"0"),amount1:String(e.amount1||e.amountB||"0"),feeAmount0:String(e.feeAmount0||e.feesA||"0"),feeAmount1:String(e.feeAmount1||e.feesB||"0"),...e.createdAt&&{createdAt:new Date(e.createdAt)},...e.updatedAt&&{updatedAt:new Date(e.updatedAt)}}}parseTokenFlexible(e){try{return Do(e)}catch(t){if(t instanceof Error&&t.message?.includes("Plain token string"))return this.logger.debug("Using default TokenClassKey for simple token symbol",{token:e}),{collection:"Token",category:"Unit",type:e,additionalKey:"none"};throw t}}transformRawTokenToDexToken(e){return{image:e.image,name:e.name,symbol:e.symbol,decimals:parseInt(e.decimals,10)||18,description:e.description,verified:e.verify,compositeKey:e.compositeKey,additionalKey:e.additionalKey,category:e.category,type:e.type,collection:e.collection,subscribePrice:e.subscribePrice}}transformRawTokenToUserAsset(e){const t=e.symbol||"UNKNOWN";try{const o=e.compositeKey?Do(e.compositeKey.replace(/\$/g,"|")):Do(`${t}|Unit|none|none`);return{...this.transformRawTokenToDexToken(e),tokenId:o,balance:(n=e.quantity||"0",void 0!==r?wr(n).toFixed(r):wr(n).toFixed())}}catch(e){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:e instanceof Error?e.message:String(e)}),null}var n,r}async getUserLiquidityPositions(t,n=10,r,o){try{this.logger.debug("Fetching user liquidity positions",{ownerAddress:t,limit:n,bookmark:r});const i=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,s={user:t,limit:n,bookmark:r||""};this.logger.debug("Sending position query request",{endpoint:i,payload:s});const a=await e.post(i,s,{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==a.status||1!==a.data?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:a.status,apiStatus:a.data?.Status}),{items:[]};const c=a.data.Data||{},u=c.positions||[],l=c.nextBookMark,h=u.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(e=>this.normalizePositionResponse(e,t));let d;this.logger.debug("Retrieved liquidity positions",{count:h.length,hasNextBookmark:!!l,nextBookmark:l}),o?.withPrices&&h.length>0&&(d=await this.fetchPositionPrices(h));const f={items:h};return void 0!==l&&(f.nextBookmark=l),void 0!==d&&(f.prices=d),f}catch(e){if(e&&"object"==typeof e&&"response"in e){const n=e;this.logger.error("Position query failed with HTTP error",{status:n.response?.status,statusText:n.response?.statusText,data:n.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:t})}this.handleGSwapError("Failed to fetch user liquidity positions",se,e)}}async getAllSwapUserLiquidityPositions(e,t){try{this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const n=async t=>{const n=await this.getUserLiquidityPositions(e,Ko,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},r=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:o=20}=t,i=[];let s,a=0;for(;a<n;){r&&r.debug(`Auto-pagination (bookmark): fetching page ${a+1} with pageSize ${o}`,{bookmark:s});const t=await e(s,o);let n,c,u;if(Array.isArray(t))n=t,c=void 0,u=!1;else{if(!t||"object"!=typeof t||!("items"in t)){r&&r.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}n=t.items,c=t.nextBookmark,u=!0}if(!Array.isArray(n)){r&&r.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===n.length){r&&r.debug(`Auto-pagination (bookmark): no items returned on page ${a+1}, exiting loop`);break}i.push(...n),a++,r&&r.debug(`Auto-pagination (bookmark): page ${a} returned ${n.length} items`,{hasNextBookmark:!!c,format:u?"BookmarkPaginationResult":"legacy-array"});const l=n.length<o;if(u&&(""===c||void 0===c)){r&&r.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(l){r&&r.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:n.length,pageSize:o,format:u?"BookmarkPaginationResult":"legacy-array"});break}s=c}return a>=n&&r&&r.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${n}, stopping iteration`),r&&r.debug(`Auto-pagination (bookmark): completed with total items: ${i.length}`,{pageCount:a}),{items:i,total:i.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:Ko}),o=r.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:o.length}),t?.withPrices&&o.length>0){return{items:o,prices:await this.fetchPositionPrices(o)}}return o}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",se,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1),o=$o(n),i=$o(r),s=(await this.gatewayClient.getPositions({owner:e,token0:o,token1:i,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new Error("Invalid position data returned from API");const a=this.normalizePositionResponse(s,e);return this.logger.debug("Retrieved liquidity position",{positionId:a.positionId}),a}catch(e){this.handleGSwapError("Failed to fetch liquidity position",se,e)}}async getLiquidityPositionById(e,t,n,r,o,i,s){try{let a;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:!!n,hasToken1:!!r,hasFee:!!o,hasTickLower:void 0!==i,hasTickUpper:void 0!==s});let c=null;const u=5,l=2e3;for(let h=1;h<=u;h++)try{if(n&&r&&void 0!==o&&void 0!==i&&void 0!==s)try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:n,token1:r,feeTier:o,tickLower:i,tickUpper:s});if(a=(await this.gatewayClient.getPositionById(e,n,r,o,i,s,t)).Data,a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position via compound key",{attempt:h,positionId:t});break}throw new Error("Invalid position data from compound key lookup")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:h,error:e instanceof Error?e.message:e})}try{if(a=(await this.gatewayClient.getPositionById(t)).Data,a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position on attempt",{attempt:h,positionId:t});break}throw new Error("Invalid position data from direct lookup")}catch(n){this.logger.debug("Direct position lookup failed, trying fallback via GetUserPositions",{attempt:h,positionId:t,error:n instanceof Error?n.message:n});const r=await this.getUserLiquidityPositions(e,10);if(Array.isArray(r.items)&&r.items.length>0){const e=r.items.find(e=>(e.positionId||e.id||"").toLowerCase()===t.toLowerCase());if(e){a=e,this.logger.debug("Found position via fallback (GetUserPositions)",{attempt:h,positionId:t});break}}if(c=new Error("Position not found in owner positions"),h<u){this.logger.warn("Fallback query did not find position, retrying",{attempt:h,positionId:t,ownerAddress:e,foundCount:Array.isArray(r?.items)?r.items.length:0}),await new Promise(e=>setTimeout(e,l));continue}}}catch(e){if(h<u){this.logger.warn("Error fetching position, retrying",{attempt:h,positionId:t,error:e instanceof Error?e.message:e}),await new Promise(e=>setTimeout(e,l));continue}c=e instanceof Error?e:new Error(String(e))}if(!a||"object"!=typeof a||!("positionId"in a)&&!("id"in a))throw this.logger.error("Invalid position data returned from API after retries",{positionId:t,resultType:typeof a,resultKeys:a?Object.keys(a):"null",resultValue:JSON.stringify(a),lastError:c?.message}),c||new Error("Invalid position data returned from API");const h=this.normalizePositionResponse(a,e);return this.logger.debug("Retrieved liquidity position by ID",{positionId:h.positionId}),h}catch(e){this.handleGSwapError("Failed to fetch liquidity position by ID",se,e)}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t="string"==typeof e.token0?this.parseTokenFlexible(e.token0):e.token0,n={token0:t,token1:"string"==typeof e.token1?this.parseTokenFlexible(e.token1):e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner},r=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetPositions`;this.logger.debug("Calling position endpoint via compound key",{url:r});const o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!o.ok){if(404===o.status)throw new Error("Position not found (HTTP 404): No position exists for this compound key");if(400===o.status)throw new Error("Invalid parameters (HTTP 400): Check token format, fee (500|3000|10000), and tick ranges");throw new Error(`HTTP ${o.status}: ${o.statusText}`)}const i=await o.json();if(1!==i.Status||!i.Data)throw new Error(`Position not found: ${i.Message||"API returned no position data"}`);const s=this.normalizePositionResponse(i.Data,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:s.positionId,token0:s.token0,token1:s.token1}),s}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",se,e)}}async estimateRemoveLiquidity(e){try{this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1,owner:e.owner}),this.validateTickSpacing(e.tickLower,e.tickUpper,e.fee);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1),r=$o(t),o=$o(n),i=await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:o,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});return this.logger.debug("Estimated removal",{result:i}),i}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",se,e)}}async addLiquidityByPrice(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected(),this.logger.debug("Converting price range to ticks",{token0:e.token0,token1:e.token1,minPrice:e.minPrice,maxPrice:e.maxPrice,fee:e.fee});const r=Do(t),o=Do(n),i=(await this.gatewayClient.getPoolData({token0:r,token1:o,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:i,fee:e.fee});const s=new y(e.minPrice),a=new y(e.maxPrice),c=Math.floor(kr(s)),u=Math.ceil(kr(a)),l=Math.floor(c/i)*i,h=Math.ceil(u/i)*i;this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:l,tickUpper:h,tickSpacing:i});const d=this.getWalletAddress();if(!d)throw new Error("GSwapService: No wallet address available - cannot create position");const f="string"==typeof e.token0?Do(e.token0):e.token0,p="string"==typeof e.token1?Do(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${l}-${h}`,walletAddress:d});const g=await this.sendAddLiquidityToBundler({token0:f,token1:p,fee:e.fee,tickLower:l,tickUpper:h,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:d}),m={transactionId:g};if(m.positionId&&g){this.logger.debug("Position ID returned directly from backend",{transactionId:g,positionId:m.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(g);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:g,status:e.status});const t=this.getWalletAddress();if(t&&m.positionId)try{const n=await this.getLiquidityPositionById(t,m.positionId),{createdAt:r,updatedAt:o,...i}=n,s=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,a={...m,...i,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(g)}};return void 0!==s&&(a.createdAt=s),a}catch(t){return{...m,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(g)}}}}if(g){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:g}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(g);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:g,status:t.status});let r=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");const o=(await this.getUserLiquidityPositions(t,10)).items;if(o&&o.length>0){const t=e.token0.split("|")[0].toUpperCase(),i=e.token1.split("|")[0].toUpperCase(),s=[];for(const n of o){if(!n||!n.positionId)continue;const r=n.token0?.toUpperCase(),o=n.token1?.toUpperCase();if(!r||!o)continue;const a=r===t&&o===i||r===i&&o===t,c=n.feeTier===e.fee;a&&c&&s.push(n)}s.length>0&&(r=s[s.length-1],n=r.positionId,this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:o.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}let o=r;if(n)try{o=await this.getLiquidityPositionById(d,n)}catch(e){}return{...m,...o,positionId:n,status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(g)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),m}catch(e){Error,this.handleGSwapError("Failed to add liquidity by price",se,e)}}async addSwapLiquidityByTicks(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");const t=this.getWalletAddress();if(!t)throw new Error("GSwapService: No wallet address available - cannot create position");this.logger.debug("Adding liquidity by ticks with direct bundler",{token0:e.token0,token1:e.token1,fee:e.fee,walletAddress:t,tickRange:`${e.tickLower}-${e.tickUpper}`});const n="string"==typeof e.token0?Do(e.token0):e.token0,r="string"==typeof e.token1?Do(e.token1):e.token1;await this.ensureWebSocketConnected();const o=await this.sendAddLiquidityToBundler({token0:n,token1:r,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:t});this.logger.info("Liquidity transaction submitted to bundler",{transactionId:o});const i=this.webSocketService.waitForTransaction(o),s={transactionId:o};if(s.positionId&&o){this.logger.info("Position ID returned directly from backend",{transactionId:o,positionId:s.positionId});const e=await i;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:o,status:e.status});const t=this.getWalletAddress();if(t&&s.positionId)try{this.logger.debug("Fetching full position details",{positionId:s.positionId});const n=await this.getLiquidityPositionById(t,s.positionId);this.logger.debug("Fetched full position data",{positionId:n.positionId,liquidity:n.liquidity,amount0:n.amount0,amount1:n.amount1});const{createdAt:r,updatedAt:i,...a}=n,c=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,u={...s,...a,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(o)}};return void 0!==c&&(u.createdAt=c),u}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:t instanceof Error?t.message:String(t)}),{...s,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(o)}}}}if(o){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:o});const n=await i;let r;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:o,status:n.status});let a=null;const c="string"==typeof e.token0?e.token0:e.token0?.type??"unknown",u="string"==typeof e.token1?e.token1:e.token1?.type??"unknown";this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:u,fee:e.fee});try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:Ko});const n=3,o=5e3,i=3e3;let s=[];for(let c=1;c<=n;c++){const u=1===c?o:i;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:n,delayMs:u}),await new Promise(e=>setTimeout(e,u)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:Ko});if(s=(await this.getUserLiquidityPositions(t,Ko)).items,this.logger.debug("Got positions from API",{count:s?.length||0}),s&&s.length>0){const t=("string"==typeof e.token0?e.token0.split("|")[0]:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?e.token1.split("|")[0]:e.token1.collection).toUpperCase(),o=[];for(const r of s){if(!r||!r.positionId)continue;const i=r.token0?.toUpperCase(),s=r.token1?.toUpperCase();if(!i||!s){this.logger.debug("Skipping position with empty tokens",{positionId:r.positionId});continue}const a=i===t&&s===n||i===n&&s===t,c=r.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:r.positionId,tokens:`${i}/${s}`,tokensMatch:a,fee:r.feeTier,feeMatches:c}),a&&c&&o.push(r)}if(o.length>0){a=o[o.length-1],r=a.positionId,this.logger.info("Found newly created position",{positionId:r,liquidity:a.liquidity,amount0:a.amount0,amount1:a.amount1,fee:a.feeTier}),this.logger.debug("Found newly created position",{positionId:r,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:s.length});break}this.logger.debug("No matching position found in this attempt")}else this.logger.debug("No positions returned from API in this attempt")}}catch(e){this.logger.error("Error fetching positions during discovery",{error:e instanceof Error?e.message:String(e)}),this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}this.logger.debug("Position discovery complete",{positionId:r||"not found",found:!!r}),this.logger.debug("Matched position data",{positionId:a?.positionId,liquidity:a?.liquidity,amount0:a?.amount0,amount1:a?.amount1,feeAmount0:a?.feeAmount0,feeAmount1:a?.feeAmount1,token0:a?.token0,token1:a?.token1,feeTier:a?.feeTier});let l=a;if(r)try{this.logger.debug("Fetching full position details",{positionId:r}),l=await this.getLiquidityPositionById(t,r),this.logger.debug("Fetched full position data",{positionId:l.positionId,liquidity:l.liquidity,amount0:l.amount0,amount1:l.amount1,feeAmount0:l.feeAmount0,feeAmount1:l.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:r,error:e instanceof Error?e.message:String(e)})}return{...s,...l,positionId:r,status:n.status,transactionId:n.transactionId,timestamp:new Date(n.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(o)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),s}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",se,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let r;try{const o=await t;r={status:o.status,transactionId:o.transactionId||e,timestamp:o.timestamp||Date.now(),data:o.data},this.logger.debug(`${n} transaction confirmed on-chain`,{transactionId:e,status:r.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${n} transaction, returning result with transaction ID`,{transactionId:e,error:t instanceof Error?t.message:String(t)}),{transactionId:e,status:"SUBMITTED",timestamp:new Date,wait:async t=>{try{await this.webSocketService.waitForTransaction(e)}catch{this.logger.debug("Explicit wait also timed out",{transactionId:e})}}}}return{transactionId:r.transactionId,status:r.status,timestamp:new Date(r.timestamp),wait:async t=>{await this.webSocketService.waitForTransaction(e)}}}async removeLiquidity(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});try{const t=parseFloat(e.liquidity);if(isNaN(t))throw new Error(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${e.positionId||"unknown"}`);if(0===t)throw new Error(`Cannot remove zero liquidity from position. This would waste gas fees without any effect. Position ID: ${e.positionId||"unknown"}`)}catch(e){if(e instanceof Error&&e.message.includes("Cannot remove zero liquidity"))throw e;if(e instanceof Error&&e.message.includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?Do(e.token0):e.token0,n="string"==typeof e.token1?Do(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,n,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||"");this.logger.debug("Liquidity removal submitted to bundler",{transactionId:r});const o=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,o,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",se,e)}}async collectPositionFees(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");if(e.ownerAddress&&e.positionId&&!e.token0){this.logger.debug("Fetching position data before collecting fees",{ownerAddress:e.ownerAddress,positionId:e.positionId});const t=await this.getLiquidityPositionById(e.ownerAddress,e.positionId);if(!t)throw new Error(`Position ${e.positionId} not found for owner ${e.ownerAddress}`);if(!t.token0||!t.token1)throw new Error("Position missing token information");const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1);return this.collectPositionFees({token0:n,token1:r,fee:t.feeTier,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Requested:e.amount0Max||e.amount0Requested||"0",amount1Requested:e.amount1Max||e.amount1Requested||"0",positionId:e.positionId})}if(!e.token0||!e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper)throw new Error("Missing required parameters: token0, token1, fee, tickLower, tickUpper are required when not using ownerAddress pattern");this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0?.type??"unknown",token1:"string"==typeof e.token1?e.token1:e.token1?.type??"unknown",tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?Do(e.token0):e.token0,n="string"==typeof e.token1?Do(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendCollectPositionFeesToBundler(t,n,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||"");this.logger.debug("Fee collection submitted to bundler",{transactionId:r});const o=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,o,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",se,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:r,gswapToken1:o}=this.convertTokenPair(e,t),i=Do(r),s=Do(o),a=await this.gatewayClient.getPoolData({token0:i,token1:s,fee:n}),c=this.calculatePriceFromSqrtPriceX96(new y(a.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:n,liquidity:a.liquidity.toString(),sqrtPriceX96:a.sqrtPrice.toString(),tick:a.tick,feeGrowthGlobal0X128:a.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:a.feeGrowthGlobal1.toString(),currentPrice:c.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",oe,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const r=await this.getPoolData(e,t,n),o=wr(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:o.toFixed(),invertedPrice:vr(o,!0),tick:r.tick,liquidity:r.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",oe,e)}}async calculateOptimalPositionSize(e,t,n,r,o,i,s){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:r,desiredAmount1:o});const a=(await this.getPoolData(e,t,n)).tick,c=w(i),u=w(a),l=w(s),h=b(new y(r),new y(o),c,u,l),d=k(h,u,c,l),f=d[0],p=d[1],g=new y(r),m=new y(o);return{amount0:f.toFixed(),amount1:p.toFixed(),liquidity:h.toFixed(),ratio:f.dividedBy(p).toFixed(),utilizationPercent:{amount0:f.dividedBy(g).multipliedBy(100).toFixed(2),amount1:p.dividedBy(m).multipliedBy(100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",se,e)}}async validatePositionParameters(e,t,n,r,o,i,s){const a=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:r,tickUpper:o});const u=[500,3e3,1e4];u.includes(n)||a.push(`Invalid fee tier: ${n}. Must be one of: ${u.join(", ")}`);const l=this.getTickSpacing(n);let h;r%l!==0&&a.push(`tickLower must be multiple of ${l}`),o%l!==0&&a.push(`tickUpper must be multiple of ${l}`),r>=o&&a.push(`tickLower (${r}) must be less than tickUpper (${o})`);try{h=await this.getPoolData(e,t,n)}catch{return a.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}const d=new y(i),f=new y(s);if(d.isNaN()||f.isNaN())a.push("Amounts must be valid numbers");else try{Sr(d,f)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}const p=h.tick;(p<r||p>o)&&c.push("Position is out of current price range - will not earn fees until price moves into range");new y(h.liquidity||"0").lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const g=0===a.length?35e4:0;return{valid:0===a.length,errors:a,warnings:c,gasEstimate:g,tickSpacing:l,currentTick:p,poolLiquidity:h.liquidity}}catch(e){const t=e;return a.includes(t?.message||"")||a.push(`Validation failed: ${t?.message||String(e)}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}}async calculateTicksForPrice(e,t,n,r,o){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:r});const i=this.getTickSpacing(o),s=new y(n),a=new y(r);if(s.gte(a))throw new Error("minPrice must be less than maxPrice");const c=Math.floor(kr(s)),u=Math.ceil(kr(a)),l=Math.floor(c/i)*i,h=Math.ceil(u/i)*i,d=Math.pow(1.0001,l),f=Math.pow(1.0001,h),p=new y(d),g=new y(f);return{tokenA:e,tokenB:t,feeTier:o,tickLower:l,tickUpper:h,tickSpacing:i,requestedMinPrice:n,requestedMaxPrice:r,actualMinPrice:p.toFixed(8),actualMaxPrice:g.toFixed(8),priceDeviation:{minPriceDeviation:p.minus(s).dividedBy(s).multipliedBy(100).toFixed(4),maxPriceDeviation:g.minus(a).dividedBy(a).multipliedBy(100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",se,e)}}async calculatePriceForTicks(e,t,n,r){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:r});const o=Math.pow(1.0001,n),i=Math.pow(1.0001,r);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const a=new y(o),c=new y(i),u={tokenA:e,tokenB:t,tickLower:n,tickUpper:r,minPrice:a.toFixed(8),maxPrice:c.toFixed(8),priceRange:`${a.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:r-n};return void 0!==s&&(u.currentPrice=s),u}catch(e){this.handleGSwapError("Failed to calculate price for ticks",se,e)}}calculateExecutionPrice(e,t){try{const n=new y(e),r=new y(t);return n.isZero()?"0":r.dividedBy(n).toFixed()}catch{return"0"}}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw new Error(`Invalid fee tier: ${e}`)}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new Error(`Invalid tickLower: ${e} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`);if(t%r!==0)throw new Error(`Invalid tickUpper: ${t} must be a multiple of ${r} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`)}calculatePriceFromSqrtPriceX96(e){try{const t=new y(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new y(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return new y(0)}}async getPoolSlot0(t,n,r){try{this.logger.debug("Fetching pool slot0 data",{token0:t,token1:n,fee:r});const o="string"==typeof t?Do(t):t,i="string"==typeof n?Do(n):n,s=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetSlot0`,a=await e.post(s,{token0:o,token1:i,fee:r},{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==a.status||1!==a.data?.Status)throw this.logger.warn("Unexpected GetSlot0 API response",{httpStatus:a.status,apiStatus:a.data?.Status}),new oe("GetSlot0 API returned unexpected status",{httpStatus:a.status,apiStatus:a.data?.Status});const c=a.data.Data||{},u={sqrtPrice:c.sqrtPrice||"0",tick:c.tick||0,liquidity:c.liquidity||"0",grossPoolLiquidity:c.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:u.sqrtPrice,tick:u.tick,liquidity:u.liquidity}),u}catch(e){this.handleGSwapError("Failed to fetch pool slot0 data",oe,e,{token0:t,token1:n,fee:r})}}async getPositionCurrentPrice(e){try{this.logger.debug("Fetching position current price",{token0:e.token0,token1:e.token1,feeTier:e.feeTier});const t=await this.getPoolSlot0(e.token0,e.token1,e.feeTier),n=new y(t.sqrtPrice),r={price:this.calculatePriceFromSqrtPriceDecimal(n).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:r.price,tick:r.tick}),r}catch(t){this.handleGSwapError("Failed to fetch position current price",oe,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,n){try{const r=br(t),o=br(n);return v(e,r,o)}catch{return new y(0)}}calculateLiquidityFromAmount1(e,t,n){try{const r=br(t),o=br(n);return E(e,r,o)}catch{return new y(0)}}calculateAmount0FromLiquidity(e,t,n){try{const r=br(t),o=br(n);return S(r,o,e)}catch{return new y(0)}}calculateAmount1FromLiquidity(e,t,n){try{const r=br(t),o=br(n);return A(r,o,e)}catch{return new y(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(n){if(!this.privateKey)throw new Error("GSwapService: AddLiquidity requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:n.token0?.type??"unknown",token1:n.token1?.type??"unknown",fee:n.fee,tickRange:`${n.tickLower}-${n.tickUpper}`});const r=`galaswap - operation - ${F()}-${Date.now()}-${n.owner}`,o={token0:n.token0,token1:n.token1,fee:n.fee,owner:n.owner,tickLower:n.tickLower,tickUpper:n.tickUpper,amount0Desired:n.amount0Desired,amount1Desired:n.amount1Desired,amount0Min:n.amount0Min,amount1Min:n.amount1Min,positionId:"",uniqueKey:r},i=new t.Wallet(this.privateKey),s={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},a={name:"ethereum",chainId:1},c=this.calculatePersonalSignPrefix(o),u={...o,prefix:c},l=await i.signTypedData(a,s,u),h={...u,signature:l,types:s,domain:a};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:h.signature?.substring(0,20)+"...",prefix:h.prefix,tickLower:o.tickLower,tickUpper:o.tickUpper});const d=this.buildLiquidityStringsInstructions(n.token0,n.token1,n.fee,n.owner),f=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),p=await f.post("/bundle",{method:"AddLiquidity",signedDto:h,stringsInstructions:d}),g=p.data?.data||p.data?.transactionId||p.data?.id;if(!g)throw this.logger.error("Bundler response structure",{status:p.status,data:p.data,dataType:typeof p.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(p.data)}`);return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:g}),g}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(n,r,o,i,s,a,c,u,l){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const h=new t.Wallet(this.privateKey),d=await h.getAddress(),f=`galaswap - operation - ${F()}-${Date.now()}-${d}`,p={tickLower:n,tickUpper:r,amount:o,token0:i,token1:s,fee:a,amount0Min:c,amount1Min:u,positionId:l,uniqueKey:f},g={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},b=await h.signTypedData(m,g,w),k={...w,signature:b,types:g,domain:m},v=this.buildLiquidityStringsInstructions(i,s,a,d);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:n,tickUpper:r,amount:o,fee:a,positionId:l,transactionId:f});const E=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),S=await E.post("/bundle",{method:"RemoveLiquidity",signedDto:k,stringsInstructions:v}),A=S.data?.data||S.data?.transactionId||S.data?.id;if(!A)throw this.logger.error("Bundler response structure",{status:S.status,data:S.data,dataType:typeof S.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(S.data)}`);return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:A}),A}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(n,r,o,i,s,a,c,u){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const l=new t.Wallet(this.privateKey),h=await l.getAddress(),d=`galaswap - operation - ${F()}-${Date.now()}-${h}`,f={token0:n,token1:r,fee:o,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:u,uniqueKey:d},p={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},g={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(f),y={...f,prefix:m},w=await l.signTypedData(g,p,y),b={...y,signature:w,types:p,domain:g},k=this.buildLiquidityStringsInstructions(n,r,o,h);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:o,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:u,transactionId:d});const v=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),E=await v.post("/bundle",{method:"CollectPositionFees",signedDto:b,stringsInstructions:k}),S=E.data?.data||E.data?.transactionId||E.data?.id;if(!S)throw this.logger.error("Bundler response structure",{status:E.status,data:E.data,dataType:typeof E.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(E.data)}`);return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:S}),S}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(n){if(!this.privateKey)throw new Error("GSwapService: Swap requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const r=[500,3e3,1e4];if(!r.includes(n.feeTier))throw new Error(`GSwapService: Invalid fee tier ${n.feeTier}. Must be one of: ${r.join(", ")} (basis points)`);try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof n.fromToken?n.fromToken:n.fromToken?.type??"unknown",toToken:"string"==typeof n.toToken?n.toToken:n.toToken?.type??"unknown",inputAmount:n.inputAmount,minOutput:n.minOutput,feeTier:n.feeTier});let r=n.fromToken,o=n.toToken;"string"==typeof r&&(r=Do(r)),"string"==typeof o&&(o=Do(o));const i=`${r.collection}|${r.category}|${r.type}|${r.additionalKey}`,s=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`,a=i<s?[r,o,i,s]:[o,r,s,i],[c,u,l,h]=a,d="string"==typeof n.fromToken?Do(n.fromToken):n.fromToken,f=`${d.collection}|${d.category}|${d.type}|${d.additionalKey}`,p=f===l,g=`galaswap - operation - ${F()}-${Date.now()}-${n.walletAddress}`;let m;if(!n.currentSqrtPrice)throw new Error("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation");const w=new y(n.currentSqrtPrice),b=n.slippageTolerance??.01;if(p){const e=new y(1).minus(b);m=w.multipliedBy(e).toString()}else{const e=new y(1).plus(b);m=w.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:n.currentSqrtPrice,slippageTolerance:100*b+"%",zeroForOne:p,sqrtPriceLimit:m,direction:p?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const k={token0:c,token1:u,fee:n.feeTier,amount:new y(n.inputAmount).toFixed(),zeroForOne:p,sqrtPriceLimit:m,recipient:n.walletAddress,amountOutMinimum:new y(n.minOutput).multipliedBy(-1).toFixed(),uniqueKey:g};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:l,orderedToken1String:h,fromTokenStr:f,zeroForOne:p?`TRUE (${l} → ${h})`:`FALSE (${h} → ${l})`,inputAmount:n.inputAmount,expectedOutput:n.minOutput,slippageTolerance:100*(n.slippageTolerance||.01)+"%",currentSqrtPrice:n.currentSqrtPrice,swapDto:{amount:k.amount,zeroForOne:k.zeroForOne,sqrtPriceLimit:k.sqrtPriceLimit,amountOutMinimum:k.amountOutMinimum}});const v=new t.Wallet(this.privateKey),E={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},S={name:"ethereum",chainId:1},A=this.calculatePersonalSignPrefix(k),T={...k,prefix:A},I=await v.signTypedData(S,E,T),x={...T,signature:I,types:E,domain:S};this.logger.debug("Swap DTO signed",{signature:x.signature?.substring(0,20)+"...",prefix:x.prefix,zeroForOne:k.zeroForOne});const B=this.buildLiquidityStringsInstructions(c,u,n.feeTier,n.walletAddress),C=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),P=await C.post("/bundle",{method:"Swap",signedDto:x,stringsInstructions:B}),N=P.data?.data||P.data?.transactionId||P.data?.id;if(!N)throw this.logger.error("Bundler response structure",{status:P.status,data:P.data,dataType:typeof P.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(P.data)}`);return this.logger.debug("Swap transaction sent to bundler",{transactionId:N,inputAmount:n.inputAmount,minOutput:n.minOutput}),N}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,r){const o=`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`,i=`$${t.collection}$${t.category}$${t.type}$${t.additionalKey}`,s=`$pool${o}${i}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${s}`,`$tokenBalance${i}${s}`]}handleGSwapError(e,t,n,r){this.logger.error(e,n);const o=this.extractGSwapErrorCode(n),i=n,s=[`${e}: ${i?.message||String(n)}`,n];throw r&&("GSwapSwapError"===t.name&&r.transactionHash&&s.push(r.transactionHash),"GSwapPoolError"===t.name&&(r.tokenA&&s.push(r.tokenA),r.tokenB&&s.push(r.tokenB)),"GSwapAssetError"===t.name&&r.walletAddress&&s.push(r.walletAddress)),o&&s.push(o),new t(...s)}extractGSwapErrorCode(e){if(e&&"object"==typeof e){const t=e;if(t.constructor&&"GSwapSDKError"===t.constructor.name)return t.code;if("code"in t&&"string"==typeof t.code)return t.code}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}}class Wo{}Wo.BASE_PRICE=1650667151e-14,Wo.PRICE_SCALING_FACTOR=1166069e-12,Wo.TRADING_FEE_FACTOR=.001,Wo.GAS_FEE="1",Wo.MIN_UNBONDING_FEE_FACTOR=0,Wo.MAX_UNBONDING_FEE_FACTOR=.5,Wo.NET_UNBONDING_FEE_FACTOR=.5,Wo.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class zo extends zn{constructor(e=!1){super(e),this.cache=new Map}getLRUKey(){const e=this.cache.keys().next().value;return void 0!==e?e:null}normalizeTokenName(e){return e.trim().toLowerCase().replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=zo.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n||{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeTokenName(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeTokenName(e);this.updateCacheEntry(n,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),n=this.cache.get(t);return n?.maxSupply||Wo.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeTokenName(e);return this.cache.has(t)}clear(e){if(e){const t=this.normalizeTokenName(e);this.cache.delete(t)}else this.cache.clear()}dump(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let o=0;o+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(o+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(o+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(o+=8),o+=8,n.vaultAddress&&(o+=2*n.vaultAddress.length),n.maxSupply&&(o+=2*n.maxSupply.length),n.symbol&&(o+=2*n.symbol.length),o+=32,t+=o}),{totalTokens:this.cache.size,cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.get(t)||null}setByTokenId(e,t){const n=`token:${e.toLowerCase().trim()}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.has(t)}}zo.MAX_CACHE_SIZE=1e4;class jo extends Wn{constructor(e,t,n=void 0,r=5,o=!1){super(e,o),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=n,this.pricingConcurrency=r}setGSwapService(e){this.gswapService=e}setPricingConcurrency(e){this.pricingConcurrency=Math.max(1,Math.min(e,20))}async enrichPoolsWithPricing(e){if(!this.gswapService)return this.logger.warn("GSwap service not available, skipping pricing enrichment"),e;if(0===e.length)return e;this.logger.debug("Starting pricing enrichment",{poolCount:e.length,concurrency:this.pricingConcurrency});const t=[];for(let n=0;n<e.length;n++){const r=e[n];t.push({poolIndex:n,token:r.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:r.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${r.token0}`,{error:e.message})})}),t.push({poolIndex:n,token:r.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:r.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${r.token1}`,{error:e.message})})})}const n=new Map;for(let t=0;t<e.length;t++)n.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const r=t.slice(e,e+this.pricingConcurrency),o=await Promise.allSettled(r.map(e=>e.task));for(let e=0;e<r.length;e++){const t=r[e],i=o[e],s=n.get(t.poolIndex)||{};"fulfilled"===i.status&&i.value&&(t.isToken0?s.token0Price=i.value:s.token1Price=i.value),n.set(t.poolIndex,s)}}const r=e.map((e,t)=>{const r=n.get(t)||{},o={...e};return void 0!==r.token0Price&&(o.token0Price=r.token0Price),void 0!==r.token1Price&&(o.token1Price=r.token1Price),o}),o=r.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:o,failed:e.length-o}),r}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:r="desc",page:o=Kn.DEFAULT_PAGE,limit:i=Kn.DEFAULT_LIMIT,withPrices:s=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:r,page:o,limit:i,withPrices:s});const a=new URLSearchParams({page:o.toString(),limit:Math.min(i,20).toString(),sortBy:n,sortOrder:r});t&&a.append("search",t);const c=`${this.dexBackendBaseUrl}/explore/pools?${a}`;try{const e=await this.http.get(c);if(!e||!e.data)throw new Error("No response from DEX pool service");let t=e.data.pools;const n=e.data.count,r=Math.min(i,20),a=Math.ceil(n/r);return s&&(t=await this.enrichPoolsWithPricing(t)),this.logger.debug("DEX pools fetched successfully",{poolCount:t.length,total:n,totalPages:a,withPrices:s}),{pools:t,page:o,limit:r,total:n,totalPages:a,hasNext:o<a,hasPrevious:o>1}}catch(e){throw this.logger.error("Failed to fetch DEX pools",{error:e,url:c}),e}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=await No((t,n)=>this.fetchDexPools({...e,page:t,limit:n}).then(e=>({items:e.pools,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:20});this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.items.length,totalCount:t.total,withPrices:e.withPrices});return _o(t.items,t.total,"pools")}}const Ho=5;class Vo extends Wn{constructor(e,t,n=!1,r=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=r}validateFetchCompositePoolDataInput(e,t,n){if(!e||"string"!=typeof e)throw new ae("token0 must be a non-empty string",{token0:e});if(!t||"string"!=typeof t)throw new ae("token1 must be a non-empty string",{token1:t});const r=e.split("|"),o=t.split("|");if(4!==r.length)throw new ae("token0 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token0:e});if(4!==o.length)throw new ae("token1 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token1:t});const i=[500,3e3,1e4];if(!Number.isInteger(n)||!i.includes(n))throw new ae(`fee must be one of: ${i.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!e||"string"!=typeof e)throw new ae("amount must be a non-empty string",{amount:e});const t=new y(e);try{Ar(t,"amount","for quote calculation")}catch(t){throw new ae(t.message,{amount:e})}}convertTokenClassKey(e){const t=new U;return t.collection=e.collection,t.category=e.category,t.type=e.type,t.additionalKey=e.additionalKey,t}setCompositePoolFetchConcurrency(e){this.compositePoolFetchConcurrency=Math.max(1,Math.min(e,20)),this.logger.debug(`Composite pool fetch concurrency set to ${this.compositePoolFetchConcurrency}`)}async fetchCompositePoolData(e){const{token0:t,token1:n,fee:r,gatewayBaseUrl:o}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:r}),this.validateFetchCompositePoolDataInput(t,n,r);try{const e=$o(t),i=$o(n),s=this.convertTokenClassKey(e),a=this.convertTokenClassKey(i),c=new B(s,a,r),u=`${o||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,l=await this.http.post(u,c);if(!l||1!==l.Status)throw new ce(`Pool not found: ${t}/${n} with fee ${r}`);const h=function(e){return{pool:e.pool,tickDataMap:e.tickDataMap,token0Balance:e.token0Balance,token1Balance:e.token1Balance,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals,compositePoolDto:e}}(function(e){const t=new T(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,new y(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=new y(e.pool.grossPoolLiquidity),t.liquidity=new y(e.pool.liquidity),t.feeGrowthGlobal0=new y(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=new y(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=new y(e.pool.protocolFeesToken0),t.protocolFeesToken1=new y(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=new y(e.pool.maxLiquidityPerTick);const n={};Object.keys(e.tickDataMap).forEach(t=>{const r=e.tickDataMap[t],o=new I(r.poolHash,r.tick);o.initialised=r.initialised,o.liquidityNet=new y(r.liquidityNet),o.liquidityGross=new y(r.liquidityGross),o.feeGrowthOutside0=new y(r.feeGrowthOutside0),o.feeGrowthOutside1=new y(r.feeGrowthOutside1),n[t]=o});const r={...e.token0Balance},o=new D(r);o.quantity=new y(e.token0Balance.quantity);const i={...e.token1Balance},s=new D(i);return s.quantity=new y(e.token1Balance.quantity),new x(t,n,o,s,e.token0Decimals,e.token1Decimals)}(l.Data),l.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:r,liquidity:h.pool.liquidity.toString()}),h}catch(e){if(e instanceof ce)throw e;const o=e instanceof Error?e.message:String(e);throw this.logger.error("Failed to fetch composite pool data",e),new ae(`Failed to fetch composite pool data: ${o}`,{token0:t,token1:n,fee:r})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:o}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:r,amount:o}),this.validateQuoteAmount(o),!t)throw new ae("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),i=$o(n),s=$o(r),a=this.convertTokenClassKey(i),c=this.convertTokenClassKey(s),[u,l]=n<r?[a,c]:[c,a],h=new C(u,l,t.pool.fee,new y(o),e,t.compositePoolDto),d=await P(void 0,h);return this.logger.debug("Local quote calculated",{amount0:d.amount0,amount1:d.amount1}),{amount0:d.amount0.toString(),amount1:d.amount1.toString(),currentSqrtPrice:d.currentSqrtPrice.toString(),newSqrtPrice:d.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("Local quote calculation failed",e),new ae(`Local quote calculation failed: ${t}`,{fromToken:n,toToken:r,amount:o})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:o}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:r,amount:o}),this.validateQuoteAmount(o),!t)throw new ae("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),i=$o(n),s=$o(r),a=this.convertTokenClassKey(i),c=this.convertTokenClassKey(s),u=new C(a,c,t.pool.fee,new y(o),e,void 0),l=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,h=await this.http.post(l,u);if(!h||1!==h.Status)throw new ae("External quote failed: "+(h?.Message||"Unknown error"));const d=h.Data;return this.logger.debug("External quote calculated",{amount0:d.amount0,amount1:d.amount1}),{amount0:d.amount0.toString(),amount1:d.amount1.toString(),currentSqrtPrice:d.currentSqrtPrice.toString(),newSqrtPrice:d.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("External quote calculation failed",e),new ae(`External quote calculation failed: ${t}`,{fromToken:n,toToken:r,amount:o})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class Xo{constructor(){this.eventLatencies=[],this.maxLatencySamples=1e4,this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.perPoolMetrics=new Map,this.memorySnapshots=[],this.maxMemorySnapshots=100,this.recordMemory()}recordEventLatency(e){this.eventLatencies.push(e),this.eventLatencies.length>this.maxLatencySamples&&this.eventLatencies.shift(),this.eventsProcessed++,this.lastEventTime=new Date}recordEventDropped(){this.eventsDropped++}updateQueueDepth(e){this.queueDepth=e,this.maxQueueDepth=Math.max(this.maxQueueDepth,e)}recordPoolCacheHit(e,t){const n=this.getPoolMetrics(e);n.cacheHits++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}recordPoolCacheMiss(e,t){const n=this.getPoolMetrics(e);n.cacheMisses++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}getLatencyPercentiles(){if(0===this.eventLatencies.length)return{p50:0,p95:0,p99:0};const e=[...this.eventLatencies].sort((e,t)=>e-t),t=Math.floor(.5*e.length),n=Math.floor(.95*e.length),r=Math.floor(.99*e.length);return{p50:e[t]??0,p95:e[n]??0,p99:e[r]??0}}getCacheHitRate(){if(0===this.eventsProcessed)return 0;let e=0;for(const t of this.perPoolMetrics.values())e+=t.cacheHits;return e/this.eventsProcessed*100}getThroughputPerSecond(){const e=(Date.now()-this.startTime)/1e3;return 0===e?0:this.eventsProcessed/e}recordMemory(){if("undefined"!=typeof process&&process.memoryUsage){const e=process.memoryUsage().heapUsed/1024/1024;this.memorySnapshots.push(e),this.memorySnapshots.length>this.maxMemorySnapshots&&this.memorySnapshots.shift()}}getMemoryUsedMB(){return"undefined"!=typeof process&&process.memoryUsage?process.memoryUsage().heapUsed/1024/1024:0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?t.totalLatency/t.eventsProcessed:0}getPoolCacheHitRate(e){const t=this.perPoolMetrics.get(e);if(!t)return 0;const n=t.cacheHits+t.cacheMisses;return 0===n?0:t.cacheHits/n*100}getHealthMetrics(e,t,n,r,o){const i=this.getLatencyPercentiles(),s=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:i.p50,latencyP95:i.p95,latencyP99:i.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:Math.round(10*s)/10,maxMB:o,percentUsed:Math.round(s/o*1e3)/10},pools:{totalMonitored:e,hotCacheSize:t,warmCacheSize:n,coldCacheSize:r}}}reset(){this.eventLatencies=[],this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.lastEventTime=void 0,this.perPoolMetrics.clear(),this.memorySnapshots=[]}getSummary(){const e=this.eventLatencies.length>0?this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length:0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:Math.round(e),memoryUsedMB:Math.round(10*this.getMemoryUsedMB())/10,throughputPerSecond:Math.round(100*this.getThroughputPerSecond())/100}}getPoolMetrics(e){let t=this.perPoolMetrics.get(e);return t||(t={eventsProcessed:0,totalLatency:0,cacheHits:0,cacheMisses:0},this.perPoolMetrics.set(e,t)),t}}class Qo{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!e||"string"!=typeof e)return null;const t=e.split("/");if(3!==t.length)return null;const n=t[0]?.trim(),r=t[1]?.trim(),o=t[2]?.trim();if(!n||!r||!o)return null;const i=Number.parseInt(o,10);return Number.isNaN(i)?null:{token0:n,token1:r,feeTier:i}}static isValidPoolKey(e){if("string"!=typeof e)return!1;return null!==this.parsePoolKey(e)}static getToken0(e){const t=this.parsePoolKey(e);return t?.token0??null}static getToken1(e){const t=this.parsePoolKey(e);return t?.token1??null}static getFeeTier(e){const t=this.parsePoolKey(e);return t?.feeTier??null}static containsToken(e,t){const n=this.parsePoolKey(e);return!!n&&(n.token0===t||n.token1===t)}static containsTokenPair(e,t,n){const r=this.parsePoolKey(e);if(!r)return!1;const o=r.token0===t||r.token1===t,i=r.token0===n||r.token1===n;return o&&i&&t!==n}static normalizeFee(e){if(null==e)return null;const t="number"==typeof e?e:Number.parseFloat(String(e).replace("%","").trim());return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)&&t>0?t:null}static formatFeeAsPercentage(e){return`${(e/1e4).toFixed(2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class Zo{constructor(e){this.logger=e||new H({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const n=[],r=new WeakSet,o=(e,i=0)=>{if(i>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(r.has(e))return;r.add(e);const s=this.extractSwapFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))o(t,i+1)}};return o(e,0),n}extractSwapFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const n=e.Data,r=n&&"object"==typeof n&&!Array.isArray(n)?n:e,o=this.extractToken(r,"token0","fromToken","source"),i=this.extractToken(r,"token1","toToken","destination");if(!o||!i)return null;const s=this.extractAmount(r,"amount0","amountIn","inputAmount"),a=this.extractAmount(r,"amount1","amountOut","outputAmount");if(!s||!a)return null;const c=this.extractFeeTier(r);if(null===c)return null;const u=this.extractTimestamp(r),l=this.buildPoolKey(o,i,c),h=this.determineDirection(r,o,i),d={transactionId:t,poolKey:l,token0:o,token1:i,amount0:s,amount1:a,feeTier:c,direction:h,timestamp:u,exactInput:this.determineExactInput(r,h)},f=this.extractUser(r);return void 0!==f&&(d.user=f),d}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractAmount(e,...t){for(const n of t){const t=e[n];if(null!=t){const e=String(t).trim();if(/^-?\d+(\.\d+)?([eE]-?\d+)?$/.test(e))return e}}return null}extractFeeTier(e){const t=["poolFee","feeTier","fee","feeTierBps","liquidityFeeBps","feeAmount"];for(const n of t){const t=e[n],r=this.normalizeFee(t);if(null!==r)return r}return null}normalizeFee(e){if(null==e)return null;const t="number"==typeof e?e:Number.parseFloat(String(e).replace("%","").trim());return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)?t:null}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if("string"==typeof t){const e=new Date(t).getTime();if(!Number.isNaN(e))return e}}return Date.now()}extractUser(e){const t=["userAddress","user","from","sender","wallet","address"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}}determineDirection(e,t,n){const r=e.zeroForOne||e.direction;if("boolean"==typeof r)return r?"zeroForOne":"oneForZero";if("string"==typeof r){if("zerotoone"===r.toLowerCase()||"0to1"===r)return"zeroForOne";if("onetozero"===r.toLowerCase()||"1to0"===r)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===n||e.inputToken===n)return"oneForZero";const o=this.extractAmount(e,"amount0","amountIn");return o&&Number(o),"zeroForOne"}determineExactInput(e,t){if("boolean"==typeof e.exactInput)return e.exactInput;if("boolean"==typeof e.exactOutput)return!e.exactOutput;const n=void 0!==e.amountIn&&null!==e.amountIn,r=void 0!==e.amountOut&&null!==e.amountOut,o=void 0!==e.inputAmount&&null!==e.inputAmount,i=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!n||r)||!(r&&!n)&&(!(!o||i)||!(i&&!o))}buildPoolKey(e,t,n){return`${e}/${t}/${n}`}}class Yo{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,new y(e)),this.CACHE.get(t)}static clearCache(){this.CACHE.clear()}static getCacheStats(){return{size:this.CACHE.size,entries:Array.from(this.CACHE.keys())}}static trimCache(e=1e3){if(this.CACHE.size>e){const t=this.CACHE.size-e,n=Array.from(this.CACHE.keys());for(let e=0;e<t;e++)this.CACHE.delete(n[e])}}}Yo.CACHE=new Map,Yo.ZERO=new y(0),Yo.ONE=new y(1),Yo.FEE_PIPS=new y(1e6),Yo.MIN_SQRT_RATIO=new y("4295128739"),Yo.MAX_SQRT_RATIO=new y("1461446703485210103287273052203988822378723970342");const Jo={maxIterations:100,enableBigNumberCache:!0,roundingMode:y.ROUND_DOWN,debugLogging:!1};class ei{static calculateSwapDelta(e,t,n={}){const r=Date.now(),o={...Jo,...n};try{const n=this.initializeSwapState(e,t,o);o.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const i=this.computeSwapLoop(n,e,t,o);o.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:i.stepCount,ticksCrossed:i.ticksCrossed.length,priceHitLimit:i.priceHitLimit});const s=this.createUpdatedPool(e.pool,i.state,t,o),a=this.calculateFinalAmounts(n,i.state,t);let c;if(t.actualSqrtPrice){const e=new y(s.sqrtPrice),n=new y(t.actualSqrtPrice);c=e.minus(n).abs().div(n).times(100).toNumber()}const u=Date.now()-r;o.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:u,amount0:a.amount0.toString(),amount1:a.amount1.toString(),driftPercentage:c}),u>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:u,stepCount:i.stepCount,ticksCrossed:i.ticksCrossed.length}),i.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:i.stepCount}),i.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:i.stepCount,ticksCrossed:i.ticksCrossed.length});return{updatedPool:s,updatedTicks:i.updatedTicks,amount0:a.amount0,amount1:a.amount1,feeAmount0:a.feeAmount0,feeAmount1:a.feeAmount1,ticksCrossed:i.ticksCrossed,metadata:{calculationTimeMs:u,swapSteps:i.stepCount,priceHitLimit:i.priceHitLimit,...void 0!==c&&{driftPercentage:c}}}}catch(e){this.logger.error("Swap delta calculation failed",e);const t=e instanceof Error?e.message:String(e);throw new Error(`Swap delta calculation failed: ${t}`)}}static initializeSwapState(e,t,n){const{pool:r}=e;if(!r.sqrtPrice||!r.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const o=n.enableBigNumberCache?Yo.getCached.bind(Yo):e=>new y(e),i="string"==typeof r.sqrtPrice?r.sqrtPrice:new y(r.sqrtPrice).toFixed(0),s="string"==typeof r.liquidity?r.liquidity:new y(r.liquidity).toFixed(0),a=o(i),c=o(s),u=r.tick??0,l=N(new y(i)),h=Math.abs(l-u);h>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:u,calculatedTick:l,drift:h,threshold:100});const d=o(t.amountSpecified);Ar(d,"amountSpecified","for swap operation");const f="string"==typeof r.feeGrowthGlobal1?r.feeGrowthGlobal1:new y(r.feeGrowthGlobal1).toFixed(0),p="string"==typeof r.feeGrowthGlobal0?r.feeGrowthGlobal0:new y(r.feeGrowthGlobal0).toFixed(0),g=t.zeroForOne?o(f):o(p);return{sqrtPrice:a,liquidity:c,tick:u,amountSpecifiedRemaining:d,amountCalculated:Yo.ZERO,feeGrowthGlobalX:g,protocolFee:Yo.ZERO}}static computeSwapLoop(e,t,n,r){const{pool:o,tickDataMap:i}=t,s=[],a={};let c=0;const u=n.zeroForOne?Yo.MIN_SQRT_RATIO:Yo.MAX_SQRT_RATIO,l=new y("0.000001");for(;e.amountSpecifiedRemaining.gt(l)&&!e.sqrtPrice.eq(u)&&c<r.maxIterations;){c++;const[t,l]=this.findNextInitializedTick(i,e.tick,o.tickSpacing,n.zeroForOne);let h;if(r.debugLogging&&this.logger.debug(`Swap step ${c}`,{currentTick:e.tick,tickNext:t,initialized:l,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),l&&t>=-887272&&t<=887272){const e=w(t);h=e instanceof y?e:new y(String(e))}else h=u;const d=n.zeroForOne?y.max(h,u):y.min(h,u),f=this.executeSwapStep(e.sqrtPrice,d,e.liquidity,e.amountSpecifiedRemaining,o.fee,n.exactInput);if(e.sqrtPrice=f.sqrtPriceNext,n.exactInput){const t=f.amountIn.plus(f.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=Yo.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=Yo.ZERO)),e.amountCalculated=e.amountCalculated.minus(f.amountOut)}else{f.amountOut.lte(0)?e.amountSpecifiedRemaining=Yo.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(f.amountOut),e.amountCalculated=e.amountCalculated.plus(f.amountIn.plus(f.feeAmount))}if(e.liquidity.gt(0)){const t=f.feeAmount.div(e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(h)&&l){const o=i[t.toString()];if(!o)throw new Error(`Missing tick data for initialized tick ${t}`);const c=n.zeroForOne?new y(o.liquidityNet).negated():new y(o.liquidityNet);if(e.liquidity=e.liquidity.plus(c),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);s.push(t),a[t.toString()]=o,r.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:c.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(h))e.tick=n.zeroForOne?t-1:t;else{const t=N(new y(e.sqrtPrice.toString()));e.tick=t}}if(c>=r.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${r.maxIterations}). Possible infinite loop or very complex swap.`);const h=e.sqrtPrice.eq(u);return{state:e,ticksCrossed:s,priceHitLimit:h,stepCount:c,updatedTicks:a}}static createUpdatedPool(e,t,n,r){const o=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(o.sqrtPrice=t.sqrtPrice.toFixed(0),o.liquidity=t.liquidity.toFixed(0),o.tick=t.tick,n.zeroForOne?o.feeGrowthGlobal1=t.feeGrowthGlobalX.toFixed(0):o.feeGrowthGlobal0=t.feeGrowthGlobalX.toFixed(0),n.zeroForOne){const n=new y(e.protocolFeesToken0);o.protocolFeesToken0=n.plus(t.protocolFee).toFixed(0)}else{const n=new y(e.protocolFeesToken1);o.protocolFeesToken1=n.plus(t.protocolFee).toFixed(0)}return o}static calculateFinalAmounts(e,t,n){let r,o,i,s;if(n.exactInput){const e=new y(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=e.negated(),o=a,i=Yo.ZERO,s=Yo.ZERO):(r=a,o=e.negated(),i=Yo.ZERO,s=Yo.ZERO)}else{const e=new y(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=a.negated(),o=e,i=Yo.ZERO,s=Yo.ZERO):(r=e,o=a.negated(),i=Yo.ZERO,s=Yo.ZERO)}const a=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?s=a:i=a,{amount0:r,amount1:o,feeAmount0:i,feeAmount1:s}}static findNextInitializedTick(e,t,n,r){const o=Object.keys(e).map(e=>parseInt(e,10)).sort((e,t)=>e-t);if(0===o.length){return[r?-887272:887272,!1]}if(r){const e=o.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=o.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,r,o,i){Sr(n),Ar(r,"amountRemaining","for swap step");const s=[500,3e3,1e4];if(!s.includes(o))throw new Error(`Invalid fee tier: ${o}. Must be one of: ${s.join(", ")}`);const a=_(e,t,n,r,o,t.lt(e)),c=a[0],u=a[1],l=a[2],h=a[3],d=y.isBigNumber(c)?c:new y(String(c)),f=y.isBigNumber(u)?u:new y(String(u)),p=y.isBigNumber(l)?l:new y(String(l)),g=y.isBigNumber(h)?h:new y(String(h));return{sqrtPriceStart:e,tickNext:N(d),sqrtPriceNext:d,initialised:!1,amountIn:f,amountOut:p,feeAmount:g}}}ei.logger=new H({debug:!1,context:"SwapDeltaCalculator"});class ti{constructor(e,t,n,r){this.cache=new Map,this.tierSizes={hot:50,warm:200,cold:0},this.tierTTLs={hot:1/0,warm:18e5,cold:3e5},this.refetchThresholds={swapCount:50,driftPercent:.05},this.fetchPoolFn=e,this.config=t,this.metrics=n,this.logger=r||new H({debug:!1,context:"PoolCacheManager"}),this.tierSizes.cold=Math.max(0,this.config.maxPools-this.tierSizes.hot-this.tierSizes.warm),this.logger.debug(`Initialized with cache limits: hot=${this.tierSizes.hot}, warm=${this.tierSizes.warm}, cold=${this.tierSizes.cold}, max=${this.config.maxPools}`)}async getPool(e){const t=this.cache.get(e);if(t){if(!(Date.now()>t.expiresAt))return t.lastAccessTime=Date.now(),this.checkRefetchNeeded(e,t),this.metrics.recordPoolCacheHit(e,0),t.poolData;this.cache.delete(e),this.logger.debug(`Cache expired for pool ${e}`)}this.metrics.recordPoolCacheMiss(e,0);try{const t=await this.fetchPoolFn(e),n=this.determineTier(),r={poolData:t,tier:n,lastAccessTime:Date.now(),expiresAt:Date.now()+this.tierTTLs[n],swapsSinceRefetch:0,cumulativeDrift:0,lastDeltaAppliedTime:Date.now()};return this.cache.set(e,r),this.cache.size>this.config.maxPools&&this.evictLRU(),this.logger.debug(`Fetched pool ${e} (tier: ${n})`),t}catch(t){throw this.logger.error(`Failed to fetch pool ${e}:`,t),t}}updatePoolWithSwapDelta(e,t,n,r,o){const i=this.cache.get(e);if(!i)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(o){const s="zeroForOne"===t,a=s?n:r,c={transactionId:o.transactionId,timestamp:o.timestamp,amountSpecified:a,zeroForOne:s,exactInput:o.exactInput},u=ei.calculateSwapDelta(i.poolData,c);i.poolData={...i.poolData,pool:u.updatedPool},i.swapsSinceRefetch++,i.lastDeltaAppliedTime=Date.now(),void 0!==u.metadata.driftPercentage?(i.cumulativeDrift+=u.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${u.metadata.driftPercentage.toFixed(4)}%, cumulative=${i.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${u.ticksCrossed.length} ticks crossed`)}else i.swapsSinceRefetch++,i.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(i)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${i.swapsSinceRefetch}, drift=${(100*i.cumulativeDrift).toFixed(2)}%`),i.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),i.expiresAt=Date.now(),!1}}getStats(){const e={totalCached:this.cache.size,hotCacheSize:0,warmCacheSize:0,coldCacheSize:0,memoryUsedMB:this.metrics.getMemoryUsedMB()};for(const t of this.cache.values())"hot"===t.tier?e.hotCacheSize++:"warm"===t.tier?e.warmCacheSize++:e.coldCacheSize++;return e}getPoolInfo(e){const t=this.cache.get(e);return t?{poolKey:e,tier:t.tier,lastAccessTime:new Date(t.lastAccessTime),expiresAt:new Date(t.expiresAt),swapsSinceRefetch:t.swapsSinceRefetch,cumulativeDrift:t.cumulativeDrift,isExpired:Date.now()>t.expiresAt}:null}async warmCache(e){if(this.cache.has(e))return!0;try{return await this.getPool(e),this.logger.debug(`Cache warmed for ${e}`),!0}catch(t){return this.logger.error(`Failed to warm cache for ${e}:`,t),!1}}async warmCacheBatch(e,t=5){const n={succeeded:0,failed:0,total:e.length};let r=0;const o=new Set;for(;r<e.length||o.size>0;){for(;r<e.length&&o.size<t;){const t=e[r];r++;const i=this.warmCache(t).then(e=>{e?n.succeeded++:n.failed++});o.add(i),i.finally(()=>o.delete(i))}o.size>0&&await Promise.race(o)}return this.logger.debug(`Cache warming complete: ${n.succeeded}/${n.total} succeeded`),n}clear(){this.cache.clear(),this.logger.debug("Cache cleared")}clearExpired(){const e=Date.now();let t=0;for(const[n,r]of this.cache)e>r.expiresAt&&(this.cache.delete(n),t++);t>0&&this.logger.debug(`Cleared ${t} expired entries`)}determineTier(){const e=Array.from(this.cache.values()).filter(e=>"hot"===e.tier).length,t=Array.from(this.cache.values()).filter(e=>"warm"===e.tier).length;return e<this.tierSizes.hot?"hot":t<this.tierSizes.warm?"warm":"cold"}checkRefetchNeeded(e,t){this.shouldRefetch(t)&&(this.logger.debug(`Scheduling refetch for ${e}: swaps=${t.swapsSinceRefetch}, drift=${(100*t.cumulativeDrift).toFixed(2)}%`),t.expiresAt=Date.now())}shouldRefetch(e){return e.swapsSinceRefetch>=this.refetchThresholds.swapCount||e.cumulativeDrift>=this.refetchThresholds.driftPercent}evictLRU(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"cold"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(0===e.length){this.logger.warn("No cold cache entries to evict, trying warm cache");const e=Array.from(this.cache.entries()).filter(([e,t])=>"warm"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(e.length>0){const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted warm cache entry: ${t}`)}return}const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted cold cache entry: ${t}`)}async refreshWarmAndHotTiers(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"hot"===t.tier||"warm"===t.tier).sort((e,t)=>t[1].lastAccessTime-e[1].lastAccessTime).slice(0,10);if(0===e.length)return;const t=e.map(([e,t])=>this.fetchPoolFn(e).then(n=>{t&&(t.poolData=n,t.lastAccessTime=Date.now(),t.swapsSinceRefetch=0,t.cumulativeDrift=0),this.logger.debug(`Refreshed ${e} during background warming`)}).catch(t=>{this.logger.debug(`Failed to refresh ${e} during background warming:`,t)})),n=new Promise(e=>setTimeout(()=>e(),5e3));await Promise.race([Promise.all(t),n])}}class ni{constructor(e,t,n){this.queue=[],this.isShuttingDown=!1,this.currentConcurrency=0,this.maxConcurrencyReached=0,this.eventsDropped=0,this.totalBatchesProcessed=0,this.totalBatchSize=0,this.eventsProcessedCount=0,this.processor=null,this.processingScheduled=!1,this.scheduleProcessing=e=>{"undefined"!=typeof setImmediate?setImmediate(e):Promise.resolve().then(e)},this.config=e,this.metrics=t,this.logger=n||new H({debug:!1,context:"SwapEventQueue"}),this.logger.debug(`Initialized with maxQueueSize=${this.config.maxQueueSize}, batchSize=${this.config.batchSize}, maxConcurrent=${this.config.maxConcurrent}`)}setProcessor(e){this.processor=e}enqueue(e){return this.isShuttingDown?(this.logger.debug(`Rejecting event (queue shutting down): ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):this.queue.length>=this.config.maxQueueSize?(this.logger.warn(`Queue full (${this.queue.length}/${this.config.maxQueueSize}), dropping event: ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):(this.queue.push(e),this.metrics.updateQueueDepth(this.queue.length),this.processingScheduled||this.isShuttingDown||(this.processingScheduled=!0,this.scheduleProcessing(()=>this.processNextBatch())),!0)}getQueueSize(){return this.queue.length}getStats(){return{queueSize:this.queue.length,eventsProcessed:this.eventsProcessedCount,eventsDropped:this.eventsDropped,currentConcurrent:this.currentConcurrency,maxConcurrentReached:this.maxConcurrencyReached,averageBatchSize:this.totalBatchesProcessed>0?Math.floor(this.totalBatchSize/this.totalBatchesProcessed):0,totalBatchesProcessed:this.totalBatchesProcessed}}async waitForEmpty(e){return new Promise(t=>{const n=()=>{0!==this.queue.length||0!==this.currentConcurrency?setTimeout(n,10):t()};e&&setTimeout(()=>t(),e),n()})}async shutdown(e=3e4){this.isShuttingDown=!0,this.logger.debug("Shutting down queue...");const t=Date.now();for(;this.queue.length>0||this.currentConcurrency>0;){if(Date.now()-t>e){this.logger.warn(`Queue shutdown timeout: ${this.queue.length} events remaining, ${this.currentConcurrency} processing`);break}await new Promise(e=>setTimeout(e,50))}this.logger.debug("Queue shutdown complete")}clear(){const e=this.queue.length;this.queue.length=0,this.eventsDropped+=e,this.metrics.updateQueueDepth(0),this.logger.warn(`Cleared ${e} events from queue`)}async processNextBatch(){if(this.processingScheduled=!1,this.isShuttingDown&&0===this.queue.length)return;if(this.currentConcurrency>=this.config.maxConcurrent)return void setTimeout(()=>{this.processingScheduled||(this.processingScheduled=!0,setImmediate(()=>this.processNextBatch()))},10);const e=Math.min(this.config.batchSize,this.queue.length,this.config.maxConcurrent-this.currentConcurrency);if(0===e)return;const t=this.queue.splice(0,e);this.metrics.updateQueueDepth(this.queue.length),this.currentConcurrency+=t.length,this.currentConcurrency>this.maxConcurrencyReached&&(this.maxConcurrencyReached=this.currentConcurrency),this.totalBatchSize+=t.length,this.totalBatchesProcessed++;try{const e=await Promise.allSettled(t.map(e=>this.processEvent(e)));for(let n=0;n<e.length;n++){const r=e[n];this.eventsProcessedCount++,"rejected"===r.status&&this.logger.error(`Failed to process event ${t[n].transactionId}:`,r.reason)}}finally{this.currentConcurrency-=t.length}this.queue.length>0&&!this.processingScheduled&&(this.processingScheduled=!0,this.scheduleProcessing(()=>this.processNextBatch()))}async processEvent(e){if(!this.processor)return void this.logger.warn("No processor set, discarding event:",e.transactionId);const t=Date.now();try{await this.processor(e);const n=Date.now()-t;this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class ri{constructor(e,t,n,r={},o){this.socket=null,this.maxSeenTransactions=1e4,this.listeners=[],this.onErrorCallbacks=[],this.isActive=!1,this.listenerRegistered=!1,this.handleSwapEvent=null,this.warmingIntervalHandle=null,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.reconnectDelayMs=1e3,this.logger=o||new H({debug:!1,context:"MultiPoolStateManager"}),e instanceof Promise?this.socketReady=e.then(e=>(this.socket=e,this.setupConnectionMonitoring(),e)).catch(e=>{throw this.logger.error("Failed to resolve socket promise:",e),e}):(this.socket=e,this.socketReady=Promise.resolve(e),this.setupConnectionMonitoring()),this.metrics=new Xo,this.config=this.applyDefaults(r),this.eventExtractor=new Zo(this.logger),this.quoteService=n,this.cacheManager=new ti(t,this.config,this.metrics,this.logger),this.eventQueue=new ni(this.config,this.metrics,this.logger),this.seenTransactions=new oi(this.maxSeenTransactions),this.eventQueue.setProcessor(e=>this.processSwapEvent(e)),this.logger.debug("Initialized MultiPoolStateManager")}subscribe(e,t){this.listeners.push(t),e.onError&&this.onErrorCallbacks.push(e.onError),this.isActive||(this.setupWebSocketListener(e),this.isActive=!0);const n=this;return()=>{n.listeners=n.listeners.filter(e=>e!==t),e.onError&&(n.onErrorCallbacks=n.onErrorCallbacks.filter(t=>t!==e.onError)),0===n.listeners.length&&0===n.onErrorCallbacks.length&&n.unsubscribe()}}getHealth(){const e=this.cacheManager.getStats(),t=this.eventQueue.getStats(),n=this.metrics.getHealthMetrics(e.totalCached,e.hotCacheSize,e.warmCacheSize,e.coldCacheSize,this.getMaxMemoryMB()),r=this.determineHealthStatus(t,e),o={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectAttempts};this.socket?.connected&&(o.lastConnectionTime=new Date);const i=t.queueSize/this.config.maxQueueSize*100,s=e.totalCached/this.config.maxPools*100,a=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(r,i,s,a,n.metrics.cacheHitRate);return{...n,status:r,websocket:o,recommendations:c,detailedMetrics:{eventQueueUtilization:i,cacheUtilization:s,memoryUtilization:a}}}generateHealthRecommendations(e,t,n,r,o){const i=[];return"failed"===e&&(i.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||i.push("Reconnect WebSocket - connection lost"),t>90&&i.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(i.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&i.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),r>80&&i.push(`Memory usage ${r.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(o<50&&i.push(`Cache hit rate ${o.toFixed(1)}% is low - consider warming more pools`),r>50&&i.push("Memory usage is moderate - monitor for growth trends"),t>50&&i.push("Queue utilization is elevated - monitor for bottlenecks")),i}getSummary(){return{...this.metrics.getSummary(),queueStats:this.eventQueue.getStats(),cacheStats:this.cacheManager.getStats()}}startBackgroundWarming(){if(this.warmingIntervalHandle)return;const e=this.config.refreshIntervalMs;this.warmingIntervalHandle=setInterval(()=>{this.performBackgroundWarming().catch(e=>{this.logger.error("Background warming error:",e)})},e),this.logger.debug(`Background warming started (interval: ${e}ms)`)}stopBackgroundWarming(){this.warmingIntervalHandle&&(clearInterval(this.warmingIntervalHandle),this.warmingIntervalHandle=null,this.logger.debug("Background warming stopped"))}async performBackgroundWarming(){const e=this.cacheManager.getStats();if(0!==e.totalCached)try{await this.cacheManager.refreshWarmAndHotTiers(),this.logger.debug(`Background warming completed: ${e.totalCached} pools in cache (hot: ${e.hotCacheSize}, warm: ${e.warmCacheSize})`)}catch(e){this.logger.debug("Background warming encountered an error:",e)}}async shutdown(){this.stopBackgroundWarming(),await this.unsubscribe(),await this.eventQueue.shutdown(),this.cacheManager.clear(),this.metrics.reset()}setupConnectionMonitoring(){this.socket&&(this.socket.on("disconnect",()=>{this.logger.warn("WebSocket disconnected"),this.notifyError(new Error("WebSocket disconnected")),this.config.autoRecover&&this.attemptReconnection().catch(e=>{this.logger.error("Reconnection failed:",e)})}),this.socket.on("connect_error",e=>{this.logger.error("WebSocket connection error:",e),this.notifyError(e instanceof Error?e:new Error(String(e)))}))}async attemptReconnection(){if(this.logger.debug(`Reconnection attempt ${this.reconnectAttempts+1}/${this.maxReconnectAttempts}`),this.reconnectAttempts>=this.maxReconnectAttempts)return this.logger.error(`Max reconnection attempts (${this.maxReconnectAttempts}) exceeded - performing full reset`),void await this.performFullReset();this.reconnectAttempts<2&&(0===this.reconnectAttempts?this.logger.debug("Tier 1: Quick reconnect"):(this.logger.debug(`Tier 2: Exponential backoff (${this.reconnectDelayMs}ms)`),await new Promise(e=>setTimeout(e,this.reconnectDelayMs)),this.reconnectDelayMs=Math.min(2*this.reconnectDelayMs,3e4)));try{this.socket?.disconnect&&(this.socket.disconnect(),this.logger.debug("Disconnected for reconnection")),this.socket?.connect?.(),this.logger.debug("Reconnection initiated"),this.reconnectAttempts++}catch(e){throw this.logger.error("Failed to initiate reconnection:",e),e}}async performFullReset(){this.logger.warn("Performing full system reset due to connection failures"),this.stopBackgroundWarming();const e=this.getHealth();this.logger.debug("System state before reset:",{status:e.status,queueSize:e.eventProcessing.eventsProcessed,cachedPools:e.pools.totalMonitored,memory:`${e.memory.usedMB}MB / ${e.memory.maxMB}MB`,cacheHitRate:`${e.metrics.cacheHitRate.toFixed(2)}%`}),this.cacheManager.clear(),this.metrics.reset(),this.reconnectAttempts=0,this.reconnectDelayMs=1e3,this.notifyError(new Error("System reset: connection lost and recovery failed - please restart monitoring")),this.logger.info("System reset complete - ready for restart")}setupWebSocketListener(e){if(this.listenerRegistered)return void this.logger.debug("WebSocket listener already registered");const t=this;this.handleSwapEvent=(n,...r)=>{try{const n=Date.now(),o=r[0],i=t.eventExtractor.walkPayloadForSwaps(o,t.seenTransactions);if(0===i.length)return;t.logger.debug(`Extracted ${i.length} swaps from payload`);for(const n of i){if(t.filterSwap(n,e)){t.eventQueue.enqueue(n)||t.logger.debug(`Swap dropped due to queue overflow: ${n.transactionId}`)}}const s=Date.now()-n;t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(e instanceof Error?e:new Error(String(e)))}},this.socket?(this.socket.onAny(this.handleSwapEvent),this.listenerRegistered=!0,this.setupConnectionMonitoring()):this.logger.warn("Socket not available for listener registration"),this.startBackgroundWarming(),this.logger.debug("WebSocket listener registered for all events")}async unsubscribe(){this.stopBackgroundWarming(),this.handleSwapEvent&&this.listenerRegistered&&this.socket&&(this.socket.offAny(this.handleSwapEvent),this.listenerRegistered=!1),this.isActive=!1,this.listeners=[],this.onErrorCallbacks=[],this.logger.debug("Unsubscribed from swap events")}filterSwap(e,t){if(t.tokenFilter){if(!Qo.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,r]=t.pairTokens;if(!Qo.containsTokenPair(e.poolKey,n,r))return!1}if(t.feeTierFilter){if(Qo.normalizeFee(t.feeTierFilter)!==e.feeTier)return!1}return!t.userFilter||e.user===t.userFilter}async processSwapEvent(e){const t=Date.now();try{const n=this.cacheManager.updatePoolWithSwapDelta(e.poolKey,e.direction,e.amount0,e.amount1,e);e.poolStateUpdated=n;const r=Date.now()-t;this.metrics.recordEventLatency(r);for(const t of this.listeners)try{const n=t(e);n instanceof Promise&&await n}catch(t){this.logger.error(`Listener error for swap ${e.transactionId}:`,t)}}catch(t){this.logger.error(`Failed to process swap ${e.transactionId}:`,t),this.notifyError(t instanceof Error?t:new Error(String(t)))}}notifyError(e){for(const t of this.onErrorCallbacks)try{t(e)}catch(e){this.logger.error("Error in error callback:",e)}}determineHealthStatus(e,t){return!this.socket?.connected||e.queueSize>.9*this.config.maxQueueSize?"failed":e.queueSize>.75*this.config.maxQueueSize||t.memoryUsedMB>.9*this.getMaxMemoryMB()?"degraded":"healthy"}getMaxMemoryMB(){switch(this.config.memoryProfile){case"conservative":return 55;case"aggressive":return 530;default:return 250}}applyDefaults(e){return{memoryProfile:e.memoryProfile??"moderate",maxPools:e.maxPools??500,softLimit:e.softLimit??200,preloadTopN:e.preloadTopN??200,warmingTimeoutMs:e.warmingTimeoutMs??3e4,refreshIntervalMs:e.refreshIntervalMs??3e5,maxQueueSize:e.maxQueueSize??1e4,batchSize:e.batchSize??100,maxConcurrent:e.maxConcurrent??10,autoRecover:e.autoRecover??!0,maxParallelRefetch:e.maxParallelRefetch??20,enableDeltaOptimization:e.enableDeltaOptimization??!0,enableOfflineQuotes:e.enableOfflineQuotes??!0,metricsEnabled:e.metricsEnabled??!0,debug:e.debug??!1}}}class oi{constructor(e){this.map=new Map,this.maxSize=e}has(e){return this.map.has(e)}add(e){if(this.map.has(e))return this.map.delete(e),this.map.set(e,Date.now()),this;if(this.map.size>=this.maxSize){const e=this.map.keys().next().value;this.map.delete(e)}return this.map.set(e,Date.now()),this}delete(e){return this.map.delete(e)}clear(){this.map.clear()}get size(){return this.map.size}}class ii extends zn{constructor(e=!1){super(e),this.cache=new Map,this.tokenIdIndex=new Map,this.fetchTimestamps=new Map}normalizeSymbol(e){return e.trim().toUpperCase()}normalizeTokenId(e){return e.trim().toUpperCase()}has(e){const t=this.cache.get(e);return void 0!==t&&t.size>0}getAll(e){const t=this.cache.get(e);return t?Array.from(t.values()):[]}getBySymbol(e,t){const n=this.normalizeSymbol(t);return this.cache.get(e)?.get(n)}getContractAddress(e,t){const n=this.getBySymbol(e,t);if(n)return"ETHEREUM"===e?n.ethereumContractAddress:n.solanaContractAddress}set(e,t){const n=new Map,r=new Map;for(const e of t){const t=this.normalizeSymbol(e.symbol);n.set(t,e);const o=this.normalizeTokenId(e.stringifiedTokenClassKey);r.set(o,e)}this.cache.set(e,n),this.tokenIdIndex.set(e,r),this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Cached ${t.length} bridgeable tokens for ${e}`)}merge(e,t){let n=this.cache.get(e);n||(n=new Map,this.cache.set(e,n));let r=this.tokenIdIndex.get(e);r||(r=new Map,this.tokenIdIndex.set(e,r));for(const e of t){const t=this.normalizeSymbol(e.symbol);n.set(t,e);const o=this.normalizeTokenId(e.stringifiedTokenClassKey);r.set(o,e)}this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Merged ${t.length} bridgeable tokens for ${e} (total: ${n.size})`)}getFetchTimestamp(e){return this.fetchTimestamps.get(e)}getStats(){const e=[];let t=0;const n={ETHEREUM:0,SOLANA:0},r={};for(const[o,i]of this.cache){e.push(o),t+=i.size,n[o]=i.size;const s=this.fetchTimestamps.get(o);s&&(r[o]=s)}return{networks:e,totalTokens:t,tokensByNetwork:n,fetchTimestamps:r}}clear(e){e?(this.cache.delete(e),this.tokenIdIndex.delete(e),this.fetchTimestamps.delete(e),this.logger.debug(`Cleared bridgeable token cache for ${e}`)):(this.cache.clear(),this.tokenIdIndex.clear(),this.fetchTimestamps.clear(),this.logger.debug("Cleared all bridgeable token caches"))}size(e){return this.cache.get(e)?.size??0}isTokenBridgeable(e,t){return void 0!==this.getBySymbol(e,t)}getByTokenId(e,t){const n=this.normalizeTokenId(t);return this.tokenIdIndex.get(e)?.get(n)}getCachedNetworks(){return Array.from(this.cache.keys())}dump(){const e={};for(const t of["ETHEREUM","SOLANA"])this.has(t)&&(e[t]=this.getAll(t));return e}}const si=1e3,ai=1e3;class ci{constructor(e,t=!1){this.dexApiHttp=e,this.logger=new H({debug:t,context:"BridgeableTokenService"}),this.cache=new ii(t)}resolveTokenSymbol(e){if("string"==typeof e){const t=e.split("|");if(4!==t.length)throw new Y(`Invalid tokenId format: "${e}". Expected pipe-delimited format "collection|category|type|additionalKey" (e.g., "GALA|Unit|none|none") or TokenClassKey object.`,"tokenId","INVALID_FORMAT");const n=t[0],r=t[2];return"Token"===n?r:n}if(!e.collection||!e.category||!e.type||void 0===e.additionalKey)throw new Y("Invalid TokenClassKey: must have collection, category, type, and additionalKey fields.","tokenId","INVALID_FORMAT");return"Token"===e.collection?e.type:e.collection}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:r=ai}=e,o=Math.min(r,si);this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${o})`);try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{canBridgeTo:t.toLowerCase(),limit:o,offset:n}}),r=this.transformTokens(e.tokens,t);return 0===n?this.cache.set(t,r):this.cache.merge(t,r),{tokens:r,network:t,fetchedAt:Date.now(),tokenCount:r.length}}catch(e){throw this.logger.error(`Failed to fetch bridgeable tokens for ${t}:`,e),de(`Failed to fetch bridgeable tokens for ${t}: ${nr(e)}`,void 0,e instanceof Error?e:void 0)}}async fetchAllBridgeableTokensByNetwork(e){if(this.cache.has(e)){const t=this.cache.getAll(e);return this.logger.debug(`Returning ${t.length} cached bridgeable tokens for ${e}`),{tokens:t,network:e,fetchedAt:this.cache.getFetchTimestamp(e)||Date.now(),tokenCount:t.length}}this.logger.debug(`Fetching all bridgeable tokens for ${e} (no cache)`);const t=[];let n=0,r=!0;for(;r;)try{const o=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{canBridgeTo:e.toLowerCase(),limit:si,offset:n}}),i=this.transformTokens(o.tokens,e);t.push(...i),r=o.tokens.length===si,n+=si,this.logger.debug(`Fetched ${t.length} tokens so far for ${e} (hasMore=${r})`)}catch(t){throw this.logger.error(`Failed to fetch bridgeable tokens for ${e} at offset ${n}:`,t),de(`Failed to fetch bridgeable tokens for ${e}: ${nr(t)}`,void 0,t instanceof Error?t:void 0)}return this.cache.set(e,t),{tokens:t,network:e,fetchedAt:Date.now(),tokenCount:t.length}}async fetchAllTokensBridgeableToEthereum(){return this.fetchAllBridgeableTokensByNetwork("ETHEREUM")}async fetchAllTokensBridgeableToSolana(){return this.fetchAllBridgeableTokensByNetwork("SOLANA")}async isTokenBridgeableToNetwork(e){const{tokenId:t,network:n}=e,r=this.resolveTokenSymbol(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const o=this.cache.getBySymbol(n,r),i=void 0!==o,s=i?"ETHEREUM"===n?o.ethereumContractAddress:o.solanaContractAddress:void 0,a={isBridgeable:i,tokenSymbol:r,network:n};return void 0!==s&&(a.contractAddress=s),a}async isTokenBridgeableToEthereum(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"ETHEREUM"})}async isTokenBridgeableToSolana(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"SOLANA"})}async getTokenBySymbol(e,t){const n=this.cache.getBySymbol(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getBySymbol(t,e))}async getTokenByTokenId(e,t){const n=this.cache.getByTokenId(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getByTokenId(t,e))}async getContractAddress(e,t){const n=await this.getTokenBySymbol(e,t);if(n)return"ETHEREUM"===t?n.ethereumContractAddress:n.solanaContractAddress}async getSupportedTokenSymbols(e){return this.cache.has(e)||await this.fetchAllBridgeableTokensByNetwork(e),this.cache.getAll(e).map(e=>e.symbol)}async preload(){this.logger.debug("Preloading bridgeable tokens for all networks"),await Promise.all([this.fetchAllBridgeableTokensByNetwork("ETHEREUM"),this.fetchAllBridgeableTokensByNetwork("SOLANA")]),this.logger.debug("Preloading complete")}getCacheStats(){return this.cache.getStats()}clearCache(e){this.cache.clear(e)}transformTokens(e,t){return e.map(e=>{const t=e.otherNetworks?.find(e=>"Ethereum"===e.network),n=e.otherNetworks?.find(e=>"Solana"===e.network),r=e.canBridgeTo.map(e=>e.network).filter(e=>"Ethereum"===e||"Solana"===e),o={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,verified:e.verified,supportedChains:r};return t?.contractAddress&&(o.ethereumContractAddress=t.contractAddress),t?.symbol&&(o.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(o.ethereumAllowanceSlot=t.allowanceStorageSlot),n?.contractAddress&&(o.solanaContractAddress=n.contractAddress),n?.symbol&&(o.solanaSymbol=n.symbol),e.image&&(o.image=e.image),e.description&&(o.description=e.description),o})}}class ui extends zn{constructor(e=!1){super(e),this.lastFetchedAt=null,this.cache=new Map}normalizeTokenId(e){return e.trim().toUpperCase()}has(){return this.cache.size>0}getAll(){return Array.from(this.cache.values())}getByTokenId(e){const t=this.normalizeTokenId(e);return this.cache.get(t)}set(e){this.cache.clear();for(const t of e){const e=this.normalizeTokenId(t.stringifiedTokenClassKey);this.cache.set(e,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Cached ${e.length} wrappable tokens`)}merge(e){for(const t of e){const e=this.normalizeTokenId(t.stringifiedTokenClassKey);this.cache.set(e,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Merged ${e.length} wrappable tokens (total: ${this.cache.size})`)}getFetchTimestamp(){return this.lastFetchedAt}getStats(){return{tokenCount:this.cache.size,isPopulated:this.cache.size>0,lastFetchedAt:this.lastFetchedAt}}clear(){this.cache.clear(),this.lastFetchedAt=null,this.logger.debug("Cleared wrappable token cache")}size(){return this.cache.size}isTokenWrappable(e){return void 0!==this.getByTokenId(e)}getWrapCounterpart(e){const t=this.getByTokenId(e);if(t)return this.getByTokenId(t.wrapCounterpart)}}const li=1e3,hi=1e3;class di{constructor(e,t=!1){this.dexApiHttp=e,this.logger=new H({debug:t,context:"WrappableTokenService"}),this.cache=new ui(t)}normalizeTokenId(e){if("string"==typeof e){if(!e||!e.trim())throw new Y("tokenId must be a non-empty string","tokenId","INVALID_FORMAT");if(4!==e.split("|").length)throw new Y(`Invalid tokenId format: "${e}". Expected pipe-delimited format "collection|category|type|additionalKey" (e.g., "$MUSIC|Unit|none|none") or TokenClassKey object.`,"tokenId","INVALID_FORMAT");return e}if(!e.collection||!e.category||!e.type||void 0===e.additionalKey)throw new Y("Invalid TokenClassKey: must have collection, category, type, and additionalKey fields.","tokenId","INVALID_FORMAT");return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}async fetchWrappableTokens(e={}){const{offset:t=0,limit:n=hi}=e,r=Math.min(n,li);this.logger.debug(`Fetching wrappable tokens (offset=${t}, limit=${r})`);try{const e={wrappable:!0,limit:r,offset:t},n=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:e});if(!n||!Array.isArray(n.tokens))throw new Y("Invalid API response: expected { tokens: WrappableTokenApiResponse[] }","response","INVALID_RESPONSE");const o=this.transformTokens(n.tokens);try{0===t?this.cache.set(o):this.cache.merge(o)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:o,fetchedAt:Date.now(),tokenCount:o.length}}catch(e){throw this.logger.error("Failed to fetch wrappable tokens:",e),de(`Failed to fetch wrappable tokens: ${nr(e)}`,void 0,e instanceof Error?e:void 0)}}async fetchAllWrappableTokens(){if(this.cache.has()){const e=this.cache.getAll();return this.logger.debug(`Returning ${e.length} cached wrappable tokens`),{tokens:e,fetchedAt:this.cache.getFetchTimestamp()||Date.now(),tokenCount:e.length}}this.logger.debug("Fetching all wrappable tokens");const e=[];let t=0,n=!0;for(;n;)try{const r={wrappable:!0,limit:li,offset:t},o=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:r});if(!o||!Array.isArray(o.tokens))throw new Y("Invalid API response: expected { tokens: WrappableTokenApiResponse[] }","response","INVALID_RESPONSE");const i=this.transformTokens(o.tokens);e.push(...i),n=o.tokens.length===li,t+=li,this.logger.debug(`Fetched ${e.length} tokens so far (hasMore=${n})`)}catch(e){throw this.logger.error(`Failed to fetch wrappable tokens at offset ${t}:`,e),de(`Failed to fetch wrappable tokens: ${nr(e)}`,void 0,e instanceof Error?e:void 0)}try{this.cache.set(e)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:e,fetchedAt:Date.now(),tokenCount:e.length}}async getWrappableToken(e){const t=this.normalizeTokenId(e),n=this.cache.getByTokenId(t);return n||(this.cache.has()?void 0:(await this.fetchAllWrappableTokens(),this.cache.getByTokenId(t)))}async getWrapCounterpart(e){const t=await this.getWrappableToken(e);if(t)return this.getWrappableToken(t.wrapCounterpart)}async isTokenWrappable(e){const t=this.normalizeTokenId(e);this.cache.has()||await this.fetchAllWrappableTokens();const n=this.cache.getByTokenId(t),r=void 0!==n,o={isWrappable:r,tokenId:t};return r&&n&&(o.wrapCounterpart=n.wrapCounterpart),o}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}transformTokens(e){return e.map(e=>{const t={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,wrapCounterpart:e.wrap,swappable:e.swappable,verified:e.verified};return e.channel&&(t.channel=e.channel),void 0!==e.trending&&(t.trending=e.trending),e.image&&(t.image=e.image),e.description&&(t.description=e.description),e.currentPrices&&(t.currentPrices=e.currentPrices),t})}}function fi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function pi(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var gi,mi,yi,wi,bi,ki;function vi(){return wi?yi:(wi=1,yi={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys})}var Ei=function(){if(ki)return bi;ki=1;const e=mi?gi:(mi=1,gi={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify}),t=vi().isFunction,n=vi().isBoolean,r=vi().isObject,o=vi().isArray,i=vi().isRegex,s=vi().assign,a=vi().keys;return bi=function(c,u){u=u||s({},e),t(u)&&(u={compare:u});const l=u.space||e.space,h=n(u.cycles)?u.cycles:e.cycles,d=u.replacer||e.replacer,f=u.stringify||e.stringify,p=u.compare&&(g=u.compare,function(e){return function(t,n){const r={key:t,value:e[t]},o={key:n,value:e[n]};return g(r,o)}});var g;h||f(c);const m=[];return function e(t,n,s,c){const u=l?"\n"+new Array(c+1).join(l):"",g=l?": ":":";if(s=function(e){return null==e?e:i(e)?e.toString():e.toJSON?e.toJSON():e}(s),void 0!==(s=d.call(t,n,s))){if(!r(s)||null===s)return f(s);if(o(s)){const t=[];for(let n=0;n<s.length;n++){const r=e(s,n,s[n],c+1)||f(null);t.push(u+l+r)}return"["+t.join(",")+u+"]"}{if(h){if(-1!==m.indexOf(s))return f("[Circular]");m.push(s)}const t=a(s).sort(p&&p(s)),n=[];for(let r=0;r<t.length;r++){const o=t[r],i=e(s,o,s[o],c+1);if(!i)continue;const a=f(o)+g+i;n.push(u+l+a)}return m.splice(m.indexOf(s),1),"{"+n.join(",")+u+"}"}}}({"":c},"",c,0)},bi}(),Si=fi(Ei);const Ai={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},Ti={ASSET:1,MUSIC:3};function Ii(e){return Object.values(Ti).includes(e)}const xi=12,Bi=15e3,Ci=27e5,Pi={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},Ni="https://ethereum.publicnode.com",_i="https://api.mainnet-beta.solana.com",Ui="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Di="0x6a1734E09f3099a3675645D214ce547080ea67e0",Ri="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",Fi="https://dex-api-platform-dex-prod-gala.gala.com",Li=[{symbol:"GALA",amount:"1",contractAddress:"0xd1d2Eb1B1e90B638588728b4130137D262C87cae",bridgeUsesPermit:!0,decimals:8},{symbol:"GWETH",amount:"0.0001",contractAddress:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",bridgeUsesPermit:!1,decimals:18},{symbol:"GUSDC",amount:"1",contractAddress:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",bridgeUsesPermit:!1,decimals:6},{symbol:"GUSDT",amount:"1",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",bridgeUsesPermit:!1,decimals:6},{symbol:"GWTRX",amount:"1",contractAddress:"0x50327c6c5a14DCaDE707ABad2E27eB517df87AB5",bridgeUsesPermit:!1,decimals:6},{symbol:"GWBTC",amount:"0.00001",contractAddress:"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",bridgeUsesPermit:!1,decimals:8}],Oi=[{symbol:"GALA",amount:"1",contractAddress:"0x9fBFf09325C1967A135AC9b4860b1cf89aca52DA",bridgeUsesPermit:!0,decimals:8},{symbol:"GWETH",amount:"0.0001",contractAddress:"0xC3F00B9CbC4221D85A66EEbe928551d0d8dD9158",bridgeUsesPermit:!1,decimals:18},{symbol:"GUSDC",amount:"1",contractAddress:"0x081e78E33bfa612b23A99ef61e7c194649AA318E",bridgeUsesPermit:!1,decimals:6},{symbol:"GUSDT",amount:"1",contractAddress:"0x461e3595f087bfb0E32B6e44BCbF4C74D99B0001",bridgeUsesPermit:!1,decimals:6},{symbol:"GWBTC",amount:"0.00001",contractAddress:"0x5f69276935EF17e5aF5289b60aFBf6d48B344770",bridgeUsesPermit:!1,decimals:8}];function Mi(e){return"PROD"===e?Li:Oi}function $i(e){return"PROD"===e?Ui:Di}const qi=Li,Ki=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],Gi={GALA:{descriptor:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},decimals:8,channel:"asset"},GWETH:{descriptor:{collection:"GWETH",category:"Unit",type:"none",additionalKey:"none"},decimals:18,channel:"asset"},GUSDC:{descriptor:{collection:"GUSDC",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GUSDT:{descriptor:{collection:"GUSDT",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GWTRX:{descriptor:{collection:"GWTRX",category:"Unit",type:"none",additionalKey:"none"},decimals:6,channel:"asset"},GWBTC:{descriptor:{collection:"GWBTC",category:"Unit",type:"none",additionalKey:"none"},decimals:8,channel:"asset"},GSOL:{descriptor:{collection:"GSOL",category:"Unit",type:"none",additionalKey:"none"},decimals:9,channel:"asset"}},Wi=["function decimals() view returns (uint8)","function balanceOf(address owner) view returns (uint256)","function approve(address spender, uint256 value) returns (bool)","function allowance(address owner, address spender) view returns (uint256)","function transfer(address to, uint256 value) returns (bool)","function name() view returns (string)","function nonces(address owner) view returns (uint256)","function permit(address owner,address spender,uint256 value,uint256 deadline,uint8 v,bytes32 r,bytes32 s)"],zi=["function bridgeOut(address token,uint256 amount,uint256 tokenId,uint16 destinationChainId,bytes recipient) external","function bridgeOutWithPermit(address token,uint256 amount,uint16 destinationChainId,bytes recipient,uint256 deadline,uint8 v,bytes32 r,bytes32 s) external"],ji={BRIDGE_OUT:Buffer.from([27,194,57,119,215,165,247,150]),BRIDGE_OUT_NATIVE:Buffer.from([243,44,75,224,249,206,98,79])};function Hi(e){const t=e.toUpperCase(),n=Gi[t];if(n)return n;if(!t.startsWith("G")){const e=Gi[`G${t}`];if(e)return e}}function Vi(e){const t=e.toUpperCase();return qi.find(e=>e.symbol.toUpperCase()===t||e.symbol.toUpperCase()===`G${t}`)}function Xi(e){const t=e.toUpperCase();return Ki.find(e=>e.symbol.toUpperCase()===t||e.symbol.toUpperCase()===`G${t}`)}function Qi(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}const Zi={name:"GalaConnect",chainId:1},Yi=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],Ji=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],es=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],ts=[{name:"name",type:"string"},{name:"symbol",type:"string"}],ns={GalaTransaction:Yi,destinationChainTxFee:[{name:"bridgeToken",type:"bridgeToken"},{name:"bridgeTokenIsNonFungible",type:"bool"},{name:"estimatedPricePerTxFeeUnit",type:"string"},{name:"estimatedTotalTxFeeInExternalToken",type:"string"},{name:"estimatedTotalTxFeeInGala",type:"string"},{name:"estimatedTxFeeUnitsTotal",type:"string"},{name:"galaDecimals",type:"uint256"},{name:"galaExchangeRate",type:"galaExchangeRate"},{name:"timestamp",type:"uint256"},{name:"signingIdentity",type:"string"},{name:"signature",type:"string"}],bridgeToken:Ji,galaExchangeRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"baseToken",type:"baseToken"},{name:"exchangeRate",type:"string"},{name:"externalQuoteToken",type:"externalQuoteToken"}],baseToken:es,externalQuoteToken:ts,tokenInstance:es},rs={GalaTransaction:Yi,destinationChainTxFee:[{name:"bridgeToken",type:"bridgeToken"},{name:"bridgeTokenIsNonFungible",type:"bool"},{name:"estimatedPricePerTxFeeUnit",type:"string"},{name:"estimatedTotalTxFeeInExternalToken",type:"string"},{name:"estimatedTotalTxFeeInGala",type:"string"},{name:"estimatedTxFeeUnitsTotal",type:"string"},{name:"galaDecimals",type:"uint256"},{name:"galaExchangeCrossRate",type:"galaExchangeCrossRate"},{name:"timestamp",type:"uint256"},{name:"signingIdentity",type:"string"},{name:"signature",type:"string"}],bridgeToken:Ji,galaExchangeCrossRate:[{name:"baseTokenCrossRate",type:"baseTokenCrossRate"},{name:"crossRate",type:"string"},{name:"externalCrossRateToken",type:"externalCrossRateToken"},{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"quoteTokenCrossRate",type:"quoteTokenCrossRate"},{name:"source",type:"string"},{name:"timestamp",type:"uint256"}],baseTokenCrossRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"exchangeRate",type:"string"},{name:"externalBaseToken",type:"externalBaseToken"},{name:"externalQuoteToken",type:"externalQuoteToken"},{name:"signature",type:"string"}],externalBaseToken:ts,externalQuoteToken:ts,externalCrossRateToken:ts,quoteTokenCrossRate:[{name:"identity",type:"string"},{name:"oracle",type:"string"},{name:"source",type:"string"},{name:"sourceUrl",type:"string"},{name:"timestamp",type:"uint256"},{name:"baseToken",type:"baseToken"},{name:"exchangeRate",type:"string"},{name:"externalQuoteToken",type:"externalQuoteToken"},{name:"signature",type:"string"}],baseToken:es,tokenInstance:es};function os(e){return e?rs:ns}const is={GalaTransaction:[{name:"quantity",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"destinationChainId",type:"uint256"},{name:"recipient",type:"string"},{name:"wrap",type:"bool"},{name:"uniqueKey",type:"string"}],tokenInstance:es};class ss{constructor(e){this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService,this.wallet=e.wallet,this.walletAddress=e.walletAddress,this.logger=e.logger??new H({debug:!1,context:"WrapService"})}async wrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new Y(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new Y(`Cannot wrap ${t.symbol} - it's already on asset channel. Use unwrapToken() instead.`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new Y(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...e.recipient&&{recipient:e.recipient},...e.memo&&{memo:e.memo},isWrap:!0})}async unwrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new Y(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new Y(`Cannot unwrap ${t.symbol} - it's not on asset channel. Use wrapToken() instead.`,"tokenId","NOT_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new Y(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...e.recipient&&{recipient:e.recipient},...e.memo&&{memo:e.memo},isWrap:!1})}async estimateWrapFee(e,t){const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new Y(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new Y(`Cannot wrap ${n.symbol} - it's already on asset channel`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const r=this.determineChannelRouting(n,!0);return{fee:"0",feeToken:"GALA",authorizationType:r.authType,feeChannel:r.sourceChannel}}async estimateUnwrapFee(e,t){const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new Y(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new Y(`Cannot unwrap ${n.symbol} - it's not on asset channel`,"tokenId","NOT_ON_ASSET_CHANNEL");const r=this.determineChannelRouting(n,!1);return{fee:"0",feeToken:"GALA",authorizationType:r.authType,feeChannel:r.sourceChannel}}async getWrapStatus(e){return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:o,isWrap:i}=e;if(!this.wallet||!this.walletAddress)throw new Y("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const s=this.walletAddress,a=this.determineChannelRouting(t,i),c=`galaswap-operation-${O.randomUUID()}`,u=is,l={quantity:r,tokenInstance:{collection:t.galaChainDescriptor.collection,category:t.galaChainDescriptor.category,type:t.galaChainDescriptor.type,additionalKey:t.galaChainDescriptor.additionalKey,instance:"0"},destinationChainId:a.destinationChannelId,recipient:o||s,wrap:!0,uniqueKey:c};this.logger.debug?.(`[WrapService] ${i?"Wrap":"Unwrap"} message (pre-signing):`,JSON.stringify(l,null,2));try{const e=await this.wallet.signTypedData(Zi,u,l),o=`Ethereum Signed Message:\n${Si({domain:Zi,message:l,primaryType:"GalaTransaction",types:u}).length}`,s={...l,signature:e,prefix:o,types:u,domain:Zi};this.logger.debug?.(`[WrapService] ${i?"Wrap":"Unwrap"} request (signed):`,JSON.stringify(s,null,2));const c=await this.galaConnectClient.requestBridgeOut(s);if(this.logger.debug?.("[WrapService] Response:",JSON.stringify(c,null,2)),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(c)){const e=`Status=${c.Status}`,o=c.Message?`: ${c.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:`GalaChain request failed (${e}${o})`}}if(function(e){return"object"==typeof e&&null!==e&&"Data"in e&&"string"==typeof e.Data}(c)){const e=c.Data;this.logger.debug?.("[WrapService] Step 1 complete, bridgeRequestId:",e);const o={bridgeFromChannel:a.sourceChannel,bridgeRequestId:e};this.logger.debug?.("[WrapService] Step 2 - BridgeTokenOut payload:",JSON.stringify(o,null,2));const s=await this.galaConnectClient.bridgeTokenOut(o);return this.logger.debug?.("[WrapService] BridgeTokenOut response:",JSON.stringify(s,null,2)),1!==s.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:`BridgeTokenOut failed: ${JSON.stringify(s)}`}:{success:!0,transactionId:s.Hash||e,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:`Unexpected response format from GalaChain: ${JSON.stringify(c)}`}}catch(e){const o=e instanceof Error?e.message:"Unknown error";return this.logger.error?.("[WrapService] Error:",o),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:a.sourceChannel,toChannel:i?"asset":n.channel||"music",error:o}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel||"music",destinationChannelId:Ti.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Ti.MUSIC,authType:"automatic"}}requireWallet(){if(!this.walletAddress)throw new Y("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}}function as(e){const t=function(e){const t=Qt(e);return t.success?[]:t.errors||["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}const cs="/api/asset/launchpad-contract/CallNativeTokenIn",us="/api/asset/launchpad-contract/CallNativeTokenOut",ls="/api/asset/launchpad-contract/CallMemeTokenIn",hs="/api/asset/launchpad-contract/CallMemeTokenOut";class ds extends p{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,e.websiteUrl&&(this.websiteUrl=e.websiteUrl),e.telegramUrl&&(this.telegramUrl=e.telegramUrl),e.twitterUrl&&(this.twitterUrl=e.twitterUrl),this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function fs(e){if(!e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.Status&&void 0!==t.Data&&"object"==typeof t.Data&&null!==t.Data&&"string"==typeof t.Data.calculatedQuantity&&void 0!==t.Data.extraFees&&"object"==typeof t.Data.extraFees&&null!==t.Data.extraFees&&"string"==typeof t.Data.extraFees.reverseBondingCurve&&"string"==typeof t.Data.extraFees.transactionFees}const ps={NATIVE:"native",EXACT:"exact"},gs={RECENT:"recent",POPULAR:"popular"},ms={LOCAL:"local",EXTERNAL:"external"};class ys{static calculateBuyWithExact(e,t){const n=parseFloat(e),r=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:s,GAS_FEE:a}=Wo,c=this.roundUp(o*(Math.exp((r+n)*i)-Math.exp(r*i))/i,8),u=new y(c).multipliedBy(s).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:a}}static calculateBuyWithNative(e,t){const n=parseFloat(e),r=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:s,GAS_FEE:a}=Wo,c=Math.log(n*i/o+Math.exp(r*i))/i-r,u=new y(c).multipliedBy(s).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:a}}static calculateSellWithExact(e,t,n,r,o){const i=parseFloat(e),s=parseFloat(t),a=parseFloat(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:l,GAS_FEE:h}=Wo,d=c*(Math.exp(s*u)-Math.exp((s-i)*u))/u,f=new y(d),p=r+s/a*(o-r),g=f.multipliedBy(p).toFixed(8,y.ROUND_UP),m=f.multipliedBy(l).toFixed();return{amount:d.toString(),reverseBondingCurveFee:g,transactionFee:m,gasFee:h}}static calculateSellWithNative(e,t,n,r,o){const i=parseFloat(e),s=parseFloat(t),a=parseFloat(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:l,GAS_FEE:h}=Wo;if(i>=c*(Math.exp(s*u)-1)/u){const e=new y(i),t=r+s/a*(o-r),n=e.multipliedBy(t).toFixed(8,y.ROUND_UP),c=e.multipliedBy(l).toFixed();return{amount:s.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:h}}const d=s-Math.log(Math.exp(s*u)-i*u/c)/u,f=new y(i),p=r+s/a*(o-r),g=f.multipliedBy(p).toFixed(8,y.ROUND_UP),m=f.multipliedBy(l).toFixed();return{amount:d.toString(),reverseBondingCurveFee:g,transactionFee:m,gasFee:h}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class ws{constructor(e,t,n,r,o,i,s="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=o,this.dexApiHttp=i,this.defaultCalculateAmountMode=s,this.metadataCache=new zo}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;gn(t);const r=`${t}.png`;hr(n.file,r,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&n.file instanceof File)e.append("image",n.file);else{if(!Buffer.isBuffer(n.file))throw he("file","a File object (browser) or Buffer (Node.js)");{const r=`${n.tokenName||t}.png`,o=new Blob([n.file],{type:"image/png"});e.append("image",o,r)}}const r=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(n.tokenName||t)}`,data:e,headers:{}});if(!0===r.error||200!==r.status||!r.data?.imageUrl)throw de(r.message||"Image upload failed - no URL returned",r.status);return r.data.imageUrl}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw fe("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){mn(e),e.tokenName&&gn(e.tokenName);const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const n=V(t),r=await this.http.get("/launchpad/fetch-pool",n);if(!0===r.error||200!==r.status||!r.data)throw de(r.message||"Failed to fetch pools",r.status);let o=[];const i=(await import("bignumber.js")).default;if(r.data.tokens)if(Array.isArray(r.data.tokens))o=r.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!new i(t).isZero()||!new i(n).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}});else{const e=r.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",s=!new i(t).isZero()||!new i(n).isZero();o=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:s,createdAt:e.created_at||e.createdAt||""}]}else r.data.pools&&Array.isArray(r.data.pools)&&(o=r.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!new i(t).isZero()||!new i(n).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:s,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return tk});o.forEach(e=>{if(!a(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=s(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=r.data.count??r.data.total??0,u=r.data.page??e.page??1,l=r.data.limit??e.limit??10,h=l>0?Math.ceil(c/l):1;return{pools:o,page:u,limit:l,total:c,totalPages:h,hasNext:u<h,hasPrevious:u>1}}async _getAmount(e){if(wn(e),!this.galaChainHttp)throw fe("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:n}=((e,t,n,r)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:cs,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:us,body:{vaultAddress:n,tokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:ls,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:hs,body:{vaultAddress:n,nativeTokenQuantity:r,IsPreMint:!1}};throw he("type-method","one of: NATIVE-IN, NATIVE-OUT, MEME-IN, MEME-OUT")})(e.type,e.method,e.vaultAddress,e.amount);try{const e=await this.galaChainHttp.post(t,n);if(!fs(e))throw de("Malformed response data from GalaChain gateway");if(1!==e.Status)throw de(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:r,extraFees:o}=e.Data;return{amount:r,reverseBondingCurveFee:o.reverseBondingCurve,transactionFee:o.transactionFees,gasFee:"1"}}catch(r){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:n,error:r instanceof Error?r.message:r}),r}}async checkPool(e){yn(e),e.tokenName&&gn(e.tokenName);const t=V(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw de(n.message||"Failed to check pool",n.status);const r=n.data;return e.symbol?r?.isSymbolExist??!1:e.tokenName?r?.isNameExist??!1:r?.exists??!1}async fetchVolumeData(e){if(!Qn(e))throw new Y("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:o}=e;if(gn(t),!n||!r||!o)throw new Y("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:o};bn(i);const s=V(i),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status||!a.data)throw de(a.message||"Failed to fetch graph data",a.status);return{dataPoints:a.data}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={page:e.page||1,limit:e.limit||10};return e.search&&(n.search=e.search),e.tokenName&&(n.tokenName=e.tokenName),t&&(n.type=t),this.fetchPoolsFromAPI(n)}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async calculateBuyAmount(e){if(!e||"object"!=typeof e)throw new Y("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:n,type:r,currentSupply:o}=e,i=e.mode??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw new Y(`Invalid calculation mode "${i}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new Y("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!n||"string"!=typeof n)throw new Y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==ps.NATIVE&&r!==ps.EXACT)throw new Y('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===i?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",o))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e,o=await this.tokenResolver.resolveTokenToVault(t);if(!o)throw new Y(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return r===ps.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:o,amount:n}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:o,amount:n})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:o,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new Y(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new Y("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!n||"string"!=typeof n)throw new Y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==ps.EXACT&&r!==ps.NATIVE)throw new Y('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==o&&{currentSupply:o},...void 0!==i&&{maxSupply:i},...void 0!==s&&{reverseBondingCurveMaxFeeFactor:s},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e,o=await this.tokenResolver.resolveTokenToVault(t);if(!o)throw new Y(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return r===ps.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:o,amount:n}):this._getAmount({type:"MEME",method:"IN",vaultAddress:o,amount:n})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:o}=e;if(!n||"string"!=typeof n)throw new Y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==ps.NATIVE&&r!==ps.EXACT)throw new Y('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==o&&vn(o,"currentSupply");const i=!o;if(i&&!t)throw new Y("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&gn(t);let s=o;if(i){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===ps.EXACT?ys.calculateBuyWithExact(n,s):ys.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:o,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!n||"string"!=typeof n)throw new Y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(r!==ps.EXACT&&r!==ps.NATIVE)throw new Y('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==o&&vn(o,"currentSupply");const c=!o||!i||void 0===s||void 0===a;if(c&&!t)throw new Y("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&gn(t);let u=o,l=i,h=s,d=a;if(c&&t){const e=this.metadataCache.get(t);l=l??this.metadataCache.getMaxSupply(t),h=h??e?.reverseBondingCurveMaxFeeFactor,d=d??e?.reverseBondingCurveMinFeeFactor,u||(u=await this.fetchCurrentSupply(t));if(void 0===h||void 0===d){const e=await this.fetchPoolDetailsForCalculation(t);h=h??e.reverseBondingCurveMaxFeeFactor,d=d??e.reverseBondingCurveMinFeeFactor}}return r===ps.EXACT?ys.calculateSellWithExact(n,u,l,d,h):ys.calculateSellWithNative(n,u,l,d,h)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return jn(t,"tokenName")&&Xn(t)&&Hn(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:n,calculateAmountMode:r,currentSupply:o}=t;gn(n);const i=await this.tokenResolver.resolveTokenToVault(n);if(!i)throw new Y(Z(n),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw fe("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:i});if(1!==s.Status)throw de(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=(await import("bignumber.js")).default,u=o??new c(a.maxSupply).minus(a.sellingTokenQuantity).toFixed(),l=a.sellingTokenQuantity;if("0"===l)throw new Y(`Token ${n} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const h={tokenName:n,amount:l,type:"exact",currentSupply:u,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(h),remainingTokens:l}}async launchToken(e){if(!this.bundleHttp)throw fe("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");as(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new Y("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration,r=Number(t),o=Number(n);if(isNaN(r)||isNaN(o))throw new Y("Reverse bonding curve fees must be valid numbers","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG");if(r<.1)throw new Y("Minimum fee must be >= 0.1","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG");if(o>.5)throw new Y("Maximum fee must be <= 0.5","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG");if(o<r)throw new Y("Maximum fee must be >= minimum fee","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG")}let n="";if(e.tokenImage)if(e.tokenImage instanceof File||Buffer.isBuffer(e.tokenImage)){const t=await this.uploadImageByTokenName({tokenName:e.tokenName,options:{file:e.tokenImage,tokenName:e.tokenName}});if(!t)throw de("Image upload failed: No URL returned");n=t}else"string"==typeof e.tokenImage&&(n=e.tokenImage);const r=`galaswap - operation - ${F()}-${Date.now()}-${this.http.getAddress()}`,o={tokenName:e.tokenName.trim(),tokenSymbol:e.tokenSymbol.trim().toUpperCase(),tokenDescription:e.tokenDescription.trim(),tokenImage:n.trim(),preBuyQuantity:t.toString(),tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:r};e.websiteUrl?.trim()&&(o.websiteUrl=e.websiteUrl.trim()),e.telegramUrl?.trim()&&(o.telegramUrl=e.telegramUrl.trim()),e.twitterUrl?.trim()&&(o.twitterUrl=e.twitterUrl.trim()),o.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration?.minFeePortion?.toString()||"0.1",maxFeePortion:e.reverseBondingCurveConfiguration?.maxFeePortion?.toString()||"0.5"};const i=new ds(o),s=await this.http.signWithGalaChain("CreateSale",i,d.SIGN_TYPED_DATA),{signature:a,types:c,domain:u,prefix:l}=s,h={tokenName:i.tokenName,tokenSymbol:i.tokenSymbol,tokenDescription:i.tokenDescription,tokenImage:i.tokenImage,preBuyQuantity:i.preBuyQuantity,...i.websiteUrl&&{websiteUrl:i.websiteUrl},...i.telegramUrl&&{telegramUrl:i.telegramUrl},...i.twitterUrl&&{twitterUrl:i.twitterUrl},tokenCategory:i.tokenCategory,tokenCollection:i.tokenCollection,uniqueKey:i.uniqueKey,signature:a,types:c,domain:u,...l&&{prefix:l},...i.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:i.reverseBondingCurveConfiguration}},f=`${e.tokenName.trim()}$Unit$none$none`,p="GALA$Unit$none$none";let g;if(parseFloat(t)>0){const e=`$service$${f}$launchpad`;g=[e,`$token$${f}$${e}`,`$tokenBalance$${f}$${e}`,`$tokenBalance$${f}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`]}else{const e=`$service$${f}$launchpad`;g=[e,`$token$${f}$${e}`,`$tokenBalance$${f}$${e}`]}const m={signedDto:h,stringsInstructions:g,method:"CreateSale"},y=await this.bundleHttp.post("/bundle",m);if(y.error||!y.data)throw de(y.message||"Token launch failed");return y.data}async fetchTokenDistribution(e){if(!e)throw le("tokenName","Token name");gn(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Y(Z(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const n=encodeURIComponent(t),r=await this.http.get(`/holders/${n}`);if(!0===r.error||200!==r.status||!r.data)throw de(r.message||"Failed to fetch token distribution",r.status);const o=r.data;if(!Array.isArray(o))throw de("Invalid API response: expected array of holders",r.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw de("Invalid holder data: missing or invalid owner field",r.status);if(!e.quantity||"string"!=typeof e.quantity)throw de("Invalid holder data: missing or invalid quantity field",r.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw de(`Invalid holder quantity: "${e.quantity}"`,r.status)}const i=o.reduce((e,t)=>e.plus(t.quantity),new y(0));return{holders:o.map(e=>{const t=new y(e.quantity),n=i.isZero()?0:t.dividedBy(i).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:i.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw le("tokenName","Token name");gn(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw de(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const o=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return o?.isActive||!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.nativeTokenQuantity&&(void 0===t.vaultAddress||"string"==typeof t.vaultAddress)}(e))throw new Y("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw fe("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},n=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!fs(n))throw de("Malformed response data from GalaChain gateway");if(1!==n.Status)throw de(`GalaChain calculation failed with status ${n.Status}`,n.Status);const{calculatedQuantity:r,extraFees:o}=n.Data;return{amount:r,reverseBondingCurveFee:o.reverseBondingCurve,transactionFee:o.transactionFees,gasFee:"1"}}catch(e){if(e instanceof Error){const t=new Error(`Pre-mint calculation failed: ${e.message}`);throw e.stack&&(t.stack=e.stack),t}throw new Error(`Pre-mint calculation failed: ${String(e)}`)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Y(Z(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw fe("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw de(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,o=new(0,(await import("bignumber.js")).default)(r.maxSupply).minus(r.sellingTokenQuantity).toFixed(),i=r.sellingTokenQuantity,s=r.maxSupply;let a=.5,c=0;r.reverseBondingCurveConfiguration?(a=parseFloat(r.reverseBondingCurveConfiguration.maxFeePortion),c=parseFloat(r.reverseBondingCurveConfiguration.minFeePortion)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const u=a-c;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:u}),{currentSupply:o,remainingTokens:i,maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:u}}async fetchCurrentSupply(e){gn(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Y(Z(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw fe("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw de(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,o=new(0,(await import("bignumber.js")).default)(r.maxSupply).minus(r.sellingTokenQuantity).toFixed(),i=r.maxSupply;return this.metadataCache.set(e,{maxSupply:i}),o}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return kn(e)}validateTokenName(e){return gn(e)}validatePagination(e){return mn(e)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw fe("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw le("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),n=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&n.push({symbol:e.symbol,price:e.currentPrices.usd})}),n}catch(e){throw de(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return jn(t,"tokenName")&&Xn(t)&&Hn(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:n,calculateAmountMode:r,currentSupply:o}=t;if(!n||"string"!=typeof n)throw le("tokenName","Token name (string)");try{const e={tokenName:n,amount:"1",type:"native",...void 0!==r&&{mode:r},...void 0!==o&&{currentSupply:o}},t=await this.calculateBuyAmount(e),i=(await this.fetchTokenPrice("GALA"))[0];if(!i)throw de("GALA price not available");const s=Number(t.amount);if(s<=0)throw new Y(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");const a=i.price/s;return{symbol:n.toUpperCase(),price:a}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${n}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${n}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}class bs{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw new Error("requestsPerSecond must be greater than zero");this.minIntervalMs=1e3/e}async schedule(e){let t,n;const r=new Promise((e,r)=>{t=e,n=r});if(this.pendingPromise=this.pendingPromise.then(async()=>{const r=Date.now()-this.lastTimestamp,o=Math.max(0,this.minIntervalMs-r);o>0&&await new Promise(e=>setTimeout(e,o)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}function ks(e,t){const n=new y(e);if(!n.isFinite())throw new Error(`Invalid amount: ${e}`);const r=n.multipliedBy(new y(10).pow(t));if(!r.isInteger())throw new Error(`Amount ${e} cannot be represented with ${t} decimals`);return BigInt(r.toFixed(0))}function vs(e,t){return new y(e.toString()).dividedBy(new y(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}function Es(e,t=6){const n=new y(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!n.isZero())return n.toExponential(2);const r=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return n.toFixed(r).replace(/\.?0+$/,"")}function Ss(e,t){const n=new y(e),r=new y(t);return n.comparedTo(r)}const As={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},Ts=new Set([408,429,500,502,503,504]),Is=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function xs(e){if(e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return Ts.has(t.status);if("number"==typeof t.statusCode)return Ts.has(t.statusCode);if("string"==typeof t.code&&("ECONNRESET"===t.code||"ECONNREFUSED"===t.code||"ETIMEDOUT"===t.code||"ENOTFOUND"===t.code||"EAI_AGAIN"===t.code))return!0}const t=e instanceof Error?e.message:String(e);return Is.some(e=>e.test(t))}function Bs(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),r=Math.min(n,t.maxDelayMs),o=r*t.jitterFactor*Math.random();return Math.floor(r+o)}function Cs(e){let t;if("string"==typeof e)t=function(e){const t=e.split("|");if(t.length<4)throw new Error(`Invalid token string format: "${e}". Expected "collection|category|type|additionalKey" format.`);return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}(e);else{if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.collection&&"string"==typeof t.category&&"string"==typeof t.type&&"string"==typeof t.additionalKey}(e))throw new Error('Invalid tokenId format. Expected pipe-delimited string (e.g., "GALA|Unit|none|none") or TokenClassKey object.');t=e}var n;return{tokenClassKey:t,stringified:`${(n=t).collection}|${n.category}|${n.type}|${n.additionalKey}`}}class Ps extends Error{constructor(e,t,n){super(`GalaConnect request to ${t} failed with status ${e}${n?`: ${JSON.stringify(n)}`:""}`),this.status=e,this.path=t,this.responseBody=n,this.name="GalaConnectHttpError"}}const Ns=Fi,_s="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",Us=12,Ds=!0,Rs=3,Fs=1e3;class Ls{constructor(e){this.baseUrl=e.baseUrl??Ns,this.galachainBaseUrl=e.galachainBaseUrl??_s,this.walletAddress=e.walletAddress,this.rateLimiter=new bs(e.requestsPerSecond??Us),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??Ds;this.retryOptions=t?{maxRetries:e.maxRetries??Rs,initialDelayMs:e.retryInitialDelayMs??Fs,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>xs(e instanceof Ps?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){const t=new URL("/v1/connect/bridge-configurations",this.baseUrl);t.searchParams.set("searchprefix",e);const n=await this.request(t.toString(),{method:"GET"});if(!n.ok)throw new Ps(n.status,"/v1/connect/bridge-configurations",await this.safeParseJson(n));return(await n.json()).data.tokens}async fetchBridgeFee(e){return this.postJson("/v1/bridge/fee",e,{skipWalletHeader:!0})}async requestBridgeOut(e){return this.postJson("/v1/RequestTokenBridgeOut",e)}async bridgeTokenOut(e){return this.postJson("/v1/BridgeTokenOut",e)}async getBridgeStatus(e){return this.postJson("/v1/bridge/status",{hash:e})}async registerBridgeTransaction(e){return this.postJson("/v1/bridge/transaction",e)}async fetchBalances(e="asset"){return this.postJson("/v1/FetchBalances",{owner:this.walletAddress,channel:e},{baseUrl:this.galachainBaseUrl})}async postJson(e,t,n={}){const r=n.baseUrl??this.baseUrl,o=new URL(e,r),i=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,s=await this.request(o.toString(),{method:"POST",headers:i,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)}),a=await s.text();let c;if(a)try{c=JSON.parse(a)}catch(t){const n=new Error(`Failed to parse JSON response from ${e}: ${t.message}`);if(!s.ok)throw new Ps(s.status,e,{parseError:n.message,rawBody:a.slice(0,500)});throw n}if(!s.ok)throw new Ps(s.status,e,c);return c}async request(e,t){const n=async()=>this.rateLimiter.schedule(async()=>{const n={...this.defaultHeaders,...t.headers};""===n["X-Wallet-Address"]?delete n["X-Wallet-Address"]:n["X-Wallet-Address"]||(n["X-Wallet-Address"]=this.walletAddress);const r=await fetch(e,{...t,headers:n});if(this.retryOptions&&!r.ok){const t=r.status;if(429===t||t>=500){const n=r.clone(),o=await this.safeParseJson(n);throw new Ps(t,e,o)}}return r});return this.retryOptions?async function(e,t={}){const n={...As,...t},r=t.shouldRetry??(e=>xs(e));let o;for(let i=1;i<=n.maxRetries+1;i++)try{return await e()}catch(e){if(o=e,i>n.maxRetries)break;if(!r(e,i))break;const s=Bs(i,n);t.onRetry&&t.onRetry(e,i,s),await new Promise(e=>setTimeout(e,s))}throw o}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}var Os;!function(e){e[e.PENDING=0]="PENDING",e[e.SUBMITTED=1]="SUBMITTED",e[e.CONFIRMED=2]="CONFIRMED",e[e.PROCESSING=3]="PROCESSING",e[e.FINALIZING=4]="FINALIZING",e[e.COMPLETED=5]="COMPLETED",e[e.FAILED=6]="FAILED",e[e.DELIVERY_FAILED=7]="DELIVERY_FAILED"}(Os||(Os={}));class Ms{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:o}=t,i=Date.now();for(;;){const t=await this.getStatus(e);if(o&&o(t),t.status===Os.COMPLETED||t.status===Os.FAILED||t.status===Os.DELIVERY_FAILED)return t;if(Date.now()-i>r)throw new Error(`Bridge transaction ${e} timed out after ${r}ms. Last status: ${t.status}`);await new Promise(e=>setTimeout(e,n))}}}class $s extends Ms{constructor(e){if(super(),this.network="Ethereum",this.tokenMetadataCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,!e.ethereumPrivateKey||!/^0x[a-fA-F0-9]{64}$/.test(e.ethereumPrivateKey))throw new Error("Invalid Ethereum private key format. Expected 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)");const t=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new n(t),this.ethereumWallet=new r(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenConfigs=new Map;const o=e.tokenConfigs??qi;for(const e of o)this.tokenConfigs.set(e.symbol.toUpperCase(),e)}async estimateFee(e,t){const n=await this.getTokenMetadata(e),r=await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor});return{estimatedFeeInGala:r.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:r.estimatedTotalTxFeeInExternalToken,feeToken:r.bridgeToken,pricePerUnit:r.estimatedPricePerTxFeeUnit,estimatedGasUnits:r.estimatedTxFeeUnitsTotal,exchangeRate:r.galaExchangeRate?.exchangeRate??"0",timestamp:r.timestamp,raw:r}}async bridgeOut(e){const{amount:t,recipientAddress:n,tokenSymbol:r}=e;if(!r)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const i=r,s=parseFloat(t);if(isNaN(s)||s<=0)throw new Error(`Invalid bridge amount for ${i}: "${t}". Amount must be a positive number.`);if(!o(n))throw new Error(`Invalid Ethereum recipient address: "${n}". Expected valid 0x-prefixed address.`);const a=await this.getTokenMetadata(i),c=await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:a.descriptor}),u={destinationChainId:Ai.ETHEREUM,destinationChainTxFee:c,quantity:t,recipient:n,tokenInstance:{...a.descriptor,instance:"0"}},l=await this.buildBridgeOutPayload(u),h=await this.galaConnectClient.requestBridgeOut(l),d=this.extractBridgeRequestId(h);if(!d)throw new Error("Bridge request ID missing from RequestTokenBridgeOut response");const f=await this.galaConnectClient.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:d}),p=f.Hash??f.hash??"";if(!p)throw new Error("BridgeTokenOut response missing transaction hash");return{direction:"outbound",fromChain:"GalaChain",toChain:"Ethereum",transactionHash:p,tokenSymbol:i,amount:t,feePaid:c.estimatedTotalTxFeeInGala,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${p}`}}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:o,tokenSymbol:s}=e;if(!s)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const a=s,c=parseFloat(t);if(isNaN(c)||c<=0)throw new Error(`Invalid bridge amount for ${a}: "${t}". Amount must be a positive number.`);if(n&&!/^0x[a-fA-F0-9]{64}$/.test(n))throw new Error("Invalid sourcePrivateKey format. Expected 0x-prefixed 64-character hex string.");const u=n?new r(n,this.ethereumProvider):this.ethereumWallet,l=this.tokenConfigs.get(a.toUpperCase());if(!l)throw new Error(`Token ${a} not supported for Ethereum bridge`);const h=await this.getTokenMetadata(a),d=new i(l.contractAddress,Wi,u),f=await d.decimals(),p=Number(f),g=ks(t,p),m=BigInt(await d.balanceOf(u.address));if(m<g){const e=vs(g,p),t=vs(m,p);throw new Error(`Insufficient ${a} balance on Ethereum. Needed ${e}, have ${t}`)}const y=this.normalizeGalaChainAddress(o??this.galaChainWalletAddress),w=await this.executeBridgeDeposit({wallet:u,tokenContract:d,tokenConfig:l,amountBaseUnits:g,decimals:p,recipient:y,metadata:h});return{direction:"inbound",fromChain:"Ethereum",toChain:"GalaChain",transactionHash:w.txHash,tokenSymbol:a,amount:t,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${w.txHash}`}}async getStatus(e){const t=await this.galaConnectClient.getBridgeStatus(e),n=t.status;return{status:n,statusDescription:t.statusDescription,fromChain:t.fromChain,toChain:t.toChain,quantity:t.quantity,transactionHash:t.emitterTransactionHash,tokenInstance:t.tokenInstance,isComplete:5===n,isFailed:6===n||7===n}}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(e.toUpperCase())}isValidAddress(e){return/^0x[a-fA-F0-9]{40}$/.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const n=this.tokenConfigs.get(e.toUpperCase());if(!n){const t=Array.from(this.tokenConfigs.keys()).join(", ");throw new Error(`Token ${e} not supported for Ethereum. Supported: ${t}`)}const r=t??this.ethereumWalletAddress;if(!o(r))throw new Error(`Invalid Ethereum address: "${r}"`);const s=new i(n.contractAddress,Wi,this.ethereumProvider);return vs(await s.balanceOf(r),n.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;if(!o(t))throw new Error(`Invalid Ethereum address: "${t}"`);return vs(await this.ethereumProvider.getBalance(t),18)}async getEthereumTransactionStatus(e){if(!/^0x[a-fA-F0-9]{64}$/.test(e))throw new Error(`Invalid Ethereum transaction hash format: "${e}". Expected 0x-prefixed 64-character hex string (66 total characters).`);const t=e.toLowerCase();try{const e=await this.ethereumProvider.getTransactionReceipt(t);if(e){const n=await this.ethereumProvider.getBlockNumber()-e.blockNumber+1;if(!(1===e.status))return{confirmed:!1,status:"failed",blockNumber:e.blockNumber,confirmations:n,transactionHash:t,gasUsed:e.gasUsed.toString(),effectiveGasPrice:e.gasPrice?.toString(),error:"Transaction reverted during execution"};return{confirmed:!0,status:n>=$s.ETHEREUM_FINALITY_THRESHOLD?"finalized":"confirmed",blockNumber:e.blockNumber,confirmations:n,transactionHash:t,gasUsed:e.gasUsed.toString(),effectiveGasPrice:e.gasPrice?.toString()}}return await this.ethereumProvider.getTransaction(t)?{confirmed:!1,status:"pending",transactionHash:t}:{confirmed:!1,status:"not_found",transactionHash:t,error:"Transaction not found on Ethereum network"}}catch(e){return{confirmed:!1,status:"not_found",transactionHash:t,error:`Failed to query transaction status: ${e instanceof Error?e.message:String(e)}`}}}async getTokenMetadata(e){const t=this.tokenMetadataCache.get(e.toUpperCase());if(t)return t;const n=Gi[e.toUpperCase()];if(n)return this.tokenMetadataCache.set(e.toUpperCase(),n),n;let r=e,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified);if(i||e.startsWith("G")||(r=`G${e}`,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified)),!i)throw new Error(`Unable to locate token metadata for ${e}`);const s={descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:i.decimals,...i.channel&&{channel:i.channel}};return this.tokenMetadataCache.set(e.toUpperCase(),s),s}async buildBridgeOutPayload(e){const t=e.uniqueKey??`galaconnect-operation-${O.randomUUID()}`,n="string"==typeof e.destinationChainId?Number(e.destinationChainId):e.destinationChainId,r=this.normalizeDestinationChainTxFee(e.destinationChainTxFee),o=Boolean(r.galaExchangeCrossRate),i=o?{...r,galaExchangeRate:void 0}:{...r,galaExchangeCrossRate:void 0},s={destinationChainId:n,destinationChainTxFee:this.sanitizeObject(i),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:t},a=os(o),c=await this.ethereumWallet.signTypedData(Zi,a,s),u=`Ethereum Signed Message:\n${Si({domain:Zi,message:s,primaryType:"GalaTransaction",types:a}).length}`;return{...s,signature:c,prefix:u,types:a,domain:Zi}}async executeBridgeDeposit(e){const t=new i(this.ethereumBridgeContract,zi,e.wallet),n=(new TextEncoder).encode(e.recipient);let r;r=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,t,e.amountBaseUnits,n):await this.bridgeWithApproval(e.wallet,e.tokenContract,t,e.tokenConfig,e.amountBaseUnits,n);if(!await r.wait())throw new Error("Bridge transaction receipt not available");await this.delay(3e4);const o={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:vs(e.amountBaseUnits,e.decimals),tokenInstance:o,fromChain:"Ethereum",toChain:"GC",hash:r.hash}),{txHash:r.hash}}async bridgeWithPermit(e,t,n,r,o,i){const a=await this.ethereumProvider.getNetwork(),c=await t.name(),u=await t.nonces(e.address),l=BigInt(Math.floor(Date.now()/1e3)+3600),h=await e.signTypedData({name:c,version:"1",chainId:Number(a.chainId),verifyingContract:n.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:e.address,spender:this.ethereumBridgeContract,value:o,nonce:u,deadline:l}),d=s.from(h);return r.bridgeOutWithPermit(n.contractAddress,o,Ai.GALA_CHAIN,i,l,d.v,d.r,d.s)}async bridgeWithApproval(e,t,n,r,o,i){const s=await t.allowance(e.address,this.ethereumBridgeContract);if(BigInt(s)<o){const e=await t.approve(this.ethereumBridgeContract,o);await e.wait()}return n.bridgeOut(r.contractAddress,o,0,Ai.GALA_CHAIN,i)}normalizeDestinationChainTxFee(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Number(e.galaDecimals):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Number(e.timestamp):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Number(e.galaExchangeRate.timestamp):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Number(n.timestamp):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Number(n.baseTokenCrossRate.timestamp):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Number(n.quoteTokenCrossRate.timestamp):n.quoteTokenCrossRate.timestamp})}return t}sanitizeObject(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=this.sanitizeObject(r):t[n]=r);return t}extractBridgeRequestId(e){if("string"==typeof e.Data)return e.Data;if(null!=e.data){if("string"==typeof e.data)return e.data;if("object"==typeof e.data){const t=e.data;if("string"==typeof t.Data)return t.Data}}}async delay(e){return new Promise(t=>setTimeout(t,e))}normalizeGalaChainAddress(e){let t;if(e.startsWith("eth|"))t=e.slice(4);else{if(e.startsWith("client|"))return e;t=e}if((t.startsWith("0x")||t.startsWith("0X"))&&(t=t.slice(2)),!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid GalaChain address format: ${e}`);return`eth|${a("0x"+t).slice(2)}`}}$s.ETHEREUM_FINALITY_THRESHOLD=12;var qs,Ks={},Gs={};function Ws(){if(qs)return Gs;qs=1,Gs.byteLength=function(e){var t=i(e),n=t[0],r=t[1];return 3*(n+r)/4-r},Gs.toByteArray=function(e){var r,o,s=i(e),a=s[0],c=s[1],u=new n(function(e,t,n){return 3*(t+n)/4-n}(0,a,c)),l=0,h=c>0?a-4:a;for(o=0;o<h;o+=4)r=t[e.charCodeAt(o)]<<18|t[e.charCodeAt(o+1)]<<12|t[e.charCodeAt(o+2)]<<6|t[e.charCodeAt(o+3)],u[l++]=r>>16&255,u[l++]=r>>8&255,u[l++]=255&r;2===c&&(r=t[e.charCodeAt(o)]<<2|t[e.charCodeAt(o+1)]>>4,u[l++]=255&r);1===c&&(r=t[e.charCodeAt(o)]<<10|t[e.charCodeAt(o+1)]<<4|t[e.charCodeAt(o+2)]>>2,u[l++]=r>>8&255,u[l++]=255&r);return u},Gs.fromByteArray=function(t){for(var n,r=t.length,o=r%3,i=[],s=16383,c=0,u=r-o;c<u;c+=s)i.push(a(t,c,c+s>u?u:c+s));1===o?(n=t[r-1],i.push(e[n>>2]+e[n<<4&63]+"==")):2===o&&(n=(t[r-2]<<8)+t[r-1],i.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"="));return i.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)e[o]=r[o],t[r.charCodeAt(o)]=o;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function s(t){return e[t>>18&63]+e[t>>12&63]+e[t>>6&63]+e[63&t]}function a(e,t,n){for(var r,o=[],i=t;i<n;i+=3)r=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),o.push(s(r));return o.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,Gs}var zs,js,Hs={};function Vs(){return zs||(zs=1,Hs.read=function(e,t,n,r,o){var i,s,a=8*o-r-1,c=(1<<a)-1,u=c>>1,l=-7,h=n?o-1:0,d=n?-1:1,f=e[t+h];for(h+=d,i=f&(1<<-l)-1,f>>=-l,l+=a;l>0;i=256*i+e[t+h],h+=d,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=r;l>0;s=256*s+e[t+h],h+=d,l-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,r),i-=u}return(f?-1:1)*s*Math.pow(2,i-r)},Hs.write=function(e,t,n,r,o,i){var s,a,c,u=8*i-o-1,l=(1<<u)-1,h=l>>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:i-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(s++,c/=2),s+h>=l?(a=0,s=l):s+h>=1?(a=(t*c-1)*Math.pow(2,o),s+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,o),s=0));o>=8;e[n+f]=255&a,f+=p,a/=256,o-=8);for(s=s<<o|a,u+=o;u>0;e[n+f]=255&s,f+=p,s/=256,u-=8);e[n+f-p]|=128*g}),Hs}var Xs=(js||(js=1,function(e){const t=Ws(),n=Vs(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;function i(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=i(n);const o=r.write(e,t);return o!==n&&(r=r.slice(0,o)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);const o=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||V(e.length)?i(0):l(e):"Buffer"===e.type&&Array.isArray(e.data)?l(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),i(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=i(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function d(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(o)return r?-1:W(e).length;t=(""+t).toLowerCase(),o=!0}}function p(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return B(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return j(W(t,e.length-n),e,n,r)}function k(e,t,n,r){return j(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return j(z(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function A(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=o,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let o=0;for(n=0;n<e.length;++n){let t=e[n];if(H(t,Uint8Array))o+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)g(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?A(this,0,e):p.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,o){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){i=u[e],a=l[e];break}return i<a?-1:a<i?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function x(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function B(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=X[e[r]];return o}function C(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function P(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function U(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function F(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,8),n.write(e,t,r,o,52,8),r+8}s.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return _(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=Q(function(e,t=0){return _(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const o=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),o},s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{const i=s.isBuffer(e)?e:s.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%a]}return this};const L={};function O(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function M(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,o,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,o,i)}function q(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}O("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),O("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),O("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=M(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=M(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function z(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function H(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(Ks)),Ks);const Qs="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Zs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Ys(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Js(e,...t){if(!Zs(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ea(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Ys(e.outputLen),Ys(e.blockLen)}function ta(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function na(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ra(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function oa(e,t){return e<<32-t|e>>>t}const ia=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),sa=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function aa(e){if(Js(e),ia)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=sa[e[n]];return t}const ca=48,ua=57,la=65,ha=70,da=97,fa=102;function pa(e){return e>=ca&&e<=ua?e-ca:e>=la&&e<=ha?e-(la-10):e>=da&&e<=fa?e-(da-10):void 0}function ga(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(ia)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,o=0;t<n;t++,o+=2){const n=pa(e.charCodeAt(o)),i=pa(e.charCodeAt(o+1));if(void 0===n||void 0===i){const t=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+o)}r[t]=16*n+i}return r}function ma(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),Js(e),e}function ya(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Js(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const o=e[t];n.set(o,r),r+=o.length}return n}class wa{}function ba(e){const t=t=>e().update(ma(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function ka(e=32){if(Qs&&"function"==typeof Qs.getRandomValues)return Qs.getRandomValues(new Uint8Array(e));if(Qs&&"function"==typeof Qs.randomBytes)return Uint8Array.from(Qs.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function va(e,t,n){return e&t^~e&n}function Ea(e,t,n){return e&t^e&n^t&n}class Sa extends wa{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=ra(this.buffer)}update(e){ta(this),Js(e=ma(e));const{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){const s=Math.min(r-this.pos,o-i);if(s===r){const t=ra(e);for(;r<=o-i;i+=r)this.process(t,i);continue}n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ta(this),function(e,t){Js(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:o}=this;let{pos:i}=this;t[i++]=128,na(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(n,0),i=0);for(let e=i;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),c=r?4:0,u=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+u,a,r)}(n,r-8,BigInt(8*this.length),o),this.process(n,0);const s=ra(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)s.setUint32(4*e,u[e],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=o,e.length=r,e.pos=s,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Aa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ta=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ia=BigInt(2**32-1),xa=BigInt(32);function Ba(e,t=!1){return t?{h:Number(e&Ia),l:Number(e>>xa&Ia)}:{h:0|Number(e>>xa&Ia),l:0|Number(e&Ia)}}const Ca=(e,t,n)=>e>>>n,Pa=(e,t,n)=>e<<32-n|t>>>n,Na=(e,t,n)=>e>>>n|t<<32-n,_a=(e,t,n)=>e<<32-n|t>>>n,Ua=(e,t,n)=>e<<64-n|t>>>n-32,Da=(e,t,n)=>e>>>n-32|t<<64-n;function Ra(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:0|o}}const Fa=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),La=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Oa=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ma=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,$a=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),qa=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0,Ka=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]),Ga=new Uint32Array(64);class Wa extends Sa{constructor(e=32){super(64,e,8,!1),this.A=0|Aa[0],this.B=0|Aa[1],this.C=0|Aa[2],this.D=0|Aa[3],this.E=0|Aa[4],this.F=0|Aa[5],this.G=0|Aa[6],this.H=0|Aa[7]}get(){const{A:e,B:t,C:n,D:r,E:o,F:i,G:s,H:a}=this;return[e,t,n,r,o,i,s,a]}set(e,t,n,r,o,i,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|i,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)Ga[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Ga[e-15],n=Ga[e-2],r=oa(t,7)^oa(t,18)^t>>>3,o=oa(n,17)^oa(n,19)^n>>>10;Ga[e]=o+Ga[e-7]+r+Ga[e-16]|0}let{A:n,B:r,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(oa(s,6)^oa(s,11)^oa(s,25))+va(s,a,c)+Ka[e]+Ga[e]|0,l=(oa(n,2)^oa(n,13)^oa(n,22))+Ea(n,r,o)|0;u=c,c=a,a=s,s=i+t|0,i=o,o=r,r=n,n=t+l|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,o,i,s,a,c,u)}roundClean(){na(Ga)}destroy(){this.set(0,0,0,0,0,0,0,0),na(this.buffer)}}const za=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){const{h:n,l:s}=Ba(e[i],t);[r[i],o[i]]=[n,s]}return[r,o]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),ja=(()=>za[0])(),Ha=(()=>za[1])(),Va=new Uint32Array(80),Xa=new Uint32Array(80);class Qa extends Sa{constructor(e=64){super(128,e,16,!1),this.Ah=0|Ta[0],this.Al=0|Ta[1],this.Bh=0|Ta[2],this.Bl=0|Ta[3],this.Ch=0|Ta[4],this.Cl=0|Ta[5],this.Dh=0|Ta[6],this.Dl=0|Ta[7],this.Eh=0|Ta[8],this.El=0|Ta[9],this.Fh=0|Ta[10],this.Fl=0|Ta[11],this.Gh=0|Ta[12],this.Gl=0|Ta[13],this.Hh=0|Ta[14],this.Hl=0|Ta[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:o,Cl:i,Dh:s,Dl:a,Eh:c,El:u,Fh:l,Fl:h,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[e,t,n,r,o,i,s,a,c,u,l,h,d,f,p,g]}set(e,t,n,r,o,i,s,a,c,u,l,h,d,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|o,this.Cl=0|i,this.Dh=0|s,this.Dl=0|a,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|h,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let n=0;n<16;n++,t+=4)Va[n]=e.getUint32(t),Xa[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Va[e-15],n=0|Xa[e-15],r=Na(t,n,1)^Na(t,n,8)^Ca(t,0,7),o=_a(t,n,1)^_a(t,n,8)^Pa(t,n,7),i=0|Va[e-2],s=0|Xa[e-2],a=Na(i,s,19)^Ua(i,s,61)^Ca(i,0,6),c=_a(i,s,19)^Da(i,s,61)^Pa(i,s,6),u=Oa(o,c,Xa[e-7],Xa[e-16]),l=Ma(u,r,a,Va[e-7],Va[e-16]);Va[e]=0|l,Xa[e]=0|u}let{Ah:n,Al:r,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:u,Eh:l,El:h,Fh:d,Fl:f,Gh:p,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Na(l,h,14)^Na(l,h,18)^Ua(l,h,41),w=_a(l,h,14)^_a(l,h,18)^Da(l,h,41),b=l&d^~l&p,k=$a(y,w,h&f^~h&g,Ha[e],Xa[e]),v=qa(k,m,t,b,ja[e],Va[e]),E=0|k,S=Na(n,r,28)^Ua(n,r,34)^Ua(n,r,39),A=_a(n,r,28)^Da(n,r,34)^Da(n,r,39),T=n&o^n&s^o&s,I=r&i^r&a^i&a;m=0|p,y=0|g,p=0|d,g=0|f,d=0|l,f=0|h,({h:l,l:h}=Ra(0|c,0|u,0|v,0|E)),c=0|s,u=0|a,s=0|o,a=0|i,o=0|n,i=0|r;const x=Fa(E,A,I);n=La(x,v,S,T),r=0|x}({h:n,l:r}=Ra(0|this.Ah,0|this.Al,0|n,0|r)),({h:o,l:i}=Ra(0|this.Bh,0|this.Bl,0|o,0|i)),({h:s,l:a}=Ra(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:u}=Ra(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:h}=Ra(0|this.Eh,0|this.El,0|l,0|h)),({h:d,l:f}=Ra(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=Ra(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:y}=Ra(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,o,i,s,a,c,u,l,h,d,f,p,g,m,y)}roundClean(){na(Va,Xa)}destroy(){na(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Za=ba(()=>new Wa),Ya=ba(()=>new Qa),Ja=BigInt(0),ec=BigInt(1);function tc(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function nc(e,t,n=""){const r=Zs(e),o=e?.length,i=void 0!==t;if(!r||i&&o!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(r?`length=${o}`:"type="+typeof e))}return e}function rc(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function oc(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Ja:BigInt("0x"+e)}function ic(e){return oc(aa(e))}function sc(e){return Js(e),oc(aa(Uint8Array.from(e).reverse()))}function ac(e,t){return ga(e.toString(16).padStart(2*t,"0"))}function cc(e,t){return ac(e,t).reverse()}function uc(e,t,n){let r;if("string"==typeof t)try{r=ga(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Zs(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const o=r.length;if("number"==typeof n&&o!==n)throw new Error(e+" of length "+n+" expected, got "+o);return r}function lc(e){return Uint8Array.from(e)}const hc=e=>"bigint"==typeof e&&Ja<=e;function dc(e,t,n,r){if(!function(e,t,n){return hc(e)&&hc(t)&&hc(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function fc(e){let t;for(t=0;e>Ja;e>>=ec,t+=1);return t}const pc=e=>(ec<<BigInt(e))-ec;function gc(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const o=e[t];if(r&&void 0===o)return;const i=typeof o;if(i!==n||null===o)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function mc(e){const t=new WeakMap;return(n,...r)=>{const o=t.get(n);if(void 0!==o)return o;const i=e(n,...r);return t.set(n,i),i}}const yc=BigInt(0),wc=BigInt(1),bc=BigInt(2),kc=BigInt(3),vc=BigInt(4),Ec=BigInt(5),Sc=BigInt(7),Ac=BigInt(8),Tc=BigInt(9),Ic=BigInt(16);function xc(e,t){const n=e%t;return n>=yc?n:t+n}function Bc(e,t,n){let r=e;for(;t-- >yc;)r*=r,r%=n;return r}function Cc(e,t){if(e===yc)throw new Error("invert: expected non-zero number");if(t<=yc)throw new Error("invert: expected positive modulus, got "+t);let n=xc(e,t),r=t,o=yc,i=wc;for(;n!==yc;){const e=r%n,t=o-i*(r/n);r=n,n=e,o=i,i=t}if(r!==wc)throw new Error("invert: does not exist");return xc(o,t)}function Pc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Nc(e,t){const n=(e.ORDER+wc)/vc,r=e.pow(t,n);return Pc(e,r,t),r}function _c(e,t){const n=(e.ORDER-Ec)/Ac,r=e.mul(t,bc),o=e.pow(r,n),i=e.mul(t,o),s=e.mul(e.mul(i,bc),o),a=e.mul(i,e.sub(s,e.ONE));return Pc(e,a,t),a}function Uc(e){if(e<kc)throw new Error("sqrt is not defined for small field");let t=e-wc,n=0;for(;t%bc===yc;)t/=bc,n++;let r=bc;const o=Mc(e);for(;1===Lc(o,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Nc;let i=o.pow(r,t);const s=(t+wc)/bc;return function(e,r){if(e.is0(r))return r;if(1!==Lc(e,r))throw new Error("Cannot find square root");let o=n,a=e.mul(e.ONE,i),c=e.pow(r,t),u=e.pow(r,s);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===o)throw new Error("Cannot find square root");const r=wc<<BigInt(o-t-1),i=e.pow(a,r);o=t,a=e.sqr(i),c=e.mul(c,a),u=e.mul(u,i)}return u}}function Dc(e){return e%vc===kc?Nc:e%Ac===Ec?_c:e%Ic===Tc?function(e){const t=Mc(e),n=Uc(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+Sc)/Ic;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,r);const c=e.mul(n,o),u=e.mul(n,i),l=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);n=e.cmov(n,a,l),a=e.cmov(u,c,h);const d=e.eql(e.sqr(a),t),f=e.cmov(n,a,d);return Pc(e,f,t),f}}(e):Uc(e)}const Rc=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Fc(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce((t,n,o)=>e.is0(n)?t:(r[o]=t,e.mul(t,n)),e.ONE),i=e.inv(o);return t.reduceRight((t,n,o)=>e.is0(n)?t:(r[o]=e.mul(t,r[o]),e.mul(t,n)),i),r}function Lc(e,t){const n=(e.ORDER-wc)/bc,r=e.pow(t,n),o=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Oc(e,t){void 0!==t&&Ys(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Mc(e,t,n=!1,r={}){if(e<=yc)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,i,s,a=!1;if("object"==typeof t&&null!=t){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(o=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),s=e.allowedLengths}else"number"==typeof t&&(o=t),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:u}=Oc(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const h=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:u,MASK:pc(c),ZERO:yc,ONE:wc,allowedLengths:s,create:t=>xc(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return yc<=t&&t<e},is0:e=>e===yc,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&wc)===wc,neg:t=>xc(-t,e),eql:(e,t)=>e===t,sqr:t=>xc(t*t,e),add:(t,n)=>xc(t+n,e),sub:(t,n)=>xc(t-n,e),mul:(t,n)=>xc(t*n,e),pow:(e,t)=>function(e,t,n){if(n<yc)throw new Error("invalid exponent, negatives unsupported");if(n===yc)return e.ONE;if(n===wc)return t;let r=e.ONE,o=t;for(;n>yc;)n&wc&&(r=e.mul(r,o)),o=e.sqr(o),n>>=wc;return r}(h,e,t),div:(t,n)=>xc(t*Cc(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Cc(t,e),sqrt:i||(t=>(l||(l=Dc(e)),l(h,t))),toBytes:e=>n?cc(e,u):ac(e,u),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>u)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);const e=new Uint8Array(u);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+t.length);let o=n?sc(t):ic(t);if(a&&(o=xc(o,e)),!r&&!h.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o},invertBatch:e=>Fc(h,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(h)}function $c(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function qc(e){const t=$c(e);return t+Math.ceil(t/2)}const Kc=BigInt(0),Gc=BigInt(1);function Wc(e,t){const n=t.negate();return e?n:t}function zc(e,t){const n=Fc(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function jc(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Hc(e,t){jc(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:pc(e),maxNumber:n,shiftBy:BigInt(e)}}function Vc(e,t,n){const{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n;let a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=Gc);const u=t*r;return{nextN:c,offset:u+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:u}}const Xc=new WeakMap,Qc=new WeakMap;function Zc(e){return Qc.get(e)||1}function Yc(e){if(e!==Kc)throw new Error("invalid wNAF")}class Jc{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>Kc;)t&Gc&&(n=n.add(r)),r=r.double(),t>>=Gc;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Hc(t,this.bits),o=[];let i=e,s=i;for(let e=0;e<n;e++){s=i,o.push(s);for(let e=1;e<r;e++)s=s.add(i),o.push(s);i=s.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,o=this.BASE;const i=Hc(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:u,isNegF:l,offsetF:h}=Vc(n,e,i);n=s,c?o=o.add(Wc(l,t[h])):r=r.add(Wc(u,t[a]))}return Yc(n),{p:r,f:o}}wNAFUnsafe(e,t,n,r=this.ZERO){const o=Hc(e,this.bits);for(let e=0;e<o.windows&&n!==Kc;e++){const{nextN:i,offset:s,isZero:a,isNeg:c}=Vc(n,e,o);if(n=i,!a){const e=t[s];r=r.add(c?e.negate():e)}}return Yc(n),r}getPrecomputes(e,t,n){let r=Xc.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Xc.set(t,r))),r}cached(e,t,n){const r=Zc(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const o=Zc(e);return 1===o?this._unsafeLadder(e,t,r):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,r)}createCache(e,t){jc(t,this.bits),Qc.set(e,t),Xc.delete(e)}hasCache(e){return 1!==Zc(e)}}function eu(e,t,n,r){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}(n,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}(r,t);const o=n.length,i=r.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=fc(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=pc(c),l=new Array(Number(u)+1).fill(s);let h=s;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){l.fill(s);for(let t=0;t<i;t++){const o=r[t],i=Number(o>>BigInt(e)&u);l[i]=l[i].add(n[t])}let t=s;for(let e=l.length-1,n=s;e>0;e--)n=n.add(l[e]),t=t.add(n);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function tu(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){gc(e,Rc.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Mc(e,{isLE:n})}function nu(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>Kc))throw new Error(`CURVE.${e} must be positive bigint`)}const o=tu(t.p,n.Fp,r),i=tu(t.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of s)if(!o.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:o,Fn:i}}const ru=BigInt(0),ou=BigInt(1),iu=BigInt(2),su=BigInt(8);function au(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');gc(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:i,Fn:s}=e,a=n.randomBytes||ka,c=n.adjustScalarBytes||(e=>e),u=n.domain||((e,t,n)=>{if(tc(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return s.create(sc(e))}function h(e){const{head:n,prefix:r,scalar:i}=function(e){const n=m.secretKey;e=uc("private key",e,n);const r=uc("hashed private key",t(e),2*n),o=c(r.slice(0,n));return{head:o,prefix:r.slice(n,2*n),scalar:l(o)}}(e),s=o.multiply(i),a=s.toBytes();return{head:n,prefix:r,scalar:i,point:s,pointBytes:a}}function d(e){return h(e).pointBytes}function f(e=Uint8Array.of(),...n){const o=ya(...n);return l(t(u(o,uc("context",e),!!r)))}const p={zip215:!0};const g=i.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function y(e=a(m.seed)){return nc(e,m.seed,"seed")}const w={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:function(e){return Zs(e)&&e.length===s.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},toMontgomery(t){const{y:n}=e.fromBytes(t),r=m.publicKey,o=32===r;if(!o&&57!==r)throw new Error("only defined for 25519 and 448");const s=o?i.div(ou+n,ou-n):i.div(n-ou,n+ou);return i.toBytes(s)},toMontgomerySecret(e){const n=m.secretKey;nc(e,n);const r=t(e.subarray(0,n));return c(r).subarray(0,n)},randomPrivateKey:y,precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=w.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign:function(e,t,n={}){e=uc("message",e),r&&(e=r(e));const{prefix:i,scalar:a,pointBytes:c}=h(t),u=f(n.context,i,e),l=o.multiply(u).toBytes(),d=f(n.context,l,c,e),p=s.create(u+d*a);if(!s.isValid(p))throw new Error("sign failed: invalid s");return nc(ya(l,s.toBytes(p)),m.signature,"result")},verify:function(t,n,i,s=p){const{context:a,zip215:c}=s,u=m.signature;t=uc("signature",t,u),n=uc("message",n),i=uc("publicKey",i,m.publicKey),void 0!==c&&tc(c,"zip215"),r&&(n=r(n));const l=u/2,h=t.subarray(0,l),d=sc(t.subarray(l,u));let g,y,w;try{g=e.fromBytes(i,c),y=e.fromBytes(h,c),w=o.multiplyUnsafe(d)}catch(e){return!1}if(!c&&g.isSmallOrder())return!1;const b=f(a,y.toBytes(),g.toBytes(),n);return y.add(g.multiplyUnsafe(b)).subtract(w).clearCofactor().is0()},utils:w,Point:e,lengths:m})}function cu(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:o}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n={Fp:e.Fp,Fn:Mc(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}(e),i=function(e,t={}){const n=nu("edwards",e,t,t.FpFnLE),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s}=i;gc(t,{},{uvRatio:"function"});const a=iu<<BigInt(8*o.BYTES)-ou,c=e=>r.create(e),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch(e){return{isValid:!1,value:ru}}});if(!function(e,t,n,r){const o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(e,t,n=!1){return dc("coordinate "+e,t,n?ou:ru,a),t}function h(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const d=mc((e,t)=>{const{X:n,Y:o,Z:i}=e,s=e.is0();null==t&&(t=s?su:r.inv(i));const a=c(n*t),u=c(o*t),l=r.mul(i,t);if(s)return{x:ru,y:ou};if(l!==ou)throw new Error("invZ was invalid");return{x:a,y:u}}),f=mc(e=>{const{a:t,d:n}=i;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:o,Z:s,T:a}=e,u=c(r*r),l=c(o*o),h=c(s*s),d=c(h*h),f=c(u*t);if(c(h*c(f+l))!==c(d+c(n*c(u*l))))throw new Error("bad point: equation left != right (1)");if(c(r*o)!==c(s*a))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(e,t,n,r){this.X=l("x",e),this.Y=l("y",t),this.Z=l("z",n,!0),this.T=l("t",r),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return l("x",t),l("y",n),new p(t,n,ou,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:o,d:s}=i;e=lc(nc(e,n,"point")),tc(t,"zip215");const l=lc(e),h=e[n-1];l[n-1]=-129&h;const d=sc(l),f=t?a:r.ORDER;dc("point.y",d,ru,f);const g=c(d*d),m=c(g-ou),y=c(s*g-o);let{isValid:w,value:b}=u(m,y);if(!w)throw new Error("bad point: invalid y coordinate");const k=(b&ou)===ou,v=!!(128&h);if(!t&&b===ru&&v)throw new Error("bad point: x=0 and x_0=1");return v!==k&&(b=c(-b)),p.fromAffine({x:b,y:d})}static fromHex(e,t=!1){return p.fromBytes(uc("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(iu),this}assertValidity(){f(this)}equals(e){h(e);const{X:t,Y:n,Z:r}=this,{X:o,Y:i,Z:s}=e,a=c(t*s),u=c(o*r),l=c(n*s),d=c(i*r);return a===u&&l===d}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:n,Z:r}=this,o=c(t*t),s=c(n*n),a=c(iu*c(r*r)),u=c(e*o),l=t+n,h=c(c(l*l)-o-s),d=u+s,f=d-a,g=u-s,m=c(h*f),y=c(d*g),w=c(h*g),b=c(f*d);return new p(m,y,b,w)}add(e){h(e);const{a:t,d:n}=i,{X:r,Y:o,Z:s,T:a}=this,{X:u,Y:l,Z:d,T:f}=e,g=c(r*u),m=c(o*l),y=c(a*n*f),w=c(s*d),b=c((r+o)*(u+l)-g-m),k=w-y,v=w+y,E=c(m-t*g),S=c(b*k),A=c(v*E),T=c(b*E),I=c(k*v);return new p(S,A,I,T)}subtract(e){return this.add(e.negate())}multiply(e){if(!o.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=g.cached(this,e,e=>zc(p,e));return zc(p,[t,n])[0]}multiplyUnsafe(e,t=p.ZERO){if(!o.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===ru?p.ZERO:this.is0()||e===ou?this:g.unsafe(this,e,e=>zc(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return s===ou?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&ou?128:0,n}toHex(){return aa(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(e){return zc(p,e)}static msm(e,t){return eu(p,o,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,ou,c(i.Gx*i.Gy)),p.ZERO=new p(ru,ou,ou,ru),p.Fp=r,p.Fn=o;const g=new Jc(p,o.BITS);return p.BASE.precompute(8),p}(t,n);return function(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(e,au(i,r,o))}const uu=BigInt(1),lu=BigInt(2);BigInt(3);const hu=BigInt(5),du=BigInt(8),fu=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),pu=(()=>({p:fu,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:du,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function gu(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const mu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function yu(e,t){const n=fu,r=xc(t*t*t,n),o=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=fu,s=e*e%i*e%i,a=Bc(s,lu,i)*s%i,c=Bc(a,uu,i)*e%i,u=Bc(c,hu,i)*c%i,l=Bc(u,t,i)*u%i,h=Bc(l,n,i)*l%i,d=Bc(h,r,i)*h%i,f=Bc(d,o,i)*d%i,p=Bc(f,o,i)*d%i,g=Bc(p,t,i)*u%i;return{pow_p_5_8:Bc(g,lu,i)*e%i,b2:s}}(e*xc(r*r*t,n)).pow_p_5_8;let i=xc(e*r*o,n);const s=xc(t*i*i,n),a=i,c=xc(i*mu,n),u=s===e,l=s===xc(-e,n),h=s===xc(-e*mu,n);return u&&(i=a),(l||h)&&(i=c),(xc(i,n)&wc)===wc&&(i=xc(-i,n)),{isValid:u||l,value:i}}const wu=(()=>Mc(pu.p,{isLE:!0}))(),bu=(()=>({...pu,Fp:wu,hash:Ya,adjustScalarBytes:gu,uvRatio:yu}))(),ku=(()=>cu(bu))();var vu,Eu={exports:{}},Su=pi(Object.freeze({__proto__:null,default:{}})),Au=Eu.exports;function Tu(){return vu||(vu=1,function(e,t){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function o(e,t,n){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var i;"object"==typeof e?e.exports=o:t.BN=o,o.BN=o,o.wordSize=26;try{i="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:Su.Buffer}catch(e){}function s(e,t){var r=e.charCodeAt(t);return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+e)}function a(e,t,n){var r=s(e,n);return n-1>=t&&(r|=s(e,n-1)<<4),r}function c(e,t,r,o){for(var i=0,s=0,a=Math.min(e.length,r),c=t;c<a;c++){var u=e.charCodeAt(c)-48;i*=o,s=u>=49?u-49+10:u>=17?u-17+10:u,n(u>=0&&s<o,"Invalid character"),i+=s}return i}function u(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var o=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(o++,this.negative=1),o<e.length&&(16===t?this._parseHex(e,o,r):(this._parseBase(e,t,o),"le"===r&&this._initArray(this.toArray(),t,r)))},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var o=0;o<this.length;o++)this.words[o]=0;var i,s,a=0;if("be"===r)for(o=e.length-1,i=0;o>=0;o-=3)s=e[o]|e[o-1]<<8|e[o-2]<<16,this.words[i]|=s<<a&67108863,this.words[i+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);else if("le"===r)for(o=0,i=0;o<e.length;o+=3)s=e[o]|e[o+1]<<8|e[o+2]<<16,this.words[i]|=s<<a&67108863,this.words[i+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);return this._strip()},o.prototype._parseHex=function(e,t,n){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var o,i=0,s=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)o=a(e,t,r)<<i,this.words[s]|=67108863&o,i>=18?(i-=18,s+=1,this.words[s]|=o>>>26):i+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)o=a(e,t,r)<<i,this.words[s]|=67108863&o,i>=18?(i-=18,s+=1,this.words[s]|=o>>>26):i+=8;this._strip()},o.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,o=1;o<=67108863;o*=t)r++;r--,o=o/t|0;for(var i=e.length-n,s=i%r,a=Math.min(i,i-s)+n,u=0,l=n;l<a;l+=r)u=c(e,l,l+r,t),this.imuln(o),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u);if(0!==s){var h=1;for(u=c(e,l,e.length,t),l=0;l<s;l++)h*=t;this.imuln(h),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u)}this._strip()},o.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},o.prototype._move=function(e){u(e,this)},o.prototype.clone=function(){var e=new o(null);return this.copy(e),e},o.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},o.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=l}catch(e){o.prototype.inspect=l}else o.prototype.inspect=l;function l(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var h=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function p(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var o=0|e.words[0],i=0|t.words[0],s=o*i,a=67108863&s,c=s/67108864|0;n.words[0]=a;for(var u=1;u<r;u++){for(var l=c>>>26,h=67108863&c,d=Math.min(u,t.length-1),f=Math.max(0,u-e.length+1);f<=d;f++){var p=u-f|0;l+=(s=(o=0|e.words[p])*(i=0|t.words[f])+h)/67108864|0,h=67108863&s}n.words[u]=0|h,c=0|l}return 0!==c?n.words[u]=0|c:n.length--,n._strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var o=0,i=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<o|i)).toString(16);i=a>>>24-o&16777215,(o+=2)>=26&&(o-=26,s--),r=0!==i||s!==this.length-1?h[6-c.length]+c+r:c+r}for(0!==i&&(r=i.toString(16)+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var u=d[e],l=f[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modrn(l).toString(e);r=(p=p.idivn(l)).isZero()?g+r:h[u-g.length]+g+r}for(this.isZero()&&(r="0"+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16,2)},i&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(i,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){this._strip();var o=this.byteLength(),i=r||Math.max(1,o);n(o<=i,"byte array longer than desired length"),n(i>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,i);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,o),s},o.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,o=0,i=0;o<this.length;o++){var s=this.words[o]<<i|r;e[n++]=255&s,n<e.length&&(e[n++]=s>>8&255),n<e.length&&(e[n++]=s>>16&255),6===i?(n<e.length&&(e[n++]=s>>24&255),r=0,i=0):(r=s>>>24,i+=2)}if(n<e.length)for(e[n++]=r;n<e.length;)e[n++]=0},o.prototype._toArrayLikeBE=function(e,t){for(var n=e.length-1,r=0,o=0,i=0;o<this.length;o++){var s=this.words[o]<<i|r;e[n--]=255&s,n>=0&&(e[n--]=s>>8&255),n>=0&&(e[n--]=s>>16&255),6===i?(n>=0&&(e[n--]=s>>24&255),r=0,i=0):(r=s>>>24,i+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 8191&t||(n+=13,t>>>=13),127&t||(n+=7,t>>>=7),15&t||(n+=4,t>>>=4),3&t||(n+=2,t>>>=2),1&t||n++,n},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var n=this._zeroBits(this.words[t]);if(e+=n,26!==n)break}return e},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},o.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return 0!==this.negative},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this._strip()},o.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},o.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;n<t.length;n++)this.words[n]=this.words[n]&e.words[n];return this.length=t.length,this._strip()},o.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},o.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;r<n.length;r++)this.words[r]=t.words[r]^n.words[r];if(this!==t)for(;r<t.length;r++)this.words[r]=t.words[r];return this.length=t.length,this._strip()},o.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},o.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var o=0;o<t;o++)this.words[o]=67108863&~this.words[o];return r>0&&(this.words[o]=~this.words[o]&67108863>>26-r),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,o=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<<o:this.words[r]&~(1<<o),this._strip()},o.prototype.iadd=function(e){var t,n,r;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(n=this,r=e):(n=e,r=this);for(var o=0,i=0;i<r.length;i++)t=(0|n.words[i])+(0|r.words[i])+o,this.words[i]=67108863&t,o=t>>>26;for(;0!==o&&i<n.length;i++)t=(0|n.words[i])+o,this.words[i]=67108863&t,o=t>>>26;if(this.length=n.length,0!==o)this.words[this.length]=o,this.length++;else if(n!==this)for(;i<n.length;i++)this.words[i]=n.words[i];return this},o.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,o=this.cmp(e);if(0===o)return this.negative=0,this.length=1,this.words[0]=0,this;o>0?(n=this,r=e):(n=e,r=this);for(var i=0,s=0;s<r.length;s++)i=(t=(0|n.words[s])-(0|r.words[s])+i)>>26,this.words[s]=67108863&t;for(;0!==i&&s<n.length;s++)i=(t=(0|n.words[s])+i)>>26,this.words[s]=67108863&t;if(0===i&&s<n.length&&n!==this)for(;s<n.length;s++)this.words[s]=n.words[s];return this.length=Math.max(this.length,s),n!==this&&(this.negative=1),this._strip()},o.prototype.sub=function(e){return this.clone().isub(e)};var g=function(e,t,n){var r,o,i,s=e.words,a=t.words,c=n.words,u=0,l=0|s[0],h=8191&l,d=l>>>13,f=0|s[1],p=8191&f,g=f>>>13,m=0|s[2],y=8191&m,w=m>>>13,b=0|s[3],k=8191&b,v=b>>>13,E=0|s[4],S=8191&E,A=E>>>13,T=0|s[5],I=8191&T,x=T>>>13,B=0|s[6],C=8191&B,P=B>>>13,N=0|s[7],_=8191&N,U=N>>>13,D=0|s[8],R=8191&D,F=D>>>13,L=0|s[9],O=8191&L,M=L>>>13,$=0|a[0],q=8191&$,K=$>>>13,G=0|a[1],W=8191&G,z=G>>>13,j=0|a[2],H=8191&j,V=j>>>13,X=0|a[3],Q=8191&X,Z=X>>>13,Y=0|a[4],J=8191&Y,ee=Y>>>13,te=0|a[5],ne=8191&te,re=te>>>13,oe=0|a[6],ie=8191&oe,se=oe>>>13,ae=0|a[7],ce=8191&ae,ue=ae>>>13,le=0|a[8],he=8191&le,de=le>>>13,fe=0|a[9],pe=8191&fe,ge=fe>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(u+(r=Math.imul(h,q))|0)+((8191&(o=(o=Math.imul(h,K))+Math.imul(d,q)|0))<<13)|0;u=((i=Math.imul(d,K))+(o>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(p,q),o=(o=Math.imul(p,K))+Math.imul(g,q)|0,i=Math.imul(g,K);var ye=(u+(r=r+Math.imul(h,W)|0)|0)+((8191&(o=(o=o+Math.imul(h,z)|0)+Math.imul(d,W)|0))<<13)|0;u=((i=i+Math.imul(d,z)|0)+(o>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,q),o=(o=Math.imul(y,K))+Math.imul(w,q)|0,i=Math.imul(w,K),r=r+Math.imul(p,W)|0,o=(o=o+Math.imul(p,z)|0)+Math.imul(g,W)|0,i=i+Math.imul(g,z)|0;var we=(u+(r=r+Math.imul(h,H)|0)|0)+((8191&(o=(o=o+Math.imul(h,V)|0)+Math.imul(d,H)|0))<<13)|0;u=((i=i+Math.imul(d,V)|0)+(o>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(k,q),o=(o=Math.imul(k,K))+Math.imul(v,q)|0,i=Math.imul(v,K),r=r+Math.imul(y,W)|0,o=(o=o+Math.imul(y,z)|0)+Math.imul(w,W)|0,i=i+Math.imul(w,z)|0,r=r+Math.imul(p,H)|0,o=(o=o+Math.imul(p,V)|0)+Math.imul(g,H)|0,i=i+Math.imul(g,V)|0;var be=(u+(r=r+Math.imul(h,Q)|0)|0)+((8191&(o=(o=o+Math.imul(h,Z)|0)+Math.imul(d,Q)|0))<<13)|0;u=((i=i+Math.imul(d,Z)|0)+(o>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(S,q),o=(o=Math.imul(S,K))+Math.imul(A,q)|0,i=Math.imul(A,K),r=r+Math.imul(k,W)|0,o=(o=o+Math.imul(k,z)|0)+Math.imul(v,W)|0,i=i+Math.imul(v,z)|0,r=r+Math.imul(y,H)|0,o=(o=o+Math.imul(y,V)|0)+Math.imul(w,H)|0,i=i+Math.imul(w,V)|0,r=r+Math.imul(p,Q)|0,o=(o=o+Math.imul(p,Z)|0)+Math.imul(g,Q)|0,i=i+Math.imul(g,Z)|0;var ke=(u+(r=r+Math.imul(h,J)|0)|0)+((8191&(o=(o=o+Math.imul(h,ee)|0)+Math.imul(d,J)|0))<<13)|0;u=((i=i+Math.imul(d,ee)|0)+(o>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(I,q),o=(o=Math.imul(I,K))+Math.imul(x,q)|0,i=Math.imul(x,K),r=r+Math.imul(S,W)|0,o=(o=o+Math.imul(S,z)|0)+Math.imul(A,W)|0,i=i+Math.imul(A,z)|0,r=r+Math.imul(k,H)|0,o=(o=o+Math.imul(k,V)|0)+Math.imul(v,H)|0,i=i+Math.imul(v,V)|0,r=r+Math.imul(y,Q)|0,o=(o=o+Math.imul(y,Z)|0)+Math.imul(w,Q)|0,i=i+Math.imul(w,Z)|0,r=r+Math.imul(p,J)|0,o=(o=o+Math.imul(p,ee)|0)+Math.imul(g,J)|0,i=i+Math.imul(g,ee)|0;var ve=(u+(r=r+Math.imul(h,ne)|0)|0)+((8191&(o=(o=o+Math.imul(h,re)|0)+Math.imul(d,ne)|0))<<13)|0;u=((i=i+Math.imul(d,re)|0)+(o>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(C,q),o=(o=Math.imul(C,K))+Math.imul(P,q)|0,i=Math.imul(P,K),r=r+Math.imul(I,W)|0,o=(o=o+Math.imul(I,z)|0)+Math.imul(x,W)|0,i=i+Math.imul(x,z)|0,r=r+Math.imul(S,H)|0,o=(o=o+Math.imul(S,V)|0)+Math.imul(A,H)|0,i=i+Math.imul(A,V)|0,r=r+Math.imul(k,Q)|0,o=(o=o+Math.imul(k,Z)|0)+Math.imul(v,Q)|0,i=i+Math.imul(v,Z)|0,r=r+Math.imul(y,J)|0,o=(o=o+Math.imul(y,ee)|0)+Math.imul(w,J)|0,i=i+Math.imul(w,ee)|0,r=r+Math.imul(p,ne)|0,o=(o=o+Math.imul(p,re)|0)+Math.imul(g,ne)|0,i=i+Math.imul(g,re)|0;var Ee=(u+(r=r+Math.imul(h,ie)|0)|0)+((8191&(o=(o=o+Math.imul(h,se)|0)+Math.imul(d,ie)|0))<<13)|0;u=((i=i+Math.imul(d,se)|0)+(o>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(_,q),o=(o=Math.imul(_,K))+Math.imul(U,q)|0,i=Math.imul(U,K),r=r+Math.imul(C,W)|0,o=(o=o+Math.imul(C,z)|0)+Math.imul(P,W)|0,i=i+Math.imul(P,z)|0,r=r+Math.imul(I,H)|0,o=(o=o+Math.imul(I,V)|0)+Math.imul(x,H)|0,i=i+Math.imul(x,V)|0,r=r+Math.imul(S,Q)|0,o=(o=o+Math.imul(S,Z)|0)+Math.imul(A,Q)|0,i=i+Math.imul(A,Z)|0,r=r+Math.imul(k,J)|0,o=(o=o+Math.imul(k,ee)|0)+Math.imul(v,J)|0,i=i+Math.imul(v,ee)|0,r=r+Math.imul(y,ne)|0,o=(o=o+Math.imul(y,re)|0)+Math.imul(w,ne)|0,i=i+Math.imul(w,re)|0,r=r+Math.imul(p,ie)|0,o=(o=o+Math.imul(p,se)|0)+Math.imul(g,ie)|0,i=i+Math.imul(g,se)|0;var Se=(u+(r=r+Math.imul(h,ce)|0)|0)+((8191&(o=(o=o+Math.imul(h,ue)|0)+Math.imul(d,ce)|0))<<13)|0;u=((i=i+Math.imul(d,ue)|0)+(o>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(R,q),o=(o=Math.imul(R,K))+Math.imul(F,q)|0,i=Math.imul(F,K),r=r+Math.imul(_,W)|0,o=(o=o+Math.imul(_,z)|0)+Math.imul(U,W)|0,i=i+Math.imul(U,z)|0,r=r+Math.imul(C,H)|0,o=(o=o+Math.imul(C,V)|0)+Math.imul(P,H)|0,i=i+Math.imul(P,V)|0,r=r+Math.imul(I,Q)|0,o=(o=o+Math.imul(I,Z)|0)+Math.imul(x,Q)|0,i=i+Math.imul(x,Z)|0,r=r+Math.imul(S,J)|0,o=(o=o+Math.imul(S,ee)|0)+Math.imul(A,J)|0,i=i+Math.imul(A,ee)|0,r=r+Math.imul(k,ne)|0,o=(o=o+Math.imul(k,re)|0)+Math.imul(v,ne)|0,i=i+Math.imul(v,re)|0,r=r+Math.imul(y,ie)|0,o=(o=o+Math.imul(y,se)|0)+Math.imul(w,ie)|0,i=i+Math.imul(w,se)|0,r=r+Math.imul(p,ce)|0,o=(o=o+Math.imul(p,ue)|0)+Math.imul(g,ce)|0,i=i+Math.imul(g,ue)|0;var Ae=(u+(r=r+Math.imul(h,he)|0)|0)+((8191&(o=(o=o+Math.imul(h,de)|0)+Math.imul(d,he)|0))<<13)|0;u=((i=i+Math.imul(d,de)|0)+(o>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(O,q),o=(o=Math.imul(O,K))+Math.imul(M,q)|0,i=Math.imul(M,K),r=r+Math.imul(R,W)|0,o=(o=o+Math.imul(R,z)|0)+Math.imul(F,W)|0,i=i+Math.imul(F,z)|0,r=r+Math.imul(_,H)|0,o=(o=o+Math.imul(_,V)|0)+Math.imul(U,H)|0,i=i+Math.imul(U,V)|0,r=r+Math.imul(C,Q)|0,o=(o=o+Math.imul(C,Z)|0)+Math.imul(P,Q)|0,i=i+Math.imul(P,Z)|0,r=r+Math.imul(I,J)|0,o=(o=o+Math.imul(I,ee)|0)+Math.imul(x,J)|0,i=i+Math.imul(x,ee)|0,r=r+Math.imul(S,ne)|0,o=(o=o+Math.imul(S,re)|0)+Math.imul(A,ne)|0,i=i+Math.imul(A,re)|0,r=r+Math.imul(k,ie)|0,o=(o=o+Math.imul(k,se)|0)+Math.imul(v,ie)|0,i=i+Math.imul(v,se)|0,r=r+Math.imul(y,ce)|0,o=(o=o+Math.imul(y,ue)|0)+Math.imul(w,ce)|0,i=i+Math.imul(w,ue)|0,r=r+Math.imul(p,he)|0,o=(o=o+Math.imul(p,de)|0)+Math.imul(g,he)|0,i=i+Math.imul(g,de)|0;var Te=(u+(r=r+Math.imul(h,pe)|0)|0)+((8191&(o=(o=o+Math.imul(h,ge)|0)+Math.imul(d,pe)|0))<<13)|0;u=((i=i+Math.imul(d,ge)|0)+(o>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(O,W),o=(o=Math.imul(O,z))+Math.imul(M,W)|0,i=Math.imul(M,z),r=r+Math.imul(R,H)|0,o=(o=o+Math.imul(R,V)|0)+Math.imul(F,H)|0,i=i+Math.imul(F,V)|0,r=r+Math.imul(_,Q)|0,o=(o=o+Math.imul(_,Z)|0)+Math.imul(U,Q)|0,i=i+Math.imul(U,Z)|0,r=r+Math.imul(C,J)|0,o=(o=o+Math.imul(C,ee)|0)+Math.imul(P,J)|0,i=i+Math.imul(P,ee)|0,r=r+Math.imul(I,ne)|0,o=(o=o+Math.imul(I,re)|0)+Math.imul(x,ne)|0,i=i+Math.imul(x,re)|0,r=r+Math.imul(S,ie)|0,o=(o=o+Math.imul(S,se)|0)+Math.imul(A,ie)|0,i=i+Math.imul(A,se)|0,r=r+Math.imul(k,ce)|0,o=(o=o+Math.imul(k,ue)|0)+Math.imul(v,ce)|0,i=i+Math.imul(v,ue)|0,r=r+Math.imul(y,he)|0,o=(o=o+Math.imul(y,de)|0)+Math.imul(w,he)|0,i=i+Math.imul(w,de)|0;var Ie=(u+(r=r+Math.imul(p,pe)|0)|0)+((8191&(o=(o=o+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;u=((i=i+Math.imul(g,ge)|0)+(o>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(O,H),o=(o=Math.imul(O,V))+Math.imul(M,H)|0,i=Math.imul(M,V),r=r+Math.imul(R,Q)|0,o=(o=o+Math.imul(R,Z)|0)+Math.imul(F,Q)|0,i=i+Math.imul(F,Z)|0,r=r+Math.imul(_,J)|0,o=(o=o+Math.imul(_,ee)|0)+Math.imul(U,J)|0,i=i+Math.imul(U,ee)|0,r=r+Math.imul(C,ne)|0,o=(o=o+Math.imul(C,re)|0)+Math.imul(P,ne)|0,i=i+Math.imul(P,re)|0,r=r+Math.imul(I,ie)|0,o=(o=o+Math.imul(I,se)|0)+Math.imul(x,ie)|0,i=i+Math.imul(x,se)|0,r=r+Math.imul(S,ce)|0,o=(o=o+Math.imul(S,ue)|0)+Math.imul(A,ce)|0,i=i+Math.imul(A,ue)|0,r=r+Math.imul(k,he)|0,o=(o=o+Math.imul(k,de)|0)+Math.imul(v,he)|0,i=i+Math.imul(v,de)|0;var xe=(u+(r=r+Math.imul(y,pe)|0)|0)+((8191&(o=(o=o+Math.imul(y,ge)|0)+Math.imul(w,pe)|0))<<13)|0;u=((i=i+Math.imul(w,ge)|0)+(o>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(O,Q),o=(o=Math.imul(O,Z))+Math.imul(M,Q)|0,i=Math.imul(M,Z),r=r+Math.imul(R,J)|0,o=(o=o+Math.imul(R,ee)|0)+Math.imul(F,J)|0,i=i+Math.imul(F,ee)|0,r=r+Math.imul(_,ne)|0,o=(o=o+Math.imul(_,re)|0)+Math.imul(U,ne)|0,i=i+Math.imul(U,re)|0,r=r+Math.imul(C,ie)|0,o=(o=o+Math.imul(C,se)|0)+Math.imul(P,ie)|0,i=i+Math.imul(P,se)|0,r=r+Math.imul(I,ce)|0,o=(o=o+Math.imul(I,ue)|0)+Math.imul(x,ce)|0,i=i+Math.imul(x,ue)|0,r=r+Math.imul(S,he)|0,o=(o=o+Math.imul(S,de)|0)+Math.imul(A,he)|0,i=i+Math.imul(A,de)|0;var Be=(u+(r=r+Math.imul(k,pe)|0)|0)+((8191&(o=(o=o+Math.imul(k,ge)|0)+Math.imul(v,pe)|0))<<13)|0;u=((i=i+Math.imul(v,ge)|0)+(o>>>13)|0)+(Be>>>26)|0,Be&=67108863,r=Math.imul(O,J),o=(o=Math.imul(O,ee))+Math.imul(M,J)|0,i=Math.imul(M,ee),r=r+Math.imul(R,ne)|0,o=(o=o+Math.imul(R,re)|0)+Math.imul(F,ne)|0,i=i+Math.imul(F,re)|0,r=r+Math.imul(_,ie)|0,o=(o=o+Math.imul(_,se)|0)+Math.imul(U,ie)|0,i=i+Math.imul(U,se)|0,r=r+Math.imul(C,ce)|0,o=(o=o+Math.imul(C,ue)|0)+Math.imul(P,ce)|0,i=i+Math.imul(P,ue)|0,r=r+Math.imul(I,he)|0,o=(o=o+Math.imul(I,de)|0)+Math.imul(x,he)|0,i=i+Math.imul(x,de)|0;var Ce=(u+(r=r+Math.imul(S,pe)|0)|0)+((8191&(o=(o=o+Math.imul(S,ge)|0)+Math.imul(A,pe)|0))<<13)|0;u=((i=i+Math.imul(A,ge)|0)+(o>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(O,ne),o=(o=Math.imul(O,re))+Math.imul(M,ne)|0,i=Math.imul(M,re),r=r+Math.imul(R,ie)|0,o=(o=o+Math.imul(R,se)|0)+Math.imul(F,ie)|0,i=i+Math.imul(F,se)|0,r=r+Math.imul(_,ce)|0,o=(o=o+Math.imul(_,ue)|0)+Math.imul(U,ce)|0,i=i+Math.imul(U,ue)|0,r=r+Math.imul(C,he)|0,o=(o=o+Math.imul(C,de)|0)+Math.imul(P,he)|0,i=i+Math.imul(P,de)|0;var Pe=(u+(r=r+Math.imul(I,pe)|0)|0)+((8191&(o=(o=o+Math.imul(I,ge)|0)+Math.imul(x,pe)|0))<<13)|0;u=((i=i+Math.imul(x,ge)|0)+(o>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(O,ie),o=(o=Math.imul(O,se))+Math.imul(M,ie)|0,i=Math.imul(M,se),r=r+Math.imul(R,ce)|0,o=(o=o+Math.imul(R,ue)|0)+Math.imul(F,ce)|0,i=i+Math.imul(F,ue)|0,r=r+Math.imul(_,he)|0,o=(o=o+Math.imul(_,de)|0)+Math.imul(U,he)|0,i=i+Math.imul(U,de)|0;var Ne=(u+(r=r+Math.imul(C,pe)|0)|0)+((8191&(o=(o=o+Math.imul(C,ge)|0)+Math.imul(P,pe)|0))<<13)|0;u=((i=i+Math.imul(P,ge)|0)+(o>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(O,ce),o=(o=Math.imul(O,ue))+Math.imul(M,ce)|0,i=Math.imul(M,ue),r=r+Math.imul(R,he)|0,o=(o=o+Math.imul(R,de)|0)+Math.imul(F,he)|0,i=i+Math.imul(F,de)|0;var _e=(u+(r=r+Math.imul(_,pe)|0)|0)+((8191&(o=(o=o+Math.imul(_,ge)|0)+Math.imul(U,pe)|0))<<13)|0;u=((i=i+Math.imul(U,ge)|0)+(o>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(O,he),o=(o=Math.imul(O,de))+Math.imul(M,he)|0,i=Math.imul(M,de);var Ue=(u+(r=r+Math.imul(R,pe)|0)|0)+((8191&(o=(o=o+Math.imul(R,ge)|0)+Math.imul(F,pe)|0))<<13)|0;u=((i=i+Math.imul(F,ge)|0)+(o>>>13)|0)+(Ue>>>26)|0,Ue&=67108863;var De=(u+(r=Math.imul(O,pe))|0)+((8191&(o=(o=Math.imul(O,ge))+Math.imul(M,pe)|0))<<13)|0;return u=((i=Math.imul(M,ge))+(o>>>13)|0)+(De>>>26)|0,De&=67108863,c[0]=me,c[1]=ye,c[2]=we,c[3]=be,c[4]=ke,c[5]=ve,c[6]=Ee,c[7]=Se,c[8]=Ae,c[9]=Te,c[10]=Ie,c[11]=xe,c[12]=Be,c[13]=Ce,c[14]=Pe,c[15]=Ne,c[16]=_e,c[17]=Ue,c[18]=De,0!==u&&(c[19]=u,n.length++),n};function m(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,o=0,i=0;i<n.length-1;i++){var s=o;o=0;for(var a=67108863&r,c=Math.min(i,t.length-1),u=Math.max(0,i-e.length+1);u<=c;u++){var l=i-u,h=(0|e.words[l])*(0|t.words[u]),d=67108863&h;a=67108863&(d=d+a|0),o+=(s=(s=s+(h/67108864|0)|0)+(d>>>26)|0)>>>26,s&=67108863}n.words[i]=a,r=s,s=o}return 0!==r?n.words[i]=r:n.length--,n._strip()}function y(e,t,n){return m(e,t,n)}Math.imul||(g=p),o.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?g(this,e,t):n<63?p(this,e,t):n<1024?m(this,e,t):y(this,e,t)},o.prototype.mul=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},o.prototype.mulf=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),y(this,e,t)},o.prototype.imul=function(e){return this.clone().mulTo(e,this)},o.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var r=0,o=0;o<this.length;o++){var i=(0|this.words[o])*e,s=(67108863&i)+(67108863&r);r>>=26,r+=i/67108864|0,r+=s>>>26,this.words[o]=67108863&s}return 0!==r&&(this.words[o]=r,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n<t.length;n++){var r=n/26|0,o=n%26;t[n]=e.words[r]>>>o&1}return t}(e);if(0===t.length)return new o(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var i=n.sqr();r<t.length;r++,i=i.sqr())0!==t[r]&&(n=n.mul(i));return n},o.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,o=(e-r)/26,i=67108863>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&i,c=(0|this.words[t])-a<<r;this.words[t]=c|s,s=a>>>26-r}s&&(this.words[t]=s,this.length++)}if(0!==o){for(t=this.length-1;t>=0;t--)this.words[t+o]=this.words[t];for(t=0;t<o;t++)this.words[t]=0;this.length+=o}return this._strip()},o.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},o.prototype.iushrn=function(e,t,r){var o;n("number"==typeof e&&e>=0),o=t?(t-t%26)/26:0;var i=e%26,s=Math.min((e-i)/26,this.length),a=67108863^67108863>>>i<<i,c=r;if(o-=s,o=Math.max(0,o),c){for(var u=0;u<s;u++)c.words[u]=this.words[u];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,u=0;u<this.length;u++)this.words[u]=this.words[u+s];else this.words[0]=0,this.length=1;var l=0;for(u=this.length-1;u>=0&&(0!==l||u>=o);u--){var h=0|this.words[u];this.words[u]=l<<26-i|h>>>i,l=h&a}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,o=1<<t;return!(this.length<=r||!(this.words[r]&o))},o.prototype.imaskn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var o=67108863^67108863>>>t<<t;this.words[this.length-1]&=o}return this._strip()},o.prototype.maskn=function(e){return this.clone().imaskn(e)},o.prototype.iaddn=function(e){return n("number"==typeof e),n(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<=e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},o.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this._strip()},o.prototype.addn=function(e){return this.clone().iaddn(e)},o.prototype.subn=function(e){return this.clone().isubn(e)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(e,t,r){var o,i,s=e.length+r;this._expand(s);var a=0;for(o=0;o<e.length;o++){i=(0|this.words[o+r])+a;var c=(0|e.words[o])*t;a=((i-=67108863&c)>>26)-(c/67108864|0),this.words[o+r]=67108863&i}for(;o<this.length-r;o++)a=(i=(0|this.words[o+r])+a)>>26,this.words[o+r]=67108863&i;if(0===a)return this._strip();for(n(-1===a),a=0,o=0;o<this.length;o++)a=(i=-(0|this.words[o])+a)>>26,this.words[o]=67108863&i;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,s=0|i.words[i.length-1];0!=(n=26-this._countBits(s))&&(i=i.ushln(n),r.iushln(n),s=0|i.words[i.length-1]);var a,c=r.length-i.length;if("mod"!==t){(a=new o(null)).length=c+1,a.words=new Array(a.length);for(var u=0;u<a.length;u++)a.words[u]=0}var l=r.clone()._ishlnsubmul(i,1,c);0===l.negative&&(r=l,a&&(a.words[c]=1));for(var h=c-1;h>=0;h--){var d=67108864*(0|r.words[i.length+h])+(0|r.words[i.length+h-1]);for(d=Math.min(d/s|0,67108863),r._ishlnsubmul(i,d,h);0!==r.negative;)d--,r.negative=0,r._ishlnsubmul(i,1,h),r.isZero()||(r.negative^=1);a&&(a.words[h]=d)}return a&&a._strip(),r._strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(i=a.div.neg()),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:i,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(i=a.div.neg()),{div:i,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),o=e.andln(1),i=n.cmp(r);return i<0||1===o&&0===i?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,o=0,i=this.length-1;i>=0;i--)o=(r*o+(0|this.words[i]))%e;return t?-o:o},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,o=this.length-1;o>=0;o--){var i=(0|this.words[o])+67108864*r;this.words[o]=i/e|0,r=i%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),s=new o(0),a=new o(0),c=new o(1),u=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++u;for(var l=r.clone(),h=t.clone();!t.isZero();){for(var d=0,f=1;0===(t.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||s.isOdd())&&(i.iadd(l),s.isub(h)),i.iushrn(1),s.iushrn(1);for(var p=0,g=1;0===(r.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(h)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(a),s.isub(c)):(r.isub(t),a.isub(i),c.isub(s))}return{a:a,b:c,gcd:r.iushln(u)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,s=new o(1),a=new o(0),c=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var u=0,l=1;0===(t.words[0]&l)&&u<26;++u,l<<=1);if(u>0)for(t.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var h=0,d=1;0===(r.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(r.iushrn(h);h-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),s.isub(a)):(r.isub(t),a.isub(s))}return(i=0===t.cmpn(1)?s:a).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var o=t.cmp(n);if(o<0){var i=t;t=n,n=i}else if(0===o||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return!(1&this.words[0])},o.prototype.isOdd=function(){return!(1&~this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,o=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=o,this;for(var i=o,s=r;0!==i&&s<this.length;s++){var a=0|this.words[s];i=(a+=i)>>>26,a&=67108863,this.words[s]=a}return 0!==i&&(this.words[s]=i,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var o=0|this.words[0];t=o===e?0:o<e?-1:1}return 0!==this.negative?0|-t:t},o.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},o.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,n=this.length-1;n>=0;n--){var r=0|this.words[n],o=0|e.words[n];if(r!==o){r<o?t=-1:r>o&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var w={k256:null,p224:null,p192:null,p25519:null};function b(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function k(){b.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){b.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function E(){b.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){b.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function T(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}b.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},b.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t<this.n?-1:n.ucmp(this.p);return 0===r?(n.words[0]=0,n.length=1):r>0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},b.prototype.split=function(e,t){e.iushrn(this.n,0,t)},b.prototype.imulK=function(e){return e.imul(this.k)},r(k,b),k.prototype.split=function(e,t){for(var n=4194303,r=Math.min(e.length,9),o=0;o<r;o++)t.words[o]=e.words[o];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var i=e.words[9];for(t.words[t.length++]=i&n,o=10;o<e.length;o++){var s=0|e.words[o];e.words[o-10]=(s&n)<<4|i>>>22,i=s}i>>>=22,e.words[o-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},k.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n<e.length;n++){var r=0|e.words[n];t+=977*r,e.words[n]=67108863&t,t=64*r+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},r(v,b),r(E,b),r(S,b),S.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,o=67108863&r;r>>>=26,e.words[n]=o,t=r}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(w[e])return w[e];var t;if("k256"===e)t=new k;else if("p224"===e)t=new v;else if("p192"===e)t=new E;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new S}return w[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0===(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(u(e,e.umod(this.m)._forceRed(this)),e)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},A.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),s=0;!i.isZero()&&0===i.andln(1);)s++,i.iushrn(1);n(!i.isZero());var a=new o(1).toRed(this),c=a.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var h=this.pow(l,i),d=this.pow(e,i.addn(1).iushrn(1)),f=this.pow(e,i),p=s;0!==f.cmp(a);){for(var g=f,m=0;0!==g.cmp(a);m++)g=g.redSqr();n(m<p);var y=this.pow(h,new o(1).iushln(p-m-1));d=d.redMul(y),h=y.redSqr(),f=f.redMul(h),p=m}return d},A.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},A.prototype.pow=function(e,t){if(t.isZero())return new o(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new o(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var i=n[0],s=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),r=t.length-1;r>=0;r--){for(var u=t.words[r],l=c-1;l>=0;l--){var h=u>>l&1;i!==n[0]&&(i=this.sqr(i)),0!==h||0!==s?(s<<=1,s|=h,(4===++a||0===r&&0===l)&&(i=this.mul(i,n[s]),a=0,s=0)):a=0}c=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new T(e)},r(T,A),T.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},T.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},T.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=n.isub(r).iushrn(this.shift),i=o;return o.cmp(this.m)>=0?i=o.isub(this.m):o.cmpn(0)<0&&(i=o.iadd(this.m)),i._forceRed(this)},T.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(Eu,Au)),Eu.exports}var Iu,xu,Bu,Cu,Pu,Nu,_u=fi(Tu()),Uu={exports:{}},Du={};function Ru(){return Iu||(Iu=1,function(e){var t=Ws(),n=Vs(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;var o=2147483647;function i(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|f(e,t),r=i(n),o=r.write(e,t);o!==n&&(r=r.slice(0,o));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(M(e,Uint8Array)){var t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(M(e,ArrayBuffer)||e&&M(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(M(e,SharedArrayBuffer)||e&&M(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);var o=function(e){if(s.isBuffer(e)){var t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||$(e.length)?i(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),i(e<0?0:0|d(e))}function l(e){for(var t=e.length<0?0:0|d(e.length),n=i(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function d(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||M(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var o=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return F(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(e).length;default:if(o)return r?-1:F(e).length;t=(""+t).toLowerCase(),o=!0}}function p(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return B(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),$(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){var i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){var l=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===l?0:i-l)){if(-1===l&&(l=i),i-l+1===c)return l*s}else-1!==l&&(i-=i-l),l=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){for(var h=!0,d=0;d<c;d++)if(u(e,i+d)!==u(t,d)){h=!1;break}if(h)return i}return-1}function w(e,t,n,r){n=Number(n)||0;var o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;var i=t.length;r>i/2&&(r=i/2);for(var s=0;s<r;++s){var a=parseInt(t.substr(2*s,2),16);if($(a))return s;e[n+s]=a}return s}function b(e,t,n,r){return O(F(t,e.length-n),e,n,r)}function k(e,t,n,r){return O(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return O(L(t),e,n,r)}function E(e,t,n,r){return O(function(e,t){for(var n,r,o,i=[],s=0;s<e.length&&!((t-=2)<0);++s)r=(n=e.charCodeAt(s))>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function A(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o<n;){var i,s,a,c,u=e[o],l=null,h=u>239?4:u>223?3:u>191?2:1;if(o+h<=n)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(i=e[o+1]))&&(c=(31&u)<<6|63&i)>127&&(l=c);break;case 3:i=e[o+1],s=e[o+2],128==(192&i)&&128==(192&s)&&(c=(15&u)<<12|(63&i)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:i=e[o+1],s=e[o+2],a=e[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),o+=h}return function(e){var t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=o,s.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(M(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),M(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=s.allocUnsafe(t),o=0;for(n=0;n<e.length;++n){var i=e[n];if(M(i,Uint8Array))o+i.length>r.length?s.from(i).copy(r,o):Uint8Array.prototype.set.call(r,i,o);else{if(!s.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(r,o)}o+=i.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},s.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},s.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},s.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?A(this,0,e):p.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var t="",n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,o){if(M(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n),h=0;h<c;++h)if(u[h]!==l[h]){i=u[h],a=l[h];break}return i<a?-1:a<i?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var T=4096;function I(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function x(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function B(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var o="",i=t;i<n;++i)o+=q[e[i]];return o}function C(e,t,n){for(var r=e.slice(t,n),o="",i=0;i<r.length-1;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}function P(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,r,o,i){return t=+t,r>>>=0,i||_(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function D(e,t,r,o,i){return t=+t,r>>>=0,i||_(e,0,r,8),n.write(e,t,r,o,52,8),r+8}s.prototype.slice=function(e,t){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e+--t],o=1;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return r>=(o*=128)&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t>>>=0,n>>>=0,r)||N(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){(e=+e,t>>>=0,n>>>=0,r)||N(this,e,t,n,Math.pow(2,8*n)-1,0);var o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var o=Math.pow(2,8*n-1);N(this,e,t,n,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i<n&&(s*=256);)e<0&&0===a&&0!==this[t+i-1]&&(a=1),this[t+i]=(e/s|0)-a&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var o=Math.pow(2,8*n-1);N(this,e,t,n,o-1,-o)}var i=n-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s|0)-a&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return D(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return D(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var o=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),o},s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var o=e.charCodeAt(0);("utf8"===r&&o<128||"latin1"===r)&&(e=o)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var i;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i<n;++i)this[i]=e;else{var a=s.isBuffer(e)?e:s.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<n-t;++i)this[i+t]=a[i%c]}return this};var R=/[^+/0-9A-Za-z-_]/g;function F(e,t){var n;t=t||1/0;for(var r=e.length,o=null,i=[],s=0;s<r;++s){if((n=e.charCodeAt(s))>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function L(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(R,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function O(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function M(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function $(e){return e!=e}var q=function(){for(var e="0123456789abcdef",t=new Array(256),n=0;n<16;++n)for(var r=16*n,o=0;o<16;++o)t[r+o]=e[n]+e[o];return t}()}(Du)),Du}function Fu(){return xu||(xu=1,function(e,t){var n=Ru(),r=n.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=i),o(r,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var o=r(e);return void 0!==t?"string"==typeof n?o.fill(t,n):o.fill(t):o.fill(0),o},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(Uu,Uu.exports)),Uu.exports}var Lu=function(){if(Nu)return Pu;Nu=1;var e=function(){if(Cu)return Bu;Cu=1;var e=Fu().Buffer;return Bu=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<t.length;o++){var i=t.charAt(o),s=i.charCodeAt(0);if(255!==n[s])throw new TypeError(i+" is ambiguous");n[s]=o}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,o=0,i=0;t[r]===c;)o++,r++;for(var s=(t.length-r)*u+1>>>0,l=new Uint8Array(s);r<t.length;){var h=t.charCodeAt(r);if(h>255)return;var d=n[h];if(255===d)return;for(var f=0,p=s-1;(0!==d||f<i)&&-1!==p;p--,f++)d+=a*l[p]>>>0,l[p]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");i=f,r++}for(var g=s-i;g!==s&&0===l[g];)g++;var m=e.allocUnsafe(o+(s-g));m.fill(0,0,o);for(var y=o;g!==s;)m[y++]=l[g++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,o=0,i=0,s=n.length;i!==s&&0===n[i];)i++,r++;for(var u=(s-i)*l+1>>>0,h=new Uint8Array(u);i!==s;){for(var d=n[i],f=0,p=u-1;(0!==d||f<o)&&-1!==p;p--,f++)d+=256*h[p]>>>0,h[p]=d%a>>>0,d=d/a>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,i++}for(var g=u-o;g!==u&&0===h[g];)g++;for(var m=c.repeat(r);g<u;++g)m+=t.charAt(h[g]);return m},decodeUnsafe:h,decode:function(e){var t=h(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},Bu}();return Pu=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}(),Ou=fi(Lu);const Mu=Za;var $u,qu,Ku,Gu,Wu={};function zu(){if(Gu)return Ku;Gu=1;var e=function(){if(qu)return $u;qu=1;var e=Fu().Buffer;return $u=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<t.length;o++){var i=t.charAt(o),s=i.charCodeAt(0);if(255!==n[s])throw new TypeError(i+" is ambiguous");n[s]=o}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,o=0,i=0;t[r]===c;)o++,r++;for(var s=(t.length-r)*u+1>>>0,l=new Uint8Array(s);r<t.length;){var h=t.charCodeAt(r);if(h>255)return;var d=n[h];if(255===d)return;for(var f=0,p=s-1;(0!==d||f<i)&&-1!==p;p--,f++)d+=a*l[p]>>>0,l[p]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");i=f,r++}for(var g=s-i;g!==s&&0===l[g];)g++;var m=e.allocUnsafe(o+(s-g));m.fill(0,0,o);for(var y=o;g!==s;)m[y++]=l[g++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,o=0,i=0,s=n.length;i!==s&&0===n[i];)i++,r++;for(var u=(s-i)*l+1>>>0,h=new Uint8Array(u);i!==s;){for(var d=n[i],f=0,p=u-1;(0!==d||f<o)&&-1!==p;p--,f++)d+=256*h[p]>>>0,h[p]=d%a>>>0,d=d/a>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,i++}for(var g=u-o;g!==u&&0===h[g];)g++;for(var m=c.repeat(r);g<u;++g)m+=t.charAt(h[g]);return m},decodeUnsafe:h,decode:function(e){var t=h(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},$u}();return Ku=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}function ju(e,t,n){return t<=e&&e<=n}function Hu(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function Vu(e){this.tokens=[].slice.call(e)}Vu.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():-1},prepend:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.unshift(t.pop());else this.tokens.unshift(e)},push:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.push(t.shift());else this.tokens.push(e)}};var Xu=-1;function Qu(e,t){if(e)throw TypeError("Decoder error");return t||65533}var Zu="utf-8";function Yu(e,t){if(!(this instanceof Yu))return new Yu(e,t);if((e=void 0!==e?String(e).toLowerCase():Zu)!==Zu)throw new Error("Encoding not supported. Only utf-8 is supported");t=Hu(t),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=Boolean(t.fatal),this._ignoreBOM=Boolean(t.ignoreBOM),Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}function Ju(e,t){if(!(this instanceof Ju))return new Ju(e,t);if((e=void 0!==e?String(e).toLowerCase():Zu)!==Zu)throw new Error("Encoding not supported. Only utf-8 is supported");t=Hu(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function el(e){var t=e.fatal,n=0,r=0,o=0,i=128,s=191;this.handler=function(e,a){if(-1===a&&0!==o)return o=0,Qu(t);if(-1===a)return Xu;if(0===o){if(ju(a,0,127))return a;if(ju(a,194,223))o=1,n=a-192;else if(ju(a,224,239))224===a&&(i=160),237===a&&(s=159),o=2,n=a-224;else{if(!ju(a,240,244))return Qu(t);240===a&&(i=144),244===a&&(s=143),o=3,n=a-240}return n<<=6*o,null}if(!ju(a,i,s))return n=o=r=0,i=128,s=191,e.prepend(a),Qu(t);if(i=128,s=191,n+=a-128<<6*(o-(r+=1)),r!==o)return null;var c=n;return n=o=r=0,c}}function tl(e){e.fatal,this.handler=function(e,t){if(-1===t)return Xu;if(ju(t,0,127))return t;var n,r;ju(t,128,2047)?(n=1,r=192):ju(t,2048,65535)?(n=2,r=224):ju(t,65536,1114111)&&(n=3,r=240);for(var o=[(t>>6*n)+r];n>0;){var i=t>>6*(n-1);o.push(128|63&i),n-=1}return o}}Yu.prototype={decode:function(e,t){var n;n="object"==typeof e&&e instanceof ArrayBuffer?new Uint8Array(e):"object"==typeof e&&"buffer"in e&&e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(0),t=Hu(t),this._streaming||(this._decoder=new el({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,o=new Vu(n),i=[];!o.endOfStream()&&(r=this._decoder.handler(o,o.read()))!==Xu;)null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r));if(!this._streaming){do{if((r=this._decoder.handler(o,o.read()))===Xu)break;null!==r&&(Array.isArray(r)?i.push.apply(i,r):i.push(r))}while(!o.endOfStream());this._decoder=null}return i.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===i[0]?(this._BOMseen=!0,i.shift()):this._BOMseen=!0)),function(e){for(var t="",n=0;n<e.length;++n){var r=e[n];r<=65535?t+=String.fromCharCode(r):(r-=65536,t+=String.fromCharCode(55296+(r>>10),56320+(1023&r)))}return t}(i)}},Ju.prototype={encode:function(e,t){e=e?String(e):"",t=Hu(t),this._streaming||(this._encoder=new tl(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],o=new Vu(function(e){for(var t=String(e),n=t.length,r=0,o=[];r<n;){var i=t.charCodeAt(r);if(i<55296||i>57343)o.push(i);else if(56320<=i&&i<=57343)o.push(65533);else if(55296<=i&&i<=56319)if(r===n-1)o.push(65533);else{var s=e.charCodeAt(r+1);if(56320<=s&&s<=57343){var a=1023&i,c=1023&s;o.push(65536+(a<<10)+c),r+=1}else o.push(65533)}r+=1}return o}(e));!o.endOfStream()&&(n=this._encoder.handler(o,o.read()))!==Xu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(o,o.read()))!==Xu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var nl,rl=pi(Object.freeze({__proto__:null,TextDecoder:Yu,TextEncoder:Ju}));var ol,il,sl=function(){if(nl)return Wu;nl=1;var e=Wu&&Wu.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),t=Wu&&Wu.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=Wu&&Wu.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},r=Wu&&Wu.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(null!=n)for(var o in n)"default"!==o&&Object.hasOwnProperty.call(n,o)&&e(r,n,o);return t(r,n),r},o=Wu&&Wu.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Wu,"__esModule",{value:!0}),Wu.deserializeUnchecked=Wu.deserialize=Wu.serialize=Wu.BinaryReader=Wu.BinaryWriter=Wu.BorshError=Wu.baseDecode=Wu.baseEncode=void 0;const i=o(Tu()),s=o(zu()),a=r(rl),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});Wu.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),s.default.encode(Buffer.from(e))},Wu.baseDecode=function(e){return Buffer.from(s.default.decode(e))};const u=1024;class l extends Error{constructor(e){super(e),this.fieldPath=[],this.originalMessage=e}addToFieldPath(e){this.fieldPath.splice(0,0,e),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}Wu.BorshError=l;class h{constructor(){this.buf=Buffer.alloc(u),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(u)]))}writeU8(e){this.maybeResize(),this.buf.writeUInt8(e,this.length),this.length+=1}writeU16(e){this.maybeResize(),this.buf.writeUInt16LE(e,this.length),this.length+=2}writeU32(e){this.maybeResize(),this.buf.writeUInt32LE(e,this.length),this.length+=4}writeU64(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",64)))}writeBuffer(e){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),e,Buffer.alloc(u)]),this.length+=e.length}writeString(e){this.maybeResize();const t=Buffer.from(e,"utf8");this.writeU32(t.length),this.writeBuffer(t)}writeFixedArray(e){this.writeBuffer(Buffer.from(e))}writeArray(e,t){this.maybeResize(),this.writeU32(e.length);for(const n of e)this.maybeResize(),t(n)}toArray(){return this.buf.subarray(0,this.length)}}function d(e,t,n){const r=n.value;n.value=function(...e){try{return r.apply(this,e)}catch(e){if(e instanceof RangeError){const t=e.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(t)>=0)throw new l("Reached the end of buffer when deserializing")}throw e}}}Wu.BinaryWriter=h;class f{constructor(e){this.buf=e,this.offset=0}readU8(){const e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readU16(){const e=this.buf.readUInt16LE(this.offset);return this.offset+=2,e}readU32(){const e=this.buf.readUInt32LE(this.offset);return this.offset+=4,e}readU64(){const e=this.readBuffer(8);return new i.default(e,"le")}readU128(){const e=this.readBuffer(16);return new i.default(e,"le")}readU256(){const e=this.readBuffer(32);return new i.default(e,"le")}readU512(){const e=this.readBuffer(64);return new i.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new l(`Expected buffer length ${e} isn't within bounds`);const t=this.buf.slice(this.offset,this.offset+e);return this.offset+=e,t}readString(){const e=this.readU32(),t=this.readBuffer(e);try{return c.decode(t)}catch(e){throw new l(`Error decoding UTF-8 string: ${e}`)}}readFixedArray(e){return new Uint8Array(this.readBuffer(e))}readArray(e){const t=this.readU32(),n=Array();for(let r=0;r<t;++r)n.push(e());return n}}function p(e){return e.charAt(0).toUpperCase()+e.slice(1)}function g(e,t,n,r,o){try{if("string"==typeof r)o[`write${p(r)}`](n);else if(r instanceof Array)if("number"==typeof r[0]){if(n.length!==r[0])throw new l(`Expecting byte array of length ${r[0]}, but got ${n.length} bytes`);o.writeFixedArray(n)}else if(2===r.length&&"number"==typeof r[1]){if(n.length!==r[1])throw new l(`Expecting byte array of length ${r[1]}, but got ${n.length} bytes`);for(let t=0;t<r[1];t++)g(e,null,n[t],r[0],o)}else o.writeArray(n,n=>{g(e,t,n,r[0],o)});else if(void 0!==r.kind)switch(r.kind){case"option":null==n?o.writeU8(0):(o.writeU8(1),g(e,t,n,r.type,o));break;case"map":o.writeU32(n.size),n.forEach((n,i)=>{g(e,t,i,r.key,o),g(e,t,n,r.value,o)});break;default:throw new l(`FieldType ${r} unrecognized`)}else m(e,n,o)}catch(e){throw e instanceof l&&e.addToFieldPath(t),e}}function m(e,t,n){if("function"==typeof t.borshSerialize)return void t.borshSerialize(n);const r=e.get(t.constructor);if(!r)throw new l(`Class ${t.constructor.name} is missing in schema`);if("struct"===r.kind)r.fields.map(([r,o])=>{g(e,r,t[r],o,n)});else{if("enum"!==r.kind)throw new l(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`);{const o=t[r.field];for(let i=0;i<r.values.length;++i){const[s,a]=r.values[i];if(s===o){n.writeU8(i),g(e,s,t[s],a,n);break}}}}}function y(e,t,n,r){try{if("string"==typeof n)return r[`read${p(n)}`]();if(n instanceof Array){if("number"==typeof n[0])return r.readFixedArray(n[0]);if("number"==typeof n[1]){const t=[];for(let o=0;o<n[1];o++)t.push(y(e,null,n[0],r));return t}return r.readArray(()=>y(e,t,n[0],r))}if("option"===n.kind){return r.readU8()?y(e,t,n.type,r):void 0}if("map"===n.kind){let o=new Map;const i=r.readU32();for(let s=0;s<i;s++){const i=y(e,t,n.key,r),s=y(e,t,n.value,r);o.set(i,s)}return o}return w(e,n,r)}catch(e){throw e instanceof l&&e.addToFieldPath(t),e}}function w(e,t,n){if("function"==typeof t.borshDeserialize)return t.borshDeserialize(n);const r=e.get(t);if(!r)throw new l(`Class ${t.name} is missing in schema`);if("struct"===r.kind){const r={};for(const[o,i]of e.get(t).fields)r[o]=y(e,o,i,n);return new t(r)}if("enum"===r.kind){const o=n.readU8();if(o>=r.values.length)throw new l(`Enum index: ${o} is out of range`);const[i,s]=r.values[o],a=y(e,i,s,n);return new t({[i]:a})}throw new l(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`)}return n([d],f.prototype,"readU8",null),n([d],f.prototype,"readU16",null),n([d],f.prototype,"readU32",null),n([d],f.prototype,"readU64",null),n([d],f.prototype,"readU128",null),n([d],f.prototype,"readU256",null),n([d],f.prototype,"readU512",null),n([d],f.prototype,"readString",null),n([d],f.prototype,"readFixedArray",null),n([d],f.prototype,"readArray",null),Wu.BinaryReader=f,Wu.serialize=function(e,t,n=h){const r=new n;return m(e,t,r),r.toArray()},Wu.deserialize=function(e,t,n,r=f){const o=new r(n),i=w(e,t,o);if(o.offset<n.length)throw new l(`Unexpected ${n.length-o.offset} bytes after deserialized data`);return i},Wu.deserializeUnchecked=function(e,t,n,r=f){return w(e,t,new r(n))},Wu}(),al={},cl={};function ul(){return ol||(ol=1,function(e){const t=Ws(),n=Vs(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;function i(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=i(n);const o=r.write(e,t);o!==n&&(r=r.slice(0,o));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);const o=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?i(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),i(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=i(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function d(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(o)return r?-1:W(e).length;t=(""+t).toLowerCase(),o=!0}}function p(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return B(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return j(W(t,e.length-n),e,n,r)}function k(e,t,n,r){return j(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return j(z(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function A(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=o,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let o=0;for(n=0;n<e.length;++n){let t=e[n];if(H(t,Uint8Array))o+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)g(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?A(this,0,e):p.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,o){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){i=u[e],a=l[e];break}return i<a?-1:a<i?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function x(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function B(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=X[e[r]];return o}function C(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function P(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function U(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function F(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,8),n.write(e,t,r,o,52,8),r+8}s.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){N(this,e,t,n,Math.pow(2,8*n)-1,0)}let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){N(this,e,t,n,Math.pow(2,8*n)-1,0)}let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return _(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=Q(function(e,t=0){return _(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const o=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),o},s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{const i=s.isBuffer(e)?e:s.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%a]}return this};const L={};function O(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function M(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,o,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,o,i)}function q(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}O("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),O("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),O("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=M(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=M(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function z(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function H(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(cl)),cl}var ll=function(){if(il)return al;il=1,Object.defineProperty(al,"__esModule",{value:!0}),al.s16=al.s8=al.nu64be=al.u48be=al.u40be=al.u32be=al.u24be=al.u16be=al.nu64=al.u48=al.u40=al.u32=al.u24=al.u16=al.u8=al.offset=al.greedy=al.Constant=al.UTF8=al.CString=al.Blob=al.Boolean=al.BitField=al.BitStructure=al.VariantLayout=al.Union=al.UnionLayoutDiscriminator=al.UnionDiscriminator=al.Structure=al.Sequence=al.DoubleBE=al.Double=al.FloatBE=al.Float=al.NearInt64BE=al.NearInt64=al.NearUInt64BE=al.NearUInt64=al.IntBE=al.Int=al.UIntBE=al.UInt=al.OffsetLayout=al.GreedyCount=al.ExternalLayout=al.bindConstructorLayout=al.nameWithProperty=al.Layout=al.uint8ArrayToBuffer=al.checkUint8Array=void 0,al.constant=al.utf8=al.cstr=al.blob=al.unionLayoutDiscriminator=al.union=al.seq=al.bits=al.struct=al.f64be=al.f64=al.f32be=al.f32=al.ns64be=al.s48be=al.s40be=al.s32be=al.s24be=al.s16be=al.ns64=al.s48=al.s40=al.s32=al.s24=void 0;const e=ul();function t(e){if(!(e instanceof Uint8Array))throw new TypeError("b must be a Uint8Array")}function n(n){return t(n),e.Buffer.from(n.buffer,n.byteOffset,n.length)}al.checkUint8Array=t,al.uint8ArrayToBuffer=n;let r=class{constructor(e,t){if(!Number.isInteger(e))throw new TypeError("span must be an integer");this.span=e,this.property=t}makeDestinationObject(){return{}}getSpan(e,t){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(e){const t=Object.create(this.constructor.prototype);return Object.assign(t,this),t.property=e,t}fromArray(e){}};function o(e,t){return t.property?e+"["+t.property+"]":e}al.Layout=r,al.nameWithProperty=o,al.bindConstructorLayout=function(e,t){if("function"!=typeof e)throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(e,"layout_"))throw new Error("Class is already bound to a layout");if(!(t&&t instanceof r))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");e.layout_=t,t.boundConstructor_=e,t.makeDestinationObject=()=>new e,Object.defineProperty(e.prototype,"encode",{value(e,n){return t.encode(this,e,n)},writable:!0}),Object.defineProperty(e,"decode",{value:(e,n)=>t.decode(e,n),writable:!0})};class i extends r{isCount(){throw new Error("ExternalLayout is abstract")}}al.ExternalLayout=i;class s extends i{constructor(e=1,t){if(!Number.isInteger(e)||0>=e)throw new TypeError("elementSpan must be a (positive) integer");super(-1,t),this.elementSpan=e}isCount(){return!0}decode(e,n=0){t(e);const r=e.length-n;return Math.floor(r/this.elementSpan)}encode(e,t,n){return 0}}al.GreedyCount=s;class a extends i{constructor(e,t=0,n){if(!(e instanceof r))throw new TypeError("layout must be a Layout");if(!Number.isInteger(t))throw new TypeError("offset must be integer or undefined");super(e.span,n||e.property),this.layout=e,this.offset=t}isCount(){return this.layout instanceof c||this.layout instanceof u}decode(e,t=0){return this.layout.decode(e,t+this.offset)}encode(e,t,n=0){return this.layout.encode(e,t,n+this.offset)}}al.OffsetLayout=a;class c extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readUIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntLE(e,r,this.span),this.span}}al.UInt=c;class u extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readUIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntBE(e,r,this.span),this.span}}al.UIntBE=u;class l extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeIntLE(e,r,this.span),this.span}}al.Int=l;class h extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeIntBE(e,r,this.span),this.span}}al.IntBE=h;const d=Math.pow(2,32);function f(e){const t=Math.floor(e/d);return{hi32:t,lo32:e-t*d}}function p(e,t){return e*d+t}class g extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),o=r.readUInt32LE(t);return p(r.readUInt32LE(t+4),o)}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeUInt32LE(o.lo32,r),i.writeUInt32LE(o.hi32,r+4),8}}al.NearUInt64=g;class m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return p(r.readUInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeUInt32BE(o.hi32,r),i.writeUInt32BE(o.lo32,r+4),8}}al.NearUInt64BE=m;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),o=r.readUInt32LE(t);return p(r.readInt32LE(t+4),o)}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeUInt32LE(o.lo32,r),i.writeInt32LE(o.hi32,r+4),8}}al.NearInt64=y;class w extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return p(r.readInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const o=f(e),i=n(t);return i.writeInt32BE(o.hi32,r),i.writeUInt32BE(o.lo32,r+4),8}}al.NearInt64BE=w;class b extends r{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatLE(t)}encode(e,t,r=0){return n(t).writeFloatLE(e,r),4}}al.Float=b;class k extends r{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatBE(t)}encode(e,t,r=0){return n(t).writeFloatBE(e,r),4}}al.FloatBE=k;class v extends r{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleLE(t)}encode(e,t,r=0){return n(t).writeDoubleLE(e,r),8}}al.Double=v;class E extends r{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleBE(t)}encode(e,t,r=0){return n(t).writeDoubleBE(e,r),8}}al.DoubleBE=E;class S extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof i&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let o=-1;!(t instanceof i)&&0<e.span&&(o=t*e.span),super(o,n),this.elementLayout=e,this.count=t}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0,r=this.count;if(r instanceof i&&(r=r.decode(e,t)),0<this.elementLayout.span)n=r*this.elementLayout.span;else{let o=0;for(;o<r;)n+=this.elementLayout.getSpan(e,t+n),++o}return n}decode(e,t=0){const n=[];let r=0,o=this.count;for(o instanceof i&&(o=o.decode(e,t));r<o;)n.push(this.elementLayout.decode(e,t)),t+=this.elementLayout.getSpan(e,t),r+=1;return n}encode(e,t,n=0){const r=this.elementLayout,o=e.reduce((e,o)=>e+r.encode(o,t,n+e),0);return this.count instanceof i&&this.count.encode(e.length,t,n),o}}al.Sequence=S;class A extends r{constructor(e,t,n){if(!Array.isArray(e)||!e.reduce((e,t)=>e&&t instanceof r,!0))throw new TypeError("fields must be array of Layout instances");"boolean"==typeof t&&void 0===n&&(n=t,t=void 0);for(const t of e)if(0>t.span&&void 0===t.property)throw new Error("fields cannot contain unnamed variable-length layout");let o=-1;try{o=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(o,t),this.fields=e,this.decodePrefixes=!!n}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;try{n=this.fields.reduce((n,r)=>{const o=r.getSpan(e,t);return t+=o,n+o},0)}catch(e){throw new RangeError("indeterminate span")}return n}decode(e,n=0){t(e);const r=this.makeDestinationObject();for(const t of this.fields)if(void 0!==t.property&&(r[t.property]=t.decode(e,n)),n+=t.getSpan(e,n),this.decodePrefixes&&e.length===n)break;return r}encode(e,t,n=0){const r=n;let o=0,i=0;for(const r of this.fields){let s=r.span;if(i=0<s?s:0,void 0!==r.property){const o=e[r.property];void 0!==o&&(i=r.encode(o,t,n),0>s&&(s=r.getSpan(t,n)))}o=n,n+=s}return o+i-r}fromArray(e){const t=this.makeDestinationObject();for(const n of this.fields)void 0!==n.property&&0<e.length&&(t[n.property]=e.shift());return t}layoutFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}offsetOf(e){if("string"!=typeof e)throw new TypeError("property must be string");let t=0;for(const n of this.fields){if(n.property===e)return t;0>n.span?t=-1:0<=t&&(t+=n.span)}}}al.Structure=A;class T{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,n){throw new Error("UnionDiscriminator is abstract")}}al.UnionDiscriminator=T;class I extends T{constructor(e,t){if(!(e instanceof i&&e.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,n){return this.layout.encode(e,t,n)}}al.UnionLayoutDiscriminator=I;class x extends r{constructor(e,t,n){let o;if(e instanceof c||e instanceof u)o=new I(new a(e));else if(e instanceof i&&e.isCount())o=new I(e);else{if(!(e instanceof T))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");o=e}if(void 0===t&&(t=null),!(null===t||t instanceof r))throw new TypeError("defaultLayout must be null or a Layout");if(null!==t){if(0>t.span)throw new Error("defaultLayout must have constant span");void 0===t.property&&(t=t.replicate("content"))}let s=-1;t&&(s=t.span,0<=s&&(e instanceof c||e instanceof u)&&(s+=o.layout.span)),super(s,n),this.discriminator=o,this.usesPrefixDiscriminator=e instanceof c||e instanceof u,this.defaultLayout=t,this.registry={};let l=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(e){return l(e)},this.configGetSourceVariant=function(e){l=e.bind(this)}}getSpan(e,t=0){if(0<=this.span)return this.span;const n=this.getVariant(e,t);if(!n)throw new Error("unable to determine span for unrecognized variant");return n.getSpan(e,t)}defaultGetSourceVariant(e){if(Object.prototype.hasOwnProperty.call(e,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(e,this.defaultLayout.property))return;const t=this.registry[e[this.discriminator.property]];if(t&&(!t.layout||t.property&&Object.prototype.hasOwnProperty.call(e,t.property)))return t}else for(const t in this.registry){const n=this.registry[t];if(n.property&&Object.prototype.hasOwnProperty.call(e,n.property))return n}throw new Error("unable to infer src variant")}decode(e,t=0){let n;const r=this.discriminator,o=r.decode(e,t),i=this.registry[o];if(void 0===i){const i=this.defaultLayout;let s=0;this.usesPrefixDiscriminator&&(s=r.layout.span),n=this.makeDestinationObject(),n[r.property]=o,n[i.property]=i.decode(e,t+s)}else n=i.decode(e,t);return n}encode(e,t,n=0){const r=this.getSourceVariant(e);if(void 0===r){const r=this.discriminator,o=this.defaultLayout;let i=0;return this.usesPrefixDiscriminator&&(i=r.layout.span),r.encode(e[r.property],t,n),i+o.encode(e[o.property],t,n+i)}return r.encode(e,t,n)}addVariant(e,t,n){const r=new B(this,e,t,n);return this.registry[e]=r,r}getVariant(e,t=0){let n;return n=e instanceof Uint8Array?this.discriminator.decode(e,t):e,this.registry[n]}}al.Union=x;class B extends r{constructor(e,t,n,o){if(!(e instanceof x))throw new TypeError("union must be a Union");if(!Number.isInteger(t)||0>t)throw new TypeError("variant must be a (non-negative) integer");if("string"==typeof n&&void 0===o&&(o=n,n=null),n){if(!(n instanceof r))throw new TypeError("layout must be a Layout");if(null!==e.defaultLayout&&0<=n.span&&n.span>e.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if("string"!=typeof o)throw new TypeError("variant must have a String property")}let i=e.span;0>e.span&&(i=n?n.span:0,0<=i&&e.usesPrefixDiscriminator&&(i+=e.discriminator.layout.span)),super(i,o),this.union=e,this.variant=t,this.layout=n||null}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span);let r=0;return this.layout&&(r=this.layout.getSpan(e,t+n)),n+r}decode(e,t=0){const n=this.makeDestinationObject();if(this!==this.union.getVariant(e,t))throw new Error("variant mismatch");let r=0;return this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout?n[this.property]=this.layout.decode(e,t+r):this.property?n[this.property]=!0:this.union.usesPrefixDiscriminator&&(n[this.union.discriminator.property]=this.variant),n}encode(e,t,n=0){let r=0;if(this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(e,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,t,n);let o=r;if(this.layout&&(this.layout.encode(e[this.property],t,n+r),o+=this.layout.getSpan(t,n+r),0<=this.union.span&&o>this.union.span))throw new Error("encoded variant overruns containing union");return o}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function C(e){return 0>e&&(e+=4294967296),e}al.VariantLayout=B;class P extends r{constructor(e,t,n){if(!(e instanceof c||e instanceof u))throw new TypeError("word must be a UInt or UIntBE layout");if("string"==typeof t&&void 0===n&&(n=t,t=!1),4<e.span)throw new RangeError("word cannot exceed 32 bits");super(e.span,n),this.word=e,this.msb=!!t,this.fields=[];let r=0;this._packedSetValue=function(e){return r=C(e),this},this._packedGetValue=function(){return r}}decode(e,t=0){const n=this.makeDestinationObject(),r=this.word.decode(e,t);this._packedSetValue(r);for(const t of this.fields)void 0!==t.property&&(n[t.property]=t.decode(e));return n}encode(e,t,n=0){const r=this.word.decode(t,n);this._packedSetValue(r);for(const t of this.fields)if(void 0!==t.property){const n=e[t.property];void 0!==n&&t.encode(n)}return this.word.encode(this._packedGetValue(),t,n)}addField(e,t){const n=new N(this,e,t);return this.fields.push(n),n}addBoolean(e){const t=new _(this,e);return this.fields.push(t),t}fieldFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}}al.BitStructure=P;class N{constructor(e,t,n){if(!(e instanceof P))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(t)||0>=t)throw new TypeError("bits must be positive integer");const r=8*e.span,o=e.fields.reduce((e,t)=>e+t.bits,0);if(t+o>r)throw new Error("bits too long for span remainder ("+(r-o)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=o,this.container.msb&&(this.start=r-o-t),this.wordMask=C(this.valueMask<<this.start),this.property=n}decode(e,t){return C(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==C(e&this.valueMask))throw new TypeError(o("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=C(e<<this.start);this.container._packedSetValue(C(t&~this.wordMask)|n)}}al.BitField=N;class _ extends N{constructor(e,t){super(e,1,t)}decode(e,t){return!!super.decode(e,t)}encode(e){"boolean"==typeof e&&(e=+e),super.encode(e)}}al.Boolean=_;class U extends r{constructor(e,t){if(!(e instanceof i&&e.isCount()||Number.isInteger(e)&&0<=e))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let n=-1;e instanceof i||(n=e),super(n,t),this.length=e}getSpan(e,t){let n=this.span;return 0>n&&(n=this.length.decode(e,t)),n}decode(e,t=0){let r=this.span;return 0>r&&(r=this.length.decode(e,t)),n(e).slice(t,t+r)}encode(e,t,r){let s=this.length;if(this.length instanceof i&&(s=e.length),!(e instanceof Uint8Array&&s===e.length))throw new TypeError(o("Blob.encode",this)+" requires (length "+s+") Uint8Array as src");if(r+s>t.length)throw new RangeError("encoding overruns Uint8Array");const a=n(e);return n(t).write(a.toString("hex"),r,s,"hex"),this.length instanceof i&&this.length.encode(s,t,r),s}}al.Blob=U;class D extends r{constructor(e){super(-1,e)}getSpan(e,n=0){t(e);let r=n;for(;r<e.length&&0!==e[r];)r+=1;return 1+r-n}decode(e,t=0){const r=this.getSpan(e,t);return n(e).slice(t,t+r-1).toString("utf-8")}encode(t,r,o=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),s=i.length;if(o+s>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return i.copy(a,o),a[o+s]=0,s+1}}al.CString=D;class R extends r{constructor(e,t){if("string"==typeof e&&void 0===t&&(t=e,e=void 0),void 0===e)e=-1;else if(!Number.isInteger(e))throw new TypeError("maxSpan must be an integer");super(-1,t),this.maxSpan=e}getSpan(e,n=0){return t(e),e.length-n}decode(e,t=0){const r=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpan<r)throw new RangeError("text length exceeds maxSpan");return n(e).slice(t,t+r).toString("utf-8")}encode(t,r,o=0){"string"!=typeof t&&(t=String(t));const i=e.Buffer.from(t,"utf8"),s=i.length;if(0<=this.maxSpan&&this.maxSpan<s)throw new RangeError("text length exceeds maxSpan");if(o+s>r.length)throw new RangeError("encoding overruns Buffer");return i.copy(n(r),o),s}}al.UTF8=R;class F extends r{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,n){return 0}}return al.Constant=F,al.greedy=(e,t)=>new s(e,t),al.offset=(e,t,n)=>new a(e,t,n),al.u8=e=>new c(1,e),al.u16=e=>new c(2,e),al.u24=e=>new c(3,e),al.u32=e=>new c(4,e),al.u40=e=>new c(5,e),al.u48=e=>new c(6,e),al.nu64=e=>new g(e),al.u16be=e=>new u(2,e),al.u24be=e=>new u(3,e),al.u32be=e=>new u(4,e),al.u40be=e=>new u(5,e),al.u48be=e=>new u(6,e),al.nu64be=e=>new m(e),al.s8=e=>new l(1,e),al.s16=e=>new l(2,e),al.s24=e=>new l(3,e),al.s32=e=>new l(4,e),al.s40=e=>new l(5,e),al.s48=e=>new l(6,e),al.ns64=e=>new y(e),al.s16be=e=>new h(2,e),al.s24be=e=>new h(3,e),al.s32be=e=>new h(4,e),al.s40be=e=>new h(5,e),al.s48be=e=>new h(6,e),al.ns64be=e=>new w(e),al.f32=e=>new b(e),al.f32be=e=>new k(e),al.f64=e=>new v(e),al.f64be=e=>new E(e),al.struct=(e,t,n)=>new A(e,t,n),al.bits=(e,t,n)=>new P(e,t,n),al.seq=(e,t,n)=>new S(e,t,n),al.union=(e,t,n)=>new x(e,t,n),al.unionLayoutDiscriminator=(e,t)=>new I(e,t),al.blob=(e,t)=>new U(e,t),al.cstr=e=>new D(e),al.utf8=(e,t)=>new R(e,t),al.constant=(e,t)=>new F(e,t),al}(),hl=1,dl=2,fl=3,pl=4,gl=5,ml=6,yl=7,wl=8,bl=9,kl=10,vl=-32700,El=-32603,Sl=-32602,Al=-32601,Tl=-32600,Il=-32016,xl=-32015,Bl=-32014,Cl=-32013,Pl=-32012,Nl=-32011,_l=-32010,Ul=-32009,Dl=-32008,Rl=-32007,Fl=-32006,Ll=-32005,Ol=-32004,Ml=-32003,$l=-32002,ql=-32001,Kl=28e5,Gl=2800001,Wl=2800002,zl=2800003,jl=2800004,Hl=2800005,Vl=2800006,Xl=2800007,Ql=2800008,Zl=2800009,Yl=2800010,Jl=2800011,eh=323e4,th=32300001,nh=3230002,rh=3230003,oh=3230004,ih=361e4,sh=3610001,ah=3610002,ch=3610003,uh=3610004,lh=3610005,hh=3610006,dh=3610007,fh=3611e3,ph=3704e3,gh=3704001,mh=3704002,yh=3704003,wh=3704004,bh=4128e3,kh=4128001,vh=4128002,Eh=4615e3,Sh=4615001,Ah=4615002,Th=4615003,Ih=4615004,xh=4615005,Bh=4615006,Ch=4615007,Ph=4615008,Nh=4615009,_h=4615010,Uh=4615011,Dh=4615012,Rh=4615013,Fh=4615014,Lh=4615015,Oh=4615016,Mh=4615017,$h=4615018,qh=4615019,Kh=4615020,Gh=4615021,Wh=4615022,zh=4615023,jh=4615024,Hh=4615025,Vh=4615026,Xh=4615027,Qh=4615028,Zh=4615029,Yh=4615030,Jh=4615031,ed=4615032,td=4615033,nd=4615034,rd=4615035,od=4615036,id=4615037,sd=4615038,ad=4615039,cd=4615040,ud=4615041,ld=4615042,hd=4615043,dd=4615044,fd=4615045,pd=4615046,gd=4615047,md=4615048,yd=4615049,wd=4615050,bd=4615051,kd=4615052,vd=4615053,Ed=4615054,Sd=5508e3,Ad=5508001,Td=5508002,Id=5508003,xd=5508004,Bd=5508005,Cd=5508006,Pd=5508007,Nd=5508008,_d=5508009,Ud=5508010,Dd=5508011,Rd=5663e3,Fd=5663001,Ld=5663002,Od=5663003,Md=5663004,$d=5663005,qd=5663006,Kd=5663007,Gd=5663008,Wd=5663009,zd=5663010,jd=5663011,Hd=5663012,Vd=5663013,Xd=5663014,Qd=5663015,Zd=5663016,Yd=5663017,Jd=5663018,ef=5663019,tf=5663020,nf=705e4,rf=7050001,of=7050002,sf=7050003,af=7050004,cf=7050005,uf=7050006,lf=7050007,hf=7050008,df=7050009,ff=7050010,pf=7050011,gf=7050012,mf=7050013,yf=7050014,wf=7050015,bf=7050016,kf=7050017,vf=7050018,Ef=7050019,Sf=7050020,Af=7050021,Tf=7050022,If=7050023,xf=7050024,Bf=7050025,Cf=7050026,Pf=7050027,Nf=7050028,_f=7050029,Uf=7050030,Df=7050031,Rf=7050032,Ff=7050033,Lf=7050034,Of=7050035,Mf=7050036,$f=8078e3,qf=8078001,Kf=8078002,Gf=8078003,Wf=8078004,zf=8078005,jf=8078006,Hf=8078007,Vf=8078008,Xf=8078009,Qf=8078010,Zf=8078011,Yf=8078012,Jf=8078013,ep=8078014,tp=8078015,np=8078016,rp=8078017,op=8078018,ip=8078019,sp=8078020,ap=8078021,cp=8078022,up=81e5,lp=8100001,hp=8100002,dp=8100003,fp=819e4,pp=8190001,gp=8190002,mp=8190003,yp=8190004,wp=99e5,bp=9900001,kp=9900002,vp=9900003,Ep=9900004;function Sp(e){if(Array.isArray(e)){return"%5B"+e.map(Sp).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Ap([e,t]){return`${e}=${Sp(t)}`}var Tp={[eh]:"Account not found at address: $address",[oh]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[rh]:"Expected decoded account at address: $address",[nh]:"Failed to decode account data at address: $address",[th]:"Accounts not found at addresses: $addresses",[Zl]:"Unable to find a viable program address bump seed.",[Wl]:"$putativeAddress is not a base58-encoded address.",[Kl]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[zl]:"The `CryptoKey` must be an `Ed25519` public key.",[Jl]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[Ql]:"Invalid seeds; point must fall off the Ed25519 curve.",[jl]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[Vl]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[Xl]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[Hl]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Yl]:"Program address cannot end with PDA marker.",[Gl]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[pl]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[hl]:"The network has progressed past the last block for which this transaction could have been committed.",[$f]:"Codec [$codecDescription] cannot decode empty byte arrays.",[cp]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[sp]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[zf]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[jf]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Wf]:"Encoder and decoder must either both be fixed-size or variable-size.",[Vf]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Kf]:"Expected a fixed-size codec, got a variable-size one.",[Jf]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Gf]:"Expected a variable-size codec, got a fixed-size one.",[ip]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[qf]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[op]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[Xf]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Qf]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[tp]:"Invalid literal union variant. Expected one of [$variants], got $value.",[Hf]:"Expected [$codecDescription] to have $expected items, got $actual.",[Yf]:"Invalid value $value for base $base with alphabet $alphabet.",[np]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[Zf]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[ep]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[ap]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[rp]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[fh]:"No random values implementation could be found.",[Nh]:"instruction requires an uninitialized account",[zh]:"instruction tries to borrow reference for an account which is already borrowed",[jh]:"instruction left account with an outstanding borrowed reference",[Gh]:"program other than the account's owner changed the size of the account data",[xh]:"account data too small for instruction",[Wh]:"instruction expected an executable account",[pd]:"An account does not have enough lamports to be rent-exempt",[md]:"Program arithmetic overflowed",[fd]:"Failed to serialize or deserialize account data: $encodedData",[Ed]:"Builtin programs must consume compute units",[ed]:"Cross-program invocation call depth too deep",[sd]:"Computational budget exceeded",[Vh]:"custom program error: #$code",[Mh]:"instruction contains duplicate accounts",[Hh]:"instruction modifications of multiply-passed account differ",[Yh]:"executable accounts must be rent exempt",[Qh]:"instruction changed executable accounts data",[Zh]:"instruction changed the balance of an executable account",[$h]:"instruction changed executable bit of an account",[Fh]:"instruction modified data of an account it does not own",[Rh]:"instruction spent from the balance of an account it does not own",[Sh]:"generic instruction error",[wd]:"Provided owner is not allowed",[hd]:"Account is immutable",[dd]:"Incorrect authority provided",[Ch]:"incorrect program id for instruction",[Bh]:"insufficient funds for instruction",[Ih]:"invalid account data for instruction",[gd]:"Invalid account owner",[Ah]:"invalid program argument",[Xh]:"program returned invalid error code",[Th]:"invalid instruction data",[id]:"Failed to reallocate account data",[od]:"Provided seeds do not result in a valid address",[bd]:"Accounts data allocations exceeded the maximum allowed per transaction",[kd]:"Max accounts exceeded",[vd]:"Max instruction trace length exceeded",[rd]:"Length of the seed is too long for address generation",[td]:"An account required by the instruction is missing",[Ph]:"missing required signature for instruction",[Dh]:"instruction illegally modified the program id of an account",[Kh]:"insufficient account keys for instruction",[ad]:"Cross-program invocation with unauthorized signer or writable account",[cd]:"Failed to create program execution environment",[ld]:"Program failed to compile",[ud]:"Program failed to complete",[Oh]:"instruction modified data of a read-only account",[Lh]:"instruction changed the balance of a read-only account",[nd]:"Cross-program invocation reentrancy not allowed for this instruction",[qh]:"instruction modified rent epoch of an account",[Uh]:"sum of account balances before and after instruction do not match",[_h]:"instruction requires an initialized account",[Eh]:"",[Jh]:"Unsupported program id",[yd]:"Unsupported sysvar",[bh]:"The instruction does not have any accounts.",[kh]:"The instruction does not have any data.",[vh]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[gl]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[dl]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[kp]:"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Ep]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[bp]:"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[wp]:"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[vp]:"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[El]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Sl]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Tl]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Al]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[vl]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[Pl]:"$__serverMessage",[ql]:"$__serverMessage",[Ol]:"$__serverMessage",[Bl]:"$__serverMessage",[_l]:"$__serverMessage",[Ul]:"$__serverMessage",[Il]:"Minimum context slot has not been reached",[Ll]:"Node is unhealthy; behind by $numSlotsBehind slots",[Dl]:"No snapshot",[$l]:"Transaction simulation failed",[Rl]:"$__serverMessage",[Nl]:"Transaction history is not available from this node",[Fl]:"$__serverMessage",[Cl]:"Transaction signature length mismatch",[Ml]:"Transaction signature verification failure",[xl]:"$__serverMessage",[ph]:"Key pair bytes must be of length 64, got $byteLength.",[gh]:"Expected private key bytes with length 32. Actual length: $actualLength.",[mh]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[wh]:"The provided private key does not match the provided public key.",[yh]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[ml]:"Lamports value must be in the range [0, 2e64-1]",[yl]:"`$value` cannot be parsed as a `BigInt`",[kl]:"$message",[wl]:"`$value` cannot be parsed as a `Number`",[fl]:"No nonce account could be found at address `$nonceAccountAddress`",[fp]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[gp]:"WebSocket was closed before payload could be added to the send buffer",[mp]:"WebSocket connection closed",[yp]:"WebSocket failed to connect",[pp]:"Failed to obtain a subscription id from the server",[dp]:"Could not find an API plan for RPC method: `$method`",[up]:"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",[hp]:"HTTP error ($statusCode): $message",[lp]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[Sd]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[Ad]:"The provided value does not implement the `KeyPairSigner` interface",[Id]:"The provided value does not implement the `MessageModifyingSigner` interface",[xd]:"The provided value does not implement the `MessagePartialSigner` interface",[Td]:"The provided value does not implement any of the `MessageSigner` interfaces",[Cd]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Pd]:"The provided value does not implement the `TransactionPartialSigner` interface",[Nd]:"The provided value does not implement the `TransactionSendingSigner` interface",[Bd]:"The provided value does not implement any of the `TransactionSigner` interfaces",[_d]:"More than one `TransactionSendingSigner` was identified.",[Ud]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Dd]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[dh]:"Cannot export a non-extractable key.",[sh]:"No digest implementation could be found.",[ih]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[ah]:"This runtime does not support the generation of Ed25519 key pairs.\n\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.",[ch]:"No signature verification implementation could be found.",[uh]:"No key generation implementation could be found.",[lh]:"No signing implementation could be found.",[hh]:"No key export implementation could be found.",[bl]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[bf]:"Transaction processing left an account with an outstanding borrowed reference",[rf]:"Account in use",[of]:"Account loaded twice",[sf]:"Attempt to debit an account but found no record of a prior credit.",[If]:"Transaction loads an address table account that doesn't exist",[lf]:"This transaction has already been processed",[hf]:"Blockhash not found",[df]:"Loader call chain is too deep",[wf]:"Transactions are currently disabled due to cluster maintenance",[Uf]:"Transaction contains a duplicate instruction ($index) that is not allowed",[cf]:"Insufficient funds for fee",[Df]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[uf]:"This account may not be used to pay transaction fees",[pf]:"Transaction contains an invalid account reference",[Bf]:"Transaction loads an address table account with invalid data",[Cf]:"Transaction address table lookup uses an invalid index",[xf]:"Transaction loads an address table account with an invalid owner",[Ff]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[mf]:"This program may not be used for executing instructions",[Pf]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[Ef]:"Transaction loads a writable account that cannot be written",[Rf]:"Transaction exceeded max loaded accounts data size cap",[ff]:"Transaction requires a fee but has no signature present",[af]:"Attempt to load a program that does not exist",[Of]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Lf]:"ResanitizationNeeded",[yf]:"Transaction failed to sanitize accounts offsets correctly",[gf]:"Transaction did not pass signature verification",[Tf]:"Transaction locked too many accounts",[Mf]:"Sum of account balances before and after transaction do not match",[nf]:"The transaction failed with the error `$errorName`",[vf]:"Transaction version is unsupported",[Af]:"Transaction would exceed account data limit within the block",[_f]:"Transaction would exceed total account data limit",[Sf]:"Transaction would exceed max account limit within the block",[kf]:"Transaction would exceed max Block Cost Limit",[Nf]:"Transaction would exceed max Vote Cost Limit",[Qd]:"Attempted to sign a transaction with an address that is not a signer for it",[zd]:"Transaction is missing an address at index: $index.",[Zd]:"Transaction has no expected signers therefore it cannot be encoded",[tf]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Ld]:"Transaction does not have a blockhash lifetime",[Od]:"Transaction is not a durable nonce transaction",[$d]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[qd]:"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",[Gd]:"No fee payer set in CompiledTransaction",[Kd]:"Could not find program address at index $index",[Jd]:"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",[ef]:"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",[jd]:"Transaction is missing a fee payer.",[Hd]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Xd]:"Transaction first instruction is not advance nonce account instruction.",[Vd]:"Transaction with no instructions cannot be durable nonce transaction.",[Rd]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Fd]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Yd]:"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.",[Wd]:"Transaction is missing signatures for addresses: $addresses.",[Md]:"Transaction version must be in the range [0, 127]. `$actualVersion` given"},Ip="i",xp="t";function Bp(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=Tp[e];if(0===n.length)return"";let r;function o(e){if(2===r[xp]){const o=n.slice(r[Ip]+1,e);i.push(o in t?`${t[o]}`:`$${o}`)}else 1===r[xp]&&i.push(n.slice(r[Ip],e))}const i=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Ip]:0,[xp]:"\\"===n[0]?0:"$"===n[0]?2:1});let i;switch(r[xp]){case 0:i={[Ip]:t,[xp]:1};break;case 1:"\\"===e?i={[Ip]:t,[xp]:0}:"$"===e&&(i={[Ip]:t,[xp]:2});break;case 2:"\\"===e?i={[Ip]:t,[xp]:0}:"$"===e?i={[Ip]:t,[xp]:2}:e.match(/\w/)||(i={[Ip]:t,[xp]:1})}i&&(r!==i&&o(t),r=i)}),o(),i.join("")}(e,t);{let n=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(n+=` '${function(e){const t=Object.entries(e).map(Ap).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Cp=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;if(t){const{cause:e,...o}=t;e&&(r={cause:e}),Object.keys(o).length>0&&(n=o)}super(Bp(e,n),r),this.context={__code:e,...n},this.name="SolanaError"}};function Pp(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function Np(e){return 1!==e?.endian}function _p(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Cp(Zf,{codecDescription:e,max:n,min:t,value:r})}(e.name,e.range[0],e.range[1],t);const o=new ArrayBuffer(e.size);return e.set(new DataView(o),t,Np(e.config)),n.set(new Uint8Array(o),r),r+e.size}},Object.freeze({...t,encode:e=>{const n=new Uint8Array(function(e,t){return"fixedSize"in t?t.fixedSize:t.getSizeFromValue(e)}(e,t));return t.write(e,n,0),n}});var t}function Up(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Cp($f,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const o=n.length-r;if(o<t)throw new Cp(qf,{bytesLength:o,codecDescription:e,expected:t})}(e.name,e.size,t,n);const r=new DataView(function(e,t,n){const r=e.byteOffset+(t??0),o=n??e.byteLength;return e.buffer.slice(r,r+o)}(t,n,e.size));return[e.get(r,Np(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var Dp=(e={})=>function(e,t){if(Pp(e)!==Pp(t))throw new Cp(Wf);if(Pp(e)&&Pp(t)&&e.fixedSize!==t.fixedSize)throw new Cp(zf,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Pp(e)&&!Pp(t)&&e.maxSize!==t.maxSize)throw new Cp(jf,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>_p({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>Up({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class Rp extends TypeError{constructor(e,t){let n;const{message:r,explanation:o,...i}=e,{path:s}=e,a=0===s.length?r:`At path: ${s.join(".")} -- ${r}`;super(o??a),null!=o&&(this.cause=a),Object.assign(this,i),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Fp(e){return"object"==typeof e&&null!=e}function Lp(e){return Fp(e)&&!Array.isArray(e)}function Op(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Mp(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:o,branch:i}=t,{type:s}=n,{refinement:a,message:c=`Expected a value of type \`${s}\`${a?` with refinement \`${a}\``:""}, but received: \`${Op(r)}\``}=e;return{value:r,type:s,refinement:a,key:o[o.length-1],path:o,branch:i,...e,message:c}}function*$p(e,t,n,r){var o;Fp(o=e)&&"function"==typeof o[Symbol.iterator]||(e=[e]);for(const o of e){const e=Mp(o,t,n,r);e&&(yield e)}}function*qp(e,t,n={}){const{path:r=[],branch:o=[e],coerce:i=!1,mask:s=!1}=n,a={path:r,branch:o,mask:s};i&&(e=t.coercer(e,a));let c="valid";for(const r of t.validator(e,a))r.explanation=n.message,c="not_valid",yield[r,void 0];for(let[u,l,h]of t.entries(e,a)){const t=qp(l,h,{path:void 0===u?r:[...r,u],branch:void 0===u?o:[...o,l],coerce:i,mask:s,message:n.message});for(const n of t)n[0]?(c=null!=n[0].refinement?"not_refined":"not_valid",yield[n[0],void 0]):i&&(l=n[1],void 0===u?e=l:e instanceof Map?e.set(u,l):e instanceof Set?e.add(l):Fp(e)&&(void 0!==l||u in e)&&(e[u]=l))}if("not_valid"!==c)for(const r of t.refiner(e,a))r.explanation=n.message,c="not_refined",yield[r,void 0];"valid"===c&&(yield[void 0,e])}let Kp=class{constructor(e){const{type:t,schema:n,validator:r,refiner:o,coercer:i=e=>e,entries:s=function*(){}}=e;this.type=t,this.schema=n,this.entries=s,this.coercer=i,this.validator=r?(e,t)=>$p(r(e,t),t,this,e):()=>[],this.refiner=o?(e,t)=>$p(o(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=zp(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return Gp(e,this,t)}is(e){return Wp(e,this)}mask(e,t){return function(e,t,n){const r=zp(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return zp(e,this,t)}};function Gp(e,t,n){const r=zp(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function Wp(e,t){return!zp(e,t)[0]}function zp(e,t,n={}){const r=qp(e,t,n),o=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(o[0]){return[new Rp(o[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,o[1]]}function jp(e,t){return new Kp({type:e,schema:null,validator:t})}function Hp(e){return new Kp({type:"array",schema:e,*entries(t){if(e&&Array.isArray(t))for(const[n,r]of t.entries())yield[n,r,e]},coercer:e=>Array.isArray(e)?e.slice():e,validator:e=>Array.isArray(e)||`Expected an array value, but received: ${Op(e)}`})}function Vp(){return jp("boolean",e=>"boolean"==typeof e)}function Xp(e){return jp("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Op(t)}`)}function Qp(e){const t=Op(e),n=typeof e;return new Kp({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Op(n)}`})}function Zp(e){return new Kp({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function Yp(){return jp("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Op(e)}`)}function Jp(e){return new Kp({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function eg(e,t){return new Kp({type:"record",schema:null,*entries(n){if(Fp(n))for(const r in n){const o=n[r];yield[r,r,e],yield[r,o,t]}},validator:e=>Lp(e)||`Expected an object, but received: ${Op(e)}`,coercer:e=>Lp(e)?{...e}:e})}function tg(){return jp("string",e=>"string"==typeof e||`Expected a string, but received: ${Op(e)}`)}function ng(e){const t=jp("never",()=>!1);return new Kp({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(e.length,n.length);for(let o=0;o<r;o++)yield[o,n[o],e[o]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${Op(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function rg(e){const t=Object.keys(e);return new Kp({type:"type",schema:e,*entries(n){if(Fp(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Lp(e)||`Expected an object, but received: ${Op(e)}`,coercer:e=>Lp(e)?{...e}:e})}function og(e){const t=e.map(e=>e.type).join(" | ");return new Kp({type:"union",schema:null,coercer(t,n){for(const r of e){const[e,o]=r.validate(t,{coerce:!0,mask:n.mask});if(!e)return o}return t},validator(n,r){const o=[];for(const t of e){const[...e]=qp(n,t,r),[i]=e;if(!i[0])return[];for(const[t]of e)t&&o.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Op(n)}`,...o]}})}function ig(){return jp("unknown",()=>!0)}function sg(e,t,n){return new Kp({...e,coercer:(r,o)=>Wp(r,t)?e.coercer(n(r,o),o):e.coercer(r,o)})}var ag,cg,ug,lg;var hg,dg=function(){if(lg)return ug;lg=1;const e=R.v4,t=function(){if(cg)return ag;cg=1;const e=R.v4;return ag=function(t,n,r,o){if("string"!=typeof t)throw new TypeError(t+" must be a string");const i="number"==typeof(o=o||{}).version?o.version:2;if(1!==i&&2!==i)throw new TypeError(i+" must be 1 or 2");const s={method:t};if(2===i&&(s.jsonrpc="2.0"),n){if("object"!=typeof n&&!Array.isArray(n))throw new TypeError(n+" must be an object, array or omitted");s.params=n}if(void 0===r){const t="function"==typeof o.generator?o.generator:function(){return e()};s.id=t(s,o)}else 2===i&&null===r?o.notificationIdNull&&(s.id=null):s.id=r;return s}}(),n=function(t,r){if(!(this instanceof n))return new n(t,r);r||(r={}),this.options={reviver:void 0!==r.reviver?r.reviver:null,replacer:void 0!==r.replacer?r.replacer:null,generator:void 0!==r.generator?r.generator:function(){return e()},version:void 0!==r.version?r.version:2,notificationIdNull:"boolean"==typeof r.notificationIdNull&&r.notificationIdNull},this.callServer=t};return ug=n,n.prototype.request=function(e,n,r,o){const i=this;let s=null;const a=Array.isArray(e)&&"function"==typeof n;if(1===this.options.version&&a)throw new TypeError("JSON-RPC 1.0 does not support batching");if(a||!a&&e&&"object"==typeof e&&"function"==typeof n)o=n,s=e;else{"function"==typeof r&&(o=r,r=void 0);const i="function"==typeof o;try{s=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(i)return o(e);throw e}if(!i)return s}let c;try{c=JSON.stringify(s,this.options.replacer)}catch(e){return o(e)}return this.callServer(c,function(e,t){i._parseResponse(e,t,o)}),s},n.prototype._parseResponse=function(e,t,n){if(e)return void n(e);if(!t)return n();let r;try{r=JSON.parse(t,this.options.reviver)}catch(e){return n(e)}if(3===n.length){if(Array.isArray(r)){const e=function(e){return void 0!==e.error},t=function(t){return!e(t)};return n(null,r.filter(e),r.filter(t))}return n(null,r.error,r.result)}n(null,r)},ug}(),fg=fi(dg),pg={};var gg,mg=(hg||(hg=1,function(e){const t=Ws(),n=Vs(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;function i(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let r=i(n);const o=r.write(e,t);return o!==n&&(r=r.slice(0,o)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);const o=function(e){if(s.isBuffer(e)){const t=0|d(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||V(e.length)?i(0):l(e):"Buffer"===e.type&&Array.isArray(e.data)?l(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),i(e<0?0:0|d(e))}function l(e){const t=e.length<0?0:0|d(e.length),n=i(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function d(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(o)return r?-1:W(e).length;t=(""+t).toLowerCase(),o=!0}}function p(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return B(this,t,n);case"utf8":case"utf-8":return A(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){let i,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let r=-1;for(i=n;i<a;i++)if(u(e,i)===u(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*s}else-1!==r&&(i-=i-r),r=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){let n=!0;for(let r=0;r<c;r++)if(u(e,i+r)!==u(t,r)){n=!1;break}if(n)return i}return-1}function w(e,t,n,r){n=Number(n)||0;const o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;const i=t.length;let s;for(r>i/2&&(r=i/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return j(W(t,e.length-n),e,n,r)}function k(e,t,n,r){return j(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return j(z(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){let n,r,o;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function A(e,t,n){n=Math.min(e.length,n);const r=[];let o=t;for(;o<n;){const t=e[o];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:n=e[o+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(i=c));break;case 3:n=e[o+1],r=e[o+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:n=e[o+1],r=e[o+2],a=e[o+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i),o+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=o,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},s.allocUnsafe=function(e){return u(e)},s.allocUnsafeSlow=function(e){return u(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let o=0;for(n=0;n<e.length;++n){let t=e[n];if(H(t,Uint8Array))o+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,o)):Uint8Array.prototype.set.call(r,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,o)}o+=t.length}return r},s.byteLength=f,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)g(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?A(this,0,e):p.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,o){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;let i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(i,a),u=this.slice(r,o),l=e.slice(t,n);for(let e=0;e<c;++e)if(u[e]!==l[e]){i=u[e],a=l[e];break}return i<a?-1:a<i?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let i=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function x(e,t,n){let r="";n=Math.min(e.length,n);for(let o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function B(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let o="";for(let r=t;r<n;++r)o+=X[e[r]];return o}function C(e,t,n){const r=e.slice(t,n);let o="";for(let e=0;e<r.length-1;e+=2)o+=String.fromCharCode(r[e]+256*r[e+1]);return o}function P(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function _(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function U(e,t,n,r,o){$(t,r,o,e,n,7);let i=Number(t&BigInt(4294967295));e[n+7]=i,i>>=8,e[n+6]=i,i>>=8,e[n+5]=i,i>>=8,e[n+4]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function D(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function F(e,t,r,o,i){return t=+t,r>>>=0,i||D(e,0,r,8),n.write(e,t,r,o,52,8),r+8}s.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e+--t],o=1;for(;t>0&&(o*=256);)r+=this[e+--t]*o;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(o)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(o)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=this[e],o=1,i=0;for(;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);let r=t,o=1,i=this[e+--r];for(;r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);let o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return _(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}let o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=Q(function(e,t=0){return _(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const o=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),o},s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{const i=s.isBuffer(e)?e:s.from(e,r),a=i.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=i[o%a]}return this};const L={};function O(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function M(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,o,i){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(r,o,i)}function q(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}O("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),O("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),O("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=M(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=M(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let o=null;const i=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function z(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){let o;for(o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function H(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(pg)),pg),yg={exports:{}};var wg=(gg||(gg=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function i(e,t,r,i,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,i||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,i=r.length,s=new Array(i);o<i;o++)s[o]=r[o].fn;return s},a.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,o,i,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,u,l=this._events[a],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,i),!0;case 6:return l.fn.call(l.context,t,r,o,i,s),!0}for(u=1,c=new Array(h-1);u<h;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var d,f=l.length;for(u=0;u<f;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),h){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l[u].fn.apply(l[u].context,c)}}return!0},a.prototype.on=function(e,t,n){return i(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,o){var i=n?n+e:e;if(!this._events[i])return this;if(!t)return s(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||s(this,i);else{for(var c=0,u=[],l=a.length;c<l;c++)(a[c].fn!==t||o&&!a[c].once||r&&a[c].context!==r)&&u.push(a[c]);u.length?this._events[i]=1===u.length?u[0]:u:s(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&s(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(yg)),yg.exports),bg=fi(wg),kg=class extends bg{socket;constructor(e,t){super(),this.socket=new window.WebSocket(e,t.protocols),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=e=>this.emit("message",e.data),this.socket.onerror=e=>this.emit("error",e),this.socket.onclose=e=>{this.emit("close",e.code,e.reason)}}send(e,t,n){const r=n||t;try{this.socket.send(e),r()}catch(e){r(e)}}close(e,t){this.socket.close(e,t)}addEventListener(e,t,n){this.socket.addEventListener(e,t,n)}};var vg=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},Eg=class extends bg{address;rpc_id;queue;options;autoconnect;ready;reconnect;reconnect_timer_id;reconnect_interval;max_reconnects;rest_options;current_reconnects;generate_request_id;socket;webSocketFactory;dataPack;constructor(e,t="ws://localhost:8080",{autoconnect:n=!0,reconnect:r=!0,reconnect_interval:o=1e3,max_reconnects:i=5,...s}={},a,c){super(),this.webSocketFactory=e,this.queue={},this.rpc_id=0,this.address=t,this.autoconnect=n,this.ready=!1,this.reconnect=r,this.reconnect_timer_id=void 0,this.reconnect_interval=o,this.max_reconnects=i,this.rest_options=s,this.current_reconnects=0,this.generate_request_id=a||(()=>"number"==typeof this.rpc_id?++this.rpc_id:Number(this.rpc_id)+1),this.dataPack=c||new vg,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(e,t,n,r){return r||"object"!=typeof n||(r=n,n=null),new Promise((o,i)=>{if(!this.ready)return i(new Error("socket not ready"));const s=this.generate_request_id(e,t),a={jsonrpc:"2.0",method:e,params:t||void 0,id:s};this.socket.send(this.dataPack.encode(a),r,e=>{if(e)return i(e);this.queue[s]={promise:[o,i]},n&&(this.queue[s].timeout=setTimeout(()=>{delete this.queue[s],i(new Error("reply timeout"))},n))})})}async login(e){const t=await this.call("rpc.login",e);if(!t)throw new Error("authentication failed");return t}async listMethods(){return await this.call("__listMethods")}notify(e,t){return new Promise((n,r)=>{if(!this.ready)return r(new Error("socket not ready"));const o={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(o),e=>{if(e)return r(e);n()})})}async subscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.on",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed subscribing to an event '"+e+"' with: "+t[e]);return t}async unsubscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.off",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed unsubscribing from an event with: "+t);return t}close(e,t){this.socket&&this.socket.close(e||1e3,t)}setAutoReconnect(e){this.reconnect=e}setReconnectInterval(e){this.reconnect_interval=e}setMaxReconnects(e){this.max_reconnects=e}getCurrentReconnects(){return this.current_reconnects}getMaxReconnects(){return this.max_reconnects}isReconnecting(){return void 0!==this.reconnect_timer_id}willReconnect(){return this.reconnect&&(0===this.max_reconnects||this.current_reconnects<this.max_reconnects)}_connect(e,t){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(e,t),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:e})=>{e instanceof ArrayBuffer&&(e=mg.Buffer.from(e).toString());try{e=this.dataPack.decode(e)}catch(e){return}if(e.notification&&this.listeners(e.notification).length){if(!Object.keys(e.params).length)return this.emit(e.notification);const t=[e.notification];if(e.params.constructor===Object)t.push(e.params);else for(let n=0;n<e.params.length;n++)t.push(e.params[n]);return Promise.resolve().then(()=>{this.emit.apply(this,t)})}if(!this.queue[e.id])return e.method?Promise.resolve().then(()=>{this.emit(e.method,e?.params)}):void 0;"error"in e=="result"in e&&this.queue[e.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[e.id].timeout&&clearTimeout(this.queue[e.id].timeout),e.error?this.queue[e.id].promise[1](e.error):this.queue[e.id].promise[0](e.result),delete this.queue[e.id]}),this.socket.addEventListener("error",e=>this.emit("error",e)),this.socket.addEventListener("close",({code:n,reason:r})=>{this.ready&&setTimeout(()=>this.emit("close",n,r),0),this.ready=!1,this.socket=void 0,1e3!==n&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||0===this.max_reconnects)?this.reconnect_timer_id=setTimeout(()=>this._connect(e,t),this.reconnect_interval):this.reconnect&&this.max_reconnects>0&&this.current_reconnects>=this.max_reconnects&&setTimeout(()=>this.emit("max_reconnects_reached",n,r),1))})}};class Sg extends wa{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ea(e);const n=ma(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<o.length;e++)o[e]^=54;this.iHash.update(o),this.oHash=e.create();for(let e=0;e<o.length;e++)o[e]^=106;this.oHash.update(o),na(o)}update(e){return ta(this),this.iHash.update(e),this}digestInto(e){ta(this),Js(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:i,outputLen:s}=this;return e.finished=r,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ag=(e,t,n)=>new Sg(e,t).update(n).digest();Ag.create=(e,t)=>new Sg(e,t);const Tg=(e,t)=>(e+(e>=0?t:-t)/_g)/t;function Ig(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function xg(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return tc(n.lowS,"lowS"),tc(n.prehash,"prehash"),void 0!==n.format&&Ig(n.format),n}class Bg extends Error{constructor(e=""){super(e)}}const Cg={Err:Bg,_tlv:{encode:(e,t)=>{const{Err:n}=Cg;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,o=rc(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?rc(o.length/2|128):"";return rc(e)+i+o+t},decode(e,t){const{Err:n}=Cg;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const o=t[r++];let i=0;if(!!(128&o)){const e=127&o;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const s=t.subarray(r,r+e);if(s.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===s[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of s)i=i<<8|e;if(r+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=o;const s=t.subarray(r,r+i);if(s.length!==i)throw new n("tlv.decode: wrong value length");return{v:s,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Cg;if(e<Pg)throw new t("integer: negative integers are not allowed");let n=rc(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Cg;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return ic(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Cg,o=uc("signature",e),{v:i,l:s}=r.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:u,l:l}=r.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(e){const{_tlv:t,_int:n}=Cg,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Pg=BigInt(0),Ng=BigInt(1),_g=BigInt(2),Ug=BigInt(3),Dg=BigInt(4);function Rg(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let o=uc("private key",t);try{r=e.fromBytes(o)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function Fg(e,t={}){const n=nu("weierstrass",e,t),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s,n:a}=i;gc(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Og(r,o);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,n){const{x:o,y:i}=t.toAffine(),s=r.toBytes(o);if(tc(n,"isCompressed"),n){l();return ya(Lg(!r.isOdd(i)),s)}return ya(Uint8Array.of(4),s,r.toBytes(i))},d=t.fromBytes||function(e){nc(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=u,o=e.length,i=e[0],s=e.subarray(1);if(o!==t||2!==i&&3!==i){if(o===n&&4===i){const e=r.BYTES,t=r.fromBytes(s.subarray(0,e)),n=r.fromBytes(s.subarray(e,2*e));if(!p(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${o}, expected compressed=${t} or uncompressed=${n}`)}{const e=r.fromBytes(s);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=f(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}l();return!(1&~i)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function f(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,i.a)),i.b)}function p(e,t){const n=r.sqr(t),o=f(e);return r.eql(n,o)}if(!p(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const g=r.mul(r.pow(i.a,Ug),Dg),m=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(g,m)))throw new Error("bad curve params: a or b");function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function w(e){if(!(e instanceof S))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,o],[i,s]]=t,a=Tg(s*e,n),c=Tg(-o*e,n);let u=e-a*r-c*i,l=-a*o-c*s;const h=u<Pg,d=l<Pg;h&&(u=-u),d&&(l=-l);const f=pc(Math.ceil(fc(n)/2))+Ng;if(u<Pg||u>=f||l<Pg||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:u,k2neg:d,k2:l}}(e,c.basises,o.ORDER)}const k=mc((e,t)=>{const{X:n,Y:o,Z:i}=e;if(r.eql(i,r.ONE))return{x:n,y:o};const s=e.is0();null==t&&(t=s?r.ONE:r.inv(i));const a=r.mul(n,t),c=r.mul(o,t),u=r.mul(i,t);if(s)return{x:r.ZERO,y:r.ZERO};if(!r.eql(u,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),v=mc(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:o}=e.toAffine();if(!r.isValid(n)||!r.isValid(o))throw new Error("bad point: x or y not field elements");if(!p(n,o))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(e,t,n,o,i){return n=new S(r.mul(n.X,e),n.Y,n.Z),t=Wc(o,t),n=Wc(i,n),t.add(n)}class S{constructor(e,t,n){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof S)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?S.ZERO:new S(t,n,r.ONE)}static fromBytes(e){const t=S.fromAffine(d(nc(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return S.fromBytes(uc("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return T.createCache(this,e),t||this.multiply(Ug),this}assertValidity(){v(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){w(e);const{X:t,Y:n,Z:o}=this,{X:i,Y:s,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(i,o)),u=r.eql(r.mul(n,a),r.mul(s,o));return c&&u}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,n=r.mul(t,Ug),{X:o,Y:s,Z:a}=this;let c=r.ZERO,u=r.ZERO,l=r.ZERO,h=r.mul(o,o),d=r.mul(s,s),f=r.mul(a,a),p=r.mul(o,s);return p=r.add(p,p),l=r.mul(o,a),l=r.add(l,l),c=r.mul(e,l),u=r.mul(n,f),u=r.add(c,u),c=r.sub(d,u),u=r.add(d,u),u=r.mul(c,u),c=r.mul(p,c),l=r.mul(n,l),f=r.mul(e,f),p=r.sub(h,f),p=r.mul(e,p),p=r.add(p,l),l=r.add(h,h),h=r.add(l,h),h=r.add(h,f),h=r.mul(h,p),u=r.add(u,h),f=r.mul(s,a),f=r.add(f,f),h=r.mul(f,p),c=r.sub(c,h),l=r.mul(f,d),l=r.add(l,l),l=r.add(l,l),new S(c,u,l)}add(e){w(e);const{X:t,Y:n,Z:o}=this,{X:s,Y:a,Z:c}=e;let u=r.ZERO,l=r.ZERO,h=r.ZERO;const d=i.a,f=r.mul(i.b,Ug);let p=r.mul(t,s),g=r.mul(n,a),m=r.mul(o,c),y=r.add(t,n),b=r.add(s,a);y=r.mul(y,b),b=r.add(p,g),y=r.sub(y,b),b=r.add(t,o);let k=r.add(s,c);return b=r.mul(b,k),k=r.add(p,m),b=r.sub(b,k),k=r.add(n,o),u=r.add(a,c),k=r.mul(k,u),u=r.add(g,m),k=r.sub(k,u),h=r.mul(d,b),u=r.mul(f,m),h=r.add(u,h),u=r.sub(g,h),h=r.add(g,h),l=r.mul(u,h),g=r.add(p,p),g=r.add(g,p),m=r.mul(d,m),b=r.mul(f,b),g=r.add(g,m),m=r.sub(p,m),m=r.mul(d,m),b=r.add(b,m),p=r.mul(g,b),l=r.add(l,p),p=r.mul(k,b),u=r.mul(y,u),u=r.sub(u,p),p=r.mul(y,g),h=r.mul(k,h),h=r.add(h,p),new S(u,l,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(S.ZERO)}multiply(e){const{endo:n}=t;if(!o.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,i;const s=e=>T.cached(this,e,e=>zc(S,e));if(n){const{k1neg:t,k1:o,k2neg:a,k2:c}=b(e),{p:u,f:l}=s(o),{p:h,f:d}=s(c);i=l.add(d),r=E(n.beta,u,h,t,a)}else{const{p:t,f:n}=s(e);r=t,i=n}return zc(S,[r,i])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!o.isValid(e))throw new Error("invalid scalar: out of range");if(e===Pg||r.is0())return S.ZERO;if(e===Ng)return r;if(T.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:o,k2neg:i,k2:s}=b(e),{p1:a,p2:c}=function(e,t,n,r){let o=t,i=e.ZERO,s=e.ZERO;for(;n>Kc||r>Kc;)n&Gc&&(i=i.add(o)),r&Gc&&(s=s.add(o)),o=o.double(),n>>=Gc,r>>=Gc;return{p1:i,p2:s}}(S,r,o,s);return E(n.beta,a,c,t,i)}return T.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){const r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return k(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===Ng||(e?e(S,this):T.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===Ng?this:e?e(S,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return tc(e,"isCompressed"),this.assertValidity(),h(S,this,e)}toHex(e=!0){return aa(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return zc(S,e)}static msm(e,t){return eu(S,o,e,t)}static fromPrivateKey(e){return S.BASE.multiply(Rg(o,e))}}S.BASE=new S(i.Gx,i.Gy,r.ONE),S.ZERO=new S(r.ZERO,r.ONE,r.ZERO),S.Fp=r,S.Fn=o;const A=o.BITS,T=new Jc(S,t.endo?Math.ceil(A/2):A);return S.BASE.precompute(8),S}function Lg(e){return Uint8Array.of(e?2:3)}function Og(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Mg(e,t={}){const{Fn:n}=e,r=t.randomBytes||ka,o=Object.assign(Og(e.Fp,n),{seed:qc(n.ORDER)});function i(e){try{return!!Rg(n,e)}catch(e){return!1}}function s(e=r(o.seed)){return function(e,t,n=!1){const r=e.length,o=$c(t),i=qc(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const s=xc(n?sc(e):ic(e),t-wc)+wc;return n?cc(s,o):ac(s,o)}(nc(e,o.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(Rg(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:i,publicKeyUncompressed:s}=o;if(n.allowedLengths||r===i)return;const a=uc("key",t).length;return a===i||a===s}const u={isValidSecretKey:i,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:i}=o;try{const o=t.length;return(!0!==n||o===r)&&((!1!==n||o===i)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:s,isValidPrivateKey:i,randomPrivateKey:s,normPrivateKeyToScalar:e=>Rg(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,o=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(r))throw new Error("second arg must be public key");const i=Rg(n,t);return e.fromHex(r).multiply(i).toBytes(o)},keygen:function(e){const t=s(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:u,lengths:o})}function $g(e,t,n={}){ea(t),gc(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||ka,o=n.hmac||((e,...n)=>Ag(t,e,ya(...n))),{Fp:i,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,lengths:f}=Mg(e,n),p={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},g="compact";function m(e){return e>a>>Ng}function y(e,t){if(!s.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class w{constructor(e,t,n){this.r=y("r",e),this.s=y("s",t),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=g){let n;if(function(e,t){Ig(t);const n=f.signature;nc(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=Cg.toSig(nc(e));return new w(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=s.BYTES,o=e.subarray(0,r),i=e.subarray(r,2*r);return new w(s.fromBytes(o),s.fromBytes(i),n)}static fromHex(e,t){return this.fromBytes(ga(e),t)}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const n=i.ORDER,{r:r,s:o,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*_g<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const u=2===c||3===c?r+a:r;if(!i.isValid(u))throw new Error("recovery id 2 or 3 invalid");const l=i.toBytes(u),h=e.fromBytes(ya(Lg(!(1&c)),l)),d=s.inv(u),f=k(uc("msgHash",t)),p=s.create(-f*d),g=s.create(o*d),m=e.BASE.multiplyUnsafe(p).add(h.multiplyUnsafe(g));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=g){if(Ig(e),"der"===e)return ga(Cg.hexFromSig(this));const t=s.toBytes(this.r),n=s.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return ya(Uint8Array.of(this.recovery),t,n)}return ya(t,n)}toHex(e){return aa(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(uc("sig",e),"compact")}static fromDER(e){return w.fromBytes(uc("sig",e),"der")}normalizeS(){return this.hasHighS()?new w(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return aa(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return aa(this.toBytes("compact"))}}const b=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=ic(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},k=n.bits2int_modN||function(e){return s.create(b(e))},v=pc(c);function E(e){return dc("num < 2^"+c,e,Pg,v),s.toBytes(e)}function S(e,n){return nc(e,void 0,"message"),n?nc(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,lengths:f,Point:e,sign:function(n,i,a={}){n=uc("message",n);const{seed:c,k2sig:u}=function(t,n,o){if(["recovered","canonical"].some(e=>e in o))throw new Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=xg(o,p);t=S(t,a);const u=k(t),l=Rg(s,n),h=[E(l),E(u)];if(null!=c&&!1!==c){const e=!0===c?r(f.secretKey):c;h.push(uc("extraEntropy",e))}const d=ya(...h),g=u;return{seed:d,k2sig:function(t){const n=b(t);if(!s.isValidNot0(n))return;const r=s.inv(n),o=e.BASE.multiply(n).toAffine(),a=s.create(o.x);if(a===Pg)return;const c=s.create(r*s.create(g+a*l));if(c===Pg)return;let u=(o.x===a?0:2)|Number(o.y&Ng),h=c;return i&&m(c)&&(h=s.neg(c),u^=1),new w(a,h,u)}}}(n,i,a);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),o=e=>Uint8Array.of(e);let i=r(e),s=r(e),a=0;const c=()=>{i.fill(1),s.fill(0),a=0},u=(...e)=>n(s,i,...e),l=(e=r(0))=>{s=u(o(0),e),i=u(),0!==e.length&&(s=u(o(1),e),i=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=u();const t=i.slice();n.push(t),e+=i.length}return ya(...n)};return(e,t)=>{let n;for(c(),l(e);!(n=t(h()));)l();return c(),n}}(t.outputLen,s.BYTES,o)(c,u)},verify:function(t,n,r,o={}){const{lowS:i,prehash:a,format:c}=xg(o,p);if(r=uc("publicKey",r),n=S(uc("message",n),a),"strict"in o)throw new Error("options.strict was renamed to lowS");const u=void 0===c?function(e){let t;const n="string"==typeof e||Zs(e),r=!n&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!n&&!r)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(r)t=new w(e.r,e.s);else if(n){try{t=w.fromBytes(uc("sig",e),"der")}catch(e){if(!(e instanceof Cg.Err))throw e}if(!t)try{t=w.fromBytes(uc("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):w.fromBytes(uc("sig",t),c);if(!1===u)return!1;try{const t=e.fromBytes(r);if(i&&u.hasHighS())return!1;const{r:o,s:a}=u,c=k(n),l=s.inv(a),h=s.create(c*l),d=s.create(o*l),f=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(d));if(f.is0())return!1;return s.create(f.x)===o}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=xg(n,p);return t=S(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function qg(e){const{CURVE:t,curveOpts:n}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:Mc(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function Kg(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=qg(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Oc(n.Fn.ORDER,n.Fn.BITS))})}(e,$g(Fg(t,n),r,o))}const Gg={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Wg={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},zg=BigInt(2);const jg=Mc(Gg.p,{sqrt:function(e){const t=Gg.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,l=u*u*e%t,h=Bc(l,n,t)*l%t,d=Bc(h,n,t)*l%t,f=Bc(d,zg,t)*u%t,p=Bc(f,o,t)*f%t,g=Bc(p,i,t)*p%t,m=Bc(g,a,t)*g%t,y=Bc(m,c,t)*m%t,w=Bc(y,a,t)*g%t,b=Bc(w,n,t)*l%t,k=Bc(b,s,t)*p%t,v=Bc(k,r,t)*u%t,E=Bc(v,zg,t);if(!jg.eql(jg.sqr(E),e))throw new Error("Cannot find square root");return E}}),Hg=function(e,t){const n=t=>Kg({...e,hash:t});return{...n(t),create:n}}({...Gg,Fp:jg,lowS:!0,endo:Wg},Za);ku.utils.randomPrivateKey;const Vg=()=>{const e=ku.utils.randomPrivateKey(),t=Xg(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},Xg=ku.getPublicKey;function Qg(e){try{return ku.ExtendedPoint.fromHex(e),!0}catch{return!1}}const Zg=ku.verify,Yg=e=>Xs.Buffer.isBuffer(e)?e:e instanceof Uint8Array?Xs.Buffer.from(e.buffer,e.byteOffset,e.byteLength):Xs.Buffer.from(e);class Jg{constructor(e){Object.assign(this,e)}encode(){return Xs.Buffer.from(sl.serialize(em,this))}static decode(e){return sl.deserialize(em,this,e)}static decodeUnchecked(e){return sl.deserializeUnchecked(em,this,e)}}const em=new Map;var tm;const nm=32;let rm=1;class om extends Jg{constructor(e){if(super({}),this._bn=void 0,function(e){return void 0!==e._bn}(e))this._bn=e._bn;else{if("string"==typeof e){const t=Ou.decode(e);if(t.length!=nm)throw new Error("Invalid public key input");this._bn=new _u(t)}else this._bn=new _u(e);if(this._bn.byteLength()>nm)throw new Error("Invalid public key input")}}static unique(){const e=new om(rm);return rm+=1,new om(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Ou.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(Xs.Buffer);if(e.length===nm)return e;const t=Xs.Buffer.alloc(32);return e.copy(t,32-e.length),t}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,n){const r=Xs.Buffer.concat([e.toBuffer(),Xs.Buffer.from(t),n.toBuffer()]),o=Mu(r);return new om(o)}static createProgramAddressSync(e,t){let n=Xs.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=Xs.Buffer.concat([n,Yg(e)])}),n=Xs.Buffer.concat([n,t.toBuffer(),Xs.Buffer.from("ProgramDerivedAddress")]);const r=Mu(n);if(Qg(r))throw new Error("Invalid seeds, address must fall off the curve");return new om(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{const o=e.concat(Xs.Buffer.from([r]));n=this.createProgramAddressSync(o,t)}catch(e){if(e instanceof TypeError)throw e;r--;continue}return[n,r]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){return Qg(new om(e).toBytes())}}tm=om,om.default=new tm("11111111111111111111111111111111"),em.set(om,{kind:"struct",fields:[["_bn","u256"]]}),new om("BPFLoader1111111111111111111111111111111111");const im=1232;class sm extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(sm.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class am extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(am.prototype,"name",{value:"TransactionExpiredTimeoutError"});class cm extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(cm.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class um{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const t of this.keySegments()){if(e<t.length)return t[e];e-=t.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const t=new Map;this.keySegments().flat().forEach((e,n)=>{t.set(e.toBase58(),n)});const n=e=>{const n=t.get(e.toBase58());if(void 0===n)throw new Error("Encountered an unknown instruction account key during compilation");return n};return e.map(e=>({programIdIndex:n(e.programId),accountKeyIndexes:e.keys.map(e=>n(e.pubkey)),data:e.data}))}}const lm=(e="publicKey")=>ll.blob(32,e),hm=(e="string")=>{const t=ll.struct([ll.u32("length"),ll.u32("lengthPadding"),ll.blob(ll.offset(ll.u32(),-8),"chars")],e),n=t.decode.bind(t),r=t.encode.bind(t),o=t;return o.decode=(e,t)=>n(e,t).chars.toString(),o.encode=(e,t,n)=>{const o={chars:Xs.Buffer.from(e,"utf8")};return r(o,t,n)},o.alloc=e=>ll.u32().span+ll.u32().span+Xs.Buffer.from(e,"utf8").length,o};function dm(e,t){const n=e=>{if(e.span>=0)return e.span;if("function"==typeof e.alloc)return e.alloc(t[e.property]);if("count"in e&&"elementLayout"in e){const r=t[e.property];if(Array.isArray(r))return r.length*n(e.elementLayout)}else if("fields"in e)return dm({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function fm(e){let t=0,n=0;for(;;){let r=e.shift();if(t|=(127&r)<<7*n,n+=1,!(128&r))break}return t}function pm(e,t){let n=t;for(;;){let t=127&n;if(n>>=7,0==n){e.push(t);break}t|=128,e.push(t)}}function gm(e,t){if(!e)throw new Error(t||"Assertion failed")}class mm{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const n=new Map,r=e=>{const t=e.toBase58();let r=n.get(t);return void 0===r&&(r={isSigner:!1,isWritable:!1,isInvoked:!1},n.set(t,r)),r},o=r(t);o.isSigner=!0,o.isWritable=!0;for(const t of e){r(t.programId).isInvoked=!0;for(const e of t.keys){const t=r(e.pubkey);t.isSigner||=e.isSigner,t.isWritable||=e.isWritable}}return new mm(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];gm(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,e])=>e.isSigner&&e.isWritable),n=e.filter(([,e])=>e.isSigner&&!e.isWritable),r=e.filter(([,e])=>!e.isSigner&&e.isWritable),o=e.filter(([,e])=>!e.isSigner&&!e.isWritable),i={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:o.length};{gm(t.length>0,"Expected at least one writable signer key");const[e]=t[0];gm(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[i,[...t.map(([e])=>new om(e)),...n.map(([e])=>new om(e)),...r.map(([e])=>new om(e)),...o.map(([e])=>new om(e))]]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[r,o]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==r.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:r},{writable:n,readonly:o}]}drainKeysFoundInLookupTable(e,t){const n=new Array,r=new Array;for(const[o,i]of this.keyMetaMap.entries())if(t(i)){const t=new om(o),i=e.findIndex(e=>e.equals(t));i>=0&&(gm(i<256,"Max lookup table index exceeded"),n.push(i),r.push(t),this.keyMetaMap.delete(o))}return[n,r]}}const ym="Reached end of buffer unexpectedly";function wm(e){if(0===e.length)throw new Error(ym);return e.shift()}function bm(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(ym);return e.splice(...t)}class km{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(e=>new om(e)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(e=>this.indexToProgramIds.set(e.programIdIndex,this.accountKeys[e.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Ou.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new um(this.staticAccountKeys)}static compile(e){const t=mm.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),o=new um(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Ou.encode(e.data)}));return new km({header:n,accountKeys:r,recentBlockhash:e.recentBlockhash,instructions:o})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){return e-t<this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];pm(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(Ou.decode(e.data));let o=[];pm(o,t.length);let i=[];return pm(i,r.length),{programIdIndex:n,keyIndicesCount:Xs.Buffer.from(o),keyIndices:t,dataLength:Xs.Buffer.from(i),data:r}});let r=[];pm(r,n.length);let o=Xs.Buffer.alloc(im);Xs.Buffer.from(r).copy(o);let i=r.length;n.forEach(e=>{const t=ll.struct([ll.u8("programIdIndex"),ll.blob(e.keyIndicesCount.length,"keyIndicesCount"),ll.seq(ll.u8("keyIndex"),e.keyIndices.length,"keyIndices"),ll.blob(e.dataLength.length,"dataLength"),ll.seq(ll.u8("userdatum"),e.data.length,"data")]).encode(e,o,i);i+=t}),o=o.slice(0,i);const s=ll.struct([ll.blob(1,"numRequiredSignatures"),ll.blob(1,"numReadonlySignedAccounts"),ll.blob(1,"numReadonlyUnsignedAccounts"),ll.blob(t.length,"keyCount"),ll.seq(lm("key"),e,"keys"),lm("recentBlockhash")]),a={numRequiredSignatures:Xs.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:Xs.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:Xs.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:Xs.Buffer.from(t),keys:this.accountKeys.map(e=>Yg(e.toBytes())),recentBlockhash:Ou.decode(this.recentBlockhash)};let c=Xs.Buffer.alloc(2048);const u=s.encode(a,c);return o.copy(c,u),c.slice(0,u+o.length)}static from(e){let t=[...e];const n=wm(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=wm(t),o=wm(t),i=fm(t);let s=[];for(let e=0;e<i;e++){const e=bm(t,0,nm);s.push(new om(Xs.Buffer.from(e)))}const a=bm(t,0,nm),c=fm(t);let u=[];for(let e=0;e<c;e++){const e=wm(t),n=bm(t,0,fm(t)),r=bm(t,0,fm(t)),o=Ou.encode(Xs.Buffer.from(r));u.push({programIdIndex:e,accounts:n,data:o})}const l={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:o},recentBlockhash:Ou.encode(Xs.Buffer.from(a)),accountKeys:s,instructions:u};return new km(l)}}class vm{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.addressTableLookups=e.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let e=0;for(const t of this.addressTableLookups)e+=t.readonlyIndexes.length+t.writableIndexes.length;return e}getAccountKeys(e){let t;if(e&&"accountKeysFromLookups"in e&&e.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=e.accountKeysFromLookups.writable.length+e.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");t=e.accountKeysFromLookups}else if(e&&"addressLookupTableAccounts"in e&&e.addressLookupTableAccounts)t=this.resolveAddressTableLookups(e.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new um(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,n=this.staticAccountKeys.length;if(e>=n){return e-n<this.addressTableLookups.reduce((e,t)=>e+t.writableIndexes.length,0)}if(e>=this.header.numRequiredSignatures){return e-t<n-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}resolveAddressTableLookups(e){const t={writable:[],readonly:[]};for(const n of this.addressTableLookups){const r=e.find(e=>e.key.equals(n.accountKey));if(!r)throw new Error(`Failed to find address lookup table account for table key ${n.accountKey.toBase58()}`);for(const e of n.writableIndexes){if(!(e<r.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.writable.push(r.state.addresses[e])}for(const e of n.readonlyIndexes){if(!(e<r.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.readonly.push(r.state.addresses[e])}}return t}static compile(e){const t=mm.compile(e.instructions,e.payerKey),n=new Array,r={writable:new Array,readonly:new Array},o=e.addressLookupTableAccounts||[];for(const e of o){const o=t.extractTableLookup(e);if(void 0!==o){const[e,{writable:t,readonly:i}]=o;n.push(e),r.writable.push(...t),r.readonly.push(...i)}}const[i,s]=t.getMessageComponents(),a=new um(s,r).compileInstructions(e.instructions);return new vm({header:i,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();pm(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();pm(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),o=Array();pm(o,this.addressTableLookups.length);const i=ll.struct([ll.u8("prefix"),ll.struct([ll.u8("numRequiredSignatures"),ll.u8("numReadonlySignedAccounts"),ll.u8("numReadonlyUnsignedAccounts")],"header"),ll.blob(e.length,"staticAccountKeysLength"),ll.seq(lm(),this.staticAccountKeys.length,"staticAccountKeys"),lm("recentBlockhash"),ll.blob(n.length,"instructionsLength"),ll.blob(t.length,"serializedInstructions"),ll.blob(o.length,"addressTableLookupsLength"),ll.blob(r.length,"serializedAddressTableLookups")]),s=new Uint8Array(im),a=i.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Ou.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(o),serializedAddressTableLookups:r},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(im);for(const n of this.compiledInstructions){const r=Array();pm(r,n.accountKeyIndexes.length);const o=Array();pm(o,n.data.length);e+=ll.struct([ll.u8("programIdIndex"),ll.blob(r.length,"encodedAccountKeyIndexesLength"),ll.seq(ll.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),ll.blob(o.length,"encodedDataLength"),ll.blob(n.data.length,"data")]).encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(r),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(o),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(im);for(const n of this.addressTableLookups){const r=Array();pm(r,n.writableIndexes.length);const o=Array();pm(o,n.readonlyIndexes.length);e+=ll.struct([lm("accountKey"),ll.blob(r.length,"encodedWritableIndexesLength"),ll.seq(ll.u8(),n.writableIndexes.length,"writableIndexes"),ll.blob(o.length,"encodedReadonlyIndexesLength"),ll.seq(ll.u8(),n.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(r),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(o),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=wm(t),r=127&n;gm(n!==r,"Expected versioned message but received legacy message");gm(0===r,`Expected versioned message with version 0 but found version ${r}`);const o={numRequiredSignatures:wm(t),numReadonlySignedAccounts:wm(t),numReadonlyUnsignedAccounts:wm(t)},i=[],s=fm(t);for(let e=0;e<s;e++)i.push(new om(bm(t,0,nm)));const a=Ou.encode(bm(t,0,nm)),c=fm(t),u=[];for(let e=0;e<c;e++){const e=wm(t),n=bm(t,0,fm(t)),r=fm(t),o=new Uint8Array(bm(t,0,r));u.push({programIdIndex:e,accountKeyIndexes:n,data:o})}const l=fm(t),h=[];for(let e=0;e<l;e++){const e=new om(bm(t,0,nm)),n=bm(t,0,fm(t)),r=bm(t,0,fm(t));h.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new vm({header:o,staticAccountKeys:i,recentBlockhash:a,compiledInstructions:u,addressTableLookups:h})}}let Em=function(e){return e[e.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",e[e.PROCESSED=1]="PROCESSED",e[e.TIMED_OUT=2]="TIMED_OUT",e[e.NONCE_INVALID=3]="NONCE_INVALID",e}({});const Sm=Xs.Buffer.alloc(64).fill(0);class Am{constructor(e){this.keys=void 0,this.programId=void 0,this.data=Xs.Buffer.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:n})=>({pubkey:e.toJSON(),isSigner:t,isWritable:n})),programId:this.programId.toJSON(),data:[...this.data]}}}class Tm{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){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,e)if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){const{minContextSlot:t,nonceInfo:n}=e;this.minNonceContextSlot=t,this.nonceInfo=n}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:t,lastValidBlockHeight:n}=e;this.recentBlockhash=t,this.lastValidBlockHeight=n}else{const{recentBlockhash:t,nonceInfo:n}=e;n&&(this.nonceInfo=n),this.recentBlockhash=t}}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(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(0===e.length)throw new Error("No instructions");return e.forEach(e=>{"instructions"in e?this.instructions=this.instructions.concat(e.instructions):"data"in e&&"programId"in e&&"keys"in e?this.instructions.push(e):this.instructions.push(new Am(e))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t,n;if(this.nonceInfo?(e=this.nonceInfo.nonce,t=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");if(t.length,this.feePayer)n=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");n=this.signatures[0].publicKey}for(let e=0;e<t.length;e++)if(void 0===t[e].programId)throw new Error(`Transaction instruction index ${e} has undefined program id`);const r=[],o=[];t.forEach(e=>{e.keys.forEach(e=>{o.push({...e})});const t=e.programId.toString();r.includes(t)||r.push(t)}),r.forEach(e=>{o.push({pubkey:new om(e),isSigner:!1,isWritable:!1})});const i=[];o.forEach(e=>{const t=e.pubkey.toString(),n=i.findIndex(e=>e.pubkey.toString()===t);n>-1?(i[n].isWritable=i[n].isWritable||e.isWritable,i[n].isSigner=i[n].isSigner||e.isSigner):i.push(e)}),i.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const s=i.findIndex(e=>e.pubkey.equals(n));if(s>-1){const[e]=i.splice(s,1);e.isSigner=!0,e.isWritable=!0,i.unshift(e)}else i.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=i.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);i[t].isSigner||(i[t].isSigner=!0)}let a=0,c=0,u=0;const l=[],h=[];i.forEach(({pubkey:e,isSigner:t,isWritable:n})=>{t?(l.push(e.toString()),a+=1,n||(c+=1)):(h.push(e.toString()),n||(u+=1))});const d=l.concat(h),f=t.map(e=>{const{data:t,programId:n}=e;return{programIdIndex:d.indexOf(n.toString()),accounts:e.keys.map(e=>d.indexOf(e.pubkey.toString())),data:Ou.encode(t)}});return f.forEach(e=>{gm(e.programIdIndex>=0),e.accounts.forEach(e=>gm(e>=0))}),new km({header:{numRequiredSignatures:a,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:u},accountKeys:d,recentBlockhash:e,instructions:f})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);if(this.signatures.length===t.length){if(this.signatures.every((e,n)=>t[n].equals(e.publicKey)))return e}return this.signatures=t.map(e=>({signature:null,publicKey:e})),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(0===e.length)throw new Error("No signers");const t=new Set;this.signatures=e.filter(e=>{const n=e.toString();return!t.has(n)&&(t.add(n),!0)}).map(e=>({signature:null,publicKey:e}))}sign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}this.signatures=n.map(e=>({signature:null,publicKey:e.publicKey}));const r=this._compile();this._partialSign(r,...n)}partialSign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}const r=this._compile();this._partialSign(r,...n)}_partialSign(e,...t){const n=e.serialize();t.forEach(e=>{const t=((e,t)=>ku.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,Yg(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){gm(64===t.length);const n=this.signatures.findIndex(t=>e.equals(t.publicKey));if(n<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[n].signature=Xs.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:r,publicKey:o}of this.signatures)null===r?t&&(n.missing||=[]).push(o):Zg(r,e,o.toBytes())||(n.invalid||=[]).push(o);return n.invalid||n.missing?n:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:n}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),r=this.serializeMessage();if(n){const e=this._getMessageSignednessErrors(r,t);if(e){let t="Signature verification failed.";throw e.invalid&&(t+=`\nInvalid signature for public key${1===e.invalid.length?"":"(s)"} [\`${e.invalid.map(e=>e.toBase58()).join("`, `")}\`].`),e.missing&&(t+=`\nMissing signature for public key${1===e.missing.length?"":"(s)"} [\`${e.missing.map(e=>e.toBase58()).join("`, `")}\`].`),new Error(t)}}return this._serialize(r)}_serialize(e){const{signatures:t}=this,n=[];pm(n,t.length);const r=n.length+64*t.length+e.length,o=Xs.Buffer.alloc(r);return gm(t.length<256),Xs.Buffer.from(n).copy(o,0),t.forEach(({signature:e},t)=>{null!==e&&(gm(64===e.length,"signature has invalid length"),Xs.Buffer.from(e).copy(o,n.length+64*t))}),e.copy(o,n.length+64*t.length),gm(o.length<=im,`Transaction too large: ${o.length} > 1232`),o}get keys(){return gm(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return gm(1===this.instructions.length),this.instructions[0].programId}get data(){return gm(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=fm(t);let r=[];for(let e=0;e<n;e++){const e=bm(t,0,64);r.push(Ou.encode(Xs.Buffer.from(e)))}return Tm.populate(km.from(t),r)}static populate(e,t=[]){const n=new Tm;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const o={signature:t==Ou.encode(Sm)?null:Ou.decode(t),publicKey:e.accountKeys[r]};n.signatures.push(o)}),e.instructions.forEach(t=>{const r=t.accounts.map(t=>{const r=e.accountKeys[t];return{pubkey:r,isSigner:n.signatures.some(e=>e.publicKey.toString()===r.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});n.instructions.push(new Am({keys:r,programId:e.accountKeys[t.programIdIndex],data:Ou.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new om("SysvarC1ock11111111111111111111111111111111"),new om("SysvarEpochSchedu1e111111111111111111111111"),new om("Sysvar1nstructions1111111111111111111111111");const Im=new om("SysvarRecentB1ockHashes11111111111111111111"),xm=new om("SysvarRent111111111111111111111111111111111");new om("SysvarRewards111111111111111111111111111111"),new om("SysvarS1otHashes111111111111111111111111111"),new om("SysvarS1otHistory11111111111111111111111111"),new om("SysvarStakeHistory1111111111111111111111111");class Bm extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const o=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",i="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let s;switch(e){case"send":s=`Transaction ${t} resulted in an error. \n${n}. `+o+i;break;case"simulate":s=`Simulation failed. \nMessage: ${n}. \n`+o+i;break;default:s=`Unknown action '${e}'`}super(s),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=n,this.transactionLogs=r||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const e=this.transactionLogs;if(null==e||"object"!=typeof e||!("then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((t,n)=>{e.getTransaction(this.signature).then(e=>{if(e&&e.meta&&e.meta.logMessages){const n=e.meta.logMessages;this.transactionLogs=n,t(n)}else n(new Error("Log messages not found"))}).catch(n)})),await this.transactionLogs}}class Cm extends Error{constructor({code:e,message:t,data:n},r){super(null!=r?`${r}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=n,this.name="SolanaJSONRPCError"}}function Pm(e){return new Promise(t=>setTimeout(t,e))}function Nm(e,t){const n=e.layout.span>=0?e.layout.span:dm(e,t),r=Xs.Buffer.alloc(n),o=Object.assign({instruction:e.index},t);return e.layout.encode(o,r),r}const _m=ll.nu64("lamportsPerSignature"),Um=ll.struct([ll.u32("version"),ll.u32("state"),lm("authorizedPubkey"),lm("nonce"),ll.struct([_m],"feeCalculator")]),Dm=Um.span;class Rm{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){const t=Um.decode(Yg(e),0);return new Rm({authorizedPubkey:new om(t.authorizedPubkey),nonce:new om(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function Fm(e){const t=ll.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),o=t,i=Dp();return o.decode=(e,t)=>{const r=n(e,t);return i.decode(r)},o.encode=(e,t,n)=>{const o=i.encode(e);return r(o,t,n)},o}const Lm=Object.freeze({Create:{index:0,layout:ll.struct([ll.u32("instruction"),ll.ns64("lamports"),ll.ns64("space"),lm("programId")])},Assign:{index:1,layout:ll.struct([ll.u32("instruction"),lm("programId")])},Transfer:{index:2,layout:ll.struct([ll.u32("instruction"),Fm("lamports")])},CreateWithSeed:{index:3,layout:ll.struct([ll.u32("instruction"),lm("base"),hm("seed"),ll.ns64("lamports"),ll.ns64("space"),lm("programId")])},AdvanceNonceAccount:{index:4,layout:ll.struct([ll.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:ll.struct([ll.u32("instruction"),ll.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:ll.struct([ll.u32("instruction"),lm("authorized")])},AuthorizeNonceAccount:{index:7,layout:ll.struct([ll.u32("instruction"),lm("authorized")])},Allocate:{index:8,layout:ll.struct([ll.u32("instruction"),ll.ns64("space")])},AllocateWithSeed:{index:9,layout:ll.struct([ll.u32("instruction"),lm("base"),hm("seed"),ll.ns64("space"),lm("programId")])},AssignWithSeed:{index:10,layout:ll.struct([ll.u32("instruction"),lm("base"),hm("seed"),lm("programId")])},TransferWithSeed:{index:11,layout:ll.struct([ll.u32("instruction"),Fm("lamports"),hm("seed"),lm("programId")])},UpgradeNonceAccount:{index:12,layout:ll.struct([ll.u32("instruction")])}});class Om{constructor(){}static createAccount(e){const t=Nm(Lm.Create,{lamports:e.lamports,space:e.space,programId:Yg(e.programId.toBuffer())});return new Am({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:t})}static transfer(e){let t,n;if("basePubkey"in e){t=Nm(Lm.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:Yg(e.programId.toBuffer())}),n=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{t=Nm(Lm.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new Am({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=Nm(Lm.AssignWithSeed,{base:Yg(e.basePubkey.toBuffer()),seed:e.seed,programId:Yg(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Nm(Lm.Assign,{programId:Yg(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Am({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=Nm(Lm.CreateWithSeed,{base:Yg(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:Yg(e.programId.toBuffer())});let n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey.equals(e.fromPubkey)||n.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new Am({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new Tm;"basePubkey"in e&&"seed"in e?t.add(Om.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:Dm,programId:this.programId})):t.add(Om.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:Dm,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=Nm(Lm.InitializeNonceAccount,{authorized:Yg(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Im,isSigner:!1,isWritable:!1},{pubkey:xm,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new Am(n)}static nonceAdvance(e){const t=Nm(Lm.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Im,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new Am(n)}static nonceWithdraw(e){const t=Nm(Lm.WithdrawNonceAccount,{lamports:e.lamports});return new Am({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:Im,isSigner:!1,isWritable:!1},{pubkey:xm,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=Nm(Lm.AuthorizeNonceAccount,{authorized:Yg(e.newAuthorizedPubkey.toBuffer())});return new Am({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static allocate(e){let t,n;if("basePubkey"in e){t=Nm(Lm.AllocateWithSeed,{base:Yg(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:Yg(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Nm(Lm.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Am({keys:n,programId:this.programId,data:t})}}function Mm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $m,qm;function Km(){if(qm)return $m;qm=1;var e=Object.prototype.toString,t=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};function n(r,o){var i,s,a,c,u,l,h;if(!0===r)return"true";if(!1===r)return"false";switch(typeof r){case"object":if(null===r)return null;if(r.toJSON&&"function"==typeof r.toJSON)return n(r.toJSON(),o);if("[object Array]"===(h=e.call(r))){for(a="[",s=r.length-1,i=0;i<s;i++)a+=n(r[i],!0)+",";return s>-1&&(a+=n(r[i],!0)),a+"]"}if("[object Object]"===h){for(s=(c=t(r).sort()).length,a="",i=0;i<s;)void 0!==(l=n(r[u=c[i]],!1))&&(a&&(a+=","),a+=JSON.stringify(u)+":"+l),i++;return"{"+a+"}"}return JSON.stringify(r);case"function":case"undefined":return o?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return $m=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Om.programId=new om("11111111111111111111111111111111"),new om("BPFLoader2111111111111111111111111111111111");var Gm=Mm(Km());function Wm(e){let t=0;for(;e>1;)e/=2,t++;return t}class zm{constructor(e,t,n,r,o){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=n,this.firstNormalEpoch=r,this.firstNormalSlot=o}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=Wm(0===(t=e+32+1)?1:(t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,1+(t|=t>>32)))-Wm(32)-1;return[n,e-(this.getSlotsInEpoch(n)-32)]}{const t=e-this.firstNormalSlot,n=Math.floor(t/this.slotsPerEpoch);return[this.firstNormalEpoch+n,t%this.slotsPerEpoch]}var t}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?32*(Math.pow(2,e)-1):(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e<this.firstNormalEpoch?Math.pow(2,e+Wm(32)):this.slotsPerEpoch}}var jm=globalThis.fetch;class Hm extends Eg{constructor(e,t,n){super(e=>{const n=function(e,t){return new kg(e,t)}(e,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t});return this.underlyingSocket="socket"in n?n.socket:n,n},e,t,n),this.underlyingSocket=void 0}call(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}notify(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}}class Vm{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const t=function(e,t){let n;try{n=e.layout.decode(t)}catch(e){throw new Error("invalid instruction; "+e)}if(n.typeIndex!==e.index)throw new Error(`invalid account data; account type mismatch ${n.typeIndex} != ${e.index}`);return n}(Xm,e),n=e.length-56;gm(n>=0,"lookup table is invalid"),gm(n%32==0,"lookup table is invalid");const r=n/32,{addresses:o}=ll.struct([ll.seq(lm(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new om(t.authority[0]):void 0,addresses:o.map(e=>new om(e))}}}const Xm={index:1,layout:ll.struct([ll.u32("typeIndex"),Fm("deactivationSlot"),ll.nu64("lastExtendedSlot"),ll.u8("lastExtendedStartIndex"),ll.u8(),ll.seq(lm(),ll.offset(ll.u8(),-1),"authority")])},Qm=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const Zm=sg(Xp(om),tg(),e=>new om(e)),Ym=ng([tg(),Qp("base64")]),Jm=sg(Xp(Xs.Buffer),Ym,e=>Xs.Buffer.from(e[0],"base64"));function ey(e){let t,n;if("string"==typeof e)t=e;else if(e){const{commitment:r,...o}=e;t=r,n=o}return{commitment:t,config:n}}function ty(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function ny(e){return og([rg({jsonrpc:Qp("2.0"),id:tg(),result:e}),rg({jsonrpc:Qp("2.0"),id:tg(),error:rg({code:ig(),message:tg(),data:Jp(jp("any",()=>!0))})})])}const ry=ny(ig());function oy(e){return sg(ny(e),ry,t=>"error"in t?t:{...t,result:Gp(t.result,e)})}function iy(e){return oy(rg({context:rg({slot:Yp()}),value:e}))}function sy(e){return rg({context:rg({slot:Yp()}),value:e})}function ay(e,t){return 0===e?new vm({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new om(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Ou.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new km(t)}const cy=rg({foundation:Yp(),foundationTerm:Yp(),initial:Yp(),taper:Yp(),terminal:Yp()}),uy=oy(Hp(Zp(rg({epoch:Yp(),effectiveSlot:Yp(),amount:Yp(),postBalance:Yp(),commission:Jp(Zp(Yp()))})))),ly=Hp(rg({slot:Yp(),prioritizationFee:Yp()})),hy=rg({total:Yp(),validator:Yp(),foundation:Yp(),epoch:Yp()}),dy=rg({epoch:Yp(),slotIndex:Yp(),slotsInEpoch:Yp(),absoluteSlot:Yp(),blockHeight:Jp(Yp()),transactionCount:Jp(Yp())}),fy=rg({slotsPerEpoch:Yp(),leaderScheduleSlotOffset:Yp(),warmup:Vp(),firstNormalEpoch:Yp(),firstNormalSlot:Yp()}),py=eg(tg(),Hp(Yp())),gy=Zp(og([rg({}),tg()])),my=rg({err:gy}),yy=Qp("receivedSignature"),wy=rg({"solana-core":tg(),"feature-set":Jp(Yp())}),by=rg({program:tg(),programId:Zm,parsed:ig()}),ky=rg({programId:Zm,accounts:Hp(Zm),data:tg()}),vy=iy(rg({err:Zp(og([rg({}),tg()])),logs:Zp(Hp(tg())),accounts:Jp(Zp(Hp(Zp(rg({executable:Vp(),owner:tg(),lamports:Yp(),data:Hp(tg()),rentEpoch:Jp(Yp())}))))),unitsConsumed:Jp(Yp()),returnData:Jp(Zp(rg({programId:tg(),data:ng([tg(),Qp("base64")])}))),innerInstructions:Jp(Zp(Hp(rg({index:Yp(),instructions:Hp(og([by,ky]))}))))})),Ey=iy(rg({byIdentity:eg(tg(),Hp(Yp())),range:rg({firstSlot:Yp(),lastSlot:Yp()})}));const Sy=oy(cy),Ay=oy(hy),Ty=oy(ly),Iy=oy(dy),xy=oy(fy),By=oy(py),Cy=oy(Yp()),Py=iy(rg({total:Yp(),circulating:Yp(),nonCirculating:Yp(),nonCirculatingAccounts:Hp(Zm)})),Ny=rg({amount:tg(),uiAmount:Zp(Yp()),decimals:Yp(),uiAmountString:Jp(tg())}),_y=iy(Hp(rg({address:Zm,amount:tg(),uiAmount:Zp(Yp()),decimals:Yp(),uiAmountString:Jp(tg())}))),Uy=iy(Hp(rg({pubkey:Zm,account:rg({executable:Vp(),owner:Zm,lamports:Yp(),data:Jm,rentEpoch:Yp()})}))),Dy=rg({program:tg(),parsed:ig(),space:Yp()}),Ry=iy(Hp(rg({pubkey:Zm,account:rg({executable:Vp(),owner:Zm,lamports:Yp(),data:Dy,rentEpoch:Yp()})}))),Fy=iy(Hp(rg({lamports:Yp(),address:Zm}))),Ly=rg({executable:Vp(),owner:Zm,lamports:Yp(),data:Jm,rentEpoch:Yp()}),Oy=rg({pubkey:Zm,account:Ly}),My=sg(og([Xp(Xs.Buffer),Dy]),og([Ym,Dy]),e=>Array.isArray(e)?Gp(e,Jm):e),$y=rg({executable:Vp(),owner:Zm,lamports:Yp(),data:My,rentEpoch:Yp()}),qy=rg({pubkey:Zm,account:$y}),Ky=rg({state:og([Qp("active"),Qp("inactive"),Qp("activating"),Qp("deactivating")]),active:Yp(),inactive:Yp()}),Gy=oy(Hp(rg({signature:tg(),slot:Yp(),err:gy,memo:Zp(tg()),blockTime:Jp(Zp(Yp()))}))),Wy=oy(Hp(rg({signature:tg(),slot:Yp(),err:gy,memo:Zp(tg()),blockTime:Jp(Zp(Yp()))}))),zy=rg({subscription:Yp(),result:sy(Ly)}),jy=rg({pubkey:Zm,account:Ly}),Hy=rg({subscription:Yp(),result:sy(jy)}),Vy=rg({parent:Yp(),slot:Yp(),root:Yp()}),Xy=rg({subscription:Yp(),result:Vy}),Qy=og([rg({type:og([Qp("firstShredReceived"),Qp("completed"),Qp("optimisticConfirmation"),Qp("root")]),slot:Yp(),timestamp:Yp()}),rg({type:Qp("createdBank"),parent:Yp(),slot:Yp(),timestamp:Yp()}),rg({type:Qp("frozen"),slot:Yp(),timestamp:Yp(),stats:rg({numTransactionEntries:Yp(),numSuccessfulTransactions:Yp(),numFailedTransactions:Yp(),maxTransactionsPerEntry:Yp()})}),rg({type:Qp("dead"),slot:Yp(),timestamp:Yp(),err:tg()})]),Zy=rg({subscription:Yp(),result:Qy}),Yy=rg({subscription:Yp(),result:sy(og([my,yy]))}),Jy=rg({subscription:Yp(),result:Yp()}),ew=rg({pubkey:tg(),gossip:Zp(tg()),tpu:Zp(tg()),rpc:Zp(tg()),version:Zp(tg())}),tw=rg({votePubkey:tg(),nodePubkey:tg(),activatedStake:Yp(),epochVoteAccount:Vp(),epochCredits:Hp(ng([Yp(),Yp(),Yp()])),commission:Yp(),lastVote:Yp(),rootSlot:Zp(Yp())}),nw=oy(rg({current:Hp(tw),delinquent:Hp(tw)})),rw=og([Qp("processed"),Qp("confirmed"),Qp("finalized")]),ow=rg({slot:Yp(),confirmations:Zp(Yp()),err:gy,confirmationStatus:Jp(rw)}),iw=iy(Hp(Zp(ow))),sw=oy(Yp()),aw=rg({accountKey:Zm,writableIndexes:Hp(Yp()),readonlyIndexes:Hp(Yp())}),cw=rg({signatures:Hp(tg()),message:rg({accountKeys:Hp(tg()),header:rg({numRequiredSignatures:Yp(),numReadonlySignedAccounts:Yp(),numReadonlyUnsignedAccounts:Yp()}),instructions:Hp(rg({accounts:Hp(Yp()),data:tg(),programIdIndex:Yp()})),recentBlockhash:tg(),addressTableLookups:Jp(Hp(aw))})}),uw=rg({pubkey:Zm,signer:Vp(),writable:Vp(),source:Jp(og([Qp("transaction"),Qp("lookupTable")]))}),lw=rg({accountKeys:Hp(uw),signatures:Hp(tg())}),hw=rg({parsed:ig(),program:tg(),programId:Zm}),dw=rg({accounts:Hp(Zm),data:tg(),programId:Zm}),fw=sg(og([dw,hw]),og([rg({parsed:ig(),program:tg(),programId:tg()}),rg({accounts:Hp(tg()),data:tg(),programId:tg()})]),e=>Gp(e,"accounts"in e?dw:hw)),pw=rg({signatures:Hp(tg()),message:rg({accountKeys:Hp(uw),instructions:Hp(fw),recentBlockhash:tg(),addressTableLookups:Jp(Zp(Hp(aw)))})}),gw=rg({accountIndex:Yp(),mint:tg(),owner:Jp(tg()),programId:Jp(tg()),uiTokenAmount:Ny}),mw=rg({writable:Hp(Zm),readonly:Hp(Zm)}),yw=rg({err:gy,fee:Yp(),innerInstructions:Jp(Zp(Hp(rg({index:Yp(),instructions:Hp(rg({accounts:Hp(Yp()),data:tg(),programIdIndex:Yp()}))})))),preBalances:Hp(Yp()),postBalances:Hp(Yp()),logMessages:Jp(Zp(Hp(tg()))),preTokenBalances:Jp(Zp(Hp(gw))),postTokenBalances:Jp(Zp(Hp(gw))),loadedAddresses:Jp(mw),computeUnitsConsumed:Jp(Yp()),costUnits:Jp(Yp())}),ww=rg({err:gy,fee:Yp(),innerInstructions:Jp(Zp(Hp(rg({index:Yp(),instructions:Hp(fw)})))),preBalances:Hp(Yp()),postBalances:Hp(Yp()),logMessages:Jp(Zp(Hp(tg()))),preTokenBalances:Jp(Zp(Hp(gw))),postTokenBalances:Jp(Zp(Hp(gw))),loadedAddresses:Jp(mw),computeUnitsConsumed:Jp(Yp()),costUnits:Jp(Yp())}),bw=og([Qp(0),Qp("legacy")]),kw=rg({pubkey:tg(),lamports:Yp(),postBalance:Zp(Yp()),rewardType:Zp(tg()),commission:Jp(Zp(Yp()))}),vw=oy(Zp(rg({blockhash:tg(),previousBlockhash:tg(),parentSlot:Yp(),transactions:Hp(rg({transaction:cw,meta:Zp(yw),version:Jp(bw)})),rewards:Jp(Hp(kw)),blockTime:Zp(Yp()),blockHeight:Zp(Yp())}))),Ew=oy(Zp(rg({blockhash:tg(),previousBlockhash:tg(),parentSlot:Yp(),rewards:Jp(Hp(kw)),blockTime:Zp(Yp()),blockHeight:Zp(Yp())}))),Sw=oy(Zp(rg({blockhash:tg(),previousBlockhash:tg(),parentSlot:Yp(),transactions:Hp(rg({transaction:lw,meta:Zp(yw),version:Jp(bw)})),rewards:Jp(Hp(kw)),blockTime:Zp(Yp()),blockHeight:Zp(Yp())}))),Aw=oy(Zp(rg({blockhash:tg(),previousBlockhash:tg(),parentSlot:Yp(),transactions:Hp(rg({transaction:pw,meta:Zp(ww),version:Jp(bw)})),rewards:Jp(Hp(kw)),blockTime:Zp(Yp()),blockHeight:Zp(Yp())}))),Tw=oy(Zp(rg({blockhash:tg(),previousBlockhash:tg(),parentSlot:Yp(),transactions:Hp(rg({transaction:lw,meta:Zp(ww),version:Jp(bw)})),rewards:Jp(Hp(kw)),blockTime:Zp(Yp()),blockHeight:Zp(Yp())}))),Iw=oy(Zp(rg({blockhash:tg(),previousBlockhash:tg(),parentSlot:Yp(),rewards:Jp(Hp(kw)),blockTime:Zp(Yp()),blockHeight:Zp(Yp())}))),xw=oy(Zp(rg({blockhash:tg(),previousBlockhash:tg(),parentSlot:Yp(),transactions:Hp(rg({transaction:cw,meta:Zp(yw)})),rewards:Jp(Hp(kw)),blockTime:Zp(Yp())}))),Bw=oy(Zp(rg({blockhash:tg(),previousBlockhash:tg(),parentSlot:Yp(),signatures:Hp(tg()),blockTime:Zp(Yp())}))),Cw=oy(Zp(rg({slot:Yp(),meta:Zp(yw),blockTime:Jp(Zp(Yp())),transaction:cw,version:Jp(bw)}))),Pw=oy(Zp(rg({slot:Yp(),transaction:pw,meta:Zp(ww),blockTime:Jp(Zp(Yp())),version:Jp(bw)}))),Nw=iy(rg({blockhash:tg(),lastValidBlockHeight:Yp()})),_w=iy(Vp()),Uw=oy(Hp(rg({slot:Yp(),numTransactions:Yp(),numSlots:Yp(),samplePeriodSecs:Yp()}))),Dw=iy(Zp(rg({feeCalculator:rg({lamportsPerSignature:Yp()})}))),Rw=oy(tg()),Fw=oy(tg()),Lw=rg({err:gy,logs:Hp(tg()),signature:tg()}),Ow=rg({result:sy(Lw),subscription:Yp()}),Mw={"solana-client":"js/1.0.0-maintenance"};class $w{constructor(e,t){let n,r,o,i,s,a;var c;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const e={};return async t=>{const{commitment:n,config:r}=ey(t),o=this._buildArgs([],n,void 0,r),i=Gm(o);return e[i]=e[i]??(async()=>{try{const e=Gp(await this._rpcRequest("getBlockHeight",o),oy(Yp()));if("error"in e)throw new Cm(e.error,"failed to get block height information");return e.result}finally{delete e[i]}})(),await e[i]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,r=t.httpHeaders,o=t.fetch,i=t.fetchMiddleware,s=t.disableRetryOnRateLimit,a=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=n||function(e){const t=e.match(Qm);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,o,i]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==o?null:parseInt(o.slice(1),10);return`${s}//${r}${null==a?"":`:${a+1}`}${i}`}(e),this._rpcClient=function(e,t,n,r,o){const i=n||jm;let s;return r&&(s=async(e,t)=>{const n=await new Promise((n,o)=>{try{r(e,t,(e,t)=>n([e,t]))}catch(e){o(e)}});return await i(...n)}),new fg(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},Mw)};try{let t,n=5,c=500;for(;t=s?await s(e,a):await i(e,a),429===t.status&&!0!==o&&(n-=1,0!==n);)await Pm(c),c*=2;const u=await t.text();t.ok?r(null,u):r(new Error(`${t.status} ${t.statusText}: ${u}`))}catch(e){e instanceof Error&&r(e)}},{})}(e,r,o,i,s),this._rpcRequest=(c=this._rpcClient,(e,t)=>new Promise((n,r)=>{c.request(e,t,(e,t)=>{e?r(e):n(t)})})),this._rpcBatchRequest=function(e){return t=>new Promise((n,r)=>{0===t.length&&n([]);const o=t.map(t=>e.request(t.methodName,t.args));e.request(o,(e,t)=>{e?r(e):n(t)})})}(this._rpcClient),this._rpcWebSocket=new Hm(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){const{commitment:n,config:r}=ey(t),o=this._buildArgs([e.toBase58()],n,void 0,r),i=Gp(await this._rpcRequest("getBalance",o),iy(Yp()));if("error"in i)throw new Cm(i.error,`failed to get balance for ${e.toBase58()}`);return i.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=Gp(await this._rpcRequest("getBlockTime",[e]),oy(Zp(Yp())));if("error"in t)throw new Cm(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=Gp(await this._rpcRequest("minimumLedgerSlot",[]),oy(Yp()));if("error"in e)throw new Cm(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=Gp(await this._rpcRequest("getFirstAvailableBlock",[]),Cy);if("error"in e)throw new Cm(e.error,"failed to get first available block");return e.result}async getSupply(e){let t={};t="string"==typeof e?{commitment:e}:e?{...e,commitment:e&&e.commitment||this.commitment}:{commitment:this.commitment};const n=Gp(await this._rpcRequest("getSupply",[t]),Py);if("error"in n)throw new Cm(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=Gp(await this._rpcRequest("getTokenSupply",n),iy(Ny));if("error"in r)throw new Cm(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=Gp(await this._rpcRequest("getTokenAccountBalance",n),iy(Ny));if("error"in r)throw new Cm(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:o}=ey(n);let i=[e.toBase58()];"mint"in t?i.push({mint:t.mint.toBase58()}):i.push({programId:t.programId.toBase58()});const s=this._buildArgs(i,r,"base64",o),a=Gp(await this._rpcRequest("getTokenAccountsByOwner",s),Uy);if("error"in a)throw new Cm(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getParsedTokenAccountsByOwner(e,t,n){let r=[e.toBase58()];"mint"in t?r.push({mint:t.mint.toBase58()}):r.push({programId:t.programId.toBase58()});const o=this._buildArgs(r,n,"jsonParsed"),i=Gp(await this._rpcRequest("getTokenAccountsByOwner",o),Ry);if("error"in i)throw new Cm(i.error,`failed to get token accounts owned by account ${e.toBase58()}`);return i.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=Gp(await this._rpcRequest("getLargestAccounts",n),Fy);if("error"in r)throw new Cm(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=Gp(await this._rpcRequest("getTokenLargestAccounts",n),_y);if("error"in r)throw new Cm(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=ey(t),o=this._buildArgs([e.toBase58()],n,"base64",r),i=Gp(await this._rpcRequest("getAccountInfo",o),iy(Zp(Ly)));if("error"in i)throw new Cm(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=ey(t),o=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=Gp(await this._rpcRequest("getAccountInfo",o),iy(Zp($y)));if("error"in i)throw new Cm(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(t){throw new Error("failed to get info about account "+e.toBase58()+": "+t)}}async getMultipleParsedAccounts(e,t){const{commitment:n,config:r}=ey(t),o=e.map(e=>e.toBase58()),i=this._buildArgs([o],n,"jsonParsed",r),s=Gp(await this._rpcRequest("getMultipleAccounts",i),iy(Hp(Zp($y))));if("error"in s)throw new Cm(s.error,`failed to get info for accounts ${o}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=ey(t),o=e.map(e=>e.toBase58()),i=this._buildArgs([o],n,"base64",r),s=Gp(await this._rpcRequest("getMultipleAccounts",i),iy(Hp(Zp(Ly))));if("error"in s)throw new Cm(s.error,`failed to get info for accounts ${o}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:o}=ey(t),i=this._buildArgs([e.toBase58()],r,void 0,{...o,epoch:null!=n?n:o?.epoch}),s=Gp(await this._rpcRequest("getStakeActivation",i),oy(Ky));if("error"in s)throw new Cm(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=ey(t),{encoding:o,...i}=r||{},s=this._buildArgs([e.toBase58()],n,o||"base64",{...i,...i.filters?{filters:ty(i.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=Hp(Oy),u=!0===i.withContext?Gp(a,iy(c)):Gp(a,oy(c));if("error"in u)throw new Cm(u.error,`failed to get accounts owned by program ${e.toBase58()}`);return u.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=ey(t),o=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=Gp(await this._rpcRequest("getProgramAccounts",o),oy(Hp(qy)));if("error"in i)throw new Cm(i.error,`failed to get accounts owned by program ${e.toBase58()}`);return i.result}async confirmTransaction(e,t){let n,r;if("string"==typeof e)n=e;else{const t=e;if(t.abortSignal?.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{r=Ou.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return gm(64===r.length,"signature has invalid length"),"string"==typeof e?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,n)=>{null!=e&&(e.aborted?n(e.reason):e.addEventListener("abort",()=>{n(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let n,r,o=!1;return{abortConfirmation:()=>{r&&(r(),r=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:new Promise((i,s)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};i({__type:Em.PROCESSED,response:r})},e);const a=new Promise(e=>{null==n?e():r=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,o)return;const n=await this.getSignatureStatus(t);if(o)return;if(null==n)return;const{context:r,value:c}=n;if(null!=c)if(c?.err)s(c.err);else{switch(e){case"confirmed":case"single":case"singleGossip":if("processed"===c.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===c.confirmationStatus||"confirmed"===c.confirmationStatus)return}o=!0,i({__type:Em.PROCESSED,response:{context:r,value:c}})}})()}catch(e){s(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let o=!1;const i=new Promise(t=>{const r=async()=>{try{return await this.getBlockHeight(e)}catch(e){return-1}};(async()=>{let e=await r();if(!o){for(;e<=n;){if(await Pm(1e3),o)return;if(e=await r(),o)return}t({__type:Em.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:r}),c=this.getCancellationPromise(t);let u;try{const e=await Promise.race([c,a,i]);if(e.__type!==Em.PROCESSED)throw new sm(r);u=e.response}finally{o=!0,s()}return u}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:o,signature:i}}){let s=!1;const a=new Promise(t=>{let i=o,a=null;const c=async()=>{try{const{context:t,value:o}=await this.getNonceAndContext(r,{commitment:e,minContextSlot:n});return a=t.slot,o?.nonce}catch(e){return i}};(async()=>{if(i=await c(),!s)for(;;){if(o!==i)return void t({__type:Em.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Pm(2e3),s)return;if(i=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:u}=this.getTransactionConfirmationPromise({commitment:e,signature:i}),l=this.getCancellationPromise(t);let h;try{const t=await Promise.race([l,u,a]);if(t.__type===Em.PROCESSED)h=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(i);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await Pm(400)}if(!r?.value)throw new cm(i);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new cm(i);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new cm(i);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new cm(i)}h={context:r.context,value:{err:r.value.err}}}}}finally{s=!0,c()}return h}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let n;const r=new Promise(t=>{let r=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":r=this._confirmTransactionInitialTimeout||3e4}n=setTimeout(()=>t({__type:Em.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:o,confirmationPromise:i}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([i,r]);if(e.__type!==Em.PROCESSED)throw new am(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(n),o()}return s}async getClusterNodes(){const e=Gp(await this._rpcRequest("getClusterNodes",[]),oy(Hp(ew)));if("error"in e)throw new Cm(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=Gp(await this._rpcRequest("getVoteAccounts",t),nw);if("error"in n)throw new Cm(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=ey(e),r=this._buildArgs([],t,void 0,n),o=Gp(await this._rpcRequest("getSlot",r),oy(Yp()));if("error"in o)throw new Cm(o.error,"failed to get slot");return o.result}async getSlotLeader(e){const{commitment:t,config:n}=ey(e),r=this._buildArgs([],t,void 0,n),o=Gp(await this._rpcRequest("getSlotLeader",r),oy(tg()));if("error"in o)throw new Cm(o.error,"failed to get slot leader");return o.result}async getSlotLeaders(e,t){const n=[e,t],r=Gp(await this._rpcRequest("getSlotLeaders",n),oy(Hp(Zm)));if("error"in r)throw new Cm(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);gm(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=Gp(await this._rpcRequest("getSignatureStatuses",n),iw);if("error"in r)throw new Cm(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=ey(e),r=this._buildArgs([],t,void 0,n),o=Gp(await this._rpcRequest("getTransactionCount",r),oy(Yp()));if("error"in o)throw new Cm(o.error,"failed to get transaction count");return o.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=Gp(await this._rpcRequest("getInflationGovernor",t),Sy);if("error"in n)throw new Cm(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:o}=ey(n),i=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...o,epoch:null!=t?t:o?.epoch}),s=Gp(await this._rpcRequest("getInflationReward",i),uy);if("error"in s)throw new Cm(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=Gp(await this._rpcRequest("getInflationRate",[]),Ay);if("error"in e)throw new Cm(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=ey(e),r=this._buildArgs([],t,void 0,n),o=Gp(await this._rpcRequest("getEpochInfo",r),Iy);if("error"in o)throw new Cm(o.error,"failed to get epoch info");return o.result}async getEpochSchedule(){const e=Gp(await this._rpcRequest("getEpochSchedule",[]),xy);if("error"in e)throw new Cm(e.error,"failed to get epoch schedule");const t=e.result;return new zm(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=Gp(await this._rpcRequest("getLeaderSchedule",[]),By);if("error"in e)throw new Cm(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=Gp(await this._rpcRequest("getMinimumBalanceForRentExemption",n),sw);return"error"in r?0:r.result}async getRecentBlockhashAndContext(e){const{context:t,value:{blockhash:n}}=await this.getLatestBlockhashAndContext(e);return{context:t,value:{blockhash:n,feeCalculator:{get lamportsPerSignature(){throw new Error("The capability to fetch `lamportsPerSignature` using the `getRecentBlockhash` API is no longer offered by the network. Use the `getFeeForMessage` API to obtain the fee for a given message.")},toJSON:()=>({})}}}}async getRecentPerformanceSamples(e){const t=Gp(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),Uw);if("error"in t)throw new Cm(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=Gp(await this._rpcRequest("getFeeCalculatorForBlockhash",n),Dw);if("error"in r)throw new Cm(r.error,"failed to get fee calculator");const{context:o,value:i}=r.result;return{context:o,value:null!==i?i.feeCalculator:null}}async getFeeForMessage(e,t){const n=Yg(e.serialize()).toString("base64"),r=this._buildArgs([n],t),o=Gp(await this._rpcRequest("getFeeForMessage",r),iy(Zp(Yp())));if("error"in o)throw new Cm(o.error,"failed to get fee for message");if(null===o.result)throw new Error("invalid blockhash");return o.result}async getRecentPrioritizationFees(e){const t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],r=Gp(await this._rpcRequest("getRecentPrioritizationFees",n),Ty);if("error"in r)throw new Cm(r.error,"failed to get recent prioritization fees");return r.result}async getRecentBlockhash(e){try{return(await this.getRecentBlockhashAndContext(e)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhash(e){try{return(await this.getLatestBlockhashAndContext(e)).value}catch(e){throw new Error("failed to get recent blockhash: "+e)}}async getLatestBlockhashAndContext(e){const{commitment:t,config:n}=ey(e),r=this._buildArgs([],t,void 0,n),o=Gp(await this._rpcRequest("getLatestBlockhash",r),Nw);if("error"in o)throw new Cm(o.error,"failed to get latest blockhash");return o.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=ey(t),o=this._buildArgs([e],n,void 0,r),i=Gp(await this._rpcRequest("isBlockhashValid",o),_w);if("error"in i)throw new Cm(i.error,"failed to determine if the blockhash `"+e+"`is valid");return i.result}async getVersion(){const e=Gp(await this._rpcRequest("getVersion",[]),oy(wy));if("error"in e)throw new Cm(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=Gp(await this._rpcRequest("getGenesisHash",[]),oy(tg()));if("error"in e)throw new Cm(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=ey(t),o=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=await this._rpcRequest("getBlock",o);try{switch(r?.transactionDetails){case"accounts":{const e=Gp(i,Sw);if("error"in e)throw e.error;return e.result}case"none":{const e=Gp(i,Ew);if("error"in e)throw e.error;return e.result}default:{const e=Gp(i,vw);if("error"in e)throw e.error;const{result:t}=e;return t?{...t,transactions:t.transactions.map(({transaction:e,meta:t,version:n})=>({meta:t,transaction:{...e,message:ay(n,e.message)},version:n}))}:null}}}catch(e){throw new Cm(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=ey(t),o=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=await this._rpcRequest("getBlock",o);try{switch(r?.transactionDetails){case"accounts":{const e=Gp(i,Tw);if("error"in e)throw e.error;return e.result}case"none":{const e=Gp(i,Iw);if("error"in e)throw e.error;return e.result}default:{const e=Gp(i,Aw);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Cm(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){const{commitment:r,...o}=e;n=r,t=o}const r=this._buildArgs([],n,"base64",t),o=Gp(await this._rpcRequest("getBlockProduction",r),Ey);if("error"in o)throw new Cm(o.error,"failed to get block production information");return o.result}async getTransaction(e,t){const{commitment:n,config:r}=ey(t),o=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=Gp(await this._rpcRequest("getTransaction",o),Cw);if("error"in i)throw new Cm(i.error,"failed to get transaction");const s=i.result;return s?{...s,transaction:{...s.transaction,message:ay(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:n,config:r}=ey(t),o=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=Gp(await this._rpcRequest("getTransaction",o),Pw);if("error"in i)throw new Cm(i.error,"failed to get transaction");return i.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=ey(t),o=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(o)).map(e=>{const t=Gp(e,Pw);if("error"in t)throw new Cm(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=ey(t),o=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(o)).map(e=>{const t=Gp(e,Cw);if("error"in t)throw new Cm(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:ay(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=Gp(await this._rpcRequest("getBlock",n),xw);if("error"in r)throw new Cm(r.error,"failed to get confirmed block");const o=r.result;if(!o)throw new Error("Confirmed block "+e+" not found");const i={...o,transactions:o.transactions.map(({transaction:e,meta:t})=>{const n=new km(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...i,transactions:i.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:Tm.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),o=Gp(await this._rpcRequest("getBlocks",r),oy(Hp(Yp())));if("error"in o)throw new Cm(o.error,"failed to get blocks");return o.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=Gp(await this._rpcRequest("getBlock",n),Bw);if("error"in r)throw new Cm(r.error,"failed to get block");const o=r.result;if(!o)throw new Error("Block "+e+" not found");return o}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=Gp(await this._rpcRequest("getBlock",n),Bw);if("error"in r)throw new Cm(r.error,"failed to get confirmed block");const o=r.result;if(!o)throw new Error("Confirmed block "+e+" not found");return o}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=Gp(await this._rpcRequest("getTransaction",n),Cw);if("error"in r)throw new Cm(r.error,"failed to get transaction");const o=r.result;if(!o)return o;const i=new km(o.transaction.message),s=o.transaction.signatures;return{...o,transaction:Tm.populate(i,s)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=Gp(await this._rpcRequest("getTransaction",n),Pw);if("error"in r)throw new Cm(r.error,"failed to get confirmed transaction");return r.result}async getParsedConfirmedTransactions(e,t){const n=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],t,"jsonParsed")}));return(await this._rpcBatchRequest(n)).map(e=>{const t=Gp(e,Pw);if("error"in t)throw new Cm(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,n){let r={},o=await this.getFirstAvailableBlock();for(;!("until"in r)&&!(--t<=0||t<o);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(r.until=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}let i=await this.getSlot("finalized");for(;!("before"in r||++n>i);)try{const e=await this.getConfirmedBlockSignatures(n);e.signatures.length>0&&(r.before=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}return(await this.getConfirmedSignaturesForAddress2(e,r)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),o=Gp(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),Gy);if("error"in o)throw new Cm(o.error,"failed to get confirmed signatures for address");return o.result}async getSignaturesForAddress(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),o=Gp(await this._rpcRequest("getSignaturesForAddress",r),Wy);if("error"in o)throw new Cm(o.error,"failed to get signatures for address");return o.result}async getAddressLookupTable(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let o=null;return null!==r&&(o=new Vm({key:e,state:Vm.deserialize(r.data)})),{context:n,value:o}}async getNonceAndContext(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let o=null;return null!==r&&(o=Rm.fromAccountData(r.data)),{context:n,value:o}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+t)})}async requestAirdrop(e,t){const n=Gp(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),Rw);if("error"in n)throw new Cm(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Pm(100);const e=Date.now()-this._blockhashInfo.lastFetch>=3e4;if(null!==this._blockhashInfo.latestBlockhash&&!e)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const e=Date.now(),t=this._blockhashInfo.latestBlockhash,n=t?t.blockhash:null;for(let e=0;e<50;e++){const e=await this.getLatestBlockhash("finalized");if(n!==e.blockhash)return this._blockhashInfo={latestBlockhash:e,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},e;await Pm(200)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){const{commitment:t,config:n}=ey(e),r=this._buildArgs([],t,"base64",n),o=Gp(await this._rpcRequest("getStakeMinimumDelegation",r),iy(Yp()));if("error"in o)throw new Cm(o.error,"failed to get stake minimum delegation");return o.result}async simulateTransaction(e,t,n){if("message"in e){const r=e.serialize(),o=Xs.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const i=t||{};i.encoding="base64","commitment"in i||(i.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(i.innerInstructions=t.innerInstructions);const s=[o,i],a=Gp(await this._rpcRequest("simulateTransaction",s),vy);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof Tm){let t=e;r=new Tm,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=Tm.populate(e),r._message=r._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const o=t;if(r.nonceInfo&&o)r.sign(...o);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(r.lastValidBlockHeight=t.lastValidBlockHeight,r.recentBlockhash=t.blockhash,!o)break;if(r.sign(...o),!r.signature)throw new Error("!signature");const n=r.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(n)&&!this._blockhashInfo.transactionSignatures.includes(n)){this._blockhashInfo.simulatedSignatures.push(n);break}e=!0}}const i=r._compile(),s=i.serialize(),a=r._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:i.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}o&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const u=[a,c],l=Gp(await this._rpcRequest("simulateTransaction",u),vy);if("error"in l){let e;if("data"in l.error&&(e=l.error.data.logs,e&&Array.isArray(e))){const t="\n ";e.join(t)}throw new Bm({action:"simulate",signature:"",transactionMessage:l.error.message,logs:e})}return l.result}async sendTransaction(e,t,n){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const n=e.serialize();return await this.sendRawTransaction(n,t)}if(void 0===t||!Array.isArray(t))throw new Error("Invalid arguments");const r=t;if(e.nonceInfo)e.sign(...r);else{let t=this._disableBlockhashCaching;for(;;){const n=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=n.lastValidBlockHeight,e.recentBlockhash=n.blockhash,e.sign(...r),!e.signature)throw new Error("!signature");const o=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(o)){this._blockhashInfo.transactionSignatures.push(o);break}t=!0}}const o=e.serialize();return await this.sendRawTransaction(o,n)}async sendRawTransaction(e,t){const n=Yg(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},r=t&&t.skipPreflight,o=!0===r?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(n.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(n.minContextSlot=t.minContextSlot),r&&(n.skipPreflight=r),o&&(n.preflightCommitment=o);const i=[e,n],s=Gp(await this._rpcRequest("sendTransaction",i),Fw);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new Bm({action:r?"send":"simulate",signature:"",transactionMessage:s.error.message,logs:e})}return s.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1}_wsOnClose(e){this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3!==e?(this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([e,t])=>{this._setSubscription(e,{...t,state:"pending"})})):this._updateSubscriptions()}_setSubscription(e,t){const n=this._subscriptionsByHash[e]?.state;if(this._subscriptionsByHash[e]=t,n!==t.state){const n=this._subscriptionStateChangeCallbacksByHash[e];n&&n.forEach(e=>{try{e(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){const n=this._subscriptionHashByClientSubscriptionId[e];if(null==n)return()=>{};const r=this._subscriptionStateChangeCallbacksByHash[n]||=new Set;return r.add(t),()=>{r.delete(t),0===r.size&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length)return void(this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(e){Error}},500)));if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected)return void this._rpcWebSocket.connect();const e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async e=>{const n=this._subscriptionsByHash[e];if(void 0!==n)switch(n.state){case"pending":case"unsubscribed":if(0===n.callbacks.size)return delete this._subscriptionsByHash[e],"unsubscribed"===n.state&&delete this._subscriptionCallbacksByServerSubscriptionId[n.serverSubscriptionId],void await this._updateSubscriptions();await(async()=>{const{args:r,method:o}=n;try{this._setSubscription(e,{...n,state:"subscribing"});const t=await this._rpcWebSocket.call(o,r);this._setSubscription(e,{...n,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=n.callbacks,await this._updateSubscriptions()}catch(r){if(!t())return;this._setSubscription(e,{...n,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===n.callbacks.size&&await(async()=>{const{serverSubscriptionId:r,unsubscribeMethod:o}=n;if(this._subscriptionsAutoDisposedByRpc.has(r))this._subscriptionsAutoDisposedByRpc.delete(r);else{this._setSubscription(e,{...n,state:"unsubscribing"}),this._setSubscription(e,{...n,state:"unsubscribing"});try{await this._rpcWebSocket.call(o,[r])}catch(r){if(Error,!t())return;return this._setSubscription(e,{...n,state:"subscribed"}),void await this._updateSubscriptions()}}this._setSubscription(e,{...n,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(e,t){const n=this._subscriptionCallbacksByServerSubscriptionId[e];void 0!==n&&n.forEach(e=>{try{e(...t)}catch(e){}})}_wsOnAccountNotification(e){const{result:t,subscription:n}=Gp(e,zy);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=Gm([e.method,t]),o=this._subscriptionsByHash[r];return void 0===o?this._subscriptionsByHash[r]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:o.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[n]=r,this._subscriptionDisposeFunctionsByClientSubscriptionId[n]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[n],delete this._subscriptionHashByClientSubscriptionId[n];const t=this._subscriptionsByHash[r];gm(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${n}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),n}onAccountChange(e,t,n){const{commitment:r,config:o}=ey(n),i=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",o);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},i)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=Gp(e,Hy);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:o,config:i}=ey(n),s=this._buildArgs([e.toBase58()],o||this._commitment||"finalized","base64",i||(r?{filters:ty(r)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},s)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,t,n){const r=this._buildArgs(["object"==typeof e?{mentions:[e.toString()]}:e],n||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},r)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:t,subscription:n}=Gp(e,Ow);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=Gp(e,Xy);this._handleServerNotification(n,[t])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:t,subscription:n}=Gp(e,Zy);this._handleServerNotification(n,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){const n=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];n&&await n()}_buildArgs(e,t,n,r){const o=t||this._commitment;if(o||n||r){let t={};n&&(t.encoding=n),o&&(t.commitment=o),r&&(t=Object.assign(t,r)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,r){const o=t||this._commitment;if(o&&!["confirmed","finalized"].includes(o))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,n,r)}_wsOnSignatureNotification(e){const{result:t,subscription:n}=Gp(e,Yy);"receivedSignature"!==t.value&&this._subscriptionsAutoDisposedByRpc.add(n),this._handleServerNotification(n,"receivedSignature"===t.value?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,n){const r=this._buildArgs([e],n||this._commitment||"finalized"),o=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(o)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},r);return o}onSignatureWithOptions(e,t,n){const{commitment:r,...o}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},i=this._buildArgs([e],r,void 0,o),s=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(s)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},i);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=Gp(e,Jy);this._handleServerNotification(n,[t])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}class qw{constructor(e){this._keypair=void 0,this._keypair=e??Vg()}static generate(){return new qw(Vg())}static fromSecretKey(e,t){if(64!==e.byteLength)throw new Error("bad secret key size");const n=e.slice(32,64);if(!t||!t.skipValidation){const t=e.slice(0,32),r=Xg(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new qw({publicKey:n,secretKey:e})}static fromSeed(e){const t=Xg(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new qw({publicKey:t,secretKey:n})}get publicKey(){return new om(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:ll.struct([ll.u32("instruction"),Fm("recentSlot"),ll.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:ll.struct([ll.u32("instruction")])},ExtendLookupTable:{index:2,layout:ll.struct([ll.u32("instruction"),Fm(),ll.seq(lm(),ll.offset(ll.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:ll.struct([ll.u32("instruction")])},CloseLookupTable:{index:4,layout:ll.struct([ll.u32("instruction")])}}),new om("AddressLookupTab1e1111111111111111111111111");const Kw=Object.freeze({RequestUnits:{index:0,layout:ll.struct([ll.u8("instruction"),ll.u32("units"),ll.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:ll.struct([ll.u8("instruction"),ll.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:ll.struct([ll.u8("instruction"),ll.u32("units")])},SetComputeUnitPrice:{index:3,layout:ll.struct([ll.u8("instruction"),Fm("microLamports")])}});class Gw{constructor(){}static requestUnits(e){const t=Nm(Kw.RequestUnits,e);return new Am({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=Nm(Kw.RequestHeapFrame,e);return new Am({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=Nm(Kw.SetComputeUnitLimit,e);return new Am({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=Nm(Kw.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new Am({keys:[],programId:this.programId,data:t})}}var Ww;Gw.programId=new om("ComputeBudget111111111111111111111111111111"),ll.struct([ll.u8("numSignatures"),ll.u8("padding"),ll.u16("signatureOffset"),ll.u16("signatureInstructionIndex"),ll.u16("publicKeyOffset"),ll.u16("publicKeyInstructionIndex"),ll.u16("messageDataOffset"),ll.u16("messageDataSize"),ll.u16("messageInstructionIndex")]),new om("Ed25519SigVerify111111111111111111111111111"),Hg.utils.isValidPrivateKey,ll.struct([ll.u8("numSignatures"),ll.u16("signatureOffset"),ll.u8("signatureInstructionIndex"),ll.u16("ethAddressOffset"),ll.u8("ethAddressInstructionIndex"),ll.u16("messageDataOffset"),ll.u16("messageDataSize"),ll.u8("messageInstructionIndex"),ll.blob(20,"ethAddress"),ll.blob(64,"signature"),ll.u8("recoveryId")]),new om("KeccakSecp256k11111111111111111111111111111"),new om("StakeConfig11111111111111111111111111111111");class zw{constructor(e,t,n){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=t,this.custodian=n}}Ww=zw,zw.default=new Ww(0,0,om.default),Object.freeze({Initialize:{index:0,layout:ll.struct([ll.u32("instruction"),((e="authorized")=>ll.struct([lm("staker"),lm("withdrawer")],e))(),((e="lockup")=>ll.struct([ll.ns64("unixTimestamp"),ll.ns64("epoch"),lm("custodian")],e))()])},Authorize:{index:1,layout:ll.struct([ll.u32("instruction"),lm("newAuthorized"),ll.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:ll.struct([ll.u32("instruction")])},Split:{index:3,layout:ll.struct([ll.u32("instruction"),ll.ns64("lamports")])},Withdraw:{index:4,layout:ll.struct([ll.u32("instruction"),ll.ns64("lamports")])},Deactivate:{index:5,layout:ll.struct([ll.u32("instruction")])},Merge:{index:7,layout:ll.struct([ll.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:ll.struct([ll.u32("instruction"),lm("newAuthorized"),ll.u32("stakeAuthorizationType"),hm("authoritySeed"),lm("authorityOwner")])}}),new om("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:ll.struct([ll.u32("instruction"),((e="voteInit")=>ll.struct([lm("nodePubkey"),lm("authorizedVoter"),lm("authorizedWithdrawer"),ll.u8("commission")],e))()])},Authorize:{index:1,layout:ll.struct([ll.u32("instruction"),lm("newAuthorized"),ll.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:ll.struct([ll.u32("instruction"),ll.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:ll.struct([ll.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:ll.struct([ll.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>ll.struct([ll.u32("voteAuthorizationType"),lm("currentAuthorityDerivedKeyOwnerPubkey"),hm("currentAuthorityDerivedKeySeed"),lm("newAuthorized")],e))()])}}),new om("Vote111111111111111111111111111111111111111"),new om("Va1idator1nfo111111111111111111111111111111"),rg({name:tg(),website:Jp(tg()),details:Jp(tg()),iconUrl:Jp(tg()),keybaseUsername:Jp(tg())}),new om("Vote111111111111111111111111111111111111111"),ll.struct([lm("nodePubkey"),lm("authorizedWithdrawer"),ll.u8("commission"),ll.nu64(),ll.seq(ll.struct([ll.nu64("slot"),ll.u32("confirmationCount")]),ll.offset(ll.u32(),-8),"votes"),ll.u8("rootSlotValid"),ll.nu64("rootSlot"),ll.nu64(),ll.seq(ll.struct([ll.nu64("epoch"),lm("authorizedVoter")]),ll.offset(ll.u32(),-8),"authorizedVoters"),ll.struct([ll.seq(ll.struct([lm("authorizedPubkey"),ll.nu64("epochOfLastAuthorizedSwitch"),ll.nu64("targetEpoch")]),32,"buf"),ll.nu64("idx"),ll.u8("isEmpty")],"priorVoters"),ll.nu64(),ll.seq(ll.struct([ll.nu64("epoch"),ll.nu64("credits"),ll.nu64("prevCredits")]),ll.offset(ll.u32(),-8),"epochCredits"),ll.struct([ll.nu64("slot"),ll.nu64("timestamp")],"lastTimestamp")]);const jw=new om("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new om("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const Hw=new om("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new om("So11111111111111111111111111111111111111112"),new om("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const Vw=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var Xw,Qw={};var Zw=(Xw||(Xw=1,Object.defineProperty(Qw,"__esModule",{value:!0}),Qw.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},Qw.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},Qw.toBufferLE=function(e,t){{const n=e.toString(16),r=Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex");return r.reverse(),r}},Qw.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}}),Qw);const Yw=(Jw=8,e=>{const t=ll.blob(Jw,e),{encode:n,decode:r}=Vw(t),o=t;return o.decode=(e,t)=>{const n=r(e,t);return Zw.toBigIntLE(Buffer.from(n))},o.encode=(e,t,r)=>{const o=Zw.toBufferLE(e,Jw);return n(o,t,r)},o});var Jw;const eb=e=>{const t=ll.u8(e),{encode:n,decode:r}=Vw(t),o=t;return o.decode=(e,t)=>!!r(e,t),o.encode=(e,t,r)=>{const o=Number(e);return n(o,t,r)},o},tb=e=>{const t=ll.blob(32,e),{encode:n,decode:r}=Vw(t),o=t;return o.decode=(e,t)=>{const n=r(e,t);return new om(n)},o.encode=(e,t,r)=>{const o=e.toBuffer();return n(o,t,r)},o};class nb extends Error{constructor(e){super(e)}}class rb extends nb{constructor(){super(...arguments),this.name="TokenAccountNotFoundError"}}class ob extends nb{constructor(){super(...arguments),this.name="TokenInvalidAccountError"}}class ib extends nb{constructor(){super(...arguments),this.name="TokenInvalidAccountOwnerError"}}class sb extends nb{constructor(){super(...arguments),this.name="TokenInvalidAccountSizeError"}}class ab extends nb{constructor(){super(...arguments),this.name="TokenOwnerOffCurveError"}}var cb;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Mint=1]="Mint",e[e.Account=2]="Account"}(cb||(cb={}));const ub=ll.struct([ll.u8("m"),ll.u8("n"),eb("isInitialized"),tb("signer1"),tb("signer2"),tb("signer3"),tb("signer4"),tb("signer5"),tb("signer6"),tb("signer7"),tb("signer8"),tb("signer9"),tb("signer10"),tb("signer11")]).span;var lb;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}(lb||(lb={}));const hb=ll.struct([tb("mint"),tb("owner"),Yw("amount"),ll.u32("delegateOption"),tb("delegate"),ll.u8("state"),ll.u32("isNativeOption"),Yw("isNative"),Yw("delegatedAmount"),ll.u32("closeAuthorityOption"),tb("closeAuthority")]),db=hb.span;async function fb(e,t,n,r=jw){return function(e,t,n=jw){if(!t)throw new rb;if(!t.owner.equals(n))throw new ib;if(t.data.length<db)throw new sb;const r=hb.decode(t.data.slice(0,db));let o=Buffer.alloc(0);if(t.data.length>db){if(t.data.length===ub)throw new sb;if(t.data[db]!=cb.Account)throw new ob;o=t.data.slice(db+1)}return{address:e,mint:r.mint,owner:r.owner,amount:r.amount,delegate:r.delegateOption?r.delegate:null,delegatedAmount:r.delegatedAmount,isInitialized:r.state!==lb.Uninitialized,isFrozen:r.state===lb.Frozen,isNative:!!r.isNativeOption,rentExemptReserve:r.isNativeOption?r.isNative:null,closeAuthority:r.closeAuthorityOption?r.closeAuthority:null,tlvData:o}}(t,await e.getAccountInfo(t,n),r)}function pb(e,t,n=!1,r=jw,o=Hw){if(!n&&!om.isOnCurve(t.toBuffer()))throw new ab;const[i]=om.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],o);return i}ll.struct([ll.u32("mintAuthorityOption"),tb("mintAuthority"),Yw("supply"),ll.u8("decimals"),eb("isInitialized"),ll.u32("freezeAuthorityOption"),tb("freezeAuthority")]).span;var gb=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");const t=new Uint8Array(256);for(let e=0;e<t.length;e++)t[e]=255;for(let n=0;n<e.length;n++){const r=e.charAt(n),o=r.charCodeAt(0);if(255!==t[o])throw new TypeError(r+" is ambiguous");t[o]=n}const n=e.length,r=e.charAt(0),o=Math.log(n)/Math.log(256),i=Math.log(256)/Math.log(n);function s(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;let i=0,s=0,a=0;for(;e[i]===r;)s++,i++;const c=(e.length-i)*o+1>>>0,u=new Uint8Array(c);for(;i<e.length;){const r=e.charCodeAt(i);if(r>255)return;let o=t[r];if(255===o)return;let s=0;for(let e=c-1;(0!==o||s<a)&&-1!==e;e--,s++)o+=n*u[e]>>>0,u[e]=o%256>>>0,o=o/256>>>0;if(0!==o)throw new Error("Non-zero carry");a=s,i++}let l=c-a;for(;l!==c&&0===u[l];)l++;const h=new Uint8Array(s+(c-l));let d=s;for(;l!==c;)h[d++]=u[l++];return h}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";let o=0,s=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,o++;const u=(c-a)*i+1>>>0,l=new Uint8Array(u);for(;a!==c;){let e=t[a],r=0;for(let t=u-1;(0!==e||r<s)&&-1!==t;t--,r++)e+=256*l[t]>>>0,l[t]=e%n>>>0,e=e/n>>>0;if(0!==e)throw new Error("Non-zero carry");s=r,a++}let h=u-s;for(;h!==u&&0===l[h];)h++;let d=r.repeat(o);for(;h<u;++h)d+=e.charAt(l[h]);return d},decodeUnsafe:s,decode:function(e){const t=s(e);if(t)return t;throw new Error("Non-base"+n+" character")}}}("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");class mb extends Ms{constructor(e){if(super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.tokenMetadataCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,!e.ethereumPrivateKey||!/^0x[a-fA-F0-9]{64}$/.test(e.ethereumPrivateKey))throw new Error("Invalid Ethereum private key format. Expected 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)");const t=new n("https://ethereum.publicnode.com");this.ethereumWallet=new r(e.ethereumPrivateKey,t);const o=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new $w(o,"confirmed");try{i=gb.decode(e.solanaPrivateKeyBase58)}catch(e){throw new Error(`Invalid Solana private key format (expected base58-encoded string): ${e instanceof Error?e.message:"decode failed"}`)}if(64!==i.length)throw new Error(`Invalid Solana private key length: expected 64 bytes, got ${i.length} bytes`);this.solanaKeypair=qw.fromSecretKey(i);const s=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new om(s),[this.solanaBridgeTokenAuthority]=om.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=om.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=om.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenConfigs=new Map;const a=e.tokenConfigs??Ki;for(const e of a)this.tokenConfigs.set(e.symbol.toUpperCase(),e)}async estimateFee(e,t){const n=await this.getTokenMetadata(e),r=await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor});return{estimatedFeeInGala:r.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:r.estimatedTotalTxFeeInExternalToken,feeToken:r.bridgeToken,pricePerUnit:r.estimatedPricePerTxFeeUnit,estimatedGasUnits:r.estimatedTxFeeUnitsTotal,exchangeRate:r.galaExchangeRate?.exchangeRate??"0",timestamp:r.timestamp,raw:r}}async bridgeOut(e){const{amount:t,recipientAddress:n,tokenSymbol:r}=e;if(!r)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const o=r,i=parseFloat(t);if(isNaN(i)||i<=0)throw new Error(`Invalid bridge amount for ${o}: "${t}". Amount must be a positive number.`);try{new om(n)}catch(e){throw new Error(`Invalid Solana recipient address: "${n}". ${e instanceof Error?e.message:"Expected valid base58 public key."}`)}const s=await this.getTokenMetadata(o),a=await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:s.descriptor}),c={destinationChainId:Ai.SOLANA,destinationChainTxFee:a,quantity:t,recipient:n,tokenInstance:{...s.descriptor,instance:"0"}},u=await this.buildBridgeOutPayload(c),l=await this.galaConnectClient.requestBridgeOut(u),h=this.extractBridgeRequestId(l);if(!h)throw new Error("Bridge request ID missing from RequestTokenBridgeOut response");const d=await this.galaConnectClient.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:h}),f=d.Hash??d.hash??"";if(!f)throw new Error("BridgeTokenOut response missing transaction hash");return{direction:"outbound",fromChain:"GalaChain",toChain:"Solana",transactionHash:f,tokenSymbol:o,amount:t,feePaid:a.estimatedTotalTxFeeInGala,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${f}`}}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:o}=e;if(!o)throw new Error("Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.");const i=o,s=parseFloat(t);if(isNaN(s)||s<=0)throw new Error(`Invalid bridge amount for ${i}: "${t}". Amount must be a positive number.`);let a=this.solanaKeypair;if(n){let e;try{e=gb.decode(n)}catch(e){throw new Error(`Invalid sourcePrivateKey format (expected base58): ${e instanceof Error?e.message:"decode failed"}`)}if(64!==e.length)throw new Error(`Invalid sourcePrivateKey length: expected 64 bytes, got ${e.length} bytes`);a=qw.fromSecretKey(e)}const c=this.tokenConfigs.get(i.toUpperCase());if(!c)throw new Error(`Token ${i} not supported for Solana bridge`);const u=await this.getTokenMetadata(i),l=ks(t,u.decimals),h=r??this.galaChainWalletAddress,d=await this.executeSolanaBridgeOut({keypair:a,tokenConfig:c,metadata:u,amountBaseUnits:l,recipient:h,amount:t});return{direction:"inbound",fromChain:"Solana",toChain:"GalaChain",transactionHash:d,tokenSymbol:i,amount:t,timestamp:Date.now(),statusUrl:`${this.galaConnectClient.getBaseUrl()}/v1/bridge/transaction?hash=${d}`}}async getStatus(e){const t=await this.galaConnectClient.getBridgeStatus(e),n=t.status;return{status:n,statusDescription:t.statusDescription,fromChain:t.fromChain,toChain:t.toChain,quantity:t.quantity,transactionHash:t.emitterTransactionHash,tokenInstance:t.tokenInstance,isComplete:5===n,isFailed:6===n||7===n}}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(e.toUpperCase())}isValidAddress(e){try{return new om(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=this.tokenConfigs.get(e.toUpperCase());if(!n)throw new Error(`Token ${e} not supported for Solana. Supported: GALA (8 decimals), GSOL (9 decimals)`);if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58();let o;try{o=new om(r)}catch{throw new Error(`Invalid Solana address: "${r}"`)}const i=pb(new om(n.mintAddress),o,!1,jw,Hw);try{const e=await fb(this.solanaConnection,i,"confirmed",jw),t=n.decimals??8;return vs(e.amount,t)}catch(t){if(t instanceof Error&&t.message.includes("could not find")){return vs(0n,n.decimals??8)}throw new Error(`Failed to fetch ${e} balance for ${r}: ${t instanceof Error?t.message:"Unknown error"}`)}}async getSolanaNativeBalance(e){const t=e??this.solanaKeypair.publicKey.toBase58();let n;try{n=new om(t)}catch{throw new Error(`Invalid Solana address: "${t}"`)}const r=await this.solanaConnection.getBalance(n,"confirmed");return vs(BigInt(r),9)}async requestDevnetAirdrop(e=1,t){if(e<=0||e>2)throw new Error(`Invalid airdrop amount: ${e} SOL. Devnet faucet limits: minimum >0 SOL, maximum 2 SOL per request.`);let n;if(t)try{n=new om(t)}catch{throw new Error(`Invalid Solana address: "${t}"`)}else n=this.solanaKeypair.publicKey;const r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw new Error(`Solana devnet faucet only available on devnet. Current RPC: ${r}. Ensure SDK is configured with environment='STAGE' for devnet access.`);const o=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,o)}async getSolanaTransactionStatus(e){if(!e||"string"!=typeof e)throw new Error("Invalid signature: must be a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw new Error(`Invalid Solana signature format: "${e.slice(0,20)}...". Expected base58-encoded string (87-88 characters).`);const t=(await this.solanaConnection.getSignatureStatuses([e])).value[0];return t?t.err?{confirmed:!1,status:"failed",slot:t.slot,error:JSON.stringify(t.err)}:{confirmed:!0,status:t.confirmationStatus||"processed",slot:t.slot}:{confirmed:!1,status:"not_found"}}async getTokenMetadata(e){const t=this.tokenMetadataCache.get(e.toUpperCase());if(t)return t;const n=Gi[e.toUpperCase()];if(n)return this.tokenMetadataCache.set(e.toUpperCase(),n),n;let r=e,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified);if(i||e.startsWith("G")||(r=`G${e}`,o=await this.galaConnectClient.getBridgeConfigurations(r),i=o.find(e=>e.symbol.toUpperCase()===r.toUpperCase()&&e.verified)),!i)throw new Error(`Unable to locate token metadata for ${e}`);const s={descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:i.decimals,...i.channel&&{channel:i.channel}};return this.tokenMetadataCache.set(e.toUpperCase(),s),s}async buildBridgeOutPayload(e){const t=e.uniqueKey??`galaconnect-operation-${O.randomUUID()}`,n="string"==typeof e.destinationChainId?Number(e.destinationChainId):e.destinationChainId,r=this.normalizeDestinationChainTxFee(e.destinationChainTxFee),o=Boolean(r.galaExchangeCrossRate),i=o?{...r,galaExchangeRate:void 0}:{...r,galaExchangeCrossRate:void 0},s={destinationChainId:n,destinationChainTxFee:this.sanitizeObject(i),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:t},a=os(o),c=await this.ethereumWallet.signTypedData(Zi,a,s),u=`Ethereum Signed Message:\n${Si({domain:Zi,message:s,primaryType:"GalaTransaction",types:a}).length}`;return{...s,signature:c,prefix:u,types:a,domain:Zi}}async executeSolanaBridgeOut(e){const t=new om(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),o=n?void 0:pb(t,e.keypair.publicKey,!1,jw,Hw),i=Buffer.from(e.recipient,"utf8"),s=Buffer.alloc(8);s.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(i.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,s,a,i):this.buildTokenBridgeInstruction(e.keypair.publicKey,o,t,r,s,a,i),u=new Tm;u.add(Gw.setComputeUnitPrice({microLamports:375e3}),Gw.setComputeUnitLimit({units:2e5}),c),u.feePayer=e.keypair.publicKey;const l=await this.sendAndConfirmWithFallback(u,e.keypair),h={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:e.amount,tokenInstance:h,fromChain:"Solana",toChain:"GC",hash:l}),l}async sendAndConfirmWithFallback(e,t,n=3){let r=null;for(let o=1;o<=n;o++){try{const i=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=i.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const s=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:s,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed"),s}catch(e){const t=e instanceof Error?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const i=await this.solanaConnection.getSignatureStatuses([s]);if("confirmed"===i.value[0]?.confirmationStatus||"finalized"===i.value[0]?.confirmationStatus)return s;r=new Error(`Transaction ${s} not confirmed - block height exceeded (attempt ${o}/${n})`)}}catch(e){r=e instanceof Error?e:new Error(String(e));const t=r.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||o===n)throw r}const i=Math.min(1e3*Math.pow(2,o-1),5e3);await new Promise(e=>setTimeout(e,i))}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const o=Buffer.concat([ji.BRIDGE_OUT_NATIVE,t,n,r]);return new Am({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!0},{pubkey:this.solanaNativeBridgePda,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:Om.programId,isSigner:!1,isWritable:!1}],data:o})}buildTokenBridgeInstruction(e,t,n,r,o,i,s){const a=Buffer.concat([ji.BRIDGE_OUT,o,i,s]);return new Am({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r.mintLookup,isSigner:!1,isWritable:!1},{pubkey:r.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:r.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:Om.programId,isSigner:!1,isWritable:!1},{pubkey:jw,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=om.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),o=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!o)throw new Error(`Mint lookup account not found for ${r.toBase58()}`);if(!o.owner.equals(this.solanaBridgeProgramId))throw new Error("Mint lookup account owner mismatch for Solana bridge program");if(o.data.length<40)throw new Error("Mint lookup account data is unexpectedly short");const i={mintLookup:r,tokenBridge:new om(o.data.slice(8,40)),bridgeTokenAccount:pb(e,this.solanaBridgeTokenAuthority,!0,jw,Hw)};return this.solanaBridgeAccountCache.set(t,i),i}normalizeDestinationChainTxFee(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Number(e.galaDecimals):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Number(e.timestamp):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Number(e.galaExchangeRate.timestamp):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Number(n.timestamp):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Number(n.baseTokenCrossRate.timestamp):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Number(n.quoteTokenCrossRate.timestamp):n.quoteTokenCrossRate.timestamp})}return t}sanitizeObject(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=this.sanitizeObject(r):t[n]=r);return t}extractBridgeRequestId(e){if("string"==typeof e.Data)return e.Data;if(null!=e.data){if("string"==typeof e.data)return e.data;if("object"==typeof e.data){const t=e.data;if("string"==typeof t.Data)return t.Data}}}}const yb={PROD:{launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",galaChainBaseUrl:"https://gateway-mainnet.galachain.com",bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},STAGE:{launchpadBaseUrl:"https://lpad-backend-dev1.defi.gala.com",galaChainBaseUrl:"https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com",bundleBaseUrl:"https://bundle-backend-dev1.defi.gala.com",webSocketUrl:"https://bundle-backend-dev1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-dev1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function wb(e){return yb[e]}const bb={PROD:{ethereum:"https://ethereum.publicnode.com",solana:"https://api.mainnet-beta.solana.com"},STAGE:{ethereum:"https://ethereum-sepolia.publicnode.com",solana:"https://api.devnet.solana.com"}},kb={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class vb{static normalizeGalaChainAddress(e){let t;if(e.startsWith("eth|"))t=e.slice(4);else{if(e.startsWith("client|"))return e;t=e}(t.startsWith("0x")||t.startsWith("0X"))&&(t=t.slice(2));return`eth|${vb.checksumAddress(t)}`}static checksumAddress(e){const t=e.toLowerCase(),{keccak256:n,toUtf8Bytes:r}=require("ethers"),o=n(r(t)).slice(2);let i="";for(let e=0;e<t.length;e++){const n=t[e];parseInt(o[e],16)>=8?i+=n.toUpperCase():i+=n}return i}constructor(e){const t=vb.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"STAGE",r=yb[n],o=bb[n],i={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.galaChainBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??o.ethereum,solanaRpcUrl:e.solanaRpcUrl??o.solana,ethereumBridgeContract:e.ethereumBridgeContract??$i(n),solanaBridgeProgram:e.solanaBridgeProgram??kb.solanaBridgeProgram,rateLimit:e.rateLimit??kb.rateLimit,pollInterval:e.pollInterval??kb.pollInterval,pollTimeout:e.pollTimeout??kb.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...i,solanaPrivateKey:e.solanaPrivateKey}:i,this.galaConnectClient=new Ls({baseUrl:this.config.galaConnectBaseUrl,galachainBaseUrl:this.config.galaChainApiBaseUrl,walletAddress:this.config.galaChainWalletAddress,requestsPerSecond:this.config.rateLimit}),e.bridgeableTokenService&&(this.bridgeableTokenService=e.bridgeableTokenService),this.strategies=new Map,this.initializeStrategies()}initializeStrategies(){const e=Mi(this.config.environment),t={galaConnectClient:this.galaConnectClient,galaChainWalletAddress:this.config.galaChainWalletAddress,ethereumPrivateKey:this.config.ethereumPrivateKey,ethereumRpcUrl:this.config.ethereumRpcUrl,ethereumBridgeContract:this.config.ethereumBridgeContract,tokenConfigs:e};if(this.strategies.set("Ethereum",new $s(t)),this.config.solanaPrivateKey){const e={galaConnectClient:this.galaConnectClient,galaChainWalletAddress:this.config.galaChainWalletAddress,ethereumPrivateKey:this.config.ethereumPrivateKey,solanaPrivateKeyBase58:this.config.solanaPrivateKey,solanaRpcUrl:this.config.solanaRpcUrl,solanaBridgeProgram:this.config.solanaBridgeProgram,tokenConfigs:Ki};this.strategies.set("Solana",new mb(e))}}async resolveTokenSymbol(e,t){if(!this.bridgeableTokenService)throw new Error("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.");const n=Cs(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",o=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!o){throw new Error([`Token "${n}" was not found in the list of tokens bridgeable to ${t}.`,"","Troubleshooting suggestions:",' 1. Verify the tokenId format is correct (e.g., "GALA|Unit|none|none")'," 2. Check if the token supports bridging to this network:",` - Use sdk.fetchAllBridgeableTokensByNetwork('${r}')`," - Or use sdk.isTokenBridgeableToNetwork({ tokenSymbol, network })"," 3. Common tokenId formats for bridge tokens:",' - GALA: "GALA|Unit|none|none"',' - GUSDC: "GUSDC|Unit|none|eth:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"'," 4. Use sdk.getSupportedBridgeTokens() to list all available tokens"].join("\n"))}return o.symbol}async estimateBridgeFee(e){const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return this.getStrategy(e.destinationChain).estimateFee(t,e.amount??"0")}async bridgeOut(e){const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw new Error(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`);if(!n.isTokenSupported(t))throw new Error(`Token ${t} is not supported for ${e.destinationChain} bridging`);return n.bridgeOut({...e,tokenSymbol:t})}async bridgeIn(e){const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw new Error(`Token ${t} is not supported for ${e.sourceChain} bridging`);return n.bridgeIn({...e,tokenSymbol:t})}async getBridgeStatus(e,t){if(t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let r;if(n)try{return await n.getStatus(e)}catch(e){r=e instanceof Error?e:new Error(String(e))}const o=this.strategies.get("Solana");if(o)try{return await o.getStatus(e)}catch(e){r=e instanceof Error?e:new Error(String(e))}const i=r?` (last error: ${r.message})`:"";throw new Error(`Unable to get status for transaction ${e}${i}`)}async waitForBridgeCompletion(e,t){const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},r=this.strategies.get("Ethereum");if(r)try{return await r.getStatus(e),r.waitForCompletion(e,n)}catch{}const o=this.strategies.get("Solana");if(o)return o.waitForCompletion(e,n);throw new Error(`Unable to wait for transaction ${e}: no suitable strategy found`)}getSupportedBridgeTokens(e){const t=[],n=Mi(this.config.environment);if(!e||"Ethereum"===e)for(const e of n)t.push({symbol:e.symbol,decimals:e.decimals??18,verified:!0,supportedChains:["Ethereum"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{ethereum:e.contractAddress}});if(!e||"Solana"===e)for(const e of Ki){const n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push("Solana"),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals??9,verified:!0,supportedChains:["Solana"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){if(t){const n=this.strategies.get(t);return n?.isTokenSupported(e)??!1}for(const t of this.strategies.values())if(t.isTokenSupported(e))return!0;return!1}isValidAddress(e,t){const n=this.strategies.get(t);return n?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){const n=this.strategies.get("Ethereum");if(!n)throw new Error("Ethereum bridge not configured");return n.getEthereumTokenBalance(e,t)}async getEthereumNativeBalance(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridge not configured");return t.getEthereumNativeBalance(e)}async getSolanaTokenBalance(e,t){const n=this.strategies.get("Solana");if(!n)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");return n.getSolanaTokenBalance(e,t)}async getSolanaNativeBalance(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");return t.getSolanaNativeBalance(e)}async fetchEthereumWalletTokenBalance(e,t){const n=this.strategies.get("Ethereum");if(!n)throw new Error("Ethereum bridging not configured. Provide ethereumPrivateKey in config.");const r=Mi(this.config.environment),o=r.find(t=>t.symbol===e);if(!o){const t=r.map(e=>e.symbol).join(", ");throw new Error(`Unsupported Ethereum token: ${e}. Supported: ${t}`)}const i=n,s=t??i.getWalletAddress(),a=await i.getEthereumTokenBalance(e,s);return{symbol:o.symbol,quantity:a,decimals:o.decimals??18,contractAddress:o.contractAddress,isNative:!1}}async fetchEthereumWalletNativeBalance(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridging not configured. Provide ethereumPrivateKey in config.");const n=t,r=e??n.getWalletAddress();return{symbol:"ETH",quantity:await n.getEthereumNativeBalance(r),decimals:18,contractAddress:null,isNative:!0}}async fetchSolanaWalletTokenBalance(e,t){const n=this.strategies.get("Solana");if(!n)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");const r=Ki.find(t=>t.symbol===e);if(!r){const t=Ki.map(e=>e.symbol).join(", ");throw new Error(`Unsupported Solana token: ${e}. Supported: ${t}`)}const o=n,i=t??o.getWalletAddress(),s=await o.getSolanaTokenBalance(e,i);return{symbol:r.symbol,quantity:s,decimals:r.decimals??9,contractAddress:r.mintAddress,isNative:r.isNative??!1}}async fetchSolanaWalletNativeBalance(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");const n=t,r=e??n.getWalletAddress();return{symbol:"SOL",quantity:await n.getSolanaNativeBalance(r),decimals:9,contractAddress:null,isNative:!0}}async requestSolanaDevnetAirdrop(e,t){const n=this.strategies.get("Solana");if(!n)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");return n.requestDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridge strategy not configured. This method requires Solana wallet configuration. Initialize SDK with solanaPrivateKey to use Solana features.");const n=t;try{return await n.getSolanaTransactionStatus(e)}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw new Error(`Failed to query Solana transaction status: ${t}`)}}async getEthereumTransactionStatus(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridge strategy not configured. This method requires Ethereum wallet configuration. Initialize SDK with ethereumPrivateKey to use Ethereum features.");const n=t;try{return await n.getEthereumTransactionStatus(e)}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw new Error(`Failed to query Ethereum transaction status: ${t}`)}}async fetchEthereumWalletAllBalances(e){const t=this.strategies.get("Ethereum");if(!t)throw new Error("Ethereum bridging not configured. Provide ethereumPrivateKey in config.");const n=t,r=e??n.getWalletAddress(),o=Mi(this.config.environment),[i,...s]=await Promise.all([n.getEthereumNativeBalance(r),...o.map(async e=>{const t=await n.getEthereumTokenBalance(e.symbol,r);return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}})]);return{address:r,native:{symbol:"ETH",quantity:i,decimals:18,contractAddress:null,isNative:!0},tokens:s,timestamp:Date.now()}}async fetchSolanaWalletAllBalances(e){const t=this.strategies.get("Solana");if(!t)throw new Error("Solana bridging not configured. Provide solanaPrivateKey in config.");const n=t,r=e??n.getWalletAddress(),[o,...i]=await Promise.all([n.getSolanaNativeBalance(r),...Ki.map(async e=>{const t=await n.getSolanaTokenBalance(e.symbol,r);return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}})]);return{address:r,native:{symbol:"SOL",quantity:o,decimals:9,contractAddress:null,isNative:!0},tokens:i,timestamp:Date.now()}}getStrategy(e){const t=this.strategies.get(e);if(!t)throw new Error(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."));return t}}class Eb extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Sb extends Eb{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Ab extends Error{constructor(e,t,n){super(`Transaction ${e} failed with status: ${t}${n?` - ${n}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function Tb(e,t){if(!e)throw new Eb(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Eb(`Invalid WebSocket response received for transaction ${t}: expected object, got ${typeof e}`);if(!Object.prototype.hasOwnProperty.call(e,"status")&&!Object.prototype.hasOwnProperty.call(e,"Status"))throw new Eb(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Ib(e,t,n,r){Tb(e,t);const o=e,i=o.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new Eb(`Invalid trade data received for transaction ${t}`);const s={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:i.inputQuantity||r.amount,outputAmount:i.outputQuantity||r.expectedAmount||"0",totalFees:i.totalFees||"0",tokenName:r.tokenName,vaultAddress:i.vaultAddress||"",timestamp:Date.now()};return void 0!==o.blockHash&&(s.blockHash=o.blockHash),void 0!==o.gasUsed&&(s.gasUsed=o.gasUsed),void 0!==r.slippageToleranceFactor&&(s.slippageTolerance=r.slippageToleranceFactor),s}const xb="4.0.22-beta.5";class Bb{constructor(e){this.logger=e||new H({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const n=[],r=new WeakSet,o=(e,i=0)=>{if(i>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(r.has(e))return;r.add(e);const s=this.extractLiquidityFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))o(t,i+1)}};return o(e,0),n}extractLiquidityFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const n=e.Data,r=n&&"object"==typeof n&&!Array.isArray(n)?n:e,o=this.extractPositionId(r),i=this.extractPoolHash(r),s=this.extractAmounts(r),a=this.extractUserAddress(r),c=this.extractPoolFee(r);if(!(o&&i&&s&&a&&null!==c))return null;const u=this.extractPoolAlias(r),l=this.extractUserBalanceDelta(r),h=this.extractTimestamp(r),d=l?.token0Balance?.collection,f=l?.token1Balance?.collection,p={transactionId:t,positionId:o,poolHash:i,poolFee:c,amounts:s,userAddress:a};return void 0!==d&&(p.token0=d),void 0!==f&&(p.token1=f),void 0!==h&&(p.timestamp=h),void 0!==u&&(p.poolAlias=u),void 0!==l&&(p.userBalanceDelta=l),p}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","poolId","pool"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}}extractAmounts(e){const t=e.amounts;if(Array.isArray(t)&&t.length>=2){const e=String(t[0]).trim(),n=String(t[1]).trim();if(e&&n)return[e,n]}const n=e.amount0||e.amount0Desired,r=e.amount1||e.amount1Desired;return void 0!==n&&void 0!==r?[String(n),String(r)]:null}extractUserAddress(e){const t=["userAddress","user","owner","from","sender","wallet","address"];for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}return null}extractPoolFee(e){const t=["poolFee","fee","feeTier","feeTierBps"];for(const n of t){const t=e[n];if("number"==typeof t)return this.normalizeFee(t);if("string"==typeof t){const e=Number(t);if(!Number.isNaN(e))return this.normalizeFee(e)}}return null}normalizeFee(e){return 1===e||1e4===e?1e4:.3===e||3e3===e?3e3:.05===e||500===e?500:Number.isInteger(e)?e:e<1?Math.round(1e4*e):e}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if("string"==typeof t){const e=new Date(t).getTime();if(!Number.isNaN(e))return e}}}extractUserBalanceDelta(e){const t=e.userBalanceDelta;if(!t||"object"!=typeof t)return;const n=t,r=this.extractBalanceObject(n.token0Balance),o=this.extractBalanceObject(n.token1Balance);if(!r&&!o)return;const i={};return void 0!==r&&(i.token0Balance=r),void 0!==o&&(i.token1Balance=o),i}extractBalanceObject(e){if(!e||"object"!=typeof e)return;const t=e,n=t.collection,r=t.category,o=t.type,i=t.additionalKey,s=t.quantity,a=t.owner;return"string"==typeof n&&"string"==typeof r&&"string"==typeof o&&"string"==typeof i&&"string"==typeof s&&"string"==typeof a?{collection:n,category:r,type:o,additionalKey:i,quantity:s,owner:a}:void 0}}class Cb{constructor(t){this.wallet=t.wallet;let n=null,r="STAGE";t.env?(r=t.env,n=wb(t.env)):t.baseUrl?.includes("prod")?(r="PROD",n=wb("PROD")):(r="STAGE",n=wb("STAGE")),this.environment=r,this.config={baseUrl:n.launchpadBaseUrl,galaChainBaseUrl:n.galaChainBaseUrl,bundleBaseUrl:n.bundleBaseUrl,webSocketUrl:n.webSocketUrl,dexApiBaseUrl:n.dexApiBaseUrl,dexBackendBaseUrl:n.dexBackendBaseUrl,launchpadFrontendUrl:n.launchpadFrontendUrl,timeout:3e4,debug:!1,...t},this.logger=new H({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===t.slippageToleranceFactor?Cb.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(t.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===t.maxAcceptableReverseBondingCurveFeeSlippageFactor?Cb.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(t.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=t.calculateAmountMode||Cb.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=t.pricingConcurrency||5,this.galaChainAddressOverride=t.galaChainAddress,this.auth=new j({wallet:t.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new X(this.auth,this.config),this.galaChainHttp=new X(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new X(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new X(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new X(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=e.create({baseURL:this.config.galaChainBaseUrl,timeout:this.config.timeout||3e4,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.cache=new zo(t.debug||!1),this.launchpadService=new pr(this.http),this.tokenResolverService=new Po(this.launchpadService.poolService),this.launchpadAPI=new ws(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new ho(this.galaChainHttp,t.wallet,this.tokenResolverService,t.debug||!1,this.galaChainPublicAxios),this.dexService=new fo(this.dexBackendHttp,this.cache,this.galaChainService,t.debug||!1),this.bundleService=new To(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,t.wallet,t.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Co({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new Uo(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new Vo(this.galaChainHttp,this.config.galaChainBaseUrl,t.debug||!1,t.dexQuoteNetworkTimeout||3e4),this.gswapService=new Go({privateKey:t.wallet?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,galaChainBaseUrl:this.config.galaChainBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new jo(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,t.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw fe("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw fe('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new r(e),n={...this.config,wallet:t};return new Cb(n)}getAddress(){return this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw new Y("Wallet is required for this operation",void 0,"WALLET_REQUIRED");return this.wallet}setWallet(e){if(!e||"object"!=typeof e||!("address"in e))throw new Y("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}getWallet(){return this.wallet}hasWallet(){return void 0!==this.wallet}getConfig(){const{wallet:e,...t}=this.config;return{...t,environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:Wo.GAS_FEE}}getVersion(){return xb}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw fe("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e||{});return await this.warmCacheFromPools(t.pools),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.pools),t}async fetchDexPools(e={}){return this.dexPoolService.fetchDexPools(e)}async fetchAllDexPools(e={}){return this.dexPoolService.fetchAllDexPools(e)}async fetchCompositePoolData(e){return this.dexQuoteService.fetchCompositePoolData(e)}async calculateDexPoolQuoteExactAmountLocal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountLocal(e)}async calculateDexPoolQuoteExactAmountExternal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountExternal(e)}async calculateDexPoolQuoteExactAmount(e,t="local"){return this.dexQuoteService.calculateDexPoolQuoteExactAmount(e,t)}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n,currentSupply:r,calculateAmountMode:o}=e;if(t&&!n){const e={tokenName:t};return r&&(e.currentSupply=r),o&&(e.calculateAmountMode=o),this.fetchLaunchpadTokenSpotPrice(e)}if(n&&!t)try{return await this.dexService.fetchTokenPrice({tokenId:n})}catch(e){const t=function(e){if(rr(e)&&e.response)return e.response.status}(e);if(400===t||404===t){this.logger.debug(`DEX spot price not available (HTTP ${t}) for tokenId, attempting launchpad fallback`);try{const t=(await this.fetchTokenDetails(n)).name.trim().toLowerCase();if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`);const i={tokenName:t};return r&&(i.currentSupply=r),o&&(i.calculateAmountMode=o),this.fetchLaunchpadTokenSpotPrice(i)}catch(t){throw this.logger.error(`Launchpad fallback failed: ${nr(t)}`),e}}throw e}if(!t&&!n)throw le("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");throw new Y("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS")}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;return this.dexService.fetchLaunchpadTokenSpotPrice(t.tokenName,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchAllDexSeasons(){return this.dexService.fetchAllDexSeasons()}async fetchCurrentDexSeason(){return this.dexService.fetchCurrentDexSeason()}async fetchDexLeaderboardBySeasonId(e){return this.dexService.fetchDexLeaderboardBySeasonId(e)}async fetchCurrentDexLeaderboard(){return this.dexService.fetchCurrentDexLeaderboard()}async fetchDexAggregatedVolumeSummary(){return this.dexService.fetchDexAggregatedVolumeSummary()}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(!t)throw new Error(Z(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,r=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=r.currentSupply,n.reverseBondingCurveMaxFeeFactor=r.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=r.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=r.reverseBondingCurveNetFeeFactor,n.tokenName=e,n}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n=t(e)||this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=e?.solanaPrivateKey??process.env.SOLANA_PRIVATE_KEY;this._bridgeService=new vb({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:e?.ethereumPrivateKey??t.privateKey,...n&&{solanaPrivateKey:n},bridgeableTokenService:this.getBridgeableTokenService(),environment:this.environment,...this.config.ethereumRpcUrl&&{ethereumRpcUrl:this.config.ethereumRpcUrl},...this.config.solanaRpcUrl&&{solanaRpcUrl:this.config.solanaRpcUrl}})}return this._bridgeService}getBridgeableTokenService(){return this._bridgeableTokenService||(this._bridgeableTokenService=new ci(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService||(this._wrappableTokenService=new di(this.dexApiHttp,this.config.debug??!1)),this._wrappableTokenService}getGalaConnectClient(){if(!this._galaConnectClient){const e=this.getAddress();if(!e)throw new Error("GalaConnectClient requires a wallet. Configure SDK with a wallet first.");if(!this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new Ls({baseUrl:this.config.dexApiBaseUrl,...this.config.galaChainBaseUrl&&{galachainBaseUrl:this.config.galaChainBaseUrl},walletAddress:e})}return this._galaConnectClient}getWrapService(){if(!this._wrapService){const e=this.getWallet();this._wrapService=new ss({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService().fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService().fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService().fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService().fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService().requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService().getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService().getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService().fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService().fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService().isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService().isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService().isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService().fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService().fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService().getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService().getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService().isTokenWrappable(e)}async wrapToken(e){return this.getWrapService().wrapToken(e)}async unwrapToken(e){return this.getWrapService().unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService().estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService().estimateUnwrapFee(e,t)}async getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async estimateBridgeFee(e){return this.getBridgeService().estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService().bridgeOut(e)}async bridgeIn(e){return this.getBridgeService().bridgeIn(e)}async getBridgeStatus(e,t){return this.getBridgeService().getBridgeStatus(e,t)}async getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Or}),r=t(e.tokenId),{collection:o,category:i,type:s,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:o,category:i,additionalKey:a,type:s,instance:"0"},e.withExpired??!1)}if(e.tokenName){const t=e.tokenName.toUpperCase();if("MUSIC"===t||"GMUSIC"===t){const r=`$${t}`;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:"Unit",additionalKey:"none",type:"none",instance:"0"},e.withExpired??!1)}}if(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...n&&{address:n}})).tokens[0];return t?{quantity:t.quantity,collection:t.collection||"Token",category:"Unit",tokenId:`${t.collection||"Token"}|Unit|${t.symbol}|none`,symbol:t.symbol,name:t.name}:null}throw le("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:o,calculateAmountMode:i,currentSupply:s}=e;let a=t;void 0===i&&void 0===s||(a={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==s&&{currentSupply:s}});const c=await this.calculateBuyAmountForGraduation(a),u={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(u.slippageToleranceFactor=n),void 0!==r&&(u.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==o&&(u.privateKey=o),await this.buy(u)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(!n)throw pe("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Ib(t,n,"buy",e))}async sell(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(!n)throw pe("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Ib(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.launchToken(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{Tb(n,t);const r=n?.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(r))throw new Eb(`Invalid launch data received for transaction ${t}`);const o={transactionId:t,vaultAddress:r.vaultAddress||"",tokenStringKey:r.tokenStringKey||"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:r.creatorAddress||this.getAddress(),timestamp:Date.now(),...n.blockHash&&{blockHash:n.blockHash},...n.gasUsed&&{gasUsed:n.gasUsed}};return"string"==typeof e.tokenImage&&(o.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(o.preBuyQuantity=e.preBuyQuantity),o.vaultAddress&&this.tokenResolverService.set(e.tokenName,o.vaultAddress),o})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n=t(e)||this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(Ln,void 0,{"x-wallet-address":e})}async fetchReferrals(e){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return En}),r=n(e.address);if(!r)throw new Y(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=e?.page??1,r=e?.limit??10,o={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(On,o,{"x-wallet-address":t});if(!Array.isArray(i))throw new J("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=[];let n=1;let r=!0;for(;r&&n<=100;){const o=await this.fetchReferrals({...e,page:n,limit:100});t.push(...o.referrals),r=o.hasMore,n++}return{referrals:t,total:t.length}}async fetchReferralsSummary(e){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return En}),r=n(e.address);if(!r)throw new Y(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.get(Mn,void 0,{"x-wallet-address":t});if(!n||"number"!=typeof n.referralCount||!n.rewardTotals)throw new J(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async registerAccount(e){let t;if(e?.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return En}),r=n(e.address);if(!r)throw new Y(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.post($n,{address:t});if(!n||"boolean"!=typeof n.exists)throw new J(`Unexpected API response: expected { exists, walletAlias? }, got ${JSON.stringify(n)}`);if(n.exists){if(!n.walletAlias)throw new J(`Unexpected API response: exists=true but walletAlias is missing, got ${JSON.stringify(n)}`);return{exists:!0,walletAlias:n.walletAlias}}return{exists:!1,walletAlias:n.walletAlias||t}}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={...e,address:t(e.address)};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.updateProfile(r)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={...e,address:t(e.address)||this.getAddress()};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.uploadProfileImage(r)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n=t(e?.address)||this.getAddress(),r={page:e?.page||1,limit:e?.limit||10,address:n};return e?.tokenName&&(r.tokenName=e.tokenName),e?.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(n.tokenName=e.tokenName),e?.search&&(n.search=e.search),this.launchpadService.fetchTokenList(n)}async fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={...e,recipientAddress:t(e.recipientAddress)};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferGala(r)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En}),n={...e,to:t(e.to)};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferToken(r)}return this.validateWallet(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return En});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.validateWallet(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.validateWallet(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.validateWallet(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),e||(this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){if(("number"!=typeof this.config.timeout||this.config.timeout<=0||this.config.timeout>3e5)&&(this.logger.warn(`Invalid timeout value: ${this.config.timeout}. Using default 30000ms.`),this.config.timeout=3e4),!this.config.baseUrl)throw fe("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw fe("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw fe(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw fe(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw fe(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw fe(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw fe(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=parseFloat(String(e));return isNaN(t)||t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${e}, using default: ${Cb.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Cb.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=parseFloat(String(e));return isNaN(t)||t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${e}, using default: ${Cb.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Cb.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if("completed"!==n.status)throw new Ab(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof Eb)throw t;throw new Eb(`Failed to transform WebSocket response for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Ab||t instanceof Eb)throw t;throw new Eb(`WebSocket confirmation failed for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}}async warmCacheFromPools(e){if(!e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return tk});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}async getSwapQuoteExactInput(e,t,n){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:n})}async getSwapQuoteExactOutput(e,t,n){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:n})}async executeSwap(e,t,n,r,o,i=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:r,feeTier:o,slippageTolerance:i})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async fetchAvailableDexTokens(e={}){return this.gswapService.fetchAvailableDexTokens(e)}async fetchAllAvailableDexTokens(e={}){return this.gswapService.fetchAllAvailableDexTokens(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,n){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:n})}async getSwapUserLiquidityPositions(e,t,n,r){let o,i;"string"==typeof n?(o=n,i=r):"object"==typeof n?i=n:r&&(i=r);return await this.gswapService.getUserLiquidityPositions(e,t,o,i)}async getAllSwapUserLiquidityPositions(e,t){const n=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(n))return n;if(n&&"items"in n)return n.items}return n}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t,n,r,o,i,s){return this.gswapService.getLiquidityPositionById(e,t,n,r,o,i,s)}async fetchSwapPositionDirect(e){return this.gswapService.fetchSwapPositionDirect(e)}async getSwapEstimateRemoveLiquidity(e){return this.gswapService.estimateRemoveLiquidity(e)}async addSwapLiquidityByPrice(e){return this.gswapService.addLiquidityByPrice(e)}async addSwapLiquidityByTicks(e){this.validateWallet();const t={token0:e.token0,token1:e.token1,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired};return void 0!==e.amount0Min&&(t.amount0Min=e.amount0Min),void 0!==e.amount1Min&&(t.amount1Min=e.amount1Min),this.gswapService.addSwapLiquidityByTicks(t)}async removeSwapLiquidity(e){return this.validateWallet(),this.gswapService.removeLiquidity(e)}async collectSwapPositionFees(e){return this.validateWallet(),this.gswapService.collectPositionFees(e)}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onDexPoolCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const o=t?.minTVL,i=t?.tokens,s=new Map;let a=!0,c=null;let u=0;const l=async()=>{if(a){try{const t=await this.fetchDexPools({limit:20});u>0&&(this.logger.debug("Successfully recovered from polling errors"),u=0),t.pools.forEach(t=>{const n=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!s.has(n)){if((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(n),o){if((t.token0Tvl+t.token1Tvl)/2<o)return}if(i&&i.length>0){if(!(i.includes(t.token0)||i.includes(t.token1)))return}e(t)}})}catch(e){u++;const t=e instanceof Error?e.message:String(e);u>=5?this.logger.error(`Polling for new DEX pools failed ${u} consecutive times. Last error: ${t}. Continuing to retry...`):u>1?this.logger.warn(`Error polling for new DEX pools (attempt ${u}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(a){const e=Math.min(Math.max(u-1,0),2),t=r*Math.pow(2,e);c=setTimeout(l,t)}}};return l(),()=>{a=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const o=t?.creatorAddress,i=new Map;let s=!0,a=null;let c=0;const u=async()=>{if(s){try{const t=await this.fetchPools({type:"recent",limit:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.pools.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),o&&t.creatorAddress!==o||e(t))})}catch(e){c++;const t=e instanceof Error?e.message:String(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(s){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(u,t)}}};return u(),()=>{s=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}normalizeFee(e){if(null==e)return null;const t="number"==typeof e?e:Number.parseFloat(String(e).replace("%","").trim());return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:!Number.isInteger(t)||500!==t&&3e3!==t&&1e4!==t?null:t}extractField(e,...t){if("object"!=typeof e||null===e)return"";const n=e;for(const e of t)if(n[e])return String(n[e]);return""}looksLikePoolPair(e){if("string"!=typeof e)return null;const t=e.trim();if(!t.includes("/"))return null;const n=t.split("/");return 3!==n.length?null:n[0]&&n[1]&&n[2]?t:null}buildPoolPairFromObject(e){if("object"!=typeof e||null===e)return null;const t=e,n=this.extractField(t,"token0ClassKey","token0Class","token0","token0Symbol")||"",r=this.extractField(t,"token1ClassKey","token1Class","token1","token1Symbol")||"",o=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return n&&r&&null!==o?`${n}/${r}/${o}`:null}parsePoolPairString(e){const t=e.split("/");if(3!==t.length)return null;const n=t[0].split("|")[0],r=t[1].split("|")[0],o=t[2];return n&&r&&o?{token0:n,token1:r,fee:o,poolPair:e}:null}serializeBalanceToken(e){if(!e||"object"!=typeof e)return"";const t=e;return[(t.collection??t.token??"")||"",(t.category??"")||"none",(t.type??"")||"none",(t.additionalKey??"none")||"none"].join("|")}buildPoolPairFromBalances(e){if("object"!=typeof e||null===e)return null;const t=e,n=t.userBalanceDelta??t.balanceDelta??t.delta;if(!n||"object"!=typeof n||null===n)return null;const r=n,o=r.token0Balance??r.token0??r.baseBalance??r.primaryBalance,i=r.token1Balance??r.token1??r.quoteBalance??r.secondaryBalance,s=this.serializeBalanceToken(o),a=this.serializeBalanceToken(i),c=this.normalizeFee(t.poolFee??t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps);return s&&a&&null!==c?`${s}/${a}/${c}`:null}extractPoolDataFromPayload(e){if("string"==typeof e){const t=this.looksLikePoolPair(e);return t?this.parsePoolPairString(t):null}if("object"!=typeof e||null===e)return null;const t=e,n=this.looksLikePoolPair(t.poolPair);if(n)return this.parsePoolPairString(n);const r=this.buildPoolPairFromBalances(t);if(r)return this.parsePoolPairString(r);const o=this.buildPoolPairFromObject(t);if(o)return this.parsePoolPairString(o);if(t.pool&&"object"==typeof t.pool&&null!==t.pool){const e=this.extractPoolDataFromPayload(t.pool);if(e)return e}return null}matchesPoolFilter(e,t){if(t?.tokenFilter){if(!(e.token0===t.tokenFilter||e.token1===t.tokenFilter))return!1}if(t?.pairTokens){const[n,r]=t.pairTokens,o=e.token0===n||e.token1===n,i=e.token0===r||e.token1===r;if(!o||!i||n===r)return!1}if(void 0!==t?.feeTierFilter){if(this.normalizeFee(t.feeTierFilter)!==this.normalizeFee(e.fee))return!1}return!0}matchesCreatorFilter(e,t){return!t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(t?.creatorFilter?` (filter: ${t.creatorFilter})`:"")),!this.websocketService)throw new Error("WebSocket service not initialized");let n=!1,r=null;const o=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(n&&n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n={tokenName:r.tokenName||"",symbol:r.symbol||"",creatorAddress:r.creatorAddress||"",description:r.description||"",image:r.image||"",vaultAddress:r.vaultAddress||"",tokenStringKey:r.tokenStringKey||"",preBuyQuantity:r.initialBuyQuantity||"0",websiteUrl:r.websiteUrl||"",telegramUrl:r.telegramUrl||"",twitterUrl:r.twitterUrl||"",isFinalized:r.isFinalized||!1};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${e instanceof Error?e.message:String(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(o),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const s=()=>{if(i=this.websocketService.getSocket(),!i&&e<Cb.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>s(),Cb.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=Cb.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Cb.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Cb.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(o),n=!0,this.logger.debug("Token creation broadcast listener registered"))};s()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(o),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}walkPayloadForPools(e,t,n=new WeakSet){const r=[];if("string"==typeof e){const n=this.looksLikePoolPair(e);if(n){const e=this.parsePoolPairString(n);e&&!t.has(e.poolPair)&&(t.add(e.poolPair),r.push(e))}return r}if("object"!=typeof e||null===e)return r;if(n.has(e))return r;n.add(e);const o=this.extractPoolDataFromPayload(e);o&&!t.has(o.poolPair)&&(t.add(o.poolPair),r.push(o));for(const o of Object.values(e)){const e=this.walkPayloadForPools(o,t,n);r.push(...e)}return r}subscribeToDexPoolAdded(e,t){if(this.logger.debug("Subscribing to DEX pool creation broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw new Error("WebSocket service not initialized");let n=!1,r=null;const o=new Set,i=(n,...r)=>{try{for(const n of r){const r=this.walkPayloadForPools(n,o);for(const n of r)this.matchesPoolFilter(n,t)&&e(n)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${e instanceof Error?e.message:String(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(i),n=!0,this.logger.debug("DEX pool broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(s=this.websocketService.getSocket(),!s&&e<Cb.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),Cb.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=Cb.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Cb.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Cb.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX pool subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(i),n=!0,this.logger.debug("DEX pool broadcast listener registered"))};o()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX pool polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(i),n=!1,this.logger.debug("Stopped listening to DEX pool broadcasts"))}catch(e){this.logger.warn("Error removing DEX pool listener:",e)}}}subscribeToDexSwapExecuted(e,t){if(this.logger.debug("Subscribing to DEX swap execution broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw new Error("WebSocket service not initialized");let n=null,r=null,o=null,i=!1;const s=async e=>{const t=Qo.parsePoolKey(e);if(!t)throw new Error(`Invalid pool key format: ${e}`);return await this.dexQuoteService.fetchCompositePoolData({token0:t.token0,token1:t.token1,fee:t.feeTier})},a=()=>{const c=this.websocketService.getSocket();if(!c)return this.logger.debug("WebSocket not yet ready for swap monitoring, polling..."),void(n=setTimeout(()=>a(),100));i=!0,r=new ri(c,s,this.dexQuoteService,t||{},this.logger),o=r.subscribe(t||{},e),this.logger.debug("DEX swap monitoring subscription established")};return this.websocketService.getSocket()||(this.logger.debug("WebSocket not yet connected, initiating connection for swap monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed for swap monitoring: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)})),a(),()=>{try{n&&clearTimeout(n),o&&i&&o(),r&&r.shutdown().catch(e=>{this.logger.warn("Error shutting down swap monitor:",e)})}catch(e){this.logger.warn("Error cleaning up swap monitor:",e)}}}subscribeToDexLiquidityAdded(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityRemoved(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityChanged(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityEvents(e,t){if(this.logger.debug("Subscribing to DEX liquidity broadcasts"+(t?.tokenFilter?` (filter: ${t.tokenFilter})`:t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),!this.websocketService)throw new Error("WebSocket service not initialized");let n=!1,r=null;const o=new Set,i=new Bb(this.logger),s=(n,...r)=>{try{for(const n of r){const r=i.walkPayloadForLiquidityEvents(n,o);for(const n of r)if(this.matchesLiquidityFilter(n,t))try{const t=e(n);t instanceof Promise&&t.catch(e=>{this.logger.warn(`Error in liquidity event callback: ${e instanceof Error?e.message:String(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${e instanceof Error?e.message:String(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${e instanceof Error?e.message:String(e)}`)}};let a=this.websocketService.getSocket();if(a)a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection for liquidity monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${e instanceof Error?e.message:String(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(a=this.websocketService.getSocket(),!a&&e<Cb.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),Cb.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=Cb.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Cb.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Cb.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX liquidity subscription timeout:",e.message),void(t?.onError&&t.onError(e))}a&&(a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered"))};o()}return async()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX liquidity polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to DEX liquidity broadcasts"))}catch(e){this.logger.warn("Error removing DEX liquidity listener:",e)}}}matchesLiquidityFilter(e,t){if(!t)return!0;if(t.positionId&&e.positionId!==t.positionId)return!1;if(t.poolHash&&e.poolHash!==t.poolHash)return!1;if(void 0!==t.feeTierFilter){const n=this.normalizeFeeTier(t.feeTierFilter);if(e.poolFee!==n)return!1}if(t.userFilter&&e.userAddress!==t.userFilter)return!1;if(t.tokenFilter){const n=e.token0?.toLowerCase().includes(t.tokenFilter.toLowerCase()),r=e.token1?.toLowerCase().includes(t.tokenFilter.toLowerCase());if(!n&&!r)return!1}if(t.pairTokens){const[n,r]=t.pairTokens.map(e=>e.toLowerCase()),o=e.token0?.toLowerCase()||"",i=e.token1?.toLowerCase()||"",s=o.includes(n)&&i.includes(r),a=o.includes(r)&&i.includes(n);if(!s&&!a)return!1}if(t.minAmount){const n=parseFloat(t.minAmount),r=parseFloat(e.amounts[0])||0,o=parseFloat(e.amounts[1])||0;if(Math.abs(r)<n&&Math.abs(o)<n)return!1}return!0}normalizeFeeTier(e){if("number"==typeof e)return e>=100?e:Math.round(1e4*e);const t=e.replace("%","").trim(),n=parseFloat(t);return n>=100?n:Math.round(1e4*n)}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),this.websocketService&&this.websocketService.disconnect(),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new H({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:n}=require("./services/WebSocketService");n.cleanupAll(e),t.debug("Global cleanup completed")}}Cb.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Cb.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Cb.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=Wo.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Cb.DEFAULT_CALCULATE_AMOUNT_MODE=ms.LOCAL,Cb.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Cb.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,Cb.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,Cb.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class Pb{static generateWallet(){try{const e=r.createRandom();if(!e.mnemonic?.phrase)throw new Error("Failed to generate wallet with mnemonic phrase");const t=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:t,mnemonic:e.mnemonic.phrase,wallet:new r(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,t="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),n=new r(t),o=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:o,mnemonic:"test test test test test test test test test test test junk",wallet:n}}throw e}}static fromPrivateKey(e){const t=new r(e),n=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:n,mnemonic:"",wallet:t}}static fromMnemonic(e,t=0){try{const n=c.fromPhrase(e),o=u.fromMnemonic(n,`m/44'/60'/0'/0/${t}`),i=new r(o.privateKey),s=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:s,mnemonic:e,wallet:i}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${t}-${e}`,o="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),i=new r(o),s=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:s,mnemonic:e,wallet:i}}throw n}}static toGalaAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid Ethereum address format: ${e}`);return`eth|${t}`}static toEthereumAddress(e){if(!e.startsWith("eth|"))throw new Error(`Invalid Gala address format: ${e}. Must start with 'eth|'`);const t=e.slice(4);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid address in Gala format: ${e}`);return`0x${t}`}static isValidEthereumAddress(e){try{const t=e.replace(/^0x/i,"");return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){try{if(!e.startsWith("eth|"))return!1;const t=e.slice(4);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static generateMultipleWallets(e=1){if(e<1||e>100)throw new Error("Count must be between 1 and 100");const t=[];if("undefined"!=typeof process&&"test"===process.env.NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++this.testCounter}`,r="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(r))}else for(let n=0;n<e;n++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${e.mnemonic||"Not available"}`];return t?n.splice(3,0,`🔑 Private Key: ${e.privateKey}`):n.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),n.push("═".repeat(50)),n.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),n.push("This is your backup to recover the wallet."),n.join("\n")}}function Nb(e){if(void 0===e)return Pb.generateWallet();const t=e.trim();if(!t)throw new Error("Input cannot be empty string");if(function(e){const t=e.replace(/^0x/i,"");return/^[a-fA-F0-9]{64}$/.test(t)}(t))return Pb.fromPrivateKey(t);if(function(e){const t=e.split(/\s+/).filter(e=>e.length>0);if(12!==t.length&&24!==t.length)return!1;return t.every(e=>/^[a-zA-Z]+$/.test(e))}(t))return Pb.fromMnemonic(t);throw new Error(`Unable to detect input format. Expected:\n- Private key: 64 hexadecimal characters (with or without 0x prefix)\n- Mnemonic: 12 or 24 space-separated words\nReceived: "${t.slice(0,50)}${t.length>50?"...":""}"`)}function _b(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw new Error("Invalid private key format. Expected 0x-prefixed 64 hex characters.");const t=new l(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}}function Ub(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw new Error("Invalid private key format. Expected 0x-prefixed 64 hex characters.");return a(h(e))}function Db(){const e=qw.generate();return{privateKey:gb.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}}function Rb(e){e||(e={});const{wallet:t,env:n,config:o={},...i}=e,s={...i,...o},{wallet:a,env:c,config:u,...l}=s;let h;if(t)if("string"==typeof t){h=Nb(t).wallet}else{if(!(t instanceof r))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");h=t}else{h=Nb().wallet}const d={wallet:h,...n&&{env:n},debug:!1,timeout:3e4,...l};return new Cb(d)}function Fb(){const e=M.join(process.cwd(),"..","..",".env");$.existsSync(e)&&q.config({path:e});const t=M.join(process.cwd(),".env");$.existsSync(t)&&q.config({path:t})}function Lb(e,t){const n=process.env[e];if(!n){throw new Error(t?`${e} not set in root or local .env (${t})`:`${e} not set in root or local .env`)}return n}function Ob(e,t){return process.env[e]??t}Pb.testCounter=0;class Mb{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=e.galaChainAddress||process.env.WALLET_ADDRESS,o={wallet:n.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{},...r?{galaChainAddress:r}:{}},i=new Cb(o),s={sdk:i,wallet:n,config:o};if(!1!==e.autoValidate){const e=await this.validateSetup(i,n);return{...s,validation:e}}return s}static async readOnlySetup(e={}){const t=e.environment||this.detectEnvironment(),n=e.galaChainAddress||process.env.WALLET_ADDRESS,r={wallet:void 0,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{},...n?{galaChainAddress:n}:{}};return{sdk:new Cb(r),config:r}}static async validateSetup(e,t){const n=[],r=[],o={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(o.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);o.hasBalance=e>0,o.canTrade=e>=.1,o.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${e instanceof Error?e.message:String(e)}`)}try{const t=await e.fetchPools({type:"recent",page:1,limit:1});t.pools&&0!==t.pools.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${e instanceof Error?e.message:String(e)}`)}return{ready:0===n.length&&o.connectionHealthy,sdk:e,wallet:t||Pb.generateWallet(),issues:n,warnings:r,capabilities:o}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(n,{debug:!1,timeout:3e4});break;case"development":Object.assign(n,{debug:!0,timeout:45e3});break;case"testing":Object.assign(n,{debug:!0,timeout:6e4})}switch(t){case"trading":n.timeout=1.5*(n.timeout||3e4);break;case"creation":n.timeout=2*(n.timeout||3e4);break;case"monitoring":n.timeout=.5*(n.timeout||3e4)}return n}static async multiWalletSetup(e,t="development"){const n={};for(const[r,o]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:o,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){const e=process.env.NODE_ENV?.toLowerCase();return"development"===e?"development":"test"===e||"testing"===e?"testing":"production"}static setupWallet(e){if(!e){const e=process.env.PRIVATE_KEY;return e?Pb.fromPrivateKey(e):Pb.generateWallet()}return"generate"===e?Pb.generateWallet():Pb.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}}function $b(e){return e.filter(e=>new y(e.liquidity).isGreaterThan(0))}function qb(e,t){const n=new y(t);return e.filter(e=>new y(e.liquidity).isGreaterThanOrEqualTo(n))}function Kb(e,t="desc"){return[...e].sort((e,n)=>{const r=new y(e.liquidity),o=new y(n.liquidity);return"desc"===t?o.minus(r).toNumber():r.minus(o).toNumber()})}function Gb(e,t,n){const r=t.toUpperCase(),o=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return t===r&&n===o||t===o&&n===r})}function Wb(e,t){const n=t.toUpperCase();return e.filter(e=>e.token0.toUpperCase()===n||e.token1.toUpperCase()===n)}function zb(e,t){return e.filter(e=>e.feeTier===t)}function jb(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t}function Hb(e){const t=new Map;return e.forEach(e=>{t.has(e.feeTier)||t.set(e.feeTier,[]),t.get(e.feeTier).push(e)}),t}function Vb(e,t,n,r){const o=t.toUpperCase(),i=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return(t===o&&n===i||t===i&&n===o)&&e.feeTier===r})}function Xb(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t}const Qb={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"};class Zb{static fastValidation(e,t,n,r=Zb.DEFAULT_CONFIG){const o=Date.now();let i=!0;try{const s=new y(e.sqrtPrice),a=new y(t.sqrtPrice);n.zeroForOne?a.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),i=!1):a.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),i=!1);const c=new y(e.liquidity),u=new y(t.liquidity);if(!c.isZero()){const e=u.minus(c).abs().div(c);e.gt(r.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:c.toString(),updatedLiquidity:u.toString(),changePct:e.times(100).toFixed(2)})}const l=new y(e.feeGrowthGlobal0),h=new y(t.feeGrowthGlobal0),d=new y(e.feeGrowthGlobal1),f=new y(t.feeGrowthGlobal1);n.zeroForOne?f.lt(d)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:d.toString(),updatedFeeGrowth1:f.toString()}),i=!1):h.lt(l)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:l.toString(),updatedFeeGrowth0:h.toString()}),i=!1);const p=new y(e.protocolFeesToken0),g=new y(t.protocolFeesToken0),m=new y(e.protocolFeesToken1),w=new y(t.protocolFeesToken1);g.lt(p)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:p.toString(),updatedProtocolFees0:g.toString()}),i=!1),w.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:m.toString(),updatedProtocolFees1:w.toString()}),i=!1);const b=Date.now()-o;return this.logger.debug("Fast validation completed",{passed:i,elapsedMs:b}),i}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=Zb.DEFAULT_CONFIG){const r=Date.now(),o=[];let i=0;try{if(t.actualSqrtPrice){const r=new y(e.sqrtPrice),s=new y(t.actualSqrtPrice),a=this.calculateDriftPercentage(r,s);i=a,a>100*n.maxDriftThreshold&&o.push(`Price drift detected: ${a.toFixed(4)}% (threshold: ${(100*n.maxDriftThreshold).toFixed(4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:r.toString(),actualSqrtPrice:s.toString(),driftPct:a.toFixed(4)})}const s=new y(e.sqrtPrice),a=new y(2).pow(96),c=s.dividedBy(a),u=N(c),l=e.tick??0,h=Math.abs(u-l);h>n.maxTickDrift&&o.push(`Tick/price mismatch: tick=${l}, calculated=${u}, drift=${h}`);const d=new y(e.feeGrowthGlobal0),f=new y(e.feeGrowthGlobal1),p=new y(e.liquidity);try{Sr(d,f,p)}catch(e){o.push(e.message)}const g=0===o.length,m=!g||i>100*n.maxDriftThreshold,w=Date.now()-r;return this.logger.debug("Moderate validation completed",{isValid:g,shouldRefetch:m,driftPercentage:i,errorCount:o.length,elapsedMs:w}),this.buildValidationResult(g,i,m,o)}catch(e){this.logger.error("Moderate validation exception",e);const t=e instanceof Error?e.message:String(e);return this.buildValidationResult(!1,0,!0,[`Exception during validation: ${t}`])}}static async fullValidation(e,t,n){const r=Date.now(),o=[];let i=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await n(),a=new y(t.pool.sqrtPrice),c=new y(s.pool.sqrtPrice),u=this.calculateDriftPercentage(a,c);i=Math.max(i,u),u>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&o.push(`Price drift: ${u.toFixed(4)}% (cached: ${a.toString()}, fresh: ${c.toString()})`);const l=new y(t.pool.liquidity),h=new y(s.pool.liquidity),d=this.calculateDriftPercentage(l,h);i=Math.max(i,d),d>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&o.push(`Liquidity drift: ${d.toFixed(4)}% (cached: ${l.toString()}, fresh: ${h.toString()})`);const f=Object.keys(t.tickDataMap).length,p=Object.keys(s.tickDataMap).length;if(p>0){const e=Math.abs(p-f)/p;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&o.push(`Tick data incomplete: cached has ${f} ticks, fresh has ${p} ticks (${(100*e).toFixed(2)}% difference)`)}const g=0===o.length,m=!g,w=Date.now()-r;return this.logger.debug("Full validation completed",{poolKey:e,isValid:g,shouldRefetch:m,maxDriftPercentage:i,priceDrift:u,liquidityDrift:d,cachedTickCount:f,freshTickCount:p,errorCount:o.length,elapsedMs:w}),this.buildValidationResult(g,i,m,o)}catch(t){this.logger.error("Full validation exception",{poolKey:e,error:t});const n=t instanceof Error?t.message:String(t);return this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${n}`])}}static calculateDriftPercentage(e,t){if(t.isZero())return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return t.minus(e).abs().div(t).times(100).toNumber()}static buildValidationResult(e,t,n,r=[]){let o;if(n&&r.length>0){const e=r.join(" ").toLowerCase();o=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const i={isValid:e,driftPercentage:t,shouldRefetch:n,validationErrors:r};return void 0!==o&&(i.refetchReason=o),i}}Zb.logger=new H({debug:!1,context:"PoolStateValidator"}),Zb.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class Yb{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return K.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){this.logger=new H({debug:t?.debug??!1,context:"PoolStateManager"});const n={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??y.ROUND_DOWN,debug:t?.debug??!1,maxSwapsSinceRefetch:t?.maxSwapsSinceRefetch??50,maxCumulativeDrift:t?.maxCumulativeDrift??5,strictValidation:t?.strictValidation??!1,enablePerformanceWarnings:t?.enablePerformanceWarnings??!0,performanceWarningThreshold:t?.performanceWarningThreshold??100};this.config={...n,...t?.onRefetchNeeded?{onRefetchNeeded:t.onRefetchNeeded}:{}},this.validationConfig=Zb.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:Yb.calculatePoolStateHash(this.pool)};if(!Zb.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new Error("Initial pool state validation failed");this.logger.info("PoolStateManager initialized",{pool:{sqrtPrice:this.pool.sqrtPrice.toString(),liquidity:this.pool.liquidity.toString(),tick:this.pool.tick},config:this.config})}async applySwapDelta(e){const t=Date.now();if(this.metadata.processedTransactions.includes(e.transactionId))throw this.logger.warn("Duplicate swap transaction",{transactionId:e.transactionId}),new Error(`Duplicate transaction ID: ${e.transactionId}`);try{const t={pool:this.pool,tickDataMap:this.tickDataMap},n={maxIterations:this.config.maxIterations,enableBigNumberCache:this.config.enableBigNumberCache,roundingMode:this.config.roundingMode,debugLogging:this.config.debug},r=ei.calculateSwapDelta(t,e,n);this.lastSwapMetrics={calculationTimeMs:r.metadata.calculationTimeMs,swapSteps:r.metadata.swapSteps,timestamp:Date.now()},this.config.enablePerformanceWarnings&&r.metadata.calculationTimeMs>this.config.performanceWarningThreshold&&this.logger.warn("Slow swap calculation",{calculationTimeMs:r.metadata.calculationTimeMs,swapSteps:r.metadata.swapSteps,threshold:this.config.performanceWarningThreshold});if(!Zb.fastValidation(t.pool,r.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new Error("Swap validation failed");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=new y(e.actualAmount0),n=new y(e.actualAmount1),o=r.amount0.minus(t).abs(),i=r.amount1.minus(n).abs(),s=t.isZero()?0:o.div(t.abs()).times(100).toNumber(),a=n.isZero()?0:i.div(n.abs()).times(100).toNumber(),c=Math.max(s,a);c>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:c.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=c)}if((this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift)&&(this.logger.info("Triggering full refetch due to drift accumulation",{swapsSinceRefetch:this.metadata.swapsSinceRefetch,cumulativeDrift:this.metadata.cumulativeDrift.toFixed(2)}),this.config.onRefetchNeeded)){const e=await this.config.onRefetchNeeded(this.pool,this.tickDataMap);this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.metadata.stateHash=Yb.calculatePoolStateHash(this.pool),this.logger.info("Full refetch completed",{sqrtPrice:this.pool.sqrtPrice.toString()})}return this.pool=r.updatedPool,Object.assign(this.tickDataMap,r.updatedTicks),this.metadata.swapsSinceRefetch++,this.metadata.stateHash=Yb.calculatePoolStateHash(this.pool),this.metadata.processedTransactions.push(e.transactionId),this.metadata.processedTransactions.length>1e3&&(this.metadata.processedTransactions=this.metadata.processedTransactions.slice(-1e3)),this.logger.debug("Swap delta applied",{transactionId:e.transactionId,amount0:r.amount0.toString(),amount1:r.amount1.toString(),sqrtPriceNew:this.pool.sqrtPrice.toString()}),r}catch(n){const r=n instanceof Error?n.message:String(n);if(this.logger.error("Failed to apply swap delta",{transactionId:e.transactionId,error:r}),this.config.strictValidation)throw n;return{updatedPool:this.pool,updatedTicks:{},amount0:new y(0),amount1:new y(0),feeAmount0:new y(0),feeAmount1:new y(0),ticksCrossed:[],metadata:{calculationTimeMs:Date.now()-t,swapSteps:0,priceHitLimit:!1}}}}forceFullRefetch(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.logger.info("Full refetch forced",{sqrtPrice:this.pool.sqrtPrice.toString()})}getPoolState(){return this.pool}getTickDataMap(){return{...this.tickDataMap}}getMetadata(){return{...this.metadata}}getLastSwapMetrics(){if(this.lastSwapMetrics)return{...this.lastSwapMetrics}}isRefetchRecommended(){return this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift}reset(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:Yb.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}function Jb(e,t){return new Yb(e,t)}class ek extends zn{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}async resolveTokenMetadata(e){const t=this.getCacheKey(e),n=this.cache[t];if(n&&!this.isCacheExpired(n.timestamp))return this.logger.debug(`Using cached metadata for token: ${t}`),n.data;const r=this.extractMetadata(e);return this.cache[t]={data:r,timestamp:Date.now()},r}async getTokenSymbol(e){return(await this.resolveTokenMetadata(e)).symbol}async getTokenDecimals(e){return(await this.resolveTokenMetadata(e)).decimals}clearCache(e){e?(delete this.cache[e],this.logger.debug(`Cleared cache for token: ${e}`)):(this.cache={},this.logger.debug("Cleared all token metadata cache"))}getCacheStats(){const e=Object.keys(this.cache);return{size:e.length,entries:e}}getCacheKey(e){if("string"==typeof e)return e.toLowerCase();return`${e.type||e.symbol||"unknown"}|${e.additionalKey||"none"}`.toLowerCase()}extractMetadata(e){let t,n,r="Token",o="Unit",i="none";if("string"==typeof e)if(e.includes("|")){const s=e.split("|");"Token"===s[0]&&s[2]?(r=s[0],o=s[1]||"Unit",t=s[2],i=s[3]||"none",n=t):(t=s[0],n=t,o=s[1]||"Unit",i=s[3]||"none")}else t=e,n=e;else t=e.type||"unknown",r=e.collection||"Token",o=e.category||"Unit",i=e.additionalKey||"none",n=e.symbol||("Token"===r?t:r)||"unknown";const s=this.getDecimalsForToken(n);return{symbol:n.toUpperCase(),decimals:s,collection:r,category:o,type:t.toUpperCase(),additionalKey:i,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return Date.now()-e>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}}"undefined"!=typeof process&&process.env&&(process.env.CORE_CHAINCODE_LOGGING_LEVEL=process.env.CORE_CHAINCODE_LOGGING_LEVEL||"ERROR");var tk=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=parseFloat(e.reverseBondingCurveMinFeePortion);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=r}if(void 0!==e.reverseBondingCurveMaxFeePortion){const r=parseFloat(e.reverseBondingCurveMaxFeePortion);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{Mb as AgentConfig,zi as BRIDGE_CONTRACT_ABI,Gi as BRIDGE_TOKEN_METADATA,Ms as BaseBridgeStrategy,bs as BridgeRateLimiter,Os as BridgeStatusCode,eo as BurnError,Jr as BurnErrorType,ms as CALCULATION_MODES,Ai as CHAIN_IDS,Ho as COMPOSITE_POOL_FETCH_CONCURRENCY,rs as CROSS_RATE_TYPED_DATA_TYPES,ee as ConfigurationError,Ui as DEFAULT_ETHEREUM_BRIDGE_CONTRACT,Ni as DEFAULT_ETHEREUM_RPC_URL,qi as DEFAULT_ETHEREUM_TOKENS,Bi as DEFAULT_POLL_INTERVAL_MS,Ci as DEFAULT_POLL_TIMEOUT_MS,xi as DEFAULT_RATE_LIMIT_RPS,Ri as DEFAULT_SOLANA_BRIDGE_PROGRAM,_i as DEFAULT_SOLANA_RPC_URL,Ki as DEFAULT_SOLANA_TOKENS,ce as DexPoolNotFoundError,ae as DexQuoteError,Wi as ERC20_ABI,Di as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,Li as ETHEREUM_TOKENS_PROD,Oi as ETHEREUM_TOKENS_STAGE,$s as EthereumBridgeStrategy,lr as FileValidationError,Ti as GALACHAIN_CHANNELS,Fi as GALACONNECT_PRODUCTION_URL,Zi as GALA_BRIDGE_TYPED_DATA_DOMAIN,po as GALA_DECIMALS,mo as GALA_TOKEN_CLASS_KEY,ie as GSwapAssetError,oe as GSwapPoolError,ne as GSwapQuoteError,re as GSwapSwapError,Ls as GalaConnectClient,Ps as GalaConnectHttpError,it as IMAGE_EXTENSIONS,go as LAUNCHPAD_TOKEN_DECIMALS,ns as LEGACY_TYPED_DATA_TYPES,zr as LOCK_CONSTRAINTS,Cb as LaunchpadSDK,Hr as LockError,jr as LockErrorType,Yr as MAX_BURN_BATCH_SIZE,qn as MAX_CONCURRENT_POOL_FETCHES,Gr as MAX_LOCK_BATCH_SIZE,Wr as MAX_UNLOCK_BATCH_SIZE,J as NetworkError,Kn as PAGINATION_DEFAULTS,Gn as POOL_FETCH_CONFIG,gs as POOL_TYPES,Yb as PoolStateManager,Qb as QUERY_FIELD_NAMES,xo as SDKTransactionStatus,xb as SDK_VERSION,Pi as SOLANA_COMPUTE,ji as SOLANA_DISCRIMINATORS,mb as SolanaBridgeStrategy,ps as TRADING_TYPES,ek as TokenMetadataService,te as TransactionError,Ab as TransactionFailedError,Y as ValidationError,Eb as WebSocketError,Sb as WebSocketTimeoutError,Ie as addressFormatSchema,nt as amountMethodSchema,tt as amountTypeSchema,at as browserFileSchema,ct as bufferFileSchema,Pt as buyTokensDataSchema,Lt as calculatePreMintDataSchema,et as checkPoolOptionsSchema,Ss as compareAmounts,Rb as createLaunchpadSDK,Re as createLimitSchema,bt as createPaginatedResultSchema,Jb as createPoolStateManager,Db as createSolanaWallet,Ct as createTradeDataSchema,Nb as createWallet,xe as ethereumAddressSchema,Et as fetchGalaBalanceOptionsSchema,Ot as fetchPoolDetailsDataSchema,It as fetchTokenBalanceOptionsSchema,Me as fileSizeSchema,st as fileUploadSchema,$e as filenameSchema,zb as filterByFeeTier,$b as filterByLiquidity,qb as filterByMinLiquidity,Vb as filterByPoolKey,Wb as filterByToken,Gb as filterByTokenPair,Be as flexibleAddressSchema,ut as flexibleFileSchema,wo as formatGalaForDTO,bo as formatLaunchpadTokenForDTO,Es as formatTokenAmount,Qi as formatTokenDescriptor,vs as fromBaseUnits,Te as fullNameSchema,Ft as getAmountOptionsSchema,Ob as getEnv,Lb as getEnvOrThrow,Ub as getEthereumAddressFromPrivateKey,$i as getEthereumBridgeContractByEnvironment,Vi as getEthereumTokenConfig,Mi as getEthereumTokensByEnvironment,os as getGalaBridgeTypedDataTypes,_b as getPublicKeyFromPrivateKey,Xi as getSolanaTokenConfig,Hi as getStaticTokenMetadata,_t as getTradeOptionsSchema,ot as graduateTokenOptionsSchema,rt as graphDataOptionsSchema,Hb as groupByFeeTier,Xb as groupByPoolKey,jb as groupByTokenPair,lt as imageExtensionSchema,ht as imageFilenameSchema,qe as imageMimeTypeSchema,Ye as imageUploadOptionsSchema,Qr as isBurnTokenEntry,Zr as isBurnTokensData,Vr as isLockTokenData,Mr as isLockTokenEntry,qr as isLockTokensData,Xr as isUnlockTokenData,$r as isUnlockTokenEntry,Kr as isUnlockTokensData,Ii as isValidGalaChainChannel,Ke as isoDateStringSchema,Ze as launchTokenDataSchema,Fb as loadEnvWithFallback,Ne as nonNegativeDecimalStringSchema,Ue as optionalUrlSchema,De as pageNumberSchema,wt as paginationResultMetaSchema,Je as poolFetchTypeSchema,gt as poolPaginationSchema,Pe as positiveDecimalStringSchema,We as privateKeySchema,Sr as requireNonNegative,Er as requirePositive,Ar as requirePositiveWithContext,Qe as reverseBondingCurveConfigSchema,Mt as reverseBondingCurveConfigurationSchema,Ae as searchQuerySchema,Nt as sellTokensDataSchema,Kb as sortByLiquidity,Fe as standardLimitSchema,dt as standardPaginationSchema,Ge as timestampSchema,ks as toBaseUnits,Ve as tokenCategorySchema,Xe as tokenCollectionSchema,Ee as tokenDescriptionSchema,Tt as tokenHoldSchema,vt as tokenListOptionsSchema,ke as tokenNameSchema,ve as tokenSymbolSchema,He as tokenUrlsSchema,Rt as tradeCalculationMethodSchema,Dt as tradeCalculationTypeSchema,Oe as tradeLimitSchema,Ut as tradeListParamsSchema,pt as tradePaginationSchema,yt as tradePaginationWithFiltersSchema,Bt as tradeTypeBackendSchema,xt as tradeTypeSchema,ze as transactionIdSchema,je as uniqueKeySchema,St as updateProfileDataSchema,At as uploadProfileImageOptionsSchema,_e as urlSchema,Le as userLimitSchema,ft as userPaginationSchema,Se as userTokenNameSchema,kt as userTokenTypeSchema,mt as userTokensPaginationSchema,Wt as validateAddress,jt as validateAmountString,an as validateBuyTokensData,dn as validateCalculatePreMintData,Jt as validateCheckPoolOptions,sn as validateCreateTradeData,tn as validateFetchGalaBalanceOptions,fn as validateFetchPoolDetailsData,on as validateFetchTokenBalanceOptions,Ht as validateFullName,hn as validateGetAmountOptions,un as validateGetTradeOptions,Yt as validateImageUploadOptions,Qt as validateLaunchTokenData,Vt as validateSearchQuery,cn as validateSellTokensData,Gt as validateTokenDescription,en as validateTokenListOptions,qt as validateTokenName,Kt as validateTokenSymbol,Zt as validateTokenUrls,ln as validateTradeListParams,nn as validateUpdateProfileData,rn as validateUploadProfileImageOptions,Xt as validateUserTokenName,zt as validateVaultAddress,Ce as vaultAddressSchema};
|