@gala-chain/launchpad-sdk 4.0.1-beta.2 → 4.0.1-beta.3

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 CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("axios"),t=require("ethers"),o=require("@gala-chain/connect"),n=require("zod"),i=require("bignumber.js"),r=require("@gala-chain/dex"),a=require("@gala-chain/api"),s=require("uuid"),c=require("socket.io-client"),l=require("path"),u=require("fs"),d=require("dotenv"),h=require("crypto");function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(o){if("default"!==o){var n=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,n.get?n:{enumerable:!0,get:function(){return e[o]}})}}),t.default=e,Object.freeze(t)}var p,m,f=g(l),y=g(u),w=g(d);if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}!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"}(p||(p={}));class k extends Error{constructor(e,t,o){super(t),this.type=e,this.originalError=o,this.name="AuthError"}}class v{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new k(p.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 k(p.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new k(p.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,o=await this.wallet.signMessage(t);return{message:t,signature:o,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof k)throw e;throw new k(p.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 k(p.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 k(p.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 k)throw e;const t=e instanceof Error?e.message:String(e);throw new k(p.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const o=Date.now(),n=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${o}`,i=await this.wallet.signMessage(n);return{"x-signature":i,"x-address":this.formatAddress(this.wallet.address),"x-message":n,"x-timestamp":o.toString()}}catch(e){if(e instanceof k)throw e;throw new k(p.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(e)))}}async signTypedData(e,t,o){this.validateWallet();try{return await this.wallet.signTypedData(e,t,o)}catch(e){if(e instanceof k)throw e;throw new k(p.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 k(p.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 k)throw e;throw new k(p.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new k(p.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new k(p.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new k(p.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"}(m||(m={}));class T{constructor(e){this.levelPriority={[m.DEBUG]:0,[m.INFO]:1,[m.WARN]:2,[m.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?m.DEBUG:m.INFO)}debug(e,t){this.log(m.DEBUG,e,t)}info(e,t){this.log(m.INFO,e,t)}warn(e,t){this.log(m.WARN,e,t)}error(e,t){this.log(m.ERROR,e,t)}log(e,t,o){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===m.DEBUG&&!this.debugEnabled)return;const n=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==o?o instanceof Error?i(`${n} ${t}`,o.message,o.stack):i(`${n} ${t}`,o):i(`${n} ${t}`)}getConsoleMethod(e){switch(e){case m.DEBUG:return console.debug;case m.INFO:return console.info;case m.WARN:return console.warn;case m.ERROR:return console.error;default:return console.log}}child(e){return new T({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[m.DEBUG]>=this.levelPriority[this.minLevel]}}function S(e){if(!e||"object"!=typeof e)return{};const t={};for(const[o,n]of Object.entries(e))null!=n&&("string"==typeof n?t[o]=n:"number"==typeof n||"boolean"==typeof n?t[o]=n.toString():Array.isArray(n)?t[o]=n.join(","):t[o]="object"==typeof n?JSON.stringify(n):String(n));return t}class b{constructor(t,o={}){this.auth=t,this.debug=o.debug??!1,this.logger=new T({debug:this.debug,context:"HttpClient"}),this.axios=e.create({baseURL:o.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:o.timeout||3e4,headers:{Accept:"application/json",...o.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:S(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 o=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:o,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const n=await this.axios.request(t);return this.logger.debug("Response:",{status:n.status,data:n.data}),n.data}catch(e){throw this.logger.error("Error:",e),e}}async get(e,t,o){return this.request({method:"GET",url:e,...t&&{params:t},...o&&{headers:o}})}async post(e,t,o){return this.request({method:"POST",url:e,data:t,...o&&{headers:o}})}async put(e,t,o){return this.request({method:"PUT",url:e,data:t,...o&&{headers:o}})}async delete(e,t,o){return this.request({method:"DELETE",url:e,...t&&{params:t},...o&&{headers:o}})}async patch(e,t,o){return this.request({method:"PATCH",url:e,data:t,...o&&{headers:o}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,o){return await this.auth.signTypedData(e,t,o)}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=o.SigningType.SIGN_TYPED_DATA){const i=this.auth.getPrivateKey(),r=new o.SigningClient(i);return await r.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 A="Token name is required and must be a string",E=e=>`Could not find vault address for token: ${e}`;class I extends Error{constructor(e,t,o){super(e),this.field=t,this.code=o,this.name="ValidationError"}}class P extends Error{constructor(e,t,o){super(e),this.statusCode=t,this.originalError=o,this.name="NetworkError"}}class x extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class N extends Error{constructor(e,t,o){super(e),this.transactionId=t,this.code=o,this.name="TransactionError"}}class D extends Error{constructor(e,t,o){super(e),this.originalError=t,this.code=o,this.name="GSwapQuoteError"}}class F extends Error{constructor(e,t,o,n){super(e),this.originalError=t,this.transactionHash=o,this.code=n,this.name="GSwapSwapError"}}class C extends Error{constructor(e,t,o,n,i){super(e),this.originalError=t,this.tokenA=o,this.tokenB=n,this.code=i,this.name="GSwapPoolError"}}class $ extends Error{constructor(e,t,o,n){super(e),this.originalError=t,this.walletAddress=o,this.code=n,this.name="GSwapAssetError"}}class L extends Error{constructor(e,t,o){super(e),this.originalError=t,this.code=o,this.name="GSwapPositionError"}}class O extends I{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class _ extends I{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function B(e,t){return new I(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function U(e,t){const o=t||e.charAt(0).toUpperCase()+e.slice(1);return new I(`${o} is required`,e,"REQUIRED_FIELD")}function M(e,t,o){const n=o||e.charAt(0).toUpperCase()+e.slice(1);return new I(`${n} must be ${t}`,e,"INVALID_FORMAT")}function q(e,t,o){return new P(e,t,o)}function R(e,t){return new x(e,t)}function K(e,t,o){return new N(e,t,o)}function G(e,t,o){const{MIN_PAGE:n,MAX_PAGE:i,MIN_LIMIT:r,MAX_LIMIT:a}=o.PAGINATION;if("number"!=typeof e||e<n||e>i)throw new I(`Page must be a number between ${n} and ${i}`,"page","INVALID_PAGE");if("number"!=typeof t||t<r||t>a)throw new I(`Limit must be a number between ${r} and ${a}`,"limit","INVALID_LIMIT")}const z={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function W(e){return"string"==typeof e&&e.trim().length>0}function j(e){return!(!e||"string"!=typeof e)&&(z.ETH_ADDRESS.test(e)||z.BACKEND_ADDRESS.test(e))}function H(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const V=n.z.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"),Q=n.z.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"),X=n.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Z=n.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Y=n.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),J=n.z.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"),ee=n.z.string().regex(z.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),te=n.z.string().regex(z.ETH_ADDRESS,"Invalid Ethereum address format"),oe=n.z.string().refine(e=>z.BACKEND_ADDRESS.test(e)||z.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),ne=n.z.string().refine(e=>z.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),ie=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),re=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),ae=n.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),se=n.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),ce=n.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),le=n.z.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 ue(e=100){return n.z.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 de=ue(100),he=ue(20),ge=ue(20),pe=n.z.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"),me=n.z.string().max(255,"Filename must be at most 255 characters"),fe=n.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),ye=n.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),we=n.z.string().datetime("Must be a valid ISO 8601 date string"),ke=n.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),ve=n.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Te=n.z.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"),Se=n.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),be=n.z.object({websiteUrl:ce,telegramUrl:ce,twitterUrl:ce}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),Ae=n.z.string().min(1,"Token category must not be empty").default("Unit"),Ee=n.z.string().min(1,"Token collection must not be empty").default("Token"),Ie=n.z.object({minFeePortion:ie,maxFeePortion:ie}),Pe=n.z.object({tokenName:V,tokenSymbol:Q,tokenDescription:X,tokenImage:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer),n.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:re.default("0"),websiteUrl:ce,telegramUrl:ce,twitterUrl:ce,tokenCategory:Ae,tokenCollection:Ee,reverseBondingCurveConfiguration:Ie.optional(),privateKey:ve.optional()}),xe=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),tokenName:V}),Ne=n.z.enum(["recent","popular"]),De=n.z.object({tokenName:V.optional(),symbol:Q.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),Fe=n.z.enum(["NATIVE","MEME"]),Ce=n.z.enum(["IN","OUT"]),$e=n.z.object({from:n.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:n.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:n.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:V}),Le=n.z.object({tokenName:V,slippageToleranceFactor:n.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:n.z.number().min(0).max(1).optional(),privateKey:ve.optional()}),Oe=[".png",".jpg",".jpeg",".gif",".webp",".svg"],_e=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),name:me,size:pe,type:fe}),Be=n.z.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"),Ue=n.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Me=n.z.union([Be,Ue]),qe=n.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Re=me.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Oe.includes(t)},`Filename must end with one of: ${Oe.join(", ")}`),Ke=n.z.object({page:le,limit:de}),Ge=n.z.object({page:le,limit:he}),ze=n.z.object({page:le,limit:ge}),We=n.z.object({page:le,limit:ue(50)}),je=Ke.extend({type:n.z.enum(["recent","popular"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),He=Ge.extend({tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),Ve=ze.extend({tradeType:n.z.enum(["BUY","SELL"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),userAddress:n.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:n.z.string().datetime().optional(),endDate:n.z.string().datetime().optional(),sortOrder:n.z.enum(["ASC","DESC"]).default("DESC")}),Qe=n.z.object({page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()});const Xe=n.z.enum(["all","DEFI","ASSET"]),Ze=Ge.extend({type:Xe.optional(),address:oe.optional(),search:Y.optional(),tokenName:Z.optional()}),Ye=n.z.object({walletAddress:oe,amount:ae}),Je=n.z.object({address:oe.optional(),refresh:n.z.boolean().optional()}),et=n.z.object({profileImage:n.z.string(),fullName:J,address:oe,privateKey:ve.optional()}),tt=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),address:oe.optional(),privateKey:ve.optional()}),ot=n.z.object({address:oe,tokenId:n.z.union([n.z.string(),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string()}),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string(),instance:n.z.string()})]).optional(),tokenName:Z.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),nt=n.z.enum(["buy","sell"]),it=n.z.enum(["BUY","SELL"]),rt=n.z.object({tradeType:nt,tokenAmount:ie,vaultAddress:ne,userAddress:oe,slippageTolerance:ie.optional(),deadline:n.z.number().int().positive().optional()}),at=n.z.object({tokenSymbol:Q,nativeTokenQuantity:ie,expectedToken:ie,maxAcceptableReverseBondingCurveFee:re.default("0").optional()}),st=n.z.object({tokenSymbol:Q,tokenQuantity:ie,expectedNativeToken:ie,maxAcceptableReverseBondingCurveFee:re.default("0").optional()}),ct=ze.extend({tokenName:Z.optional()}),lt=n.z.object({page:n.z.number().int().min(1).max(1e3).default(1).optional(),limit:n.z.number().int().min(1).max(20).default(10).optional()}),ut=n.z.enum(["NATIVE","MEME"]),dt=n.z.enum(["IN","OUT"]),ht=n.z.object({type:ut,method:dt,vaultAddress:ne,amount:ie}),gt=n.z.object({nativeTokenQuantity:ie}),pt=n.z.object({vaultAddress:ne}),mt=n.z.object({minFeePortion:ie,maxFeePortion:ie});function ft(e){return t=>{const o=e.safeParse(t);return{success:o.success,data:o.success?o.data:void 0,errors:o.success?void 0:o.error.errors.map(e=>e.message)}}}const yt=ft(V),wt=ft(Q),kt=ft(X),vt=ft(oe),Tt=ft(ne),St=ft(ie),bt=ft(ae),At=ft(J),Et=ft(Y),It=ft(Z),Pt=ft(Pe),xt=ft(be),Nt=ft(xe),Dt=ft(De),Ft=ft(Ze),Ct=ft(Ye),$t=ft(Je),Lt=ft(et),Ot=ft(tt),_t=ft(ot),Bt=ft(rt),Ut=ft(at),Mt=ft(st),qt=ft(ct),Rt=ft(lt),Kt=ft(ht),Gt=ft(gt),zt=ft(pt);function Wt(e,t){throw new I(e.join("; "),t,"VALIDATION_ERROR")}function jt(e){const t=yt(e);!t.success&&t.errors&&Wt(t.errors,"tokenName")}function Ht(e){const t=je.safeParse(e);t.success||Wt(t.error.errors.map(e=>e.message),"pagination")}function Vt(e){const t=Dt(e);!t.success&&t.errors&&Wt(t.errors,"options")}function Qt(e){const t=Kt(e);!t.success&&t.errors&&Wt(t.errors,"options")}function Xt(e){const t=$e.safeParse(e);t.success||Wt(t.error.errors.map(e=>e.message),"options")}function Zt(e){const t=oe.safeParse(e);if(!t.success)throw new I("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Yt(e,t,o=!0){if(!e||""===e.trim())throw new I(`${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 I(`${t} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,t,"INVALID_NUMERIC_STRING");const n=parseFloat(e);if(isNaN(n))throw new I(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(n))throw new I(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(n<0)throw new I(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!o&&0===n)throw new I(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var Jt=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=oe.safeParse(e);if(!t.success)throw new I(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:Zt,validateCheckPoolOptions:Vt,validateGetAmountOptions:Qt,validateGetGraphOptions:Xt,validateNumericString:Yt,validatePagination:Ht,validateTokenName:jt});function eo(e,t){const o=e,n=Number(o.page)||t.page,i=Number(o.limit)||t.limit,r=o.data,a=Number(o.total)||Number(r?.count)||0;return{page:n,limit:i,total:a,totalPages:Math.ceil(a/i)}}function to(e,t){return{hasNext:e<t,hasPrevious:e>1}}function oo(e,t,o=!1){const n=!0===e.error||200!==e.status,i=o&&!e.data;if(n||i)throw new Error(e.message||t)}const no="/launchpad/upload-image",io="/launchpad/fetch-pool",ro="/launchpad/check-pool",ao="/launchpad/get-graph-data",so="/holders",co="/launchpad/get-badge/",lo="/trade/",uo="/token/commment",ho="/token/commment",go="/user/profile",po="/user/profile",mo="/user/token-list",fo="/user/token-hold",yo="/user/transfer-faucets",wo={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};class ko{constructor(e,t=!1){this.http=e,this.logger=new T({debug:t,context:this.constructor.name})}}class vo{constructor(e=!1){this.logger=new T({debug:e,context:this.constructor.name})}}function To(e,t){return"string"==typeof e[t]}function So(e,t){return void 0===e[t]||"string"==typeof e[t]}function bo(e,t){return void 0===e[t]||"number"==typeof e[t]}function Ao(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function Eo(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&bo(t,"from")&&bo(t,"to")&&bo(t,"resolution")}class Io extends ko{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 o=S(t),n=await this.http.get(io,o);if(!n)throw q("No response from pool service",500);oo(n,"Failed to fetch pools",!0);const i=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 o=e.tokens;t=[{...o,createdAt:o.created_at||o.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(n.data),r=n.data.count??n.data.total??0;return{pools:i,total:r,totalPages:e.limit>0?Math.ceil(r/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:o,pageSize:n,...i}=e,r=[];if(o&&o>=t){const e=[];for(let n=t;n<=o;n++)e.push(n);for(let t=0;t<e.length;t+=5){const o=e.slice(t,t+5).map(e=>this.fetchSinglePage({...i,page:e,limit:n}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e}));(await Promise.all(o)).forEach(e=>{r.push(...e.pools)})}return r}let a=t,s=!0;for(;s;){const e=[];for(let t=0;t<5&&s;t++)e.push(a+t);const t=e.map(e=>this.fetchSinglePage({...i,page:e,limit:n}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e})),o=await Promise.all(t);for(const e of o){if(0===e.pools.length){s=!1;break}r.push(...e.pools)}a+=e.length,a>wo.SAFETY_MAX_PAGES&&(s=!1)}return r}async fetchPools(e={}){const t=e.page||wo.DEFAULT_PAGE,o=e.limit??wo.DEFAULT_LIMIT;let n;if(0!==o&&Ht({page:t,limit:o}),e.tokenName&&jt(e.tokenName),"recent"===e.type?n="RECENT":"popular"===e.type&&(n="POPULAR"),o>0&&o<=20){const i=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:o});return{pools:i.pools,page:t,limit:o,total:i.total,totalPages:i.totalPages,hasNext:t<i.totalPages,hasPrevious:t>1}}if(0===o){const t=wo.BACKEND_MAX_PAGE_SIZE,o=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:1,limit:t}),i=[...o.pools];if(o.pools.length>0){const r=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:2,totalPages:o.totalPages>1?o.totalPages:null,pageSize:t});i.push(...r)}return{pools:i,page:1,limit:i.length,total:o.total||i.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const i=wo.BACKEND_MAX_PAGE_SIZE,r=Math.ceil(o/i),a=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:i}),s=[...a.pools],c=Math.min(r,a.totalPages-t+1);if(c>1){const o=t+c-1,r=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:t+1,totalPages:o,pageSize:i});s.push(...r)}const l=s.slice(0,o);return{pools:l,page:t,limit:o,total:a.total,totalPages:a.totalPages,hasNext:t<a.totalPages&&l.length<a.total,hasPrevious:t>1}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){Vt(e),e.tokenName&&jt(e.tokenName);const t=S(e),o=await this.http.get(ro,t);if(!o)throw q("No response from pool service",500);oo(o,"Failed to check pool");const n=o.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.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(!Eo(e))throw new I("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:o,to:n,resolution:i}=e;if(jt(t),!o||!n||!i)throw new I("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:o,to:n,resolution:i};Xt(r);const a=S(r),s=await this.http.get(ao,a);if(!s)throw q("No response from pool service",500);return oo(s,"Failed to fetch graph data",!0),{dataPoints:s.data}}async fetchTokenDistribution(e){if(!e)throw U("tokenName","Token name");jt(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw B(e);const o=encodeURIComponent(t),n=await this.http.get(`${so}/${o}`);if(!n)throw q("No response from pool service",500);oo(n,"Failed to fetch token distribution",!0);const r=n.data;if(!Array.isArray(r))throw q("Invalid API response: expected array of holders",n.status);for(const e of r){if(!e.owner||"string"!=typeof e.owner)throw q("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw q("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw q(`Invalid holder quantity: "${e.quantity}"`,n.status)}const a=r.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:r.map(e=>{const t=new i(e.quantity),o=a.isZero()?0:t.dividedBy(a).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:o}}),totalSupply:a.toFixed(),totalHolders:r.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw U("tokenName","Token name");jt(e);const t=await this.http.get(co,{tokenName:e});if(!t)throw q("No response from pool service",500);return oo(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:o,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const i=("volume"===o?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return i?.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 Po(e,t={}){const{stringifyFields:o=[],optionalFields:n=[],fieldMappings:i={}}=t,r={};for(const[t,a]of Object.entries(e)){const e=t;if(n.includes(e)&&void 0===a)continue;if(n.includes(e)&&"string"==typeof a&&0===a.trim().length)continue;const s=i[e],c=s?String(s):t;o.includes(e)?r[c]=String(a):r[c]=a}return S(r)}const xo={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class No extends ko{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&So(t,"userAddress")&&bo(t,"page")&&bo(t,"limit")}(e))throw new I("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:o,userAddress:n,page:i=wo.DEFAULT_PAGE,limit:r=wo.DEFAULT_LIMIT,startDate:a,endDate:s,sortOrder:c}=e;if(!W(t))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");G(i,r,xo);const l=function(e,t,o){return Po({tokenName:e,page:t,limit:o},{stringifyFields:["page","limit"]})}(t,i,r),u=await this.http.get(lo,l);if(!u)throw new I("No response from trade service","response","NO_RESPONSE");const d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const g=eo(u,{page:i,limit:r}),p=to(g.page,g.totalPages);return{trades:d,...g,...p}}}const Do=new T({debug:!1,context:"DateUtils"});function Fo(e,t){if(!e)return t||new Date;if(e instanceof Date)return isNaN(e.getTime())?t||new Date:e;try{const o=new Date(e);return isNaN(o.getTime())?(Do.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):o}catch(o){return Do.warn(`Date parsing error for "${e}":`,o),t||new Date}}const Co={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class $o extends ko{constructor(e,t,o=!1){super(e,o),this.poolService=t}async fetchComments(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&bo(t,"page")&&bo(t,"limit")}(e))throw new I("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:o=wo.DEFAULT_PAGE,limit:n=wo.DEFAULT_LIMIT}=e;if(!W(t))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");G(o,n,Co);const i=await this.poolService.resolveTokenNameToVault(t);if(!i)throw B(t);const r=Po({vaultAddress:i,page:o,limit:n},{stringifyFields:["page","limit"]}),a=await this.http.get(uo,r);if(!a)throw new I("No response from comment service","response","NO_RESPONSE");if(oo(a,"Failed to fetch comments"),!a.data)throw new I("Invalid response structure from comment service: no data field","response.data","INVALID_RESPONSE");if(0===Object.keys(a.data).length)return{comments:[],total:0};if(!Array.isArray(a.data.comments))throw new I("Invalid response structure from comment service: comments must be an array, got "+typeof a.data.comments,"response.data.comments","INVALID_RESPONSE");return{comments:a.data.comments.map(e=>({...e,createdAt:Fo(e.createdAt)})),total:a.data.count||0}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&To(t,"content")}(e))throw new I("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:o}=e;if(!W(t))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if(!function(e){if(!e||"string"!=typeof e)return!1;const t=e.trim();return t.length>=Co.CONTENT.MIN_LENGTH&&t.length<=Co.CONTENT.MAX_LENGTH}(o))throw new I(`Comment content must be between ${Co.CONTENT.MIN_LENGTH} and ${Co.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const n=await this.poolService.resolveTokenNameToVault(t);if(!n)throw B(t);const i=this.http.getAddress();if(!i)throw new I("User address not available - wallet not configured","userAddress","NO_WALLET");const r={userAddress:i,vaultAddress:n,content:o},a=await this.http.post(ho,r);if(!a)throw new I("No response from comment service","response","NO_RESPONSE");oo(a,"Failed to create comment")}}function Lo(e){return e instanceof Error}function Oo(e){return Lo(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 _o(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Bo(e,t="image",o){const n=new FormData;if("undefined"!=typeof File&&e instanceof File)n.append(t,e);else{if(!Buffer.isBuffer(e))throw M("file","a File object (browser) or Buffer (Node.js)");{const i=new Blob([e],{type:"image/png"});n.append(t,i,o)}}return n}const Uo={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},FAUCET_AMOUNT:{POSITIVE_NON_ZERO_DECIMAL:/^(?!0+(\.0+)?$)\d+(\.\d+)?$/},PROFILE:{FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}}};function Mo(e){return!(!e||"string"!=typeof e)&&Uo.USER_ADDRESS.PATTERN.test(e)}const qo="Update profile";class Ro extends ko{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!Mo(t))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const o={userAddress:t},n=await this.http.get(go,o);if(!n)throw new I("No response from user service","response","NO_RESPONSE");return n}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!t||""===t.trim())try{const o=await this.fetchProfile(e.address);t=o.data?.profileImage||""}catch{t=""}const o={profileImage:t,fullName:e.fullName,userAddress:e.address},n=await this.http.signCustomMessage(qo);if(!n)throw new I("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const i={address:n.address,message:qo,publickey:n.ethereumAddress,sign:n.signature},r=await this.http.put(po,o,i);if(!r)throw new I("No response from user service","response","NO_RESPONSE");oo(r,"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new I("Wallet address not available - wallet not configured","address","NO_WALLET");try{const o=`profile-image-${t}.png`,n=Bo(e.file,"image",o),i=await this.http.request({method:"POST",url:`${no}?tokenName=${encodeURIComponent(t)}`,data:n,headers:{}});if(!i)throw new I("No response from user service","response","NO_RESPONSE");return oo(i,"Image upload failed"),"string"==typeof i.data?i.data:""}catch(e){if(e instanceof I)throw e;throw new I(`Profile image upload failed: ${Oo(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(mo,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(fo,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=wo.DEFAULT_PAGE,limit:o=wo.DEFAULT_LIMIT,search:n,tokenName:i}=e,r=this.http.getAddress();if(!r)throw new I("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"DEFI",address:r,page:t,limit:o};return void 0!==n&&(a.search=n),void 0!==i&&(a.tokenName=i),this.fetchTokenList(a)}async buildFetchRequest(e,t,o){this.validateGetTokenListOptions(t);const n={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},i=Po(o.includeType?{...n,type:"all"!==t.type&&t.type?t.type:"DEFI"}:n,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),r=await this.http.get(e,i);if(!r)throw new I("No response from user service","response","NO_RESPONSE");oo(r,o.errorMessage,!0);const a=(s=r.data)?Array.isArray(s)?s:s.token:[];var s;const c=eo(r,{page:t.page||wo.DEFAULT_PAGE,limit:t.limit||wo.DEFAULT_LIMIT}),l=to(c.page,c.totalPages);return{tokens:a,...c,...l}}validateGetTokenListOptions(e){if(G(e.page,e.limit,Uo),void 0!==e.address&&!Mo(e.address))throw new I("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>=Uo.SEARCH.MIN_LENGTH&&t.length<=Uo.SEARCH.MAX_LENGTH))throw new I(`Search query must be between ${Uo.SEARCH.MIN_LENGTH} and ${Uo.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,o;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((o=e.tokenName)&&"string"==typeof o&&o.length>=Uo.TOKEN_NAME.MIN_LENGTH&&o.length<=Uo.TOKEN_NAME.MAX_LENGTH))throw new I(`Token name must be between ${Uo.TOKEN_NAME.MIN_LENGTH} and ${Uo.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!Mo(e.address))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=Uo.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=Uo.PROFILE.FULL_NAME.MAX_LENGTH&&Uo.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new I(`Full name must be between ${Uo.PROFILE.FULL_NAME.MIN_LENGTH} and ${Uo.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!Mo(e.address))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Ko extends Error{constructor(e,t,o){super(e),this.filename=t,this.mimeType=o,this.name="FileValidationError"}}function Go(e,t,o){if(!e)throw new Ko("File is required",t,o);if("undefined"!=typeof File&&e instanceof File){const t=Be.safeParse(e);if(!t.success){const o=t.error.errors.map(e=>e.message).join("; ");throw new Ko(o,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Ko("Filename is required when uploading Buffer objects",t,o);const n=Ue.safeParse(e);if(!n.success){const e=n.error.errors.map(e=>e.message).join("; ");throw new Ko(e,t,o)}if(t.length>255)throw new Ko(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,o);const i=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!i.includes(o))throw new Ko(`Invalid file type "${o}" is not allowed. Allowed types: ${i.join(", ")}`,t,o);const r=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),a=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!a.includes(r))throw new Ko(`File extension "${r}" is not allowed. Allowed extensions: ${a.join(", ")}`,t,o);const s=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"}}(r);if(s!==o&&"application/octet-stream"!==s)throw new Ko(`File extension "${r}" does not match MIME type "${o}"`,t,o);return}throw new Ko("File must be a File object (browser) or Buffer (Node.js)",t,o)}class zo extends ko{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:o}=e;jt(t);const n=`${t}.png`;Go(o.file,n,"image/png");try{const e=`${o.tokenName??t}.png`,n=Bo(o.file,"image",e),i=await this.http.request({method:"POST",url:`${no}?tokenName=${encodeURIComponent(o.tokenName??t)}`,data:n,headers:{}});if(!i)throw R("No response from image upload service","response");return oo(i,"Image upload failed"),"string"==typeof i.data?i.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw R("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class Wo extends ko{constructor(e,t=!1){super(e,t)}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount},o=await this.http.post(yo,t);if(!o)throw new I("No response from faucet service","response","NO_RESPONSE");oo(o,"Faucet transfer failed")}validateTransferFaucetsData(e){if(!Mo(e.walletAddress))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!Uo.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new I("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class jo{constructor(e,t=!1){this.http=e,this.poolService=new Io(e,t),this.tradeService=new No(e,t),this.commentService=new $o(e,this.poolService,t),this.userService=new Ro(e,t),this.imageService=new zo(e,t),this.faucetService=new Wo(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 fetchComments(e){return this.commentService.fetchComments(e)}async postComment(e){return this.commentService.postComment(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)}async transferFaucets(e){return this.faucetService.transferFaucets(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return jt(e)}}const Ho={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var Vo;!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"}(Vo||(Vo={}));class Qo extends Error{constructor(e,t,o){super(e),this.type=t,this.details=o,this.name="TransferError"}}function Xo(e,t="0"){return new i(null==e||""===e?t:e)}function Zo(e){return r.tickToSqrtPrice(e)}function Yo(e){const t=Xo(e),o=Math.log(1.0001),n=t.toNumber();return Math.log(n)/o}function Jo(e,t=!1){const o=Xo(e),n=new i(1).dividedBy(o);return t?n.toFixed():n}function en(...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 tn(e,t,o){if(e.isNaN())throw new Error(`${t} must be a valid number, got: NaN`);if(!e.isFinite()){const n=o?`${t} must be finite ${o}, got: ${e.toString()}`:`${t} must be finite, got: ${e.toString()}`;throw new Error(n)}if(e.isLessThanOrEqualTo(0)){const n=o?`${t} must be positive ${o}, got: ${e.toString()}`:`${t} must be positive, got: ${e.toString()}`;throw new Error(n)}}class on{static validateAmount(e){const t=new i(e);try{tn(t,"amount","for transfer")}catch(t){throw new Qo(t.message,Vo.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(e){if(e.length>Ho.MAX_UNIQUE_KEY_LENGTH)throw new I(`Unique key too long. Maximum length: ${Ho.MAX_UNIQUE_KEY_LENGTH}`);if(!Ho.UNIQUE_KEY_PATTERN.test(e))throw new Qo('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Vo.INVALID_AMOUNT,{uniqueKey:e})}}}class nn{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 rn(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function an(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[o,n,i,...r]=t;if(!o||!n||!i)throw new Error("Collection, category, and type must be non-empty");const a=r.join("$");if(!a)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:n,type:i,additionalKey:a}}catch(t){throw new I(`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 sn extends o.ChainCallDTO{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,o,n,i){let r;if("string"==typeof n){r={...an(n),instance:"0"}}else r={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new sn({from:e,to:t,quantity:o,tokenInstance:r,uniqueKey:i||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,o,n){return new sn({from:e,to:t,quantity:o,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:n||`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 cn extends o.ChainCallDTO{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,o,n,i){let r;if("string"==typeof n){r={...an(n),instance:"0"}}else r={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new cn({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:o,tokenInstanceKey:r}],...void 0!==i?.expires&&{expires:i.expires},...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,o,n){return new cn({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:o,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==n?.expires&&{expires:n.expires},...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{lockAuthority:this.lockAuthority,tokenInstances:this.tokenInstances,...void 0!==this.expires&&{expires:this.expires},...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class ln extends o.ChainCallDTO{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,o,n){let i;if("string"==typeof o){i={...an(o),instance:"0"}}else i={collection:o.collection,category:o.category,type:o.type,additionalKey:o.additionalKey,instance:"0"};return new ln({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:i}],...void 0!==n?.name&&{name:n.name},uniqueKey:n?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,o){return new ln({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==o?.name&&{name:o.name},uniqueKey:o?.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 un{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},o={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,o,e),domain:t,types:o,signerPublicKey:this.wallet.signingKey.publicKey}}async signLockToken(e){const t={name:"GalaChain",chainId:1},o={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"}]},n={lockAuthority:e.lockAuthority,tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.expires&&(n.expires=e.expires),void 0!==e.name&&(n.name=e.name);return{signature:await this.wallet.signTypedData(t,o,n),domain:t,types:o,signerPublicKey:this.wallet.signingKey.publicKey}}async signUnlockToken(e){const t={name:"GalaChain",chainId:1},o={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"}]},n={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.name&&(n.name=e.name);return{signature:await this.wallet.signTypedData(t,o,n),domain:t,types:o,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const o=e.replace("0x","");return`eth|${t.ethers.getAddress(`0x${o}`).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{...an(e),instance:"0"}}}function dn(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new I(`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 I(`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 I("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 I(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function hn(e){try{const[t,o]=e.split("|");if(!o)throw new Error("Missing token part after service");const n=o.split("$");if(n.length<4)throw new Error(`Invalid vault address format. Expected at least 4 parts separated by $, got ${n.length}`);if(!(n[0]&&n[1]&&n[2]&&n[3]))throw new Error("All vault address components (collection, category, type, additionalKey) must be non-empty");const i=n.slice(3,-1),r=i.length>0?i.join("$"):n[3];return{collection:n[0],category:n[1],type:n[2],additionalKey:r}}catch(t){throw new I(`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 gn(e){return{...hn(e),instance:"0"}}function pn(e){return hn(e).type}var mn,fn=Object.freeze({__proto__:null,extractTokenSymbolFromVault:pn,normalizeToTokenInstanceKey:dn,parseVaultAddressToTokenClassKey:hn,parseVaultAddressToTokenInstance:gn});function yn(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 wn(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)}exports.LockErrorType=void 0,(mn=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",mn.INVALID_AMOUNT="INVALID_AMOUNT",mn.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",mn.SIGNATURE_FAILED="SIGNATURE_FAILED",mn.NETWORK_ERROR="NETWORK_ERROR",mn.WALLET_REQUIRED="WALLET_REQUIRED",mn.LOCK_NOT_FOUND="LOCK_NOT_FOUND",mn.LOCK_EXPIRED="LOCK_EXPIRED",mn.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",mn.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",mn.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class kn extends Error{constructor(e,t,o){super(e),this.type=t,this.details=o,this.name="LockError"}}const vn="gala-transfer-successful",Tn="token-transfer-successful",Sn="transfer-successful-no-id";class bn extends ko{constructor(e,t,o,n=!1,i){super(e,n),this.wallet=t,this.tokenResolver=o,this.publicAxios=i,this.signatureHelper=t?new un(t):void 0}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw q("No response from GalaChain service",500);if(1!==t.Status)throw q(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const o=t.Data.reverseBondingCurveConfiguration,n=o?.minFeePortion??"0",i=o?.maxFeePortion??"0",r=(await import("bignumber.js")).default,a=!new r(n).isZero()||!new r(i).isZero(),s=t.Data;return s.reverseBondingCurveMinFeePortion=n,s.reverseBondingCurveMaxFeePortion=i,s.hasReverseBondingCurveFee=a,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(!e)throw q("No response from GalaChain service",500);if(1!==e.Status)throw q(`Failed to fetch launch token fee: Status ${e.Status}`,e.Status);return e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.vaultAddress)throw new I("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new I("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new I("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e){try{const t=await this.http.post("/api/asset/token-contract/FetchBalances",e);if(!t)return null;if(1!==t.Status||!t.Data||0===t.Data.length)return null;const o=t.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 n=`${o.collection}|${o.category}|${o.additionalKey}|${o.type}`;return{quantity:o.quantity,collection:o.collection,category:o.category,tokenId:n}}catch(e){throw q(`Failed to fetch token balance from GalaChain: ${Oo(e)}`,void 0,Lo(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?dn(e):e,o={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]},n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",o)).data;if(1!==n.Status)throw q(`Failed to fetch token class from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw q(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return n.Data[0]}catch(e){if(_o(e)&&404===e.response?.status)throw q("Token not found on GalaChain",404,Lo(e)?e:void 0);const t=Oo(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw q(`Failed to fetch token class from GalaChain: ${t}`,void 0,Lo(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw new I("tokenClasses array must not be empty");const t={tokenClasses:e},o=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(1!==o.Status)throw q(`Failed to fetch token classes with supply from GalaChain: Status ${o.Status}${o.Message?` - ${o.Message}`:""}`,o.Status);if(!o.Data||0===o.Data.length)throw q("No token supply data found for requested token classes",404);return o.Data}catch(e){if(_o(e)&&404===e.response?.status)throw q("Token supply data not found on GalaChain",404,Lo(e)?e:void 0);const t=Oo(e);if(t.includes("Token")||t.includes("Status")||t.includes("tokenClasses"))throw e;throw q(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,Lo(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new Qo("Wallet required for GALA transfer operations",Vo.WALLET_REQUIRED);try{const t=H(e.recipientAddress),o=H(this.wallet.address),n=sn.forGALA(o,t,e.amount,e.uniqueKey),i=await this.signatureHelper.signTransferToken(n.toSigningPayload()),r=new sn({...n.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(r,null,2));const a=await this.http.post("/api/asset/token-contract/TransferToken",r);if(!a)throw new Qo("No response from GalaChain transfer service",Vo.NETWORK_ERROR);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(a,null,2)),this.extractTransactionIdFromResponse(a,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new Qo("Wallet required for token transfer operations",Vo.WALLET_REQUIRED);try{const t=H(e.to),o=H(this.wallet.address);let n;if(e.tokenId)n=dn(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",JSON.stringify(n,null,2));else{if(!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const i=new sn({from:o,to:t,quantity:e.amount,tokenInstance:n,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),r=await this.signatureHelper.signTransferToken(i.toSigningPayload()),a=new sn({...i.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(a,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",a);if(!s)throw new Qo("No response from GalaChain transfer service",Vo.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"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 Qo)throw t;throw new Qo(`Failed to resolve token class key for '${e}': ${Oo(t)}`,Vo.TOKEN_NOT_FOUND,{tokenName:e})}}async lockToken(e){if(this.validateLockTokenData(e),!this.wallet||!this.signatureHelper)throw new Qo("Wallet required for token lock operations",Vo.WALLET_REQUIRED);try{const t=H(this.wallet.address),o=e.lockAuthority?H(e.lockAuthority):t;let n;if(e.tokenId)n=dn(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId);else{if(!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const i=new cn({lockAuthority:o,tokenInstances:[{owner:t,quantity:e.amount,tokenInstanceKey:n}],...void 0!==e.expires&&{expires:e.expires},...void 0!==e.name&&{name:e.name},uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),r=await this.signatureHelper.signLockToken(i.toSigningPayload()),a=new cn({...i.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full Lock Request Payload:",JSON.stringify(a,null,2));const s=await this.http.post("/api/asset/token-contract/LockToken",a);if(!s)throw new Qo("No response from GalaChain lock service",Vo.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token lock response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"token")}catch(t){throw this.handleTransferError(t,"Token lock failed",e)}}async unlockToken(e){if(this.validateUnlockTokenData(e),!this.wallet||!this.signatureHelper)throw new Qo("Wallet required for token unlock operations",Vo.WALLET_REQUIRED);try{const t=H(this.wallet.address);let o;if(e.tokenId)o=dn(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId);else{if(!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);o=await this.resolveTokenInstance(e.tokenName)}const n=new ln({tokenInstances:[{owner:t,quantity:e.amount,tokenInstanceKey:o}],...void 0!==e.name&&{name:e.name},uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),i=await this.signatureHelper.signUnlockToken(n.toSigningPayload()),r=new ln({...n.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full Unlock Request Payload:",JSON.stringify(r,null,2));const a=await this.http.post("/api/asset/token-contract/UnlockToken",r);if(!a)throw new Qo("No response from GalaChain unlock service",Vo.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token unlock response:",JSON.stringify(a,null,2)),this.extractTransactionIdFromResponse(a,"token")}catch(t){throw this.handleTransferError(t,"Token unlock failed",e)}}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 I("Invalid GALA transfer data: missing required fields");if(!j(e.recipientAddress))throw new Qo("Invalid recipient address format",Vo.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});on.validateAmount(e.amount),on.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 I("Invalid token transfer data: missing required fields");if(!j(e.to))throw new Qo("Invalid recipient address format",Vo.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);if(e.tokenName&&!Ho.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Qo("Invalid token name format",Vo.TOKEN_NOT_FOUND,{tokenName:e.tokenName});on.validateAmount(e.amount),on.validateUniqueKey(e.uniqueKey)}validateLockTokenData(e){if(!yn(e))throw new I("Invalid lock token data: missing required fields");if(e.lockAuthority&&!j(e.lockAuthority))throw new Qo("Invalid lock authority address format",Vo.INVALID_RECIPIENT,{recipientAddress:e.lockAuthority});if(!e.tokenId&&!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);if(e.tokenName&&!Ho.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Qo("Invalid token name format",Vo.TOKEN_NOT_FOUND,{tokenName:e.tokenName});if(void 0!==e.expires&&(e.expires<=0||!Number.isInteger(e.expires)))throw new I("Expires must be a positive integer (epoch milliseconds)");on.validateAmount(e.amount),on.validateUniqueKey(e.uniqueKey)}validateUnlockTokenData(e){if(!wn(e))throw new I("Invalid unlock token data: missing required fields");if(!e.tokenId&&!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);if(e.tokenName&&!Ho.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Qo("Invalid token name format",Vo.TOKEN_NOT_FOUND,{tokenName:e.tokenName});on.validateAmount(e.amount),on.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Qo(`Token '${e}' not found or not available for transfer`,Vo.TOKEN_NOT_FOUND,{tokenName:e});const o=this.resolveTokenInstanceFromVaultAddress(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}':\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(o,null,2)}`),o}catch(t){if(t instanceof Qo)throw t;throw new Qo(`Failed to resolve token '${e}': ${Oo(t)}`,Vo.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){try{return gn(e)}catch(e){if(e instanceof I)throw new Qo(`Invalid vault address format: ${e.message}`,Vo.TOKEN_NOT_FOUND);throw new Qo(`Failed to parse vault address: ${e instanceof Error?e.message:String(e)}`,Vo.TOKEN_NOT_FOUND)}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const o=e;return Array.isArray(o.Data)&&o.Data.length>0?"gala"===t?vn:Tn:Sn}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Qo("Transfer succeeded but transaction ID could not be extracted",Vo.NETWORK_ERROR)}handleTransferError(e,t,o){if(e instanceof Qo)return e;if(e instanceof I)return new Qo(e.message,Vo.INVALID_AMOUNT);if(_o(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t)return new Qo(("string"==typeof n?.message?n.message:void 0)||"Invalid transfer request",Vo.INVALID_AMOUNT);if(403===t)return new Qo("Insufficient balance for transfer",Vo.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in o&&(e.tokenName=o.tokenName),new Qo("Token not found",Vo.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new Qo("Transfer request timed out",Vo.NETWORK_ERROR);const n=Oo(e);return new Qo(n||t,Vo.NETWORK_ERROR)}}class An{constructor(e,t,o,n=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=o,this.logger=new T({debug:n,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:o}=e;if(!t&&!o)throw U("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&o)throw new I("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS");if(o)return this.logger.debug(`Fetching spot price by tokenId: ${o}`),this._fetchDexTokenSpotPrice(o);throw new I("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw U("tokenId","Token ID");try{const t=dn(e),o=rn(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${o}`),!this.dexBackendHttp)throw q("DEX Backend API client not configured");const n=await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:o}});if(!n.data||"string"!=typeof n.data)throw new I("Invalid price response: data must be a string, got "+typeof n.data,"data","INVALID_RESPONSE");const i=parseFloat(n.data);if(isNaN(i))throw new I(`Invalid price value: could not parse "${n.data}" as number`,"data","INVALID_CALCULATION");const r=`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`;let a;try{if(this.cache){const e=this.cache.getByTokenId(r);if(e?.symbol)return a=e.symbol,this.logger.debug(`DEX spot price for ${a} (cached): $${i}`),{symbol:a,price:i}}this.logger.debug(`Symbol cache miss for ${r}, fetching from API`);a=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(r,{symbol:a}),this.logger.debug(`Cached symbol for ${r}: ${a}`)),this.logger.debug(`DEX spot price for ${a}: $${i}`)}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)}`),a=("Token"===t.collection?t.type:t.collection).toUpperCase(),this.logger.debug(`DEX spot price for ${a} (fallback): $${i}`)}return{symbol:a,price:i}}catch(e){if(e instanceof I)throw e;throw q(`Failed to fetch DEX spot price: ${Oo(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,o){if(!e||"string"!=typeof e)throw new Error(A);try{if(o)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await o(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const o=`${t.sellingToken.collection}|${t.sellingToken.category}|${t.sellingToken.type}|${t.sellingToken.additionalKey}`;return this._fetchDexTokenSpotPrice(o)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Oo(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),i=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(!i)throw q("GALA price not available");const r=Number(n.amount)/1e18;if(r<=0)throw new I(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const a=i.price/r;return{symbol:e.toUpperCase(),price:a}}catch(t){if(t instanceof Error)throw q(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw q(`Failed to calculate launchpad token spot price for ${e}: ${Oo(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw q("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),o={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`),o}catch(t){if((t instanceof I||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw q(`Failed to fetch token details from GalaChain for ${e}: ${Oo(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw q("DEX Backend API client not configured");const e=(await this.dexBackendHttp.request({method:"GET",url:"/leaderboard/seasons"})).data.map(e=>({id:e.id,name:e.name,start:new Date(e.start),end:new Date(e.end),rulesId:e.rules_id}));return this.logger.debug(`Fetched ${e.length} DEX seasons`),e}catch(e){if(e instanceof Error&&e.message.includes("not configured"))throw e;throw q(`Failed to fetch DEX seasons: ${Oo(e)}`)}}async fetchCurrentDexSeason(){const e=await this.fetchAllDexSeasons(),t=new Date,o=e.find(e=>t>=e.start&&t<=e.end);return o?this.logger.debug(`Current DEX season: ${o.name} (ID: ${o.id})`):this.logger.debug("No active DEX season found"),o||null}async fetchDexLeaderboardBySeasonId(e){if(!e||"number"!=typeof e||e<1)throw U("seasonId","Season ID must be a positive number");try{if(!this.dexBackendHttp)throw q("DEX Backend API client not configured");const t=(await this.dexBackendHttp.request({method:"GET",url:"/leaderboard",params:{seasonId:e.toString()}})).data.leaderboard.map(e=>({wallet:e.wallet,rank:e.rank,totalXp:e.total_xp,distributionPercent:e.distribution_percent,liquidityXp:e.liquidity_xp,tradingXp:e.trading_xp,masteryTitles:e.mastery_titles.map(e=>({name:e.name,type:e.type,order:e.order}))}));return this.logger.debug(`Fetched leaderboard for season ${e} with ${t.length} entries`),{entries:t,seasonId:e,totalEntries:t.length}}catch(t){if(t instanceof Error&&t.message.includes("must be a positive number"))throw t;throw q(`Failed to fetch DEX leaderboard for season ${e}: ${Oo(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 q("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 q(`Failed to fetch DEX volume summary: ${Oo(e)}`)}}}function En(e,t=18){const o=parseFloat(e);if(0===o)return"0";return o.toFixed(t).replace(/\.?0+$/,"")}function In(e){return En(e,8)}function Pn(e){return En(e,18)}function xn(e){return{maxAcceptableReverseBondingCurveFee:In(e.maxAcceptableReverseBondingCurveFee)}}new T({debug:!1,context:"NumberUtils"});class Nn extends o.ChainCallDTO{constructor(e,t,o="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=In(t),this.expectedToken=Pn(o),this.extraFees=xn(n)}}class Dn extends o.ChainCallDTO{constructor(e,t,o,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Pn(t),this.expectedNativeToken=In(o),this.extraFees=xn(n)}}class Fn extends o.ChainCallDTO{constructor(e,t,o="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Pn(t),this.expectedNativeToken=In(o),this.extraFees=xn(n)}}class Cn extends o.ChainCallDTO{constructor(e,t,o,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=In(t),this.expectedToken=Pn(o),this.extraFees=xn(n)}}const $n={BuyNativeDto:Nn,BuyExactDto:Dn,SellExactDto:Fn,SellNativeDto:Cn};class Ln extends vo{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),i=o.calculatePersonalSignPrefix(e),r={...e,prefix:i},{signature:a,domain:s}=await this.signWithEthersWallet(n,r),c={...e,signature:a,types:n,domain:s};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(c),signatureLength:a.length}),c}catch(e){this.logger.error("❌ Signature generation failed:",e);throw K(`Failed to sign DTO: ${Oo(e)}`)}}async signWithEthersWallet(e,t){try{let o,n;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)o={name:"ethereum",chainId:1},n=await this.walletProvider.signTypedData(o,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw R("Wallet provider does not support typed data signing","walletProvider");{const i=await this.walletProvider.getNetwork();o={name:i.name,chainId:Number(i.chainId)},n=await this.walletProvider.signTypedData(o,e,t)}}return{signature:n,domain:o}}catch(e){throw K(`Ethers.js signing failed: ${Oo(e)}`)}}generateEIP712Types(e,t){const o={};o[e]=[];const n=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),i=(e,t,n,r=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const a=i(e,t[0],n,!0);return r||o[n].push({name:e,type:(a??e)+"[]"}),a?a+"[]":void 0}if("object"==typeof t&&null!==t){if(o[e])throw new I(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return o[e]=[],Object.entries(t).forEach(([t,o])=>{i(t,o,e)}),r||o[n].push({name:e,type:e}),e}{let i;switch(typeof t){case"string":i="string";break;case"number":i="uint256";break;case"boolean":i="bool";break;default:throw new I(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return r||o[n].push({name:e,type:i}),i}}};return Object.entries(n).forEach(([t,o])=>{i(t,o,e)}),this.logger.debug("📝 Generated EIP-712 types:",o),o}}class On extends vo{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),o=this.createTokenInstance(t),n=this.createGalaInstance(),i=`$service$${o.toStringKey()}$launchpad`,r=`$tokenBalance$${o.toStringKey()}$${e}`,a=`$tokenBalance$${o.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,c=[i,r,a,s,`$tokenBalance$${n.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Oo(e);throw new I(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new a.TokenClassKey;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 a.TokenClassKey;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 U("vaultAddress","Vault address");try{const t=pn(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof I)throw M("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!e||"string"!=typeof e)throw U("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw M("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw M("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw M("vaultAddress",'having at least 5 parts separated by "$"');const o=t[2];if(!o||!/^[A-Za-z]{1,10}$/.test(o))throw M("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,o,n){return`${e}$${t}$${o}$${n}`}parseTokenClassKeyString(e){try{return an(e)}catch(e){if(e instanceof I)throw M("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function _n(e,t,o){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 n=new i(e);if(n.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const r=n.multipliedBy(t);let a;switch(o){case"buy-native":case"sell-exact":a=n.minus(r);break;case"buy-exact":case"sell-native":a=n.plus(r);break;default:throw new Error(`Unknown operation type: ${o}`)}return a.isLessThan(0)&&(a=new i(0)),a.toFixed()}class Bn extends ko{constructor(e,t,o=!1,n,i,r=.05,a=.01){super(e,o),this.tokenResolver=t,this.walletProvider=n,this.userAddress=i,this.defaultSlippageToleranceFactor=r,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.bundleEndpoint="/bundle",n&&i&&(this.signatureService=new Ln(n,o),this.tokenKeyService=new On(o))}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 o=await this.http.post(this.bundleEndpoint,t);return o?(this.logger.debug("📥 Bundle API response:",{success:o.success,hasData:!!o.data,error:o.error}),this.handleBundleResponse(o)):{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 U("bundleData","Bundle data");if(!e.signedDto)throw U("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw U("method","Method name");if(!Array.isArray(e.stringsInstructions))throw M("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new I("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw M("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new I(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new I(`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(_o(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 Oo(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw U("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 U("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:o,type:n,expectedAmount:i}=e,{effectiveSlippageFactor:r,effectiveMaxFee:a,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===n){if(!i)throw new I("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=_n(i,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:r,adjustedMinTokens:e});const t=new $n.BuyNativeDto(s,o,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyWithNative",s)}{if(!i)throw new I("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=_n(i,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:r,adjustedMaxGalaCost:e});const t=new $n.BuyExactDto(s,o,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyExactToken",s)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:o,type:n,expectedAmount:i}=e,{effectiveSlippageFactor:r,effectiveMaxFee:a,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===n){if(!i)throw new I("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=_n(i,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:r,adjustedMinGala:e});const t=new $n.SellExactDto(s,o,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"SellExactToken",s)}{if(!i)throw new I("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=_n(i,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:r,adjustedMaxTokensToSell:e});const t=new $n.SellNativeDto(s,o,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"SellWithNative",s)}}async prepareTradingOperation(e,t,o,n){const{effectiveSlippageFactor:i,effectiveMaxFee:r}=this.calculateEffectiveSlippage(t,o,n),a=await this.resolveTokenNameToVault(e);if(!a)throw B(e);return{effectiveSlippageFactor:i,effectiveMaxFee:r,vaultAddress:a}}calculateEffectiveSlippage(e,t,o){const n=o??this.defaultSlippageToleranceFactor,i=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let r=e||"0";return e&&(r=_n(e,i,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:i,adjustedMaxFee:r})),{effectiveSlippageFactor:n,effectiveFeeSlippageFactor:i,effectiveMaxFee:r}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw R("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw U("userAddress","User address")}async executeBundleTransaction(e,t,o){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${s.v4()}-${Date.now()}-${this.userAddress}`;const n=await this.signatureService.signDTO(e,t,this.userAddress),i=this.tokenKeyService.generateStringsInstructions(o),r={stringsInstructions:i,method:t,signedDto:n};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:i,dtoKeys:Object.keys(n)});const a=await this.submitTransaction(r);if(a.success&&a.data)return this.logger.debug("✅ Bundle transaction submitted:",a.data),{success:!0,data:{transactionId:a.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(a.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 Un,Mn;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Un||(Un={})),exports.SDKTransactionStatus=void 0,(Mn=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",Mn.PROCESSING="processing",Mn.COMPLETED="completed",Mn.FAILED="failed",Mn.TIMEOUT="timeout";const qn={[Un.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[Un.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[Un.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[Un.FAILED]:exports.SDKTransactionStatus.FAILED,[Un.ERROR]:exports.SDKTransactionStatus.FAILED,[Un.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[Un.PENDING]:exports.SDKTransactionStatus.PENDING};class Rn extends vo{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 c.io||(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=c.io(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 o=t[0],n=o.status||o.Status;if(n&&"string"==typeof n){if(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${n}`),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,o);const t=this.eventBufferTimeouts.get(e);t&&clearTimeout(t);const i=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,i)}}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 o=this.eventBuffer.get(e);if(o){this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,o,t)});const n=this.eventBufferTimeouts.get(e);n&&(clearTimeout(n),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e)}const n=this.config.timeout||3e5,i=setTimeout(()=>{if(this.listeners.has(e)){const o=Math.round(n/1e3),i={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${o} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${o}s)`),t(i),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},n);if(this.timeouts.set(e,i),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,o=>{this.processTransactionEvent(e,o,t)});else{const o={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(o),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,o){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const n=t,i=n?.data,r=n?.status||n?.Status||i?.status||i?.Status;let a=n?.message||n?.Message||i?.message||i?.Message||n?.error||i?.error;a&&"string"==typeof a||(a=r===Un.FAILED||r===Un.ERROR?"Transaction failed - check transaction details":r===Un.COMPLETED||r===Un.PROCESSED||r===Un.SUCCESS?"Transaction completed successfully":r?`Transaction status: ${r}`:"Unknown transaction status");const s=n?.blockHash||i?.blockHash,c=n?.gasUsed||i?.gasUsed,l=n?.Data||i?.Data,u={transactionId:e,status:this.mapSocketStatus(r),message:"string"==typeof a?a:"Transaction update received",timestamp:Date.now(),...s&&{blockHash:s},...c&&{gasUsed:c},...l&&{data:l}};if(this.logger.debug(`📡 Mapped status for ${e}: ${r} -> ${u.status}`),this.logger.debug(`📡 Final message: "${a}"`),o(u),u.status===exports.SDKTransactionStatus.COMPLETED||u.status===exports.SDKTransactionStatus.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} (${u.status})`)}}async waitForTransaction(e){return new Promise((t,o)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||o(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return qn[t]||exports.SDKTransactionStatus.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 Kn extends vo{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!W(e))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");const t=e.trim().toLowerCase(),o=this.get(t);if(o)return o;try{const o=await this.poolService.resolveTokenNameToVault(e);return o&&this.set(t,o),o}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw B(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:o}of e)this.set(t,o)}parseVaultAddressToTokenClassKey(e){try{return hn(e)}catch(e){if(e instanceof I)throw M("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}async function Gn(e,t={}){const{maxPages:o=1e4,logger:n,pageSize:i=20}=t,r=[];let a=1,s=!0,c=0;for(;s&&a<=o;){n&&n.debug(`Auto-pagination: fetching page ${a} with limit ${i}`);const t=await e(a,i);if(!t||!Array.isArray(t.items)){n&&n.warn("Auto-pagination: received invalid result structure, stopping");break}if(r.push(...t.items),c=t.total,n&&n.debug(`Auto-pagination: page ${a} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){n&&n.debug(`Auto-pagination: no items returned on page ${a}, exiting loop`);break}s=t.hasNext,a++}return a>o&&n&&n.warn(`Auto-pagination: exceeded maxPages limit of ${o}, stopping iteration`),n&&n.debug(`Auto-pagination: completed with total items: ${r.length}, total count: ${c}`),{items:r,total:c}}function zn(e,t=e.length,o="items"){return{...{page:1,limit:e.length||0,total:t,totalPages:Math.ceil(t/(e.length||1))||1,hasNext:!1,hasPrevious:!1},[o]:e}}class Wn extends ko{constructor(e,t=!1,o){super(e,t),this.tokenResolverService=o}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw R("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 R("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 R(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const o=hn(t),n=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`;return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(t instanceof Error&&t.message.includes("ConfigurationError"))throw t;throw q(`Failed to resolve token name '${e}': ${Oo(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 o=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=o,this.logger.debug(`Resolved to token ID: ${o}`)}if(!t)throw R("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:o}=await Promise.resolve().then(function(){return fn}),n=o(t),i=rn(`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`),{from:r,to:a,sortOrder:s="DESC",page:c=1,limit:l=10}=e,u={token:i,page:String(c),limit:String(l)};r&&(u.from=r.toISOString()),a&&(u.to=a.toISOString());const d=function(e){if(e)return e.toLowerCase()}(s);d&&(u.order=d),this.logger.debug(`Querying price snapshots for token ${i}, page ${c}, limit ${l}`);const h=await this.http.get("/price-oracle/fetch-price",u);if(!h)throw q("No response from price history service",500);const g=this.transformApiResponseToPriceHistory(h);return this.logger.debug(`Found ${g.snapshots.length} price snapshots, total ${g.total}`),g}catch(e){if(e instanceof Error&&(e.message.includes("ConfigurationError")||e.message.includes("NetworkError")))throw e;throw q(`Failed to fetch price history: ${Oo(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw q("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw q("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}`})),o=e.data.meta,n=o.currentPage??1,i=o.totalPages??1;return{snapshots:t,page:n,limit:o.pageSize??50,total:o.totalItems??0,totalPages:i,hasNext:n<i,hasPrevious:n>1}}async fetchAllPriceHistory(e){this.logger.debug("Fetching all price history with options:",e);const t=await Gn((t,o)=>this.fetchPriceHistory({...e,page:t,limit:o}).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 zn(t.items,t.total,"snapshots")}validateOptions(e){const{from:t,to:o,sortOrder:n,page:i=1,limit:r=10}=e;if(function(e,t,o,n={}){const{description:i="parameter",treatEmptyAsNull:r=!0}=n,a=e[t],s=e[o],c=null!=a&&(!r||""!==a),l=null!=s&&(!r||""!==s);if(!c&&!l)throw R(`Either ${t} or ${o} must be provided (${i})`,o);if(c&&l)throw R(`Cannot provide both ${t} and ${o}. Provide exactly one (${i}).`,o)}(e,"tokenName","tokenId",{description:"token identifier"}),t&&!(t instanceof Date)&&isNaN(new Date(t).getTime()))throw R("from must be a valid Date","from");if(o&&!(o instanceof Date)&&isNaN(new Date(o).getTime()))throw R("to must be a valid Date","to");if(n&&"ASC"!==n&&"DESC"!==n)throw R('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(i)||i<1)throw R("page must be a positive integer","page");if(!Number.isInteger(r)||r<1||r>50)throw R("limit must be between 1 and 50","limit")}}function jn(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new I("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:o,type:n,additionalKey:i}=e;if(!t||"string"!=typeof t)throw new I("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!o||"string"!=typeof o)throw new I("Token.category must be a non-empty string, got "+typeof o,"token.category","MISSING_OR_INVALID_CATEGORY");if(!n||"string"!=typeof n)throw new I("Token.type must be a non-empty string, got "+typeof n,"token.type","MISSING_OR_INVALID_TYPE");if(!i||"string"!=typeof i)throw new I("Token.additionalKey must be a non-empty string, got "+typeof i,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:o,type:n,additionalKey:i}}(e);if(!e)throw new I(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new I("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[o,n,i,...r]=t;if(!o||!n||!i)throw new Error("Collection, category, and type must be non-empty");const a=r.join("|");if(!a)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:n,type:i,additionalKey:a}}catch(t){const o=e.split("|");throw new I(`Invalid pipe-delimited token: "${e}" (${o.length} parts). Expected format: "collection|category|type|additionalKey" (4 parts minimum). Received: [${o.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 o=t[t.length-1],n=t[t.length-2],i=t[t.length-3],r=t.slice(0,t.length-3).join("$");if(!(r&&i&&n&&o))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:r,category:i,type:n,additionalKey:o}}catch(t){const o=e.split("$");throw new I(`Invalid dollar-delimited token: "${e}" (${o.length} parts). Expected format: "collection$category$type$additionalKey" (4 parts minimum). Received: [${o.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e);throw new I(`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 Hn extends Error{constructor(e,t,o){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=o,this.name="ApiError"}}function Vn(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 Qn(e){return"object"==typeof e&&null!==e&&"positionId"in e&&"owner"in e&&"token0"in e&&"token1"in e&&"fee"in e&&"liquidity"in e&&"string"==typeof e.positionId&&"string"==typeof e.owner&&"number"==typeof e.fee}class Xn{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 o=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&&Vn(t.token0ClassKey)&&Vn(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}(o))throw new Hn(t.status,"Invalid pool data response format",o);return o}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 o=t.data.Data;if(!Array.isArray(o.positions))throw new Hn(t.status,"Invalid positions response format: positions must be an array",o);for(const e of o.positions)if(!Qn(e))throw new Hn(t.status,"Invalid position in response",e);return o}catch(e){throw this.handleError(e,"getPositions")}}async getPositionById(e,t,o,n,i,r,a){try{let s,c;if(void 0!==t&&void 0!==o&&void 0!==n&&void 0!==i&&void 0!==r){s={owner:e,token0:"string"==typeof t?{collection:t,category:"Unit",type:"none",additionalKey:"none"}:t,token1:"string"==typeof o?{collection:o,category:"Unit",type:"none",additionalKey:"none"}:o,fee:n,tickLower:i,tickUpper:r},a&&(s.positionId=a),c=`${e}/${t}/${o}/${n}`}else s={positionId:e},c=e;const l=await this.client.post("/api/asset/dexv3-contract/GetPositions",s);this.validateResponse(l.data);const u=l.data.Data;let d;if(u&&"object"==typeof u&&"positionId"in u&&!("positions"in u))d=u;else{if(!(u&&Array.isArray(u.positions)&&u.positions.length>0))throw new Hn(404,`Position not found: ${c}`);d=u.positions[0]}const h={Data:d,Status:l.status};return void 0!==l.data.Message&&(h.Message=l.data.Message),h}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 o=t.data.Data;if("string"!=typeof o.amount0||"string"!=typeof o.amount1||"string"!=typeof o.fee0||"string"!=typeof o.fee1)throw new Hn(t.status,"Invalid removal estimation response format",o);return o}catch(e){throw this.handleError(e,"getRemoveLiquidityEstimation")}}validateResponse(e){if(!e||"object"!=typeof e)throw new Hn(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new Hn(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new Hn(e.Status,e.Message??"Gateway error",e.Data)}handleError(t,o){if(t instanceof Hn)return t;if(e.isAxiosError(t)){const e=t.response?.status??500,n=t.response?.data?.Message??t.message,i=t.response?.data?.Data??void 0;return new Hn(e,`${o}: ${n}`,i)}return new Hn(500,`${o}: ${t instanceof Error?t.message:String(t)}`)}}class Zn{constructor(e){this.http=e}async getUserAssets(e,t=20,o=0){try{if(!e||"string"!=typeof e)throw new Hn(400,"Invalid wallet address");const n=Math.max(1,Math.floor(o/t)+1),i={};i.address=e,i.page=n,i.limit=t;const r=await this.http.get("/user/assets",i);if(!r||"object"!=typeof r)throw new Hn(500,"Invalid response format: not an object");const a=r.data;if(!a||"object"!=typeof a)throw new Hn(500,"Invalid response format: missing data wrapper");const s=a.token;if(!Array.isArray(s))throw new Hn(500,"Invalid response format: token array must be an array");const c=[];for(const e of s){if("object"!=typeof e||null===e)throw new Hn(500,"Invalid asset in response: asset must be an object");const t=e;if("string"!=typeof t.symbol||"string"!=typeof t.name)throw new Hn(500,"Invalid asset in response: missing symbol or name",t);const o="number"==typeof t.decimals?t.decimals:"string"==typeof t.decimals?parseInt(t.decimals,10):void 0;if("number"!=typeof o||isNaN(o))throw new Hn(500,"Invalid asset in response: decimals must be a number",t);const n={tokenId:t.compositeKey||`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:o,balance:t.quantity||"0"};t.image&&(n.imageUrl=t.image),t.verify&&(n.verified=t.verify),c.push(n)}const l={tokens:c,count:a.count??c.length};return void 0!==a.totalValue&&(l.totalValue=a.totalValue),l}catch(t){throw this.handleError(t,`getUserAssets(${e})`)}}handleError(e,t){if(e instanceof Hn)return e;if(e instanceof Error&&e instanceof Error&&"response"in e){const o=e,n=o.response?.status??500,i=o.response?.data?.message??o.response?.data?.Message??o.message,r=o.response?.data?.Data??o.response?.data?.data??void 0;return o.response,new Hn(n,`${t}: ${i}`,r)}return new Hn(500,`${t}: ${e instanceof Error?e.message:String(e)}`)}}const Yn=10;class Jn extends vo{constructor(e,t,o){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new nn,this.webSocketService=t,this.dexQuoteService=o,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 Xn({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new Zn(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 i(e.amount).isLessThanOrEqualTo(0))throw new D("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new D("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),o=this.tokenConverter.toLaunchpadFormat(e.toToken),n=[3e3,500,1e4];let r;for(const a of n)try{const n=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:o,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),r=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:n,fromToken:t,toToken:o,amount:e.amount}),s=new i(r.currentSqrtPrice),c=new i(r.newSqrtPrice),l=s.gt(c)?s.minus(c).dividedBy(s):new i(0),u=new i(r.amount0),d=new i(r.amount1),h=u.isNegative(),g=d.isNegative();this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":r.amount0,"quoteResult.amount1":r.amount1,"amount0BN.isNegative()":h,"amount1BN.isNegative()":g});const p=h?u:d;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:h,selectedAmount:p.toFixed(),selectedAmountAbs:p.absoluteValue().toFixed()});const m=p.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:r.currentSqrtPrice,newSqrtPrice:r.newSqrtPrice}}catch(e){r=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e instanceof Error?e.message:"Unknown error"})}throw r||new D("No available fee tiers for quote",{feeTiers:n,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",D,e)}}async getSwapQuoteExactOutput(e){try{if(new i(e.amount).isLessThanOrEqualTo(0))throw new D("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new D("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),o=this.tokenConverter.toLaunchpadFormat(e.toToken),n=[3e3,500,1e4];let r;for(const a of n)try{const n=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:o,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),r=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:n,fromToken:t,toToken:o,amount:e.amount}),s=new i(r.currentSqrtPrice),c=new i(r.newSqrtPrice),l=s.gt(c)?s.minus(c).dividedBy(s):new i(0),u=n.pool.token0,d="string"==typeof u?u.split("|")[0]:"object"==typeof u&&null!==u&&"tokenName"in u?u.tokenName:String(u),h=o.split("|")[0]===d?r.amount1:r.amount0;return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:h,estimatedOutput:e.amount,feeTier:a,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(h,e.amount),currentSqrtPrice:r.currentSqrtPrice,newSqrtPrice:r.newSqrtPrice}}catch(e){r=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e instanceof Error?e.message:"Unknown error"})}throw r||new D("No available fee tiers for quote",{feeTiers:n,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",D,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:o}=this.convertTokenPair(e.fromToken,e.toToken),n=function(e,t=.01){const o=Xo(e),n=new i(1).minus(t);return o.multipliedBy(n)}(e.estimatedOutput,e.slippageTolerance||.01),r=this.getWalletAddress();if(!r)throw new Error("Wallet address required for swap execution");let a;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});a=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:a,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:o,inputAmount:e.inputAmount,minOutput:n.toFixed(),feeTier:e.feeTier,walletAddress:r,slippageTolerance:e.slippageTolerance||.01};void 0!==a&&(s.currentSqrtPrice=a);const c=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:c,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const l=await this.webSocketService.waitForTransaction(c);return{transactionId:l.transactionId,status:l.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(l.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(c)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",F,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,o=20){try{this.logger.debug("Fetching user assets",{walletAddress:e,page:t,limit:o});const n=await this.dexBackendClient.getUserAssets(e,o,(t-1)*o);return(Array.isArray(n)?n:n?.tokens||[]).map(e=>{const t=e.symbol||"UNKNOWN";try{return{tokenId:jn(`${t}|Unit|none|none`),symbol:t,balance:(o=e.quantity||e.balance||0,void 0!==n?Xo(o).toFixed(n):Xo(o).toFixed()),decimals:e.decimals||18}}catch(o){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:o instanceof Error?o.message:String(o),assetData:{symbol:t,quantity:e.quantity,balance:e.balance,decimals:e.decimals}}),null}var o,n}).filter(e=>null!==e)}catch(n){this.handleGSwapError("Failed to fetch user assets",$,n,{walletAddress:e,page:t,limit:o})}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets (auto-paginated)",{walletAddress:e});const t=await Gn((t,o)=>this.getUserAssets(e,t,o).then(e=>({items:e,page:t,limit:o,total:e.length,totalPages:1,hasNext:e.length===o,hasPrevious:t>1})),{maxPages:1e4,logger:this.logger,pageSize:20});return this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:t.items.length}),t.items}catch(t){this.handleGSwapError("Failed to fetch all user assets",$,t,{walletAddress:e})}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:o,gswapToken1:n}=this.convertTokenPair(e,t),r=[500,3e3,1e4];let a=new i(0),s=0;for(const c of r)try{const e="string"==typeof o?jn(o):o,t="string"==typeof n?jn(n):n,r=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:c});r&&(a=a.plus(new i(r.liquidity||0)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:c})}return{tokenA:e,tokenB:t,liquidity:a.toFixed(),feeTiers:r,swapCount:s}}catch(o){this.logger.warn("Failed to fetch pool info",o);const n=o;return this.logger.debug("Pool error details",{error:new C(`Failed to fetch pool info: ${n?.message||String(o)}`,o,e,t,this.extractGSwapErrorCode(o))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const o=[];for(let n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const o=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;o.has(e)||o.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const n=Array.from(o.values()),i=this.chunkArray(n,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:o.size,chunks:i.length,concurrency:t});const r=new Map;for(let e=0;e<i.length;e++){const t=i[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?r.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return r}normalizePositionResponse(e,t){const o=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""};return{positionId:e.positionId||e.id||"",ownerAddress:t||e.ownerAddress||e.owner||"",token0:e.token0Symbol||o(e.token0)||o(e.tokenA)||e.tokenSymbol0||"",token1:e.token1Symbol||o(e.token1)||o(e.tokenB)||e.tokenSymbol1||"",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 jn(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}}async getUserLiquidityPositions(t,o=10,n,i){try{this.logger.debug("Fetching user liquidity positions",{ownerAddress:t,limit:o,bookmark:n});const r=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,a={user:t,limit:o,bookmark:n||""};this.logger.debug("Sending position query request",{endpoint:r,payload:a});const s=await e.post(r,a,{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==s.status||1!==s.data?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:s.status,apiStatus:s.data?.Status}),{items:[]};const c=s.data.Data||{},l=c.positions||[],u=c.nextBookMark,d=l.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(e=>this.normalizePositionResponse(e,t));let h;this.logger.debug("Retrieved liquidity positions",{count:d.length,hasNextBookmark:!!u,nextBookmark:u}),i?.withPrices&&d.length>0&&(h=await this.fetchPositionPrices(d));const g={items:d};return void 0!==u&&(g.nextBookmark=u),void 0!==h&&(g.prices=h),g}catch(e){if(e&&"object"==typeof e&&"response"in e){const o=e;this.logger.error("Position query failed with HTTP error",{status:o.response?.status,statusText:o.response?.statusText,data:o.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:t})}this.handleGSwapError("Failed to fetch user liquidity positions",L,e)}}async getAllSwapUserLiquidityPositions(e,t){try{this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const o=async t=>{const o=await this.getUserLiquidityPositions(e,Yn,t,void 0);return{items:o.items,nextBookmark:o.nextBookmark}},n=await async function(e,t={}){const{maxPages:o=1e4,logger:n,pageSize:i=20}=t,r=[];let a,s=0;for(;s<o;){n&&n.debug(`Auto-pagination (bookmark): fetching page ${s+1} with pageSize ${i}`,{bookmark:a});const t=await e(a,i);let o,c,l;if(Array.isArray(t))o=t,c=void 0,l=!1;else{if(!t||"object"!=typeof t||!("items"in t)){n&&n.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}o=t.items,c=t.nextBookmark,l=!0}if(!Array.isArray(o)){n&&n.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===o.length){n&&n.debug(`Auto-pagination (bookmark): no items returned on page ${s+1}, exiting loop`);break}r.push(...o),s++,n&&n.debug(`Auto-pagination (bookmark): page ${s} returned ${o.length} items`,{hasNextBookmark:!!c,format:l?"BookmarkPaginationResult":"legacy-array"});const u=o.length<i;if(l&&(""===c||void 0===c)){n&&n.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(u){n&&n.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:o.length,pageSize:i,format:l?"BookmarkPaginationResult":"legacy-array"});break}a=c}return s>=o&&n&&n.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${o}, stopping iteration`),n&&n.debug(`Auto-pagination (bookmark): completed with total items: ${r.length}`,{pageCount:s}),{items:r,total:r.length}}(o,{maxPages:1e4,logger:this.logger,pageSize:Yn}),i=n.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:i.length}),t?.withPrices&&i.length>0){return{items:i,prices:await this.fetchPositionPrices(i)}}return i}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",L,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t});const{gswapToken0:o,gswapToken1:n}=this.convertTokenPair(t.token0,t.token1),i=(await this.gatewayClient.getPositions({owner:e,tokenA:o,tokenB:n,feeTier:t.fee})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!i||"object"!=typeof i||!("positionId"in i)&&!("id"in i))throw new Error("Invalid position data returned from API");const r=this.normalizePositionResponse(i,e);return this.logger.debug("Retrieved liquidity position",{positionId:r.positionId}),r}catch(e){this.handleGSwapError("Failed to fetch liquidity position",L,e)}}async getLiquidityPositionById(e,t,o,n,i,r,a){try{let s;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:!!o,hasToken1:!!n,hasFee:!!i,hasTickLower:void 0!==r,hasTickUpper:void 0!==a});let c=null;const l=5,u=2e3;for(let d=1;d<=l;d++)try{if(o&&n&&void 0!==i&&void 0!==r&&void 0!==a)try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:o,token1:n,feeTier:i,tickLower:r,tickUpper:a});if(s=(await this.gatewayClient.getPositionById(e,o,n,i,r,a,t)).Data,s&&"object"==typeof s&&("positionId"in s||"id"in s)){this.logger.debug("Successfully fetched position via compound key",{attempt:d,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:d,error:e instanceof Error?e.message:e})}try{if(s=(await this.gatewayClient.getPositionById(t)).Data,s&&"object"==typeof s&&("positionId"in s||"id"in s)){this.logger.debug("Successfully fetched position on attempt",{attempt:d,positionId:t});break}throw new Error("Invalid position data from direct lookup")}catch(o){this.logger.debug("Direct position lookup failed, trying fallback via GetUserPositions",{attempt:d,positionId:t,error:o instanceof Error?o.message:o});const n=await this.getUserLiquidityPositions(e,10);if(Array.isArray(n.items)&&n.items.length>0){const e=n.items.find(e=>(e.positionId||e.id||"").toLowerCase()===t.toLowerCase());if(e){s=e,this.logger.debug("Found position via fallback (GetUserPositions)",{attempt:d,positionId:t});break}}if(c=new Error("Position not found in owner positions"),d<l){this.logger.warn("Fallback query did not find position, retrying",{attempt:d,positionId:t,ownerAddress:e,foundCount:Array.isArray(n?.items)?n.items.length:0}),await new Promise(e=>setTimeout(e,u));continue}}}catch(e){if(d<l){this.logger.warn("Error fetching position, retrying",{attempt:d,positionId:t,error:e instanceof Error?e.message:e}),await new Promise(e=>setTimeout(e,u));continue}c=e instanceof Error?e:new Error(String(e))}if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw this.logger.error("Invalid position data returned from API after retries",{positionId:t,resultType:typeof s,resultKeys:s?Object.keys(s):"null",resultValue:JSON.stringify(s),lastError:c?.message}),c||new Error("Invalid position data returned from API");const d=this.normalizePositionResponse(s,e);return this.logger.debug("Retrieved liquidity position by ID",{positionId:d.positionId}),d}catch(e){this.handleGSwapError("Failed to fetch liquidity position by ID",L,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,o={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},n=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetPositions`;this.logger.debug("Calling position endpoint via compound key",{url:n});const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(o)});if(!i.ok){if(404===i.status)throw new Error("Position not found (HTTP 404): No position exists for this compound key");if(400===i.status)throw new Error("Invalid parameters (HTTP 400): Check token format, fee (500|3000|10000), and tick ranges");throw new Error(`HTTP ${i.status}: ${i.statusText}`)}const r=await i.json();if(1!==r.Status||!r.Data)throw new Error(`Position not found: ${r.Message||"API returned no position data"}`);const a=this.normalizePositionResponse(r.Data,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:a.positionId,token0:a.token0,token1:a.token1}),a}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",L,e)}}async estimateRemoveLiquidity(e){try{this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1});const{gswapToken0:t,gswapToken1:o}=this.convertTokenPair(e.token0,e.token1),n=await this.gatewayClient.getRemoveLiquidityEstimation({tokenA:t,tokenB:o,fee:e.fee,liquidity:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper});return this.logger.debug("Estimated removal",{result:n}),n}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",L,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:o}=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 n=jn(t),r=jn(o),a=(await this.gatewayClient.getPoolData({token0:n,token1:r,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:a,fee:e.fee});const s=new i(e.minPrice),c=new i(e.maxPrice),l=Math.floor(Yo(s)),u=Math.ceil(Yo(c)),d=Math.floor(l/a)*a,h=Math.ceil(u/a)*a;this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:d,tickUpper:h,tickSpacing:a});const g=this.getWalletAddress();if(!g)throw new Error("GSwapService: No wallet address available - cannot create position");const p="string"==typeof e.token0?jn(e.token0):e.token0,m="string"==typeof e.token1?jn(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${d}-${h}`,walletAddress:g});const f=await this.sendAddLiquidityToBundler({token0:p,token1:m,fee:e.fee,tickLower:d,tickUpper:h,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:g}),y={transactionId:f};if(y.positionId&&f){this.logger.debug("Position ID returned directly from backend",{transactionId:f,positionId:y.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(f);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:f,status:e.status});const t=this.getWalletAddress();if(t&&y.positionId)try{const o=await this.getLiquidityPositionById(t,y.positionId),{createdAt:n,updatedAt:i,...r}=o,a=n instanceof Date?n.getTime():"number"==typeof n?n:void 0,s={...y,...r,positionId:y.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}};return void 0!==a&&(s.createdAt=a),s}catch(t){return{...y,positionId:y.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}}}}if(f){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:f}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(f);let o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:f,status:t.status});let n=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");const i=(await this.getUserLiquidityPositions(t,10)).items;if(i&&i.length>0){const t=e.token0.split("|")[0].toUpperCase(),r=e.token1.split("|")[0].toUpperCase(),a=[];for(const o of i){if(!o||!o.positionId)continue;const n=o.token0?.toUpperCase(),i=o.token1?.toUpperCase();if(!n||!i)continue;const s=n===t&&i===r||n===r&&i===t,c=o.feeTier===e.fee;s&&c&&a.push(o)}a.length>0&&(n=a[a.length-1],o=n.positionId,this.logger.debug("Found newly created position",{positionId:o,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:i.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}let i=n;if(o)try{i=await this.getLiquidityPositionById(g,o)}catch(e){}return{...y,...i,positionId:o,status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),y}catch(e){Error,this.handleGSwapError("Failed to add liquidity by price",L,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 o="string"==typeof e.token0?jn(e.token0):e.token0,n="string"==typeof e.token1?jn(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendAddLiquidityToBundler({token0:o,token1:n,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:i});const r=this.webSocketService.waitForTransaction(i),a={transactionId:i};if(a.positionId&&i){this.logger.info("Position ID returned directly from backend",{transactionId:i,positionId:a.positionId});const e=await r;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:e.status});const t=this.getWalletAddress();if(t&&a.positionId)try{this.logger.debug("Fetching full position details",{positionId:a.positionId});const o=await this.getLiquidityPositionById(t,a.positionId);this.logger.debug("Fetched full position data",{positionId:o.positionId,liquidity:o.liquidity,amount0:o.amount0,amount1:o.amount1});const{createdAt:n,updatedAt:r,...s}=o,c=n instanceof Date?n.getTime():"number"==typeof n?n:void 0,l={...a,...s,positionId:a.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}};return void 0!==c&&(l.createdAt=c),l}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:a.positionId,error:t instanceof Error?t.message:String(t)}),{...a,positionId:a.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}}if(i){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:i});const o=await r;let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:o.status});let s=null;const c="string"==typeof e.token0?e.token0:e.token0.type,l="string"==typeof e.token1?e.token1:e.token1.type;this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:l,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:Yn});const o=3,i=5e3,r=3e3;let a=[];for(let c=1;c<=o;c++){const l=1===c?i:r;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:o,delayMs:l}),await new Promise(e=>setTimeout(e,l)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:Yn});if(a=(await this.getUserLiquidityPositions(t,Yn)).items,this.logger.debug("Got positions from API",{count:a?.length||0}),a&&a.length>0){const t=("string"==typeof e.token0?e.token0.split("|")[0]:e.token0.collection).toUpperCase(),o=("string"==typeof e.token1?e.token1.split("|")[0]:e.token1.collection).toUpperCase(),i=[];for(const n of a){if(!n||!n.positionId)continue;const r=n.token0?.toUpperCase(),a=n.token1?.toUpperCase();if(!r||!a){this.logger.debug("Skipping position with empty tokens",{positionId:n.positionId});continue}const s=r===t&&a===o||r===o&&a===t,c=n.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:n.positionId,tokens:`${r}/${a}`,tokensMatch:s,fee:n.feeTier,feeMatches:c}),s&&c&&i.push(n)}if(i.length>0){s=i[i.length-1],n=s.positionId,this.logger.info("Found newly created position",{positionId:n,liquidity:s.liquidity,amount0:s.amount0,amount1:s.amount1,fee:s.feeTier}),this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:a.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:n||"not found",found:!!n}),this.logger.debug("Matched position data",{positionId:s?.positionId,liquidity:s?.liquidity,amount0:s?.amount0,amount1:s?.amount1,feeAmount0:s?.feeAmount0,feeAmount1:s?.feeAmount1,token0:s?.token0,token1:s?.token1,feeTier:s?.feeTier});let u=s;if(n)try{this.logger.debug("Fetching full position details",{positionId:n}),u=await this.getLiquidityPositionById(t,n),this.logger.debug("Fetched full position data",{positionId:u.positionId,liquidity:u.liquidity,amount0:u.amount0,amount1:u.amount1,feeAmount0:u.feeAmount0,feeAmount1:u.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:n,error:e instanceof Error?e.message:String(e)})}return{...a,...u,positionId:n,status:o.status,transactionId:o.transactionId,timestamp:new Date(o.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),a}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",L,e)}}async monitorBundlerTransaction(e,t,o="bundler"){let n;try{const i=await t;n={status:i.status,transactionId:i.transactionId||e,timestamp:i.timestamp||Date.now(),data:i.data},this.logger.debug(`${o} transaction confirmed on-chain`,{transactionId:e,status:n.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${o} 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:n.transactionId,status:n.status,timestamp:new Date(n.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?jn(e.token0):e.token0,o="string"==typeof e.token1?jn(e.token1):e.token1;await this.ensureWebSocketConnected();const n=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,o,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||"");this.logger.debug("Liquidity removal submitted to bundler",{transactionId:n});const i=this.webSocketService.waitForTransaction(n);return this.monitorBundlerTransaction(n,i,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",L,e)}}async collectPositionFees(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0.type,token1:"string"==typeof e.token1?e.token1:e.token1.type,tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?jn(e.token0):e.token0,o="string"==typeof e.token1?jn(e.token1):e.token1;await this.ensureWebSocketConnected();const n=await this.sendCollectPositionFeesToBundler(t,o,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||"");this.logger.debug("Fee collection submitted to bundler",{transactionId:n});const i=this.webSocketService.waitForTransaction(n);return this.monitorBundlerTransaction(n,i,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",L,e)}}async getPoolData(e,t,o){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:o});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),a=jn(n),s=jn(r),c=await this.gatewayClient.getPoolData({token0:a,token1:s,fee:o}),l=this.calculatePriceFromSqrtPriceX96(new i(c.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:o,liquidity:c.liquidity.toString(),sqrtPriceX96:c.sqrtPrice.toString(),tick:c.tick,feeGrowthGlobal0X128:c.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:c.feeGrowthGlobal1.toString(),currentPrice:l.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",C,e)}}async calculateDexPoolSpotPrice(e,t,o){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:o});const n=await this.getPoolData(e,t,o),i=Xo(n.currentPrice);return{tokenA:e,tokenB:t,feeTier:o,price:i.toFixed(),invertedPrice:Jo(i,!0),tick:n.tick,liquidity:n.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",C,e)}}async calculateOptimalPositionSize(e,t,o,n,a,s,c){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:n,desiredAmount1:a});const l=(await this.getPoolData(e,t,o)).tick,u=r.tickToSqrtPrice(s),d=r.tickToSqrtPrice(l),h=r.tickToSqrtPrice(c),g=r.getLiquidityForAmounts(new i(n),new i(a),u,d,h),p=r.getAmountsForLiquidity(g,d,u,h),m=p[0],f=p[1],y=new i(n),w=new i(a);return{amount0:m.toFixed(),amount1:f.toFixed(),liquidity:g.toFixed(),ratio:m.dividedBy(f).toFixed(),utilizationPercent:{amount0:m.dividedBy(y).multipliedBy(100).toFixed(2),amount1:f.dividedBy(w).multipliedBy(100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",L,e)}}async validatePositionParameters(e,t,o,n,r,a,s){const c=[],l=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:n,tickUpper:r});const u=[500,3e3,1e4];u.includes(o)||c.push(`Invalid fee tier: ${o}. Must be one of: ${u.join(", ")}`);const d=this.getTickSpacing(o);let h;n%d!==0&&c.push(`tickLower must be multiple of ${d}`),r%d!==0&&c.push(`tickUpper must be multiple of ${d}`),n>=r&&c.push(`tickLower (${n}) must be less than tickUpper (${r})`);try{h=await this.getPoolData(e,t,o)}catch{return c.push(`Pool not found for ${e}/${t} at fee tier ${o}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}const g=new i(a),p=new i(s);if(g.isNaN()||p.isNaN())c.push("Amounts must be valid numbers");else try{en(g,p)}catch(e){c.push(`Liquidity amounts must be non-negative: ${e.message}`)}const m=h.tick;(m<n||m>r)&&l.push("Position is out of current price range - will not earn fees until price moves into range");new i(h.liquidity||"0").lt("1000000")&&l.push("Low pool liquidity - consider higher slippage tolerance");const f=0===c.length?35e4:0;return{valid:0===c.length,errors:c,warnings:l,gasEstimate:f,tickSpacing:d,currentTick:m,poolLiquidity:h.liquidity}}catch(e){const t=e;return c.includes(t?.message||"")||c.push(`Validation failed: ${t?.message||String(e)}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}}async calculateTicksForPrice(e,t,o,n,r){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:o,maxPrice:n});const a=this.getTickSpacing(r),s=new i(o),c=new i(n);if(s.gte(c))throw new Error("minPrice must be less than maxPrice");const l=Math.floor(Yo(s)),u=Math.ceil(Yo(c)),d=Math.floor(l/a)*a,h=Math.ceil(u/a)*a,g=Math.pow(1.0001,d),p=Math.pow(1.0001,h),m=new i(g),f=new i(p);return{tokenA:e,tokenB:t,feeTier:r,tickLower:d,tickUpper:h,tickSpacing:a,requestedMinPrice:o,requestedMaxPrice:n,actualMinPrice:m.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:m.minus(s).dividedBy(s).multipliedBy(100).toFixed(4),maxPriceDeviation:f.minus(c).dividedBy(c).multipliedBy(100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",L,e)}}async calculatePriceForTicks(e,t,o,n){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:o,tickUpper:n});const r=Math.pow(1.0001,o),a=Math.pow(1.0001,n);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const c=new i(r),l=new i(a),u={tokenA:e,tokenB:t,tickLower:o,tickUpper:n,minPrice:c.toFixed(8),maxPrice:l.toFixed(8),priceRange:`${c.toFixed(4)} - ${l.toFixed(4)}`,tickSpread:n-o};return void 0!==s&&(u.currentPrice=s),u}catch(e){this.handleGSwapError("Failed to calculate price for ticks",L,e)}}calculateExecutionPrice(e,t){try{const o=new i(e),n=new i(t);return o.isZero()?"0":n.dividedBy(o).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}`)}}calculatePriceFromSqrtPriceX96(e){try{const t=new i(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new i(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return new i(0)}}async getPoolSlot0(t,o,n){try{this.logger.debug("Fetching pool slot0 data",{token0:t,token1:o,fee:n});const i="string"==typeof t?jn(t):t,r="string"==typeof o?jn(o):o,a=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetSlot0`,s=await e.post(a,{token0:i,token1:r,fee:n},{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==s.status||1!==s.data?.Status)throw this.logger.warn("Unexpected GetSlot0 API response",{httpStatus:s.status,apiStatus:s.data?.Status}),new C("GetSlot0 API returned unexpected status",{httpStatus:s.status,apiStatus:s.data?.Status});const c=s.data.Data||{},l={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:l.sqrtPrice,tick:l.tick,liquidity:l.liquidity}),l}catch(e){this.handleGSwapError("Failed to fetch pool slot0 data",C,e,{token0:t,token1:o,fee:n})}}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),o=new i(t.sqrtPrice),n={price:this.calculatePriceFromSqrtPriceDecimal(o).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:n.price,tick:n.tick}),n}catch(t){this.handleGSwapError("Failed to fetch position current price",C,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,o){try{const n=Zo(t),i=Zo(o);return r.liquidity0(e,n,i)}catch{return new i(0)}}calculateLiquidityFromAmount1(e,t,o){try{const n=Zo(t),i=Zo(o);return r.liquidity1(e,n,i)}catch{return new i(0)}}calculateAmount0FromLiquidity(e,t,o){try{const n=Zo(t),i=Zo(o);return r.getAmount0Delta(n,i,e)}catch{return new i(0)}}calculateAmount1FromLiquidity(e,t,o){try{const n=Zo(t),i=Zo(o);return r.getAmount1Delta(n,i,e)}catch{return new i(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(o){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:o.token0.type,token1:o.token1.type,fee:o.fee,tickRange:`${o.tickLower}-${o.tickUpper}`});const n=`galaswap - operation - ${s.v4()}-${Date.now()}-${o.owner}`,i={token0:o.token0,token1:o.token1,fee:o.fee,owner:o.owner,tickLower:o.tickLower,tickUpper:o.tickUpper,amount0Desired:o.amount0Desired,amount1Desired:o.amount1Desired,amount0Min:o.amount0Min,amount1Min:o.amount1Min,positionId:"",uniqueKey:n},r=new t.ethers.Wallet(this.privateKey),a={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"}]},c={name:"ethereum",chainId:1},l=this.calculatePersonalSignPrefix(i),u={...i,prefix:l},d=await r.signTypedData(c,a,u),h={...u,signature:d,types:a,domain:c};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:h.signature?.substring(0,20)+"...",prefix:h.prefix,tickLower:i.tickLower,tickUpper:i.tickUpper});const g=this.buildLiquidityStringsInstructions(o.token0,o.token1,o.fee,o.owner),p=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),m=await p.post("/bundle",{method:"AddLiquidity",signedDto:h,stringsInstructions:g}),f=m.data?.data||m.data?.transactionId||m.data?.id;if(!f)throw this.logger.error("Bundler response structure",{status:m.status,data:m.data,dataType:typeof m.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(m.data)}`);return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:f}),f}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(o,n,i,r,a,c,l,u,d){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const h=new t.ethers.Wallet(this.privateKey),g=await h.getAddress(),p=`galaswap - operation - ${s.v4()}-${Date.now()}-${g}`,m={tickLower:o,tickUpper:n,amount:i,token0:r,token1:a,fee:c,amount0Min:l,amount1Min:u,positionId:d,uniqueKey:p},f={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"}]},y={name:"ethereum",chainId:1},w=this.calculatePersonalSignPrefix(m),k={...m,prefix:w},v=await h.signTypedData(y,f,k),T={...k,signature:v,types:f,domain:y},S=this.buildLiquidityStringsInstructions(r,a,c,g);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:o,tickUpper:n,amount:i,fee:c,positionId:d,transactionId:p});const b=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),A=await b.post("/bundle",{method:"RemoveLiquidity",signedDto:T,stringsInstructions:S}),E=A.data?.data||A.data?.transactionId||A.data?.id;if(!E)throw this.logger.error("Bundler response structure",{status:A.status,data:A.data,dataType:typeof A.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(A.data)}`);return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:E}),E}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(o,n,i,r,a,c,l,u){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const d=new t.ethers.Wallet(this.privateKey),h=await d.getAddress(),g=`galaswap - operation - ${s.v4()}-${Date.now()}-${h}`,p={token0:o,token1:n,fee:i,amount0Requested:r,amount1Requested:a,tickLower:c,tickUpper:l,positionId:u,uniqueKey:g},m={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"}]},f={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},k=await d.signTypedData(f,m,w),v={...w,signature:k,types:m,domain:f},T=this.buildLiquidityStringsInstructions(o,n,i,h);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:i,amount0Requested:r,amount1Requested:a,tickLower:c,tickUpper:l,positionId:u,transactionId:g});const S=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),b=await S.post("/bundle",{method:"CollectPositionFees",signedDto:v,stringsInstructions:T}),A=b.data?.data||b.data?.transactionId||b.data?.id;if(!A)throw this.logger.error("Bundler response structure",{status:b.status,data:b.data,dataType:typeof b.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(b.data)}`);return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:A}),A}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(o){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 n=[500,3e3,1e4];if(!n.includes(o.feeTier))throw new Error(`GSwapService: Invalid fee tier ${o.feeTier}. Must be one of: ${n.join(", ")} (basis points)`);try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof o.fromToken?o.fromToken:o.fromToken.type,toToken:"string"==typeof o.toToken?o.toToken:o.toToken.type,inputAmount:o.inputAmount,minOutput:o.minOutput,feeTier:o.feeTier});let n=o.fromToken,r=o.toToken;"string"==typeof n&&(n=jn(n)),"string"==typeof r&&(r=jn(r));const a=`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`,c=`${r.collection}|${r.category}|${r.type}|${r.additionalKey}`,l=a<c?[n,r,a,c]:[r,n,c,a],[u,d,h,g]=l,p="string"==typeof o.fromToken?jn(o.fromToken):o.fromToken,m=`${p.collection}|${p.category}|${p.type}|${p.additionalKey}`,f=m===h,y=`galaswap - operation - ${s.v4()}-${Date.now()}-${o.walletAddress}`;let w;if(!o.currentSqrtPrice)throw new Error("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation");const k=new i(o.currentSqrtPrice),v=o.slippageTolerance??.01;if(f){const e=new i(1).minus(v);w=k.multipliedBy(e).toString()}else{const e=new i(1).plus(v);w=k.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:o.currentSqrtPrice,slippageTolerance:100*v+"%",zeroForOne:f,sqrtPriceLimit:w,direction:f?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const T={token0:u,token1:d,fee:o.feeTier,amount:new i(o.inputAmount).toFixed(),zeroForOne:f,sqrtPriceLimit:w,recipient:o.walletAddress,amountOutMinimum:new i(o.minOutput).multipliedBy(-1).toFixed(),uniqueKey:y};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:h,orderedToken1String:g,fromTokenStr:m,zeroForOne:f?`TRUE (${h} → ${g})`:`FALSE (${g} → ${h})`,inputAmount:o.inputAmount,expectedOutput:o.minOutput,slippageTolerance:100*(o.slippageTolerance||.01)+"%",currentSqrtPrice:o.currentSqrtPrice,swapDto:{amount:T.amount,zeroForOne:T.zeroForOne,sqrtPriceLimit:T.sqrtPriceLimit,amountOutMinimum:T.amountOutMinimum}});const S=new t.ethers.Wallet(this.privateKey),b={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"}]},A={name:"ethereum",chainId:1},E=this.calculatePersonalSignPrefix(T),I={...T,prefix:E},P=await S.signTypedData(A,b,I),x={...I,signature:P,types:b,domain:A};this.logger.debug("Swap DTO signed",{signature:x.signature?.substring(0,20)+"...",prefix:x.prefix,zeroForOne:T.zeroForOne});const N=this.buildLiquidityStringsInstructions(u,d,o.feeTier,o.walletAddress),D=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),F=await D.post("/bundle",{method:"Swap",signedDto:x,stringsInstructions:N}),C=F.data?.data||F.data?.transactionId||F.data?.id;if(!C)throw this.logger.error("Bundler response structure",{status:F.status,data:F.data,dataType:typeof F.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(F.data)}`);return this.logger.debug("Swap transaction sent to bundler",{transactionId:C,inputAmount:o.inputAmount,minOutput:o.minOutput}),C}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,o,n){const i=`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`,r=`$${t.collection}$${t.category}$${t.type}$${t.additionalKey}`,a=`$pool${i}${r}$${o}`;return[a,`$userPosition${n}`,`$tokenBalance${i}${n}`,`$tokenBalance${r}${n}`,`$tokenBalance${i}${a}`,`$tokenBalance${r}${a}`]}handleGSwapError(e,t,o,n){this.logger.error(e,o);const i=this.extractGSwapErrorCode(o),r=o,a=[`${e}: ${r?.message||String(o)}`,o];throw n&&("GSwapSwapError"===t.name&&n.transactionHash&&a.push(n.transactionHash),"GSwapPoolError"===t.name&&(n.tokenA&&a.push(n.tokenA),n.tokenB&&a.push(n.tokenB)),"GSwapAssetError"===t.name&&n.walletAddress&&a.push(n.walletAddress)),i&&a.push(i),new t(...a)}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 ei{}ei.BASE_PRICE=1650667151e-14,ei.PRICE_SCALING_FACTOR=1166069e-12,ei.TRADING_FEE_FACTOR=.001,ei.GAS_FEE="1",ei.MIN_UNBONDING_FEE_FACTOR=0,ei.MAX_UNBONDING_FEE_FACTOR=.5,ei.NET_UNBONDING_FEE_FACTOR=.5,ei.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class ti extends vo{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 o=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=ti.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...o||{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const o=this.normalizeTokenName(e);this.updateCacheEntry(o,t)}set(e,t){const o=this.normalizeTokenName(e);this.updateCacheEntry(o,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),o=this.cache.get(t);return o?.maxSupply||ei.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,o)=>{e[o]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((o,n)=>{o.lastUpdated<e&&(e=o.lastUpdated);let i=0;i+=2*n.length,void 0!==o.reverseBondingCurveMinFeeFactor&&(i+=8),void 0!==o.reverseBondingCurveMaxFeeFactor&&(i+=8),void 0!==o.reverseBondingCurveNetFeeFactor&&(i+=8),i+=8,o.vaultAddress&&(i+=2*o.vaultAddress.length),o.maxSupply&&(i+=2*o.maxSupply.length),o.symbol&&(i+=2*o.symbol.length),i+=32,t+=i}),{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 o=`token:${e.toLowerCase().trim()}`;this.updateCacheEntry(o,t)}hasByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.has(t)}}ti.MAX_CACHE_SIZE=1e4;class oi extends ko{constructor(e,t,o=void 0,n=5,i=!1){super(e,i),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=o,this.pricingConcurrency=n}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 o=0;o<e.length;o++){const n=e[o];t.push({poolIndex:o,token:n.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:n.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${n.token0}`,{error:e.message})})}),t.push({poolIndex:o,token:n.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:n.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${n.token1}`,{error:e.message})})})}const o=new Map;for(let t=0;t<e.length;t++)o.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const n=t.slice(e,e+this.pricingConcurrency),i=await Promise.allSettled(n.map(e=>e.task));for(let e=0;e<n.length;e++){const t=n[e],r=i[e],a=o.get(t.poolIndex)||{};"fulfilled"===r.status&&r.value&&(t.isToken0?a.token0Price=r.value:a.token1Price=r.value),o.set(t.poolIndex,a)}}const n=e.map((e,t)=>{const n=o.get(t)||{},i={...e};return void 0!==n.token0Price&&(i.token0Price=n.token0Price),void 0!==n.token1Price&&(i.token1Price=n.token1Price),i}),i=n.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:i,failed:e.length-i}),n}async fetchDexPools(e={}){const{search:t,sortBy:o="tvl",sortOrder:n="desc",page:i=wo.DEFAULT_PAGE,limit:r=wo.DEFAULT_LIMIT,withPrices:a=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:o,sortOrder:n,page:i,limit:r,withPrices:a});const s=new URLSearchParams({page:i.toString(),limit:Math.min(r,20).toString(),sortBy:o,sortOrder:n});t&&s.append("search",t);const c=`${this.dexBackendBaseUrl}/explore/pools?${s}`;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 o=e.data.count,n=Math.min(r,20),s=Math.ceil(o/n);return a&&(t=await this.enrichPoolsWithPricing(t)),this.logger.debug("DEX pools fetched successfully",{poolCount:t.length,total:o,totalPages:s,withPrices:a}),{pools:t,page:i,limit:n,total:o,totalPages:s,hasNext:i<s,hasPrevious:i>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 Gn((t,o)=>this.fetchDexPools({...e,page:t,limit:o}).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 zn(t.items,t.total,"pools")}}function ni(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[o,n,i,...r]=t;if(!o||!n||!i)throw new Error("Collection, category, and type must be non-empty");const a=r.join("|");if(!a)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:n,type:i,additionalKey:a}}catch(t){throw new I(`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")}}class ii extends ko{constructor(e,t,o=!1,n=3e4){super(e,o),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=n}validateFetchCompositePoolDataInput(e,t,o){if(!e||"string"!=typeof e)throw new O("token0 must be a non-empty string",{token0:e});if(!t||"string"!=typeof t)throw new O("token1 must be a non-empty string",{token1:t});const n=e.split("|"),i=t.split("|");if(4!==n.length)throw new O("token0 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token0:e});if(4!==i.length)throw new O("token1 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token1:t});const r=[500,3e3,1e4];if(!Number.isInteger(o)||!r.includes(o))throw new O(`fee must be one of: ${r.join(", ")} (got ${o})`,{fee:o})}validateQuoteAmount(e){if(!e||"string"!=typeof e)throw new O("amount must be a non-empty string",{amount:e});const t=new i(e);try{tn(t,"amount","for quote calculation")}catch(t){throw new O(t.message,{amount:e})}}convertTokenClassKey(e){const t=new a.TokenClassKey;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:o,fee:n,gatewayBaseUrl:s}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:o,fee:n}),this.validateFetchCompositePoolDataInput(t,o,n);try{const e=ni(t),c=ni(o),l=this.convertTokenClassKey(e),u=this.convertTokenClassKey(c),d=new r.GetCompositePoolDto(l,u,n),h=`${s||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,g=await this.http.post(h,d);if(!g||1!==g.Status)throw new _(`Pool not found: ${t}/${o} with fee ${n}`);const p=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 r.Pool(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,new i(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=new i(e.pool.grossPoolLiquidity),t.liquidity=new i(e.pool.liquidity),t.feeGrowthGlobal0=new i(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=new i(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=new i(e.pool.protocolFeesToken0),t.protocolFeesToken1=new i(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=new i(e.pool.maxLiquidityPerTick);const o={};Object.keys(e.tickDataMap).forEach(t=>{const n=e.tickDataMap[t],a=new r.TickData(n.poolHash,n.tick);a.initialised=n.initialised,a.liquidityNet=new i(n.liquidityNet),a.liquidityGross=new i(n.liquidityGross),a.feeGrowthOutside0=new i(n.feeGrowthOutside0),a.feeGrowthOutside1=new i(n.feeGrowthOutside1),o[t]=a});const n={...e.token0Balance},s=new a.TokenBalance(n);s.quantity=new i(e.token0Balance.quantity);const c={...e.token1Balance},l=new a.TokenBalance(c);return l.quantity=new i(e.token1Balance.quantity),new r.CompositePoolDto(t,o,s,l,e.token0Decimals,e.token1Decimals)}(g.Data),g.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:o,fee:n,liquidity:p.pool.liquidity.toString()}),p}catch(e){if(e instanceof _)throw e;const i=e instanceof Error?e.message:String(e);throw this.logger.error("Failed to fetch composite pool data",e),new O(`Failed to fetch composite pool data: ${i}`,{token0:t,token1:o,fee:n})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:o,toToken:n,amount:a}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:o,toToken:n,amount:a}),this.validateQuoteAmount(a),!t)throw new O("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=o===t.pool.token0.replace(/\$/g,"|"),s=ni(o),c=ni(n),l=this.convertTokenClassKey(s),u=this.convertTokenClassKey(c),d=new r.QuoteExactAmountDto(l,u,t.pool.fee,new i(a),e,t.compositePoolDto),h=await r.quoteExactAmount(void 0,d);return this.logger.debug("Local quote calculated",{amount0:h.amount0,amount1:h.amount1}),{amount0:h.amount0.toString(),amount1:h.amount1.toString(),currentSqrtPrice:h.currentSqrtPrice.toString(),newSqrtPrice:h.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("Local quote calculation failed",e),new O(`Local quote calculation failed: ${t}`,{fromToken:o,toToken:n,amount:a})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:o,toToken:n,amount:a}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:o,toToken:n,amount:a}),this.validateQuoteAmount(a),!t)throw new O("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=o===t.pool.token0.replace(/\$/g,"|"),s=ni(o),c=ni(n),l=this.convertTokenClassKey(s),u=this.convertTokenClassKey(c),d=new r.QuoteExactAmountDto(l,u,t.pool.fee,new i(a),e,void 0),h=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,g=await this.http.post(h,d);if(!g||1!==g.Status)throw new O("External quote failed: "+(g?.Message||"Unknown error"));const p=g.Data;return this.logger.debug("External quote calculated",{amount0:p.amount0,amount1:p.amount1}),{amount0:p.amount0.toString(),amount1:p.amount1.toString(),currentSqrtPrice:p.currentSqrtPrice.toString(),newSqrtPrice:p.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("External quote calculation failed",e),new O(`External quote calculation failed: ${t}`,{fromToken:o,toToken:n,amount:a})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class ri{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 o=this.getPoolMetrics(e);o.cacheHits++,o.eventsProcessed++,o.totalLatency+=t,o.lastEventTime=new Date}recordPoolCacheMiss(e,t){const o=this.getPoolMetrics(e);o.cacheMisses++,o.eventsProcessed++,o.totalLatency+=t,o.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),o=Math.floor(.95*e.length),n=Math.floor(.99*e.length);return{p50:e[t]??0,p95:e[o]??0,p99:e[n]??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 o=t.cacheHits+t.cacheMisses;return 0===o?0:t.cacheHits/o*100}getHealthMetrics(e,t,o,n,i){const r=this.getLatencyPercentiles(),a=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:r.p50,latencyP95:r.p95,latencyP99:r.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:Math.round(10*a)/10,maxMB:i,percentUsed:Math.round(a/i*1e3)/10},pools:{totalMonitored:e,hotCacheSize:t,warmCacheSize:o,coldCacheSize:n}}}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 ai{static createPoolKey(e,t,o){return`${e}/${t}/${o}`}static parsePoolKey(e){if(!e||"string"!=typeof e)return null;const t=e.split("/");if(3!==t.length)return null;const o=t[0]?.trim(),n=t[1]?.trim(),i=t[2]?.trim();if(!o||!n||!i)return null;const r=Number.parseInt(i,10);return Number.isNaN(r)?null:{token0:o,token1:n,feeTier:r}}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 o=this.parsePoolKey(e);return!!o&&(o.token0===t||o.token1===t)}static containsTokenPair(e,t,o){const n=this.parsePoolKey(e);if(!n)return!1;const i=n.token0===t||n.token1===t,r=n.token0===o||n.token1===o;return i&&r&&t!==o}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 si{constructor(e){this.logger=e||new T({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const o=[],n=new WeakSet,i=(e,r=0)=>{if(r>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(n.has(e))return;n.add(e);const a=this.extractSwapFromObject(e);a&&!t.has(a.transactionId)&&(o.push(a),t.add(a.transactionId));for(const t of Object.values(e))i(t,r+1)}};return i(e,0),o}extractSwapFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const o=e.Data,n=o&&"object"==typeof o&&!Array.isArray(o)?o:e,i=this.extractToken(n,"token0","fromToken","source"),r=this.extractToken(n,"token1","toToken","destination");if(!i||!r)return null;const a=this.extractAmount(n,"amount0","amountIn","inputAmount"),s=this.extractAmount(n,"amount1","amountOut","outputAmount");if(!a||!s)return null;const c=this.extractFeeTier(n);if(null===c)return null;const l=this.extractTimestamp(n),u=this.buildPoolKey(i,r,c),d=this.determineDirection(n,i,r),h={transactionId:t,poolKey:u,token0:i,token1:r,amount0:a,amount1:s,feeTier:c,direction:d,timestamp:l,exactInput:this.determineExactInput(n,d)},g=this.extractUser(n);return void 0!==g&&(h.user=g),h}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractToken(e,...t){for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractAmount(e,...t){for(const o of t){const t=e[o];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 o of t){const t=e[o],n=this.normalizeFee(t);if(null!==n)return n}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 o of t){const t=e[o];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 o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}}determineDirection(e,t,o){const n=e.zeroForOne||e.direction;if("boolean"==typeof n)return n?"zeroForOne":"oneForZero";if("string"==typeof n){if("zerotoone"===n.toLowerCase()||"0to1"===n)return"zeroForOne";if("onetozero"===n.toLowerCase()||"1to0"===n)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===o||e.inputToken===o)return"oneForZero";const i=this.extractAmount(e,"amount0","amountIn");return i&&Number(i),"zeroForOne"}determineExactInput(e,t){if("boolean"==typeof e.exactInput)return e.exactInput;if("boolean"==typeof e.exactOutput)return!e.exactOutput;const o=void 0!==e.amountIn&&null!==e.amountIn,n=void 0!==e.amountOut&&null!==e.amountOut,i=void 0!==e.inputAmount&&null!==e.inputAmount,r=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!o||n)||!(n&&!o)&&(!(!i||r)||!(r&&!i))}buildPoolKey(e,t,o){return`${e}/${t}/${o}`}}class ci{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,new i(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,o=Array.from(this.CACHE.keys());for(let e=0;e<t;e++)this.CACHE.delete(o[e])}}}ci.CACHE=new Map,ci.ZERO=new i(0),ci.ONE=new i(1),ci.FEE_PIPS=new i(1e6),ci.MIN_SQRT_RATIO=new i("4295128739"),ci.MAX_SQRT_RATIO=new i("1461446703485210103287273052203988822378723970342");const li={maxIterations:100,enableBigNumberCache:!0,roundingMode:i.ROUND_DOWN,debugLogging:!1};class ui{static calculateSwapDelta(e,t,o={}){const n=Date.now(),r={...li,...o};try{const o=this.initializeSwapState(e,t,r);r.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:o.sqrtPrice.toString(),liquidity:o.liquidity.toString(),tick:o.tick,zeroForOne:t.zeroForOne});const a=this.computeSwapLoop(o,e,t,r);r.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:a.stepCount,ticksCrossed:a.ticksCrossed.length,priceHitLimit:a.priceHitLimit});const s=this.createUpdatedPool(e.pool,a.state,t,r),c=this.calculateFinalAmounts(o,a.state,t);let l;if(t.actualSqrtPrice){const e=new i(s.sqrtPrice),o=new i(t.actualSqrtPrice);l=e.minus(o).abs().div(o).times(100).toNumber()}const u=Date.now()-n;r.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:u,amount0:c.amount0.toString(),amount1:c.amount1.toString(),driftPercentage:l}),u>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:u,stepCount:a.stepCount,ticksCrossed:a.ticksCrossed.length}),a.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:a.stepCount}),a.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:a.stepCount,ticksCrossed:a.ticksCrossed.length});return{updatedPool:s,updatedTicks:a.updatedTicks,amount0:c.amount0,amount1:c.amount1,feeAmount0:c.feeAmount0,feeAmount1:c.feeAmount1,ticksCrossed:a.ticksCrossed,metadata:{calculationTimeMs:u,swapSteps:a.stepCount,priceHitLimit:a.priceHitLimit,...void 0!==l&&{driftPercentage:l}}}}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,o){const{pool:n}=e;if(!n.sqrtPrice||!n.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const a=o.enableBigNumberCache?ci.getCached.bind(ci):e=>new i(e),s="string"==typeof n.sqrtPrice?n.sqrtPrice:new i(n.sqrtPrice).toFixed(0),c="string"==typeof n.liquidity?n.liquidity:new i(n.liquidity).toFixed(0),l=a(s),u=a(c),d=n.tick??0,h=r.sqrtPriceToTick(new i(s)),g=Math.abs(h-d);g>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:d,calculatedTick:h,drift:g,threshold:100});const p=a(t.amountSpecified);tn(p,"amountSpecified","for swap operation");const m="string"==typeof n.feeGrowthGlobal1?n.feeGrowthGlobal1:new i(n.feeGrowthGlobal1).toFixed(0),f="string"==typeof n.feeGrowthGlobal0?n.feeGrowthGlobal0:new i(n.feeGrowthGlobal0).toFixed(0),y=t.zeroForOne?a(m):a(f);return{sqrtPrice:l,liquidity:u,tick:d,amountSpecifiedRemaining:p,amountCalculated:ci.ZERO,feeGrowthGlobalX:y,protocolFee:ci.ZERO}}static computeSwapLoop(e,t,o,n){const{pool:a,tickDataMap:s}=t,c=[],l={};let u=0;const d=o.zeroForOne?ci.MIN_SQRT_RATIO:ci.MAX_SQRT_RATIO,h=new i("0.000001");for(;e.amountSpecifiedRemaining.gt(h)&&!e.sqrtPrice.eq(d)&&u<n.maxIterations;){u++;const[t,h]=this.findNextInitializedTick(s,e.tick,a.tickSpacing,o.zeroForOne);let g;if(n.debugLogging&&this.logger.debug(`Swap step ${u}`,{currentTick:e.tick,tickNext:t,initialized:h,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),h&&t>=-887272&&t<=887272){const e=r.tickToSqrtPrice(t);g=e instanceof i?e:new i(String(e))}else g=d;const p=o.zeroForOne?i.max(g,d):i.min(g,d),m=this.executeSwapStep(e.sqrtPrice,p,e.liquidity,e.amountSpecifiedRemaining,a.fee,o.exactInput);if(e.sqrtPrice=m.sqrtPriceNext,o.exactInput){const t=m.amountIn.plus(m.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=ci.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=ci.ZERO)),e.amountCalculated=e.amountCalculated.minus(m.amountOut)}else{m.amountOut.lte(0)?e.amountSpecifiedRemaining=ci.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(m.amountOut),e.amountCalculated=e.amountCalculated.plus(m.amountIn.plus(m.feeAmount))}if(e.liquidity.gt(0)){const t=m.feeAmount.div(e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(g)&&h){const r=s[t.toString()];if(!r)throw new Error(`Missing tick data for initialized tick ${t}`);const a=o.zeroForOne?new i(r.liquidityNet).negated():new i(r.liquidityNet);if(e.liquidity=e.liquidity.plus(a),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);c.push(t),l[t.toString()]=r,n.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:a.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(g))e.tick=o.zeroForOne?t-1:t;else{const t=r.sqrtPriceToTick(new i(e.sqrtPrice.toString()));e.tick=t}}if(u>=n.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${n.maxIterations}). Possible infinite loop or very complex swap.`);const g=e.sqrtPrice.eq(d);return{state:e,ticksCrossed:c,priceHitLimit:g,stepCount:u,updatedTicks:l}}static createUpdatedPool(e,t,o,n){const r=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(r.sqrtPrice=t.sqrtPrice.toFixed(0),r.liquidity=t.liquidity.toFixed(0),r.tick=t.tick,o.zeroForOne?r.feeGrowthGlobal1=t.feeGrowthGlobalX.toFixed(0):r.feeGrowthGlobal0=t.feeGrowthGlobalX.toFixed(0),o.zeroForOne){const o=new i(e.protocolFeesToken0);r.protocolFeesToken0=o.plus(t.protocolFee).toFixed(0)}else{const o=new i(e.protocolFeesToken1);r.protocolFeesToken1=o.plus(t.protocolFee).toFixed(0)}return r}static calculateFinalAmounts(e,t,o){let n,r,a,s;if(o.exactInput){const e=new i(o.amountSpecified),c=t.amountCalculated.abs();o.zeroForOne?(n=e.negated(),r=c,a=ci.ZERO,s=ci.ZERO):(n=c,r=e.negated(),a=ci.ZERO,s=ci.ZERO)}else{const e=new i(o.amountSpecified),c=t.amountCalculated.abs();o.zeroForOne?(n=c.negated(),r=e,a=ci.ZERO,s=ci.ZERO):(n=e,r=c.negated(),a=ci.ZERO,s=ci.ZERO)}const c=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return o.zeroForOne?s=c:a=c,{amount0:n,amount1:r,feeAmount0:a,feeAmount1:s}}static findNextInitializedTick(e,t,o,n){const i=Object.keys(e).map(e=>parseInt(e,10)).sort((e,t)=>e-t);if(0===i.length){return[n?-887272:887272,!1]}if(n){const e=i.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=i.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,o,n,a,s){en(o),tn(n,"amountRemaining","for swap step");const c=[500,3e3,1e4];if(!c.includes(a))throw new Error(`Invalid fee tier: ${a}. Must be one of: ${c.join(", ")}`);const l=r.computeSwapStep(e,t,o,n,a,t.lt(e)),u=l[0],d=l[1],h=l[2],g=l[3],p=i.isBigNumber(u)?u:new i(String(u)),m=i.isBigNumber(d)?d:new i(String(d)),f=i.isBigNumber(h)?h:new i(String(h)),y=i.isBigNumber(g)?g:new i(String(g));return{sqrtPriceStart:e,tickNext:r.sqrtPriceToTick(p),sqrtPriceNext:p,initialised:!1,amountIn:m,amountOut:f,feeAmount:y}}}ui.logger=new T({debug:!1,context:"SwapDeltaCalculator"});class di{constructor(e,t,o,n){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=o,this.logger=n||new T({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),o=this.determineTier(),n={poolData:t,tier:o,lastAccessTime:Date.now(),expiresAt:Date.now()+this.tierTTLs[o],swapsSinceRefetch:0,cumulativeDrift:0,lastDeltaAppliedTime:Date.now()};return this.cache.set(e,n),this.cache.size>this.config.maxPools&&this.evictLRU(),this.logger.debug(`Fetched pool ${e} (tier: ${o})`),t}catch(t){throw this.logger.error(`Failed to fetch pool ${e}:`,t),t}}updatePoolWithSwapDelta(e,t,o,n,i){const r=this.cache.get(e);if(!r)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(i){const a="zeroForOne"===t,s=a?o:n,c={transactionId:i.transactionId,timestamp:i.timestamp,amountSpecified:s,zeroForOne:a,exactInput:i.exactInput},l=ui.calculateSwapDelta(r.poolData,c);r.poolData={...r.poolData,pool:l.updatedPool},r.swapsSinceRefetch++,r.lastDeltaAppliedTime=Date.now(),void 0!==l.metadata.driftPercentage?(r.cumulativeDrift+=l.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${l.metadata.driftPercentage.toFixed(4)}%, cumulative=${r.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${l.ticksCrossed.length} ticks crossed`)}else r.swapsSinceRefetch++,r.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(r)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${r.swapsSinceRefetch}, drift=${(100*r.cumulativeDrift).toFixed(2)}%`),r.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),r.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 o={succeeded:0,failed:0,total:e.length};let n=0;const i=new Set;for(;n<e.length||i.size>0;){for(;n<e.length&&i.size<t;){const t=e[n];n++;const r=this.warmCache(t).then(e=>{e?o.succeeded++:o.failed++});i.add(r),r.finally(()=>i.delete(r))}i.size>0&&await Promise.race(i)}return this.logger.debug(`Cache warming complete: ${o.succeeded}/${o.total} succeeded`),o}clear(){this.cache.clear(),this.logger.debug("Cache cleared")}clearExpired(){const e=Date.now();let t=0;for(const[o,n]of this.cache)e>n.expiresAt&&(this.cache.delete(o),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(o=>{t&&(t.poolData=o,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)})),o=new Promise(e=>setTimeout(()=>e(),5e3));await Promise.race([Promise.all(t),o])}}class hi{constructor(e,t,o){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=o||new T({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 o=()=>{0!==this.queue.length||0!==this.currentConcurrency?setTimeout(o,10):t()};e&&setTimeout(()=>t(),e),o()})}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 o=0;o<e.length;o++){const n=e[o];this.eventsProcessedCount++,"rejected"===n.status&&this.logger.error(`Failed to process event ${t[o].transactionId}:`,n.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 o=Date.now()-t;this.metrics.recordEventLatency(o)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class gi{constructor(e,t,o,n={},i){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=i||new T({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 ri,this.config=this.applyDefaults(n),this.eventExtractor=new si(this.logger),this.quoteService=o,this.cacheManager=new di(t,this.config,this.metrics,this.logger),this.eventQueue=new hi(this.config,this.metrics,this.logger),this.seenTransactions=new pi(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 o=this;return()=>{o.listeners=o.listeners.filter(e=>e!==t),e.onError&&(o.onErrorCallbacks=o.onErrorCallbacks.filter(t=>t!==e.onError)),0===o.listeners.length&&0===o.onErrorCallbacks.length&&o.unsubscribe()}}getHealth(){const e=this.cacheManager.getStats(),t=this.eventQueue.getStats(),o=this.metrics.getHealthMetrics(e.totalCached,e.hotCacheSize,e.warmCacheSize,e.coldCacheSize,this.getMaxMemoryMB()),n=this.determineHealthStatus(t,e),i={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectAttempts};this.socket?.connected&&(i.lastConnectionTime=new Date);const r=t.queueSize/this.config.maxQueueSize*100,a=e.totalCached/this.config.maxPools*100,s=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(n,r,a,s,o.metrics.cacheHitRate);return{...o,status:n,websocket:i,recommendations:c,detailedMetrics:{eventQueueUtilization:r,cacheUtilization:a,memoryUtilization:s}}}generateHealthRecommendations(e,t,o,n,i){const r=[];return"failed"===e&&(r.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||r.push("Reconnect WebSocket - connection lost"),t>90&&r.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(r.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&r.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),n>80&&r.push(`Memory usage ${n.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(i<50&&r.push(`Cache hit rate ${i.toFixed(1)}% is low - consider warming more pools`),n>50&&r.push("Memory usage is moderate - monitor for growth trends"),t>50&&r.push("Queue utilization is elevated - monitor for bottlenecks")),r}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=(o,...n)=>{try{const o=Date.now(),i=n[0],r=t.eventExtractor.walkPayloadForSwaps(i,t.seenTransactions);if(0===r.length)return;t.logger.debug(`Extracted ${r.length} swaps from payload`);for(const o of r){if(t.filterSwap(o,e)){t.eventQueue.enqueue(o)||t.logger.debug(`Swap dropped due to queue overflow: ${o.transactionId}`)}}const a=Date.now()-o;t.metrics.recordEventLatency(a)}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(!ai.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[o,n]=t.pairTokens;if(!ai.containsTokenPair(e.poolKey,o,n))return!1}if(t.feeTierFilter){if(ai.normalizeFee(t.feeTierFilter)!==e.feeTier)return!1}return!t.userFilter||e.user===t.userFilter}async processSwapEvent(e){const t=Date.now();try{const o=this.cacheManager.updatePoolWithSwapDelta(e.poolKey,e.direction,e.amount0,e.amount1,e);e.poolStateUpdated=o;const n=Date.now()-t;this.metrics.recordEventLatency(n);for(const t of this.listeners)try{const o=t(e);o instanceof Promise&&await o}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 pi{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}}function mi(e){const t=function(e){const t=Pt(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 fi="/api/asset/launchpad-contract/CallNativeTokenIn",yi="/api/asset/launchpad-contract/CallNativeTokenOut",wi="/api/asset/launchpad-contract/CallMemeTokenIn",ki="/api/asset/launchpad-contract/CallMemeTokenOut";class vi extends o.ChainCallDTO{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 Ti(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 Si={NATIVE:"native",EXACT:"exact"},bi={LOCAL:"local",EXTERNAL:"external"};class Ai{static calculateBuyWithExact(e,t){const o=parseFloat(e),n=parseFloat(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:a,TRADING_FEE_FACTOR:s,GAS_FEE:c}=ei,l=this.roundUp(r*(Math.exp((n+o)*a)-Math.exp(n*a))/a,8),u=new i(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateBuyWithNative(e,t){const o=parseFloat(e),n=parseFloat(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:a,TRADING_FEE_FACTOR:s,GAS_FEE:c}=ei,l=Math.log(o*a/r+Math.exp(n*a))/a-n,u=new i(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateSellWithExact(e,t,o,n,r){const a=parseFloat(e),s=parseFloat(t),c=parseFloat(o),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=ei,g=l*(Math.exp(s*u)-Math.exp((s-a)*u))/u,p=new i(g),m=n+s/c*(r-n),f=p.multipliedBy(m).toFixed(8,i.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,o,n,r){const a=parseFloat(e),s=parseFloat(t),c=parseFloat(o),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=ei,g=s-Math.log(Math.exp(s*u)-a*u/l)/u,p=new i(a),m=n+s/c*(r-n),f=p.multipliedBy(m).toFixed(8,i.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static roundUp(e,t){const o=Math.pow(10,t);return Math.ceil(e*o)/o}}class Ei{constructor(e,t,o,n,i,r,a="local"){this.http=e,this.tokenResolver=t,this.logger=o,this.bundleHttp=n,this.galaChainHttp=i,this.dexApiHttp=r,this.defaultCalculateAmountMode=a,this.metadataCache=new ti}addIfDefined(e,t,o){return void 0!==o&&(e[t]=o),e}async uploadImageByTokenName(e){const{tokenName:t,options:o}=e;jt(t);const n=`${t}.png`;Go(o.file,n,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&o.file instanceof File)e.append("image",o.file);else{if(!Buffer.isBuffer(o.file))throw M("file","a File object (browser) or Buffer (Node.js)");{const n=`${o.tokenName||t}.png`,i=new Blob([o.file],{type:"image/png"});e.append("image",i,n)}}const n=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(o.tokenName||t)}`,data:e,headers:{}});if(!0===n.error||200!==n.status||!n.data?.imageUrl)throw q(n.message||"Image upload failed - no URL returned",n.status);return n.data.imageUrl}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw R("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){Ht(e),e.tokenName&&jt(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 o=S(t),n=await this.http.get("/launchpad/fetch-pool",o);if(!0===n.error||200!==n.status||!n.data)throw q(n.message||"Failed to fetch pools",n.status);let i=[];const r=(await import("bignumber.js")).default;if(n.data.tokens)if(Array.isArray(n.data.tokens))i=n.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",o=e.reverseBondingCurveMaxFeePortion??"0",n=!new r(t).isZero()||!new r(o).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}});else{const e=n.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",o=e.reverseBondingCurveMaxFeePortion??"0",a=!new r(t).isZero()||!new r(o).isZero();i=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:a,createdAt:e.created_at||e.createdAt||""}]}else n.data.pools&&Array.isArray(n.data.pools)&&(i=n.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",o=e.reverseBondingCurveMaxFeePortion??"0",n=!new r(t).isZero()||!new r(o).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:a,isValidPoolForCaching:s}=await Promise.resolve().then(function(){return Mi});i.forEach(e=>{if(!s(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=a(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=n.data.count??n.data.total??0,l=n.data.page??e.page??1,u=n.data.limit??e.limit??10,d=u>0?Math.ceil(c/u):1;return{pools:i,page:l,limit:u,total:c,totalPages:d,hasNext:l<d,hasPrevious:l>1}}async _getAmount(e){if(Qt(e),!this.galaChainHttp)throw R("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:o}=((e,t,o,n)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:fi,body:{vaultAddress:o,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:yi,body:{vaultAddress:o,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:wi,body:{vaultAddress:o,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:ki,body:{vaultAddress:o,nativeTokenQuantity:n,IsPreMint:!1}};throw M("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,o);if(!Ti(e))throw q("Malformed response data from GalaChain gateway");if(1!==e.Status)throw q(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:n,extraFees:i}=e.Data;return{amount:n,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(n){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:o,error:n instanceof Error?n.message:n}),n}}async checkPool(e){Vt(e),e.tokenName&&jt(e.tokenName);const t=S(e),o=await this.http.get("/launchpad/check-pool",t);if(!0===o.error||200!==o.status)throw q(o.message||"Failed to check pool",o.status);const n=o.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.exists??!1}async fetchVolumeData(e){if(!Eo(e))throw new I("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:o,to:n,resolution:i}=e;if(jt(t),!o||!n||!i)throw new I("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:o,to:n,resolution:i};Xt(r);const a=S(r),s=await this.http.get("/launchpad/get-graph-data",a);if(!0===s.error||200!==s.status||!s.data)throw q(s.message||"Failed to fetch graph data",s.status);return{dataPoints:s.data}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const o={page:e.page||1,limit:e.limit||10};return e.search&&(o.search=e.search),e.tokenName&&(o.tokenName=e.tokenName),t&&(o.type=t),this.fetchPoolsFromAPI(o)}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 I("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:o,type:n,currentSupply:i}=e,r=e.mode??this.defaultCalculateAmountMode;if("local"!==r&&"external"!==r)throw new I(`Invalid calculation mode "${r}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new I("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Si.NATIVE&&n!==Si.EXACT)throw new I('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===r?this.calculateBuyAmountExternal({tokenName:t,amount:o,type:n}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:o,type:n},"currentSupply",i))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:o,type:n}=e,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw new I(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Si.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:i,amount:o}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:i,amount:o})}async calculateSellAmount(e){const{tokenName:t,amount:o,type:n,currentSupply:i,maxSupply:r,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:s}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new I(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new I("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Si.EXACT&&n!==Si.NATIVE)throw new I('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:o,type:n});{const e={tokenName:t,amount:o,type:n,...void 0!==i&&{currentSupply:i},...void 0!==r&&{maxSupply:r},...void 0!==a&&{reverseBondingCurveMaxFeeFactor:a},...void 0!==s&&{reverseBondingCurveMinFeeFactor:s}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:o,type:n}=e,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw new I(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Si.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:i,amount:o}):this._getAmount({type:"MEME",method:"IN",vaultAddress:i,amount:o})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:o,type:n,currentSupply:i}=e;if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Si.NATIVE&&n!==Si.EXACT)throw new I('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==i&&Yt(i,"currentSupply");const r=!i;if(r&&!t)throw new I("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&jt(t);let a=i;if(r){a=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return n===Si.EXACT?Ai.calculateBuyWithExact(o,a):Ai.calculateBuyWithNative(o,a)}async calculateSellAmountLocal(e){const{tokenName:t,amount:o,type:n,currentSupply:i,maxSupply:r,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:s}=e;if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Si.EXACT&&n!==Si.NATIVE)throw new I('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==i&&Yt(i,"currentSupply");const c=!i||!r||void 0===a||void 0===s;if(c&&!t)throw new I("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&jt(t);let l=i,u=r,d=a,h=s;if(c&&t){const e=this.metadataCache.get(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,l||(l=await this.fetchCurrentSupply(t));if(void 0===d||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);d=d??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return n===Si.EXACT?Ai.calculateSellWithExact(o,l,u,h,d):Ai.calculateSellWithNative(o,l,u,h,d)}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 To(t,"tokenName")&&Ao(t)&&So(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:o,calculateAmountMode:n,currentSupply:i}=t;jt(o);const r=await this.tokenResolver.resolveTokenToVault(o);if(!r)throw new I(E(o),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw R("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:r});if(1!==a.Status)throw q(`Failed to fetch pool details: Status ${a.Status}`,a.Status);const s=a.Data,c=(await import("bignumber.js")).default,l=i??new c(s.maxSupply).minus(s.sellingTokenQuantity).toFixed(),u=s.sellingTokenQuantity;if("0"===u)throw new I(`Token ${o} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const d={tokenName:o,amount:u,type:"exact",currentSupply:l,...void 0!==n&&{mode:n}};return await this.calculateBuyAmount(d)}async launchToken(e){if(!this.bundleHttp)throw R("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");mi(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new I("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:o}=e.reverseBondingCurveConfiguration,n=Number(t),i=Number(o);if(isNaN(n)||isNaN(i)||n<=0||i<=0||n>=i)throw new I("Reverse bonding curve configuration must have valid min/max fee portions with min < max","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 q("Image upload failed: No URL returned");n=t}else"string"==typeof e.tokenImage&&(n=e.tokenImage);const i=`galaswap - operation - ${s.v4()}-${Date.now()}-${this.http.getAddress()}`,r={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:i};e.websiteUrl?.trim()&&(r.websiteUrl=e.websiteUrl.trim()),e.telegramUrl?.trim()&&(r.telegramUrl=e.telegramUrl.trim()),e.twitterUrl?.trim()&&(r.twitterUrl=e.twitterUrl.trim()),e.reverseBondingCurveConfiguration&&(r.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const a=new vi(r),c=await this.http.signWithGalaChain("CreateSale",a,o.SigningType.SIGN_TYPED_DATA),{signature:l,types:u,domain:d,prefix:h}=c,g={tokenName:a.tokenName,tokenSymbol:a.tokenSymbol,tokenDescription:a.tokenDescription,tokenImage:a.tokenImage,preBuyQuantity:a.preBuyQuantity,...a.websiteUrl&&{websiteUrl:a.websiteUrl},...a.telegramUrl&&{telegramUrl:a.telegramUrl},...a.twitterUrl&&{twitterUrl:a.twitterUrl},tokenCategory:a.tokenCategory,tokenCollection:a.tokenCollection,uniqueKey:a.uniqueKey,signature:l,types:u,domain:d,...h&&{prefix:h},...a.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:a.reverseBondingCurveConfiguration}},p=`${e.tokenName.trim()}$Unit$none$none`,m="GALA$Unit$none$none";let f;if(parseFloat(t)>0){const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`]}else{const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`]}const y={signedDto:g,stringsInstructions:f,method:"CreateSale"},w=await this.bundleHttp.post("/bundle",y);if(w.error||!w.data)throw q(w.message||"Token launch failed");return w.data}async fetchTokenDistribution(e){if(!e)throw U("tokenName","Token name");jt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new I(E(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const o=encodeURIComponent(t),n=await this.http.get(`/holders/${o}`);if(!0===n.error||200!==n.status||!n.data)throw q(n.message||"Failed to fetch token distribution",n.status);const r=n.data;if(!Array.isArray(r))throw q("Invalid API response: expected array of holders",n.status);for(const e of r){if(!e.owner||"string"!=typeof e.owner)throw q("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw q("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw q(`Invalid holder quantity: "${e.quantity}"`,n.status)}const a=r.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:r.map(e=>{const t=new i(e.quantity),o=a.isZero()?0:t.dividedBy(a).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:o}}),totalSupply:a.toFixed(),totalHolders:r.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw U("tokenName","Token name");jt(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw q(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:o,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const i=("volume"===o?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return i?.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 I("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw R("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},o=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!Ti(o))throw q("Malformed response data from GalaChain gateway");if(1!==o.Status)throw q(`GalaChain calculation failed with status ${o.Status}`,o.Status);const{calculatedQuantity:n,extraFees:i}=o.Data;return{amount:n,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.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 I(E(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw R("GalaChain HTTP client not configured");const o=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==o.Status)throw q(`Failed to fetch pool details: Status ${o.Status}`,o.Status);const n=o.Data,i=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),r=n.sellingTokenQuantity,a=n.maxSupply;let s=.5,c=0;n.reverseBondingCurveConfiguration?(s=parseFloat(n.reverseBondingCurveConfiguration.maxFeePortion),c=parseFloat(n.reverseBondingCurveConfiguration.minFeePortion)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const l=s-c;return this.metadataCache.set(e,{maxSupply:a,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}),{currentSupply:i,remainingTokens:r,maxSupply:a,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}}async fetchCurrentSupply(e){jt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new I(E(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw R("GalaChain HTTP client not configured");const o=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==o.Status)throw q(`Failed to fetch pool details: Status ${o.Status}`,o.Status);const n=o.Data,i=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),r=n.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),i}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Zt(e)}validateTokenName(e){return jt(e)}validatePagination(e){return Ht(e)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw R("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw U("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}}),o=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&o.push({symbol:e.symbol,price:e.currentPrices.usd})}),o}catch(e){throw q(`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 To(t,"tokenName")&&Ao(t)&&So(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:o,calculateAmountMode:n,currentSupply:i}=t;if(!o||"string"!=typeof o)throw U("tokenName","Token name (string)");try{const e={tokenName:o,amount:"1",type:"native",...void 0!==n&&{mode:n},...void 0!==i&&{currentSupply:i}},t=await this.calculateBuyAmount(e),r=(await this.fetchTokenPrice("GALA"))[0];if(!r)throw q("GALA price not available");const a=Number(t.amount);if(a<=0)throw new I(`Invalid token amount calculation: ${a}`,"amount","INVALID_CALCULATION");const s=r.price/a;return{symbol:o.toUpperCase(),price:s}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${o}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${o}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}const Ii={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 Pi(e){return Ii[e]}class xi extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Ni extends Error{constructor(e,t,o){super(`Transaction ${e} failed with status: ${t}${o?` - ${o}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function Di(e,t){if(!e)throw new xi(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new xi(`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 xi(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Fi(e,t,o,n){Di(e,t);const i=e,r=i.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)}(r))throw new xi(`Invalid trade data received for transaction ${t}`);const a={transactionId:t,type:o,method:"native"===n.type?"native":"exact",inputAmount:r.inputQuantity||n.amount,outputAmount:r.outputQuantity||n.expectedAmount||"0",totalFees:r.totalFees||"0",tokenName:n.tokenName,vaultAddress:r.vaultAddress||"",timestamp:Date.now()};return void 0!==i.blockHash&&(a.blockHash=i.blockHash),void 0!==i.gasUsed&&(a.gasUsed=i.gasUsed),void 0!==n.slippageToleranceFactor&&(a.slippageTolerance=n.slippageToleranceFactor),a}const Ci="4.0.1-beta.2";class $i{constructor(e){this.logger=e||new T({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const o=[],n=new WeakSet,i=(e,r=0)=>{if(r>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(n.has(e))return;n.add(e);const a=this.extractLiquidityFromObject(e);a&&!t.has(a.transactionId)&&(o.push(a),t.add(a.transactionId));for(const t of Object.values(e))i(t,r+1)}};return i(e,0),o}extractLiquidityFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const o=e.Data,n=o&&"object"==typeof o&&!Array.isArray(o)?o:e,i=this.extractPositionId(n),r=this.extractPoolHash(n),a=this.extractAmounts(n),s=this.extractUserAddress(n),c=this.extractPoolFee(n);if(!(i&&r&&a&&s&&null!==c))return null;const l=this.extractPoolAlias(n),u=this.extractUserBalanceDelta(n),d=this.extractTimestamp(n),h=u?.token0Balance?.collection,g=u?.token1Balance?.collection,p={transactionId:t,positionId:i,poolHash:r,poolFee:c,amounts:a,userAddress:s};return void 0!==h&&(p.token0=h),void 0!==g&&(p.token1=g),void 0!==d&&(p.timestamp=d),void 0!==l&&(p.poolAlias=l),void 0!==u&&(p.userBalanceDelta=u),p}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","poolId","pool"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const o of t){const t=e[o];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(),o=String(t[1]).trim();if(e&&o)return[e,o]}const o=e.amount0||e.amount0Desired,n=e.amount1||e.amount1Desired;return void 0!==o&&void 0!==n?[String(o),String(n)]:null}extractUserAddress(e){const t=["userAddress","user","owner","from","sender","wallet","address"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractPoolFee(e){const t=["poolFee","fee","feeTier","feeTierBps"];for(const o of t){const t=e[o];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 o of t){const t=e[o];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 o=t,n=this.extractBalanceObject(o.token0Balance),i=this.extractBalanceObject(o.token1Balance);if(!n&&!i)return;const r={};return void 0!==n&&(r.token0Balance=n),void 0!==i&&(r.token1Balance=i),r}extractBalanceObject(e){if(!e||"object"!=typeof e)return;const t=e,o=t.collection,n=t.category,i=t.type,r=t.additionalKey,a=t.quantity,s=t.owner;return"string"==typeof o&&"string"==typeof n&&"string"==typeof i&&"string"==typeof r&&"string"==typeof a&&"string"==typeof s?{collection:o,category:n,type:i,additionalKey:r,quantity:a,owner:s}:void 0}}class Li{constructor(t){this.wallet=t.wallet;let o=null,n="STAGE";t.env?(n=t.env,o=Pi(t.env)):t.baseUrl?.includes("prod")?(n="PROD",o=Pi("PROD")):(n="STAGE",o=Pi("STAGE")),this.environment=n,this.config={baseUrl:o.launchpadBaseUrl,galaChainBaseUrl:o.galaChainBaseUrl,bundleBaseUrl:o.bundleBaseUrl,webSocketUrl:o.webSocketUrl,dexApiBaseUrl:o.dexApiBaseUrl,dexBackendBaseUrl:o.dexBackendBaseUrl,launchpadFrontendUrl:o.launchpadFrontendUrl,timeout:3e4,debug:!1,...t},this.logger=new T({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===t.slippageToleranceFactor?Li.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(t.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===t.maxAcceptableReverseBondingCurveFeeSlippageFactor?Li.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(t.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=t.calculateAmountMode||Li.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=t.pricingConcurrency||5,this.auth=new v({wallet:t.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new b(this.auth,this.config),this.galaChainHttp=new b(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new b(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new b(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new b(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 ti(t.debug||!1),this.launchpadService=new jo(this.http),this.tokenResolverService=new Kn(this.launchpadService.poolService),this.launchpadAPI=new Ei(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new bn(this.galaChainHttp,t.wallet,this.tokenResolverService,t.debug||!1,this.galaChainPublicAxios),this.dexService=new An(this.dexBackendHttp,this.cache,this.galaChainService,t.debug||!1),this.bundleService=new Bn(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,t.wallet,t.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Rn({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new Wn(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new ii(this.galaChainHttp,this.config.galaChainBaseUrl,t.debug||!1,t.dexQuoteNetworkTimeout||3e4),this.gswapService=new Jn({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 oi(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,t.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw R("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw R('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const o=new t.Wallet(e),n={...this.config,wallet:o};return new Li(n)}getAddress(){return this.validateWallet(),this.auth.getAddress()}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw new I("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 I("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}}getVersion(){return Ci}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw R("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:o,currentSupply:n,calculateAmountMode:i}=e;if(t&&!o){const e={tokenName:t};return n&&(e.currentSupply=n),i&&(e.calculateAmountMode=i),this.fetchLaunchpadTokenSpotPrice(e)}if(o&&!t)try{return await this.dexService.fetchTokenPrice({tokenId:o})}catch(e){const t=function(e){if(_o(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(o)).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 r={tokenName:t};return n&&(r.currentSupply=n),i&&(r.calculateAmountMode=i),this.fetchLaunchpadTokenSpotPrice(r)}catch(t){throw this.logger.error(`Launchpad fallback failed: ${Oo(t)}`),e}}throw e}if(!t&&!o)throw U("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");throw new I("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(E(e));const o=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return o.currentSupply=n.currentSupply,o.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,o.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,o.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,o.tokenName=e,o}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 Jt}),o=t(e)||this.getAddress();return this.galaChainService.fetchGalaBalance({owner:o,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return fn}),n=t(e.tokenId),{collection:i,category:r,type:a,additionalKey:s}=n;return this.galaChainService.fetchTokenBalance({owner:o,collection:i,category:r,additionalKey:s,type:a,instance:"0"})}if(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...o&&{address:o}})).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 U("tokenId or tokenName","Either tokenId or tokenName")}async fetchComments(e){return this.launchpadService.fetchComments(e)}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:o,maxAcceptableReverseBondingCurveFeeSlippageFactor:n,privateKey:i,calculateAmountMode:r,currentSupply:a}=e;let s=t;void 0===r&&void 0===a||(s={tokenName:t,...void 0!==r&&{calculateAmountMode:r},...void 0!==a&&{currentSupply:a}});const c=await this.calculateBuyAmountForGraduation(s),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==o&&(l.slippageToleranceFactor=o),void 0!==n&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=n),void 0!==i&&(l.privateKey=i),await this.buy(l)}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:o,...n}=e;return t.buy(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,o=t?.transactionId;if(!o)throw K("No transaction ID returned from buy operation");return this.waitForConfirmation(o,t=>Fi(t,o,"buy",e))}async sell(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.sell(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,o=t?.transactionId;if(!o)throw K("No transaction ID returned from sell operation");return this.waitForConfirmation(o,t=>Fi(t,o,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async postComment(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.postComment(n)}return this.validateWallet(),this.launchpadService.postComment(e)}async launchToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.launchToken(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,o=>{Di(o,t);const n=o?.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)}(n))throw new xi(`Invalid launch data received for transaction ${t}`);const i={transactionId:t,vaultAddress:n.vaultAddress||"",tokenStringKey:n.tokenStringKey||"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:n.creatorAddress||this.getAddress(),timestamp:Date.now(),...o.blockHash&&{blockHash:o.blockHash},...o.gasUsed&&{gasUsed:o.gasUsed}};return"string"==typeof e.tokenImage&&(i.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(i.preBuyQuantity=e.preBuyQuantity),i.vaultAddress&&this.tokenResolverService.set(e.tokenName,i.vaultAddress),i})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.uploadTokenImage(n)}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 Jt}),o=t(e)||this.getAddress();return this.launchpadService.fetchProfile(o)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,address:t(e.address)};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.updateProfile(n)}return this.validateWallet(),this.launchpadService.updateProfile(o)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,address:t(e.address)||this.getAddress()};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.uploadProfileImage(n)}return this.validateWallet(),this.launchpadService.uploadProfileImage(o)}async retrieveGalaFromFaucet(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={walletAddress:t(e)||this.getAddress(),amount:"5"};return this.launchpadService.transferFaucets(o)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o=t(e?.address)||this.getAddress(),n={page:e?.page||1,limit:e?.limit||10,address:o};return e?.tokenName&&(n.tokenName=e.tokenName),e?.search&&(n.search=e.search),this.launchpadService.fetchTokensHeld(n)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(o.tokenName=e.tokenName),e?.search&&(o.search=e.search),this.launchpadService.fetchTokenList(o)}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 Jt}),o={...e,recipientAddress:t(e.recipientAddress)};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.transferGala(n)}return this.validateWallet(),this.galaChainService.transferGala(o)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,to:t(e.to)};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.transferToken(n)}return this.validateWallet(),this.galaChainService.transferToken(o)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async lockToken(e){if(e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt});e={...e,lockAuthority:t(e.lockAuthority)}}if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.lockToken(n)}return this.validateWallet(),this.galaChainService.lockToken(e)}async unlockToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.unlockToken(n)}return this.validateWallet(),this.galaChainService.unlockToken(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}getCacheInfo(){return this.launchpadAPI.getCacheStats()}clearCache(e){this.launchpadAPI.clearCache(e)}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 R("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw R("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw R(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw R(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw R(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw R(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw R(`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: ${Li.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Li.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: ${Li.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Li.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 o=await this.websocketService.waitForTransaction(e);if("completed"!==o.status)throw new Ni(e,o.status,o.message);let n;try{n=t(o)}catch(t){if(t instanceof xi)throw t;throw new xi(`Failed to transform WebSocket response for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,n),n}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Ni||t instanceof xi)throw t;throw new xi(`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:o}=await Promise.resolve().then(function(){return Mi});e.forEach(e=>{if(!o(e))return;const n=t(e,this.logger);n&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,n)})}async getSwapQuoteExactInput(e,t,o){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:o})}async getSwapQuoteExactOutput(e,t,o){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:o})}async executeSwap(e,t,o,n,i,r=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:o,estimatedOutput:n,feeTier:i,slippageTolerance:r})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,o){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:o})}async getSwapUserLiquidityPositions(e,t,o,n){let i,r;"string"==typeof o?(i=o,r=n):"object"==typeof o?r=o:n&&(r=n);return await this.gswapService.getUserLiquidityPositions(e,t,i,r)}async getAllSwapUserLiquidityPositions(e,t){const o=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(o))return o;if(o&&"items"in o)return o.items}return o}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t,o,n,i,r,a){return this.gswapService.getLiquidityPositionById(e,t,o,n,i,r,a)}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={...e,fee:e.feeTier??e.fee};return 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 o=this.websocketService.getSocket();return o?(o.on(e,t),()=>{o.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 o=1e3,n=Math.max(t?.intervalMs??3e4,o);t?.intervalMs&&t.intervalMs<o&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const i=t?.minTVL,r=t?.tokens,a=new Map;let s=!0,c=null;let l=0;const u=async()=>{if(s){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.pools.forEach(t=>{const o=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!a.has(o)){if((e=>{if(a.set(e,!0),a.size>1e3){const e=a.keys().next().value;void 0!==e&&a.delete(e)}})(o),i){if((t.token0Tvl+t.token1Tvl)/2<i)return}if(r&&r.length>0){if(!(r.includes(t.token0)||r.includes(t.token1)))return}e(t)}})}catch(e){l++;const t=e instanceof Error?e.message:String(e);l>=5?this.logger.error(`Polling for new DEX pools failed ${l} consecutive times. Last error: ${t}. Continuing to retry...`):l>1?this.logger.warn(`Error polling for new DEX pools (attempt ${l}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(s){const e=Math.min(Math.max(l-1,0),2),t=n*Math.pow(2,e);c=setTimeout(u,t)}}};return u(),()=>{s=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const o=1e3,n=Math.max(t?.intervalMs??3e4,o);t?.intervalMs&&t.intervalMs<o&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const i=t?.creatorAddress,r=new Map;let a=!0,s=null;let c=0;const l=async()=>{if(a){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=>{r.has(t.tokenName)||((e=>{if(r.set(e,!0),r.size>1e3){const e=r.keys().next().value;void 0!==e&&r.delete(e)}})(t.tokenName),i&&t.creatorAddress!==i||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(a){const e=Math.min(Math.max(c-1,0),2),t=n*Math.pow(2,e);s=setTimeout(l,t)}}};return l(),()=>{a=!1,s&&clearTimeout(s),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 o=e;for(const e of t)if(o[e])return String(o[e]);return""}looksLikePoolPair(e){if("string"!=typeof e)return null;const t=e.trim();if(!t.includes("/"))return null;const o=t.split("/");return 3!==o.length?null:o[0]&&o[1]&&o[2]?t:null}buildPoolPairFromObject(e){if("object"!=typeof e||null===e)return null;const t=e,o=this.extractField(t,"token0ClassKey","token0Class","token0","token0Symbol")||"",n=this.extractField(t,"token1ClassKey","token1Class","token1","token1Symbol")||"",i=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return o&&n&&null!==i?`${o}/${n}/${i}`:null}parsePoolPairString(e){const t=e.split("/");if(3!==t.length)return null;const o=t[0].split("|")[0],n=t[1].split("|")[0],i=t[2];return o&&n&&i?{token0:o,token1:n,fee:i,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,o=t.userBalanceDelta??t.balanceDelta??t.delta;if(!o||"object"!=typeof o||null===o)return null;const n=o,i=n.token0Balance??n.token0??n.baseBalance??n.primaryBalance,r=n.token1Balance??n.token1??n.quoteBalance??n.secondaryBalance,a=this.serializeBalanceToken(i),s=this.serializeBalanceToken(r),c=this.normalizeFee(t.poolFee??t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps);return a&&s&&null!==c?`${a}/${s}/${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,o=this.looksLikePoolPair(t.poolPair);if(o)return this.parsePoolPairString(o);const n=this.buildPoolPairFromBalances(t);if(n)return this.parsePoolPairString(n);const i=this.buildPoolPairFromObject(t);if(i)return this.parsePoolPairString(i);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[o,n]=t.pairTokens,i=e.token0===o||e.token1===o,r=e.token0===n||e.token1===n;if(!i||!r||o===n)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 o=!1,n=null;const i=(o,...n)=>{try{if(n.length>0&&"object"==typeof n[0]&&null!==n[0]){const o=n[0].data;if(o&&o.Data&&"object"==typeof o.Data){const n=o.Data;if("CreateSale"===n.functionName){const o={tokenName:n.tokenName||"",symbol:n.symbol||"",creatorAddress:n.creatorAddress||"",description:n.description||"",image:n.image||"",vaultAddress:n.vaultAddress||"",tokenStringKey:n.tokenStringKey||"",preBuyQuantity:n.initialBuyQuantity||"0",websiteUrl:n.websiteUrl||"",telegramUrl:n.telegramUrl||"",twitterUrl:n.twitterUrl||"",isFinalized:n.isFinalized||!1};this.matchesCreatorFilter(o,t?.creatorFilter)&&e(o)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${e instanceof Error?e.message:String(e)}`)}};let r=this.websocketService.getSocket();if(r)r.onAny(i),o=!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 o=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(o)});let e=0;const a=()=>{if(r=this.websocketService.getSocket(),!r&&e<Li.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(n=setTimeout(()=>a(),Li.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!r&&e>=Li.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Li.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Li.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}r&&(r.onAny(i),o=!0,this.logger.debug("Token creation broadcast listener registered"))};a()}return()=>{try{if(null!==n&&(clearTimeout(n),n=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!o)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(i),o=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}walkPayloadForPools(e,t,o=new WeakSet){const n=[];if("string"==typeof e){const o=this.looksLikePoolPair(e);if(o){const e=this.parsePoolPairString(o);e&&!t.has(e.poolPair)&&(t.add(e.poolPair),n.push(e))}return n}if("object"!=typeof e||null===e)return n;if(o.has(e))return n;o.add(e);const i=this.extractPoolDataFromPayload(e);i&&!t.has(i.poolPair)&&(t.add(i.poolPair),n.push(i));for(const i of Object.values(e)){const e=this.walkPayloadForPools(i,t,o);n.push(...e)}return n}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 o=!1,n=null;const i=new Set,r=(o,...n)=>{try{for(const o of n){const n=this.walkPayloadForPools(o,i);for(const o of n)this.matchesPoolFilter(o,t)&&e(o)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${e instanceof Error?e.message:String(e)}`)}};let a=this.websocketService.getSocket();if(a)a.onAny(r),o=!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 o=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(o)});let e=0;const i=()=>{if(a=this.websocketService.getSocket(),!a&&e<Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(n=setTimeout(()=>i(),Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX pool subscription timeout:",e.message),void(t?.onError&&t.onError(e))}a&&(a.onAny(r),o=!0,this.logger.debug("DEX pool broadcast listener registered"))};i()}return()=>{try{if(null!==n&&(clearTimeout(n),n=null,this.logger.debug("Cleared DEX pool polling timeout")),!o)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(r),o=!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 o=null,n=null,i=null,r=!1;const a=async e=>{const t=ai.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})},s=()=>{const c=this.websocketService.getSocket();if(!c)return this.logger.debug("WebSocket not yet ready for swap monitoring, polling..."),void(o=setTimeout(()=>s(),100));r=!0,n=new gi(c,a,this.dexQuoteService,t||{},this.logger),i=n.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 o=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(o)})),s(),()=>{try{o&&clearTimeout(o),i&&r&&i(),n&&n.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 o=!1,n=null;const i=new Set,r=new $i(this.logger),a=(o,...n)=>{try{for(const o of n){const n=r.walkPayloadForLiquidityEvents(o,i);for(const o of n)if(this.matchesLiquidityFilter(o,t))try{const t=e(o);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 s=this.websocketService.getSocket();if(s)s.onAny(a),o=!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 o=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(o)});let e=0;const i=()=>{if(s=this.websocketService.getSocket(),!s&&e<Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(n=setTimeout(()=>i(),Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX liquidity subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(a),o=!0,this.logger.debug("DEX liquidity broadcast listener registered"))};i()}return async()=>{try{if(null!==n&&(clearTimeout(n),n=null,this.logger.debug("Cleared DEX liquidity polling timeout")),!o)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(a),o=!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 o=this.normalizeFeeTier(t.feeTierFilter);if(e.poolFee!==o)return!1}if(t.userFilter&&e.userAddress!==t.userFilter)return!1;if(t.tokenFilter){const o=e.token0?.toLowerCase().includes(t.tokenFilter.toLowerCase()),n=e.token1?.toLowerCase().includes(t.tokenFilter.toLowerCase());if(!o&&!n)return!1}if(t.pairTokens){const[o,n]=t.pairTokens.map(e=>e.toLowerCase()),i=e.token0?.toLowerCase()||"",r=e.token1?.toLowerCase()||"",a=i.includes(o)&&r.includes(n),s=i.includes(n)&&r.includes(o);if(!a&&!s)return!1}if(t.minAmount){const o=parseFloat(t.minAmount),n=parseFloat(e.amounts[0])||0,i=parseFloat(e.amounts[1])||0;if(Math.abs(n)<o&&Math.abs(i)<o)return!1}return!0}normalizeFeeTier(e){if("number"==typeof e)return e>=100?e:Math.round(1e4*e);const t=e.replace("%","").trim(),o=parseFloat(t);return o>=100?o:Math.round(1e4*o)}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 T({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:o}=require("./services/WebSocketService");o.cleanupAll(e),t.debug("Global cleanup completed")}}Li.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Li.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Li.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=ei.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Li.DEFAULT_CALCULATE_AMOUNT_MODE=bi.LOCAL,Li.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Li.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class Oi{static generateWallet(){try{const e=t.Wallet.createRandom();if(!e.mnemonic?.phrase)throw new Error("Failed to generate wallet with mnemonic phrase");const o=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:o,mnemonic:e.mnemonic.phrase,wallet:new t.Wallet(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,o="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),n=new t.Wallet(o),i=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:i,mnemonic:"test test test test test test test test test test test junk",wallet:n}}throw e}}static fromPrivateKey(e){const o=new t.Wallet(e),n=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:n,mnemonic:"",wallet:o}}static fromMnemonic(e,o=0){try{const n=t.Mnemonic.fromPhrase(e),i=t.HDNodeWallet.fromMnemonic(n,`m/44'/60'/0'/0/${o}`),r=new t.Wallet(i.privateKey),a=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:a,mnemonic:e,wallet:r}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${o}-${e}`,i="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),r=new t.Wallet(i),a=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:a,mnemonic:e,wallet:r}}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 o=0;o<e;o++){const e=`test-multi-${o}-${Date.now()}-${++this.testCounter}`,n="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(n))}else for(let o=0;o<e;o++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const o=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${e.mnemonic||"Not available"}`];return t?o.splice(3,0,`🔑 Private Key: ${e.privateKey}`):o.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),o.push("═".repeat(50)),o.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),o.push("This is your backup to recover the wallet."),o.join("\n")}}function _i(e){if(void 0===e)return Oi.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 Oi.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 Oi.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?"...":""}"`)}Oi.testCounter=0;class Bi{static fastValidation(e,t,o,n=Bi.DEFAULT_CONFIG){const r=Date.now();let a=!0;try{const s=new i(e.sqrtPrice),c=new i(t.sqrtPrice);o.zeroForOne?c.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:c.toString(),zeroForOne:o.zeroForOne}),a=!1):c.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:c.toString(),zeroForOne:o.zeroForOne}),a=!1);const l=new i(e.liquidity),u=new i(t.liquidity);if(!l.isZero()){const e=u.minus(l).abs().div(l);e.gt(n.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:l.toString(),updatedLiquidity:u.toString(),changePct:e.times(100).toFixed(2)})}const d=new i(e.feeGrowthGlobal0),h=new i(t.feeGrowthGlobal0),g=new i(e.feeGrowthGlobal1),p=new i(t.feeGrowthGlobal1);o.zeroForOne?p.lt(g)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:g.toString(),updatedFeeGrowth1:p.toString()}),a=!1):h.lt(d)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:d.toString(),updatedFeeGrowth0:h.toString()}),a=!1);const m=new i(e.protocolFeesToken0),f=new i(t.protocolFeesToken0),y=new i(e.protocolFeesToken1),w=new i(t.protocolFeesToken1);f.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:m.toString(),updatedProtocolFees0:f.toString()}),a=!1),w.lt(y)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:y.toString(),updatedProtocolFees1:w.toString()}),a=!1);const k=Date.now()-r;return this.logger.debug("Fast validation completed",{passed:a,elapsedMs:k}),a}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,o=Bi.DEFAULT_CONFIG){const n=Date.now(),a=[];let s=0;try{if(t.actualSqrtPrice){const n=new i(e.sqrtPrice),r=new i(t.actualSqrtPrice),c=this.calculateDriftPercentage(n,r);s=c,c>100*o.maxDriftThreshold&&a.push(`Price drift detected: ${c.toFixed(4)}% (threshold: ${(100*o.maxDriftThreshold).toFixed(4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:n.toString(),actualSqrtPrice:r.toString(),driftPct:c.toFixed(4)})}const c=new i(e.sqrtPrice),l=new i(2).pow(96),u=c.dividedBy(l),d=r.sqrtPriceToTick(u),h=e.tick??0,g=Math.abs(d-h);g>o.maxTickDrift&&a.push(`Tick/price mismatch: tick=${h}, calculated=${d}, drift=${g}`);const p=new i(e.feeGrowthGlobal0),m=new i(e.feeGrowthGlobal1),f=new i(e.liquidity);try{en(p,m,f)}catch(e){a.push(e.message)}const y=0===a.length,w=!y||s>100*o.maxDriftThreshold,k=Date.now()-n;return this.logger.debug("Moderate validation completed",{isValid:y,shouldRefetch:w,driftPercentage:s,errorCount:a.length,elapsedMs:k}),this.buildValidationResult(y,s,w,a)}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,o){const n=Date.now(),r=[];let a=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await o(),c=new i(t.pool.sqrtPrice),l=new i(s.pool.sqrtPrice),u=this.calculateDriftPercentage(c,l);a=Math.max(a,u),u>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&r.push(`Price drift: ${u.toFixed(4)}% (cached: ${c.toString()}, fresh: ${l.toString()})`);const d=new i(t.pool.liquidity),h=new i(s.pool.liquidity),g=this.calculateDriftPercentage(d,h);a=Math.max(a,g),g>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&r.push(`Liquidity drift: ${g.toFixed(4)}% (cached: ${d.toString()}, fresh: ${h.toString()})`);const p=Object.keys(t.tickDataMap).length,m=Object.keys(s.tickDataMap).length;if(m>0){const e=Math.abs(m-p)/m;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&r.push(`Tick data incomplete: cached has ${p} ticks, fresh has ${m} ticks (${(100*e).toFixed(2)}% difference)`)}const f=0===r.length,y=!f,w=Date.now()-n;return this.logger.debug("Full validation completed",{poolKey:e,isValid:f,shouldRefetch:y,maxDriftPercentage:a,priceDrift:u,liquidityDrift:g,cachedTickCount:p,freshTickCount:m,errorCount:r.length,elapsedMs:w}),this.buildValidationResult(f,a,y,r)}catch(t){this.logger.error("Full validation exception",{poolKey:e,error:t});const o=t instanceof Error?t.message:String(t);return this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${o}`])}}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,o,n=[]){let i;if(o&&n.length>0){const e=n.join(" ").toLowerCase();i=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const r={isValid:e,driftPercentage:t,shouldRefetch:o,validationErrors:n};return void 0!==i&&(r.refetchReason=i),r}}Bi.logger=new T({debug:!1,context:"PoolStateValidator"}),Bi.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class Ui{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return h.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){this.logger=new T({debug:t?.debug??!1,context:"PoolStateManager"});const o={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??i.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={...o,...t?.onRefetchNeeded?{onRefetchNeeded:t.onRefetchNeeded}:{}},this.validationConfig=Bi.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:Ui.calculatePoolStateHash(this.pool)};if(!Bi.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},o={maxIterations:this.config.maxIterations,enableBigNumberCache:this.config.enableBigNumberCache,roundingMode:this.config.roundingMode,debugLogging:this.config.debug},n=ui.calculateSwapDelta(t,e,o);this.lastSwapMetrics={calculationTimeMs:n.metadata.calculationTimeMs,swapSteps:n.metadata.swapSteps,timestamp:Date.now()},this.config.enablePerformanceWarnings&&n.metadata.calculationTimeMs>this.config.performanceWarningThreshold&&this.logger.warn("Slow swap calculation",{calculationTimeMs:n.metadata.calculationTimeMs,swapSteps:n.metadata.swapSteps,threshold:this.config.performanceWarningThreshold});if(!Bi.fastValidation(t.pool,n.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new Error("Swap validation failed");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=new i(e.actualAmount0),o=new i(e.actualAmount1),r=n.amount0.minus(t).abs(),a=n.amount1.minus(o).abs(),s=t.isZero()?0:r.div(t.abs()).times(100).toNumber(),c=o.isZero()?0:a.div(o.abs()).times(100).toNumber(),l=Math.max(s,c);l>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:l.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=l)}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=Ui.calculatePoolStateHash(this.pool),this.logger.info("Full refetch completed",{sqrtPrice:this.pool.sqrtPrice.toString()})}return this.pool=n.updatedPool,Object.assign(this.tickDataMap,n.updatedTicks),this.metadata.swapsSinceRefetch++,this.metadata.stateHash=Ui.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:n.amount0.toString(),amount1:n.amount1.toString(),sqrtPriceNew:this.pool.sqrtPrice.toString()}),n}catch(o){const n=o instanceof Error?o.message:String(o);if(this.logger.error("Failed to apply swap delta",{transactionId:e.transactionId,error:n}),this.config.strictValidation)throw o;return{updatedPool:this.pool,updatedTicks:{},amount0:new i(0),amount1:new i(0),feeAmount0:new i(0),feeAmount1:new i(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:Ui.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}var Mi=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const o={};if(e.vaultAddress&&(o.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const n=parseFloat(e.reverseBondingCurveMinFeePortion);isNaN(n)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):o.reverseBondingCurveMinFeeFactor=n}if(void 0!==e.reverseBondingCurveMaxFeePortion){const n=parseFloat(e.reverseBondingCurveMaxFeePortion);isNaN(n)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):o.reverseBondingCurveMaxFeeFactor=n}return void 0!==o.reverseBondingCurveMaxFeeFactor&&void 0!==o.reverseBondingCurveMinFeeFactor&&(o.reverseBondingCurveNetFeeFactor=o.reverseBondingCurveMaxFeeFactor-o.reverseBondingCurveMinFeeFactor),Object.keys(o).length>0?o: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}});exports.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),o=this.setupWallet(e.privateKey),n={wallet:o.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{}},i=new Li(n),r={sdk:i,wallet:o,config:n};if(!1!==e.autoValidate){const e=await this.validateSetup(i,o);return{...r,validation:e}}return r}static async readOnlySetup(e={}){const t=e.environment||this.detectEnvironment(),o={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||{}};return{sdk:new Li(o),config:o}}static async validateSetup(e,t){const o=[],n=[],i={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(i.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);i.hasBalance=e>0,i.canTrade=e>=.1,i.canCreateTokens=e>=100,0===e?n.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?n.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&n.push("GALA balance too low for token creation (minimum 100 GALA)")}else o.push("Failed to fetch GALA balance: No balance returned")}catch(e){o.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||n.push("Pool listing not accessible - some features may be limited")}catch(e){n.push(`Pool access test failed: ${e instanceof Error?e.message:String(e)}`)}return{ready:0===o.length&&i.connectionHealthy,sdk:e,wallet:t||Oi.generateWallet(),issues:o,warnings:n,capabilities:i}}static getRecommendedConfig(e,t="general"){const o={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(o,{debug:!1,timeout:3e4});break;case"development":Object.assign(o,{debug:!0,timeout:45e3});break;case"testing":Object.assign(o,{debug:!0,timeout:6e4})}switch(t){case"trading":o.timeout=1.5*(o.timeout||3e4);break;case"creation":o.timeout=2*(o.timeout||3e4);break;case"monitoring":o.timeout=.5*(o.timeout||3e4)}return o}static async multiWalletSetup(e,t="development"){const o={};for(const[n,i]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:i,agentId:`multi-wallet-${n}`,autoValidate:!1});o[n]=e}return o}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?Oi.fromPrivateKey(e):Oi.generateWallet()}return"generate"===e?Oi.generateWallet():Oi.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}},exports.CALCULATION_MODES=bi,exports.COMPOSITE_POOL_FETCH_CONCURRENCY=5,exports.ConfigurationError=x,exports.DexPoolNotFoundError=_,exports.DexQuoteError=O,exports.FileValidationError=Ko,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.GSwapAssetError=$,exports.GSwapPoolError=C,exports.GSwapQuoteError=D,exports.GSwapSwapError=F,exports.IMAGE_EXTENSIONS=Oe,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LaunchpadSDK=Li,exports.LockError=kn,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.NetworkError=P,exports.PAGINATION_DEFAULTS=wo,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PoolStateManager=Ui,exports.QUERY_FIELD_NAMES={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"},exports.SDK_VERSION=Ci,exports.TRADING_TYPES=Si,exports.TokenMetadataService=class extends vo{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}async resolveTokenMetadata(e){const t=this.getCacheKey(e),o=this.cache[t];if(o&&!this.isCacheExpired(o.timestamp))return this.logger.debug(`Using cached metadata for token: ${t}`),o.data;const n=this.extractMetadata(e);return this.cache[t]={data:n,timestamp:Date.now()},n}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,o,n="Token",i="Unit",r="none";if("string"==typeof e)if(e.includes("|")){const a=e.split("|");"Token"===a[0]&&a[2]?(n=a[0],i=a[1]||"Unit",t=a[2],r=a[3]||"none",o=t):(t=a[0],o=t,i=a[1]||"Unit",r=a[3]||"none")}else t=e,o=e;else t=e.type||"unknown",n=e.collection||"Token",i=e.category||"Unit",r=e.additionalKey||"none",o=e.symbol||("Token"===n?t:n)||"unknown";const a=this.getDecimalsForToken(o);return{symbol:o.toUpperCase(),decimals:a,collection:n,category:i,type:t.toUpperCase(),additionalKey:r,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`)}},exports.TransactionError=N,exports.TransactionFailedError=Ni,exports.ValidationError=I,exports.WebSocketError=xi,exports.WebSocketTimeoutError=class extends xi{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.addressFormatSchema=ee,exports.amountMethodSchema=Ce,exports.amountTypeSchema=Fe,exports.browserFileSchema=Be,exports.bufferFileSchema=Ue,exports.buyTokensDataSchema=at,exports.calculatePreMintDataSchema=gt,exports.checkPoolOptionsSchema=De,exports.commentMessageSchema=ye,exports.commentPaginationSchema=We,exports.createLaunchpadSDK=function(e){e||(e={});const{wallet:o,env:n,config:i={},...r}=e,a={...r,...i},{wallet:s,env:c,config:l,...u}=a;let d;if(o)if("string"==typeof o){d=_i(o).wallet}else{if(!(o instanceof t.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");d=o}else{d=_i().wallet}const h={wallet:d,...n&&{env:n},debug:!1,timeout:3e4,...u};return new Li(h)},exports.createLimitSchema=ue,exports.createPaginatedResultSchema=function(e){return n.z.object({data:n.z.array(e),page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()})},exports.createPoolStateManager=function(e,t){return new Ui(e,t)},exports.createTradeDataSchema=rt,exports.createWallet=_i,exports.ethereumAddressSchema=te,exports.faucetAmountSchema=ae,exports.fetchGalaBalanceOptionsSchema=Je,exports.fetchPoolDetailsDataSchema=pt,exports.fetchTokenBalanceOptionsSchema=ot,exports.fileSizeSchema=pe,exports.fileUploadSchema=_e,exports.filenameSchema=me,exports.filterByFeeTier=function(e,t){return e.filter(e=>e.feeTier===t)},exports.filterByLiquidity=function(e){return e.filter(e=>new i(e.liquidity).isGreaterThan(0))},exports.filterByMinLiquidity=function(e,t){const o=new i(t);return e.filter(e=>new i(e.liquidity).isGreaterThanOrEqualTo(o))},exports.filterByPoolKey=function(e,t,o,n){const i=t.toUpperCase(),r=o.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),o=e.token1.toUpperCase();return(t===i&&o===r||t===r&&o===i)&&e.feeTier===n})},exports.filterByToken=function(e,t){const o=t.toUpperCase();return e.filter(e=>e.token0.toUpperCase()===o||e.token1.toUpperCase()===o)},exports.filterByTokenPair=function(e,t,o){const n=t.toUpperCase(),i=o.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),o=e.token1.toUpperCase();return t===n&&o===i||t===i&&o===n})},exports.flexibleAddressSchema=oe,exports.flexibleFileSchema=Me,exports.formatGalaForDTO=In,exports.formatLaunchpadTokenForDTO=Pn,exports.fullNameSchema=J,exports.getAmountOptionsSchema=ht,exports.getEnv=function(e,t){return process.env[e]??t},exports.getEnvOrThrow=function(e,t){const o=process.env[e];if(!o){throw new Error(t?`${e} not set in root or local .env (${t})`:`${e} not set in root or local .env`)}return o},exports.getTradeOptionsSchema=ct,exports.graduateTokenOptionsSchema=Le,exports.graphDataOptionsSchema=$e,exports.groupByFeeTier=function(e){const t=new Map;return e.forEach(e=>{t.has(e.feeTier)||t.set(e.feeTier,[]),t.get(e.feeTier).push(e)}),t},exports.groupByPoolKey=function(e){const t=new Map;return e.forEach(e=>{const o=`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`;t.has(o)||t.set(o,[]),t.get(o).push(e)}),t},exports.groupByTokenPair=function(e){const t=new Map;return e.forEach(e=>{const o=`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`;t.has(o)||t.set(o,[]),t.get(o).push(e)}),t},exports.imageExtensionSchema=qe,exports.imageFilenameSchema=Re,exports.imageMimeTypeSchema=fe,exports.imageUploadOptionsSchema=xe,exports.isLockTokenData=yn,exports.isUnlockTokenData=wn,exports.isoDateStringSchema=we,exports.launchTokenDataSchema=Pe,exports.loadEnvWithFallback=function(){const e=f.join(process.cwd(),"..","..",".env");y.existsSync(e)&&w.config({path:e});const t=f.join(process.cwd(),".env");y.existsSync(t)&&w.config({path:t})},exports.nonNegativeDecimalStringSchema=re,exports.optionalUrlSchema=ce,exports.pageNumberSchema=le,exports.paginationResultMetaSchema=Qe,exports.poolFetchTypeSchema=Ne,exports.poolPaginationSchema=je,exports.positiveDecimalStringSchema=ie,exports.privateKeySchema=ve,exports.requireNonNegative=en,exports.requirePositive=function(...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()}`)})},exports.requirePositiveWithContext=tn,exports.reverseBondingCurveConfigSchema=Ie,exports.reverseBondingCurveConfigurationSchema=mt,exports.searchQuerySchema=Y,exports.sellTokensDataSchema=st,exports.sortByLiquidity=function(e,t="desc"){return[...e].sort((e,o)=>{const n=new i(e.liquidity),r=new i(o.liquidity);return"desc"===t?r.minus(n).toNumber():n.minus(r).toNumber()})},exports.standardLimitSchema=de,exports.standardPaginationSchema=Ke,exports.timestampSchema=ke,exports.tokenCategorySchema=Ae,exports.tokenCollectionSchema=Ee,exports.tokenDescriptionSchema=X,exports.tokenListOptionsSchema=Ze,exports.tokenNameSchema=V,exports.tokenSymbolSchema=Q,exports.tokenUrlsSchema=be,exports.tradeCalculationMethodSchema=dt,exports.tradeCalculationTypeSchema=ut,exports.tradeLimitSchema=ge,exports.tradeListParamsSchema=lt,exports.tradePaginationSchema=ze,exports.tradePaginationWithFiltersSchema=Ve,exports.tradeTypeBackendSchema=it,exports.tradeTypeSchema=nt,exports.transactionIdSchema=Te,exports.transferFaucetsDataSchema=Ye,exports.uniqueKeySchema=Se,exports.updateProfileDataSchema=et,exports.uploadProfileImageOptionsSchema=tt,exports.urlSchema=se,exports.userLimitSchema=he,exports.userPaginationSchema=Ge,exports.userTokenNameSchema=Z,exports.userTokenTypeSchema=Xe,exports.userTokensPaginationSchema=He,exports.validateAddress=vt,exports.validateAmountString=St,exports.validateBuyTokensData=Ut,exports.validateCalculatePreMintData=Gt,exports.validateCheckPoolOptions=Dt,exports.validateCreateTradeData=Bt,exports.validateFaucetAmount=bt,exports.validateFetchGalaBalanceOptions=$t,exports.validateFetchPoolDetailsData=zt,exports.validateFetchTokenBalanceOptions=_t,exports.validateFullName=At,exports.validateGetAmountOptions=Kt,exports.validateGetTradeOptions=qt,exports.validateImageUploadOptions=Nt,exports.validateLaunchTokenData=Pt,exports.validateSearchQuery=Et,exports.validateSellTokensData=Mt,exports.validateTokenDescription=kt,exports.validateTokenListOptions=Ft,exports.validateTokenName=yt,exports.validateTokenSymbol=wt,exports.validateTokenUrls=xt,exports.validateTradeListParams=Rt,exports.validateTransferFaucetsData=Ct,exports.validateUpdateProfileData=Lt,exports.validateUploadProfileImageOptions=Ot,exports.validateUserTokenName=It,exports.validateVaultAddress=Tt,exports.vaultAddressSchema=ne;
1
+ "use strict";var e=require("axios"),t=require("ethers"),o=require("@gala-chain/connect"),n=require("zod"),i=require("bignumber.js"),r=require("@gala-chain/dex"),a=require("@gala-chain/api"),s=require("uuid"),c=require("socket.io-client"),l=require("path"),u=require("fs"),d=require("dotenv"),h=require("crypto");function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(o){if("default"!==o){var n=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,n.get?n:{enumerable:!0,get:function(){return e[o]}})}}),t.default=e,Object.freeze(t)}var p,m,f=g(l),y=g(u),w=g(d);if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}!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"}(p||(p={}));class k extends Error{constructor(e,t,o){super(t),this.type=e,this.originalError=o,this.name="AuthError"}}class v{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new k(p.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 k(p.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new k(p.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,o=await this.wallet.signMessage(t);return{message:t,signature:o,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof k)throw e;throw new k(p.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 k(p.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 k(p.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 k)throw e;const t=e instanceof Error?e.message:String(e);throw new k(p.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const o=Date.now(),n=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${o}`,i=await this.wallet.signMessage(n);return{"x-signature":i,"x-address":this.formatAddress(this.wallet.address),"x-message":n,"x-timestamp":o.toString()}}catch(e){if(e instanceof k)throw e;throw new k(p.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(e)))}}async signTypedData(e,t,o){this.validateWallet();try{return await this.wallet.signTypedData(e,t,o)}catch(e){if(e instanceof k)throw e;throw new k(p.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 k(p.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 k)throw e;throw new k(p.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new k(p.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new k(p.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new k(p.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"}(m||(m={}));class T{constructor(e){this.levelPriority={[m.DEBUG]:0,[m.INFO]:1,[m.WARN]:2,[m.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?m.DEBUG:m.INFO)}debug(e,t){this.log(m.DEBUG,e,t)}info(e,t){this.log(m.INFO,e,t)}warn(e,t){this.log(m.WARN,e,t)}error(e,t){this.log(m.ERROR,e,t)}log(e,t,o){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===m.DEBUG&&!this.debugEnabled)return;const n=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==o?o instanceof Error?i(`${n} ${t}`,o.message,o.stack):i(`${n} ${t}`,o):i(`${n} ${t}`)}getConsoleMethod(e){switch(e){case m.DEBUG:return console.debug;case m.INFO:return console.info;case m.WARN:return console.warn;case m.ERROR:return console.error;default:return console.log}}child(e){return new T({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[m.DEBUG]>=this.levelPriority[this.minLevel]}}function S(e){if(!e||"object"!=typeof e)return{};const t={};for(const[o,n]of Object.entries(e))null!=n&&("string"==typeof n?t[o]=n:"number"==typeof n||"boolean"==typeof n?t[o]=n.toString():Array.isArray(n)?t[o]=n.join(","):t[o]="object"==typeof n?JSON.stringify(n):String(n));return t}class b{constructor(t,o={}){this.auth=t,this.debug=o.debug??!1,this.logger=new T({debug:this.debug,context:"HttpClient"}),this.axios=e.create({baseURL:o.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:o.timeout||3e4,headers:{Accept:"application/json",...o.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:S(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 o=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:o,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const n=await this.axios.request(t);return this.logger.debug("Response:",{status:n.status,data:n.data}),n.data}catch(e){throw this.logger.error("Error:",e),e}}async get(e,t,o){return this.request({method:"GET",url:e,...t&&{params:t},...o&&{headers:o}})}async post(e,t,o){return this.request({method:"POST",url:e,data:t,...o&&{headers:o}})}async put(e,t,o){return this.request({method:"PUT",url:e,data:t,...o&&{headers:o}})}async delete(e,t,o){return this.request({method:"DELETE",url:e,...t&&{params:t},...o&&{headers:o}})}async patch(e,t,o){return this.request({method:"PATCH",url:e,data:t,...o&&{headers:o}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,o){return await this.auth.signTypedData(e,t,o)}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=o.SigningType.SIGN_TYPED_DATA){const i=this.auth.getPrivateKey(),r=new o.SigningClient(i);return await r.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 A="Token name is required and must be a string",E=e=>`Could not find vault address for token: ${e}`;class I extends Error{constructor(e,t,o){super(e),this.field=t,this.code=o,this.name="ValidationError"}}class P extends Error{constructor(e,t,o){super(e),this.statusCode=t,this.originalError=o,this.name="NetworkError"}}class N extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class x extends Error{constructor(e,t,o){super(e),this.transactionId=t,this.code=o,this.name="TransactionError"}}class D extends Error{constructor(e,t,o){super(e),this.originalError=t,this.code=o,this.name="GSwapQuoteError"}}class C extends Error{constructor(e,t,o,n){super(e),this.originalError=t,this.transactionHash=o,this.code=n,this.name="GSwapSwapError"}}class F extends Error{constructor(e,t,o,n,i){super(e),this.originalError=t,this.tokenA=o,this.tokenB=n,this.code=i,this.name="GSwapPoolError"}}class $ extends Error{constructor(e,t,o,n){super(e),this.originalError=t,this.walletAddress=o,this.code=n,this.name="GSwapAssetError"}}class L extends Error{constructor(e,t,o){super(e),this.originalError=t,this.code=o,this.name="GSwapPositionError"}}class O extends I{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class _ extends I{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function B(e,t){return new I(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function U(e,t){const o=t||e.charAt(0).toUpperCase()+e.slice(1);return new I(`${o} is required`,e,"REQUIRED_FIELD")}function M(e,t,o){const n=o||e.charAt(0).toUpperCase()+e.slice(1);return new I(`${n} must be ${t}`,e,"INVALID_FORMAT")}function R(e,t,o){return new P(e,t,o)}function q(e,t){return new N(e,t)}function K(e,t,o){return new x(e,t,o)}function G(e,t,o){const{MIN_PAGE:n,MAX_PAGE:i,MIN_LIMIT:r,MAX_LIMIT:a}=o.PAGINATION;if("number"!=typeof e||e<n||e>i)throw new I(`Page must be a number between ${n} and ${i}`,"page","INVALID_PAGE");if("number"!=typeof t||t<r||t>a)throw new I(`Limit must be a number between ${r} and ${a}`,"limit","INVALID_LIMIT")}const z={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function W(e){return"string"==typeof e&&e.trim().length>0}function j(e){return!(!e||"string"!=typeof e)&&(z.ETH_ADDRESS.test(e)||z.BACKEND_ADDRESS.test(e))}function H(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const V=n.z.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"),Q=n.z.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"),X=n.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Z=n.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Y=n.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),J=n.z.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"),ee=n.z.string().regex(z.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),te=n.z.string().regex(z.ETH_ADDRESS,"Invalid Ethereum address format"),oe=n.z.string().refine(e=>z.BACKEND_ADDRESS.test(e)||z.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),ne=n.z.string().refine(e=>z.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),ie=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),re=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),ae=n.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),se=n.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),ce=n.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),le=n.z.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 ue(e=100){return n.z.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 de=ue(100),he=ue(20),ge=ue(20),pe=n.z.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"),me=n.z.string().max(255,"Filename must be at most 255 characters"),fe=n.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),ye=n.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),we=n.z.string().datetime("Must be a valid ISO 8601 date string"),ke=n.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),ve=n.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Te=n.z.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"),Se=n.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),be=n.z.object({websiteUrl:ce,telegramUrl:ce,twitterUrl:ce}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),Ae=n.z.string().min(1,"Token category must not be empty").default("Unit"),Ee=n.z.string().min(1,"Token collection must not be empty").default("Token"),Ie=n.z.object({minFeePortion:ie,maxFeePortion:ie}),Pe=n.z.object({tokenName:V,tokenSymbol:Q,tokenDescription:X,tokenImage:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer),n.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:re.default("0"),websiteUrl:ce,telegramUrl:ce,twitterUrl:ce,tokenCategory:Ae,tokenCollection:Ee,reverseBondingCurveConfiguration:Ie.optional(),privateKey:ve.optional()}),Ne=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),tokenName:V}),xe=n.z.enum(["recent","popular"]),De=n.z.object({tokenName:V.optional(),symbol:Q.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),Ce=n.z.enum(["NATIVE","MEME"]),Fe=n.z.enum(["IN","OUT"]),$e=n.z.object({from:n.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:n.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:n.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:V}),Le=n.z.object({tokenName:V,slippageToleranceFactor:n.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:n.z.number().min(0).max(1).optional(),privateKey:ve.optional()}),Oe=[".png",".jpg",".jpeg",".gif",".webp",".svg"],_e=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),name:me,size:pe,type:fe}),Be=n.z.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"),Ue=n.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Me=n.z.union([Be,Ue]),Re=n.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),qe=me.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Oe.includes(t)},`Filename must end with one of: ${Oe.join(", ")}`),Ke=n.z.object({page:le,limit:de}),Ge=n.z.object({page:le,limit:he}),ze=n.z.object({page:le,limit:ge}),We=n.z.object({page:le,limit:ue(50)}),je=Ke.extend({type:n.z.enum(["recent","popular"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),He=Ge.extend({tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),Ve=ze.extend({tradeType:n.z.enum(["BUY","SELL"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),userAddress:n.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:n.z.string().datetime().optional(),endDate:n.z.string().datetime().optional(),sortOrder:n.z.enum(["ASC","DESC"]).default("DESC")}),Qe=n.z.object({page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()});const Xe=n.z.enum(["all","DEFI","ASSET"]),Ze=Ge.extend({type:Xe.optional(),address:oe.optional(),search:Y.optional(),tokenName:Z.optional()}),Ye=n.z.object({walletAddress:oe,amount:ae}),Je=n.z.object({address:oe.optional(),refresh:n.z.boolean().optional()}),et=n.z.object({profileImage:n.z.string(),fullName:J,address:oe,privateKey:ve.optional()}),tt=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),address:oe.optional(),privateKey:ve.optional()}),ot=n.z.object({address:oe,tokenId:n.z.union([n.z.string(),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string()}),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string(),instance:n.z.string()})]).optional(),tokenName:Z.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),nt=n.z.enum(["buy","sell"]),it=n.z.enum(["BUY","SELL"]),rt=n.z.object({tradeType:nt,tokenAmount:ie,vaultAddress:ne,userAddress:oe,slippageTolerance:ie.optional(),deadline:n.z.number().int().positive().optional()}),at=n.z.object({tokenSymbol:Q,nativeTokenQuantity:ie,expectedToken:ie,maxAcceptableReverseBondingCurveFee:re.default("0").optional()}),st=n.z.object({tokenSymbol:Q,tokenQuantity:ie,expectedNativeToken:ie,maxAcceptableReverseBondingCurveFee:re.default("0").optional()}),ct=ze.extend({tokenName:Z.optional()}),lt=n.z.object({page:n.z.number().int().min(1).max(1e3).default(1).optional(),limit:n.z.number().int().min(1).max(20).default(10).optional()}),ut=n.z.enum(["NATIVE","MEME"]),dt=n.z.enum(["IN","OUT"]),ht=n.z.object({type:ut,method:dt,vaultAddress:ne,amount:ie}),gt=n.z.object({nativeTokenQuantity:ie}),pt=n.z.object({vaultAddress:ne}),mt=n.z.object({minFeePortion:ie,maxFeePortion:ie});function ft(e){return t=>{const o=e.safeParse(t);return{success:o.success,data:o.success?o.data:void 0,errors:o.success?void 0:o.error.errors.map(e=>e.message)}}}const yt=ft(V),wt=ft(Q),kt=ft(X),vt=ft(oe),Tt=ft(ne),St=ft(ie),bt=ft(ae),At=ft(J),Et=ft(Y),It=ft(Z),Pt=ft(Pe),Nt=ft(be),xt=ft(Ne),Dt=ft(De),Ct=ft(Ze),Ft=ft(Ye),$t=ft(Je),Lt=ft(et),Ot=ft(tt),_t=ft(ot),Bt=ft(rt),Ut=ft(at),Mt=ft(st),Rt=ft(ct),qt=ft(lt),Kt=ft(ht),Gt=ft(gt),zt=ft(pt);function Wt(e,t){throw new I(e.join("; "),t,"VALIDATION_ERROR")}function jt(e){const t=yt(e);!t.success&&t.errors&&Wt(t.errors,"tokenName")}function Ht(e){const t=je.safeParse(e);t.success||Wt(t.error.errors.map(e=>e.message),"pagination")}function Vt(e){const t=Dt(e);!t.success&&t.errors&&Wt(t.errors,"options")}function Qt(e){const t=Kt(e);!t.success&&t.errors&&Wt(t.errors,"options")}function Xt(e){const t=$e.safeParse(e);t.success||Wt(t.error.errors.map(e=>e.message),"options")}function Zt(e){const t=oe.safeParse(e);if(!t.success)throw new I("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Yt(e,t,o=!0){if(!e||""===e.trim())throw new I(`${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 I(`${t} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,t,"INVALID_NUMERIC_STRING");const n=parseFloat(e);if(isNaN(n))throw new I(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(n))throw new I(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(n<0)throw new I(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!o&&0===n)throw new I(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var Jt=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=oe.safeParse(e);if(!t.success)throw new I(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:Zt,validateCheckPoolOptions:Vt,validateGetAmountOptions:Qt,validateGetGraphOptions:Xt,validateNumericString:Yt,validatePagination:Ht,validateTokenName:jt});function eo(e,t){const o=e,n=Number(o.page)||t.page,i=Number(o.limit)||t.limit,r=o.data,a=Number(o.total)||Number(r?.count)||0;return{page:n,limit:i,total:a,totalPages:Math.ceil(a/i)}}function to(e,t){return{hasNext:e<t,hasPrevious:e>1}}function oo(e,t,o=!1){const n=!0===e.error||200!==e.status,i=o&&!e.data;if(n||i)throw new Error(e.message||t)}const no="/launchpad/upload-image",io="/launchpad/fetch-pool",ro="/launchpad/check-pool",ao="/launchpad/get-graph-data",so="/holders",co="/launchpad/get-badge/",lo="/trade/",uo="/token/commment",ho="/token/commment",go="/user/profile",po="/user/profile",mo="/user/token-list",fo="/user/token-hold",yo="/user/transfer-faucets",wo={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};class ko{constructor(e,t=!1){this.http=e,this.logger=new T({debug:t,context:this.constructor.name})}}class vo{constructor(e=!1){this.logger=new T({debug:e,context:this.constructor.name})}}function To(e,t){return"string"==typeof e[t]}function So(e,t){return void 0===e[t]||"string"==typeof e[t]}function bo(e,t){return void 0===e[t]||"number"==typeof e[t]}function Ao(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function Eo(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&bo(t,"from")&&bo(t,"to")&&bo(t,"resolution")}class Io extends ko{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 o=S(t),n=await this.http.get(io,o);if(!n)throw R("No response from pool service",500);oo(n,"Failed to fetch pools",!0);const i=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 o=e.tokens;t=[{...o,createdAt:o.created_at||o.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(n.data),r=n.data.count??n.data.total??0;return{pools:i,total:r,totalPages:e.limit>0?Math.ceil(r/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:o,pageSize:n,...i}=e,r=[];if(o&&o>=t){const e=[];for(let n=t;n<=o;n++)e.push(n);for(let t=0;t<e.length;t+=5){const o=e.slice(t,t+5).map(e=>this.fetchSinglePage({...i,page:e,limit:n}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e}));(await Promise.all(o)).forEach(e=>{r.push(...e.pools)})}return r}let a=t,s=!0;for(;s;){const e=[];for(let t=0;t<5&&s;t++)e.push(a+t);const t=e.map(e=>this.fetchSinglePage({...i,page:e,limit:n}).catch(e=>{if(400===e?.launchpadError?.statusCode)return{pools:[],total:0,totalPages:0};throw e})),o=await Promise.all(t);for(const e of o){if(0===e.pools.length){s=!1;break}r.push(...e.pools)}a+=e.length,a>wo.SAFETY_MAX_PAGES&&(s=!1)}return r}async fetchPools(e={}){const t=e.page||wo.DEFAULT_PAGE,o=e.limit??wo.DEFAULT_LIMIT;let n;if(0!==o&&Ht({page:t,limit:o}),e.tokenName&&jt(e.tokenName),"recent"===e.type?n="RECENT":"popular"===e.type&&(n="POPULAR"),o>0&&o<=20){const i=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:o});return{pools:i.pools,page:t,limit:o,total:i.total,totalPages:i.totalPages,hasNext:t<i.totalPages,hasPrevious:t>1}}if(0===o){const t=wo.BACKEND_MAX_PAGE_SIZE,o=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:1,limit:t}),i=[...o.pools];if(o.pools.length>0){const r=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:2,totalPages:o.totalPages>1?o.totalPages:null,pageSize:t});i.push(...r)}return{pools:i,page:1,limit:i.length,total:o.total||i.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const i=wo.BACKEND_MAX_PAGE_SIZE,r=Math.ceil(o/i),a=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:i}),s=[...a.pools],c=Math.min(r,a.totalPages-t+1);if(c>1){const o=t+c-1,r=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:t+1,totalPages:o,pageSize:i});s.push(...r)}const l=s.slice(0,o);return{pools:l,page:t,limit:o,total:a.total,totalPages:a.totalPages,hasNext:t<a.totalPages&&l.length<a.total,hasPrevious:t>1}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){Vt(e),e.tokenName&&jt(e.tokenName);const t=S(e),o=await this.http.get(ro,t);if(!o)throw R("No response from pool service",500);oo(o,"Failed to check pool");const n=o.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.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(!Eo(e))throw new I("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:o,to:n,resolution:i}=e;if(jt(t),!o||!n||!i)throw new I("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:o,to:n,resolution:i};Xt(r);const a=S(r),s=await this.http.get(ao,a);if(!s)throw R("No response from pool service",500);return oo(s,"Failed to fetch graph data",!0),{dataPoints:s.data}}async fetchTokenDistribution(e){if(!e)throw U("tokenName","Token name");jt(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw B(e);const o=encodeURIComponent(t),n=await this.http.get(`${so}/${o}`);if(!n)throw R("No response from pool service",500);oo(n,"Failed to fetch token distribution",!0);const r=n.data;if(!Array.isArray(r))throw R("Invalid API response: expected array of holders",n.status);for(const e of r){if(!e.owner||"string"!=typeof e.owner)throw R("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw R("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw R(`Invalid holder quantity: "${e.quantity}"`,n.status)}const a=r.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:r.map(e=>{const t=new i(e.quantity),o=a.isZero()?0:t.dividedBy(a).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:o}}),totalSupply:a.toFixed(),totalHolders:r.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw U("tokenName","Token name");jt(e);const t=await this.http.get(co,{tokenName:e});if(!t)throw R("No response from pool service",500);return oo(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:o,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const i=("volume"===o?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return i?.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 Po(e,t={}){const{stringifyFields:o=[],optionalFields:n=[],fieldMappings:i={}}=t,r={};for(const[t,a]of Object.entries(e)){const e=t;if(n.includes(e)&&void 0===a)continue;if(n.includes(e)&&"string"==typeof a&&0===a.trim().length)continue;const s=i[e],c=s?String(s):t;o.includes(e)?r[c]=String(a):r[c]=a}return S(r)}const No={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class xo extends ko{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&So(t,"userAddress")&&bo(t,"page")&&bo(t,"limit")}(e))throw new I("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:o,userAddress:n,page:i=wo.DEFAULT_PAGE,limit:r=wo.DEFAULT_LIMIT,startDate:a,endDate:s,sortOrder:c}=e;if(!W(t))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");G(i,r,No);const l=function(e,t,o){return Po({tokenName:e,page:t,limit:o},{stringifyFields:["page","limit"]})}(t,i,r),u=await this.http.get(lo,l);if(!u)throw new I("No response from trade service","response","NO_RESPONSE");const d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const g=eo(u,{page:i,limit:r}),p=to(g.page,g.totalPages);return{trades:d,...g,...p}}}const Do=new T({debug:!1,context:"DateUtils"});function Co(e,t){if(!e)return t||new Date;if(e instanceof Date)return isNaN(e.getTime())?t||new Date:e;try{const o=new Date(e);return isNaN(o.getTime())?(Do.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):o}catch(o){return Do.warn(`Date parsing error for "${e}":`,o),t||new Date}}const Fo={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class $o extends ko{constructor(e,t,o=!1){super(e,o),this.poolService=t}async fetchComments(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&bo(t,"page")&&bo(t,"limit")}(e))throw new I("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:o=wo.DEFAULT_PAGE,limit:n=wo.DEFAULT_LIMIT}=e;if(!W(t))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");G(o,n,Fo);const i=await this.poolService.resolveTokenNameToVault(t);if(!i)throw B(t);const r=Po({vaultAddress:i,page:o,limit:n},{stringifyFields:["page","limit"]}),a=await this.http.get(uo,r);if(!a)throw new I("No response from comment service","response","NO_RESPONSE");if(oo(a,"Failed to fetch comments"),!a.data)throw new I("Invalid response structure from comment service: no data field","response.data","INVALID_RESPONSE");if(0===Object.keys(a.data).length)return{comments:[],total:0};if(!Array.isArray(a.data.comments))throw new I("Invalid response structure from comment service: comments must be an array, got "+typeof a.data.comments,"response.data.comments","INVALID_RESPONSE");return{comments:a.data.comments.map(e=>({...e,createdAt:Co(e.createdAt)})),total:a.data.count||0}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&To(t,"content")}(e))throw new I("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:o}=e;if(!W(t))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if(!function(e){if(!e||"string"!=typeof e)return!1;const t=e.trim();return t.length>=Fo.CONTENT.MIN_LENGTH&&t.length<=Fo.CONTENT.MAX_LENGTH}(o))throw new I(`Comment content must be between ${Fo.CONTENT.MIN_LENGTH} and ${Fo.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const n=await this.poolService.resolveTokenNameToVault(t);if(!n)throw B(t);const i=this.http.getAddress();if(!i)throw new I("User address not available - wallet not configured","userAddress","NO_WALLET");const r={userAddress:i,vaultAddress:n,content:o},a=await this.http.post(ho,r);if(!a)throw new I("No response from comment service","response","NO_RESPONSE");oo(a,"Failed to create comment")}}function Lo(e){return e instanceof Error}function Oo(e){return Lo(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 _o(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Bo(e,t="image",o){const n=new FormData;if("undefined"!=typeof File&&e instanceof File)n.append(t,e);else{if(!Buffer.isBuffer(e))throw M("file","a File object (browser) or Buffer (Node.js)");{const i=new Blob([e],{type:"image/png"});n.append(t,i,o)}}return n}const Uo={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},FAUCET_AMOUNT:{POSITIVE_NON_ZERO_DECIMAL:/^(?!0+(\.0+)?$)\d+(\.\d+)?$/},PROFILE:{FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}}};function Mo(e){return!(!e||"string"!=typeof e)&&Uo.USER_ADDRESS.PATTERN.test(e)}const Ro="Update profile";class qo extends ko{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!Mo(t))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const o={userAddress:t},n=await this.http.get(go,o);if(!n)throw new I("No response from user service","response","NO_RESPONSE");return n}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!t||""===t.trim())try{const o=await this.fetchProfile(e.address);t=o.data?.profileImage||""}catch{t=""}const o={profileImage:t,fullName:e.fullName,userAddress:e.address},n=await this.http.signCustomMessage(Ro);if(!n)throw new I("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const i={address:n.address,message:Ro,publickey:n.ethereumAddress,sign:n.signature},r=await this.http.put(po,o,i);if(!r)throw new I("No response from user service","response","NO_RESPONSE");oo(r,"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new I("Wallet address not available - wallet not configured","address","NO_WALLET");try{const o=`profile-image-${t}.png`,n=Bo(e.file,"image",o),i=await this.http.request({method:"POST",url:`${no}?tokenName=${encodeURIComponent(t)}`,data:n,headers:{}});if(!i)throw new I("No response from user service","response","NO_RESPONSE");return oo(i,"Image upload failed"),"string"==typeof i.data?i.data:""}catch(e){if(e instanceof I)throw e;throw new I(`Profile image upload failed: ${Oo(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(mo,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(fo,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=wo.DEFAULT_PAGE,limit:o=wo.DEFAULT_LIMIT,search:n,tokenName:i}=e,r=this.http.getAddress();if(!r)throw new I("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"DEFI",address:r,page:t,limit:o};return void 0!==n&&(a.search=n),void 0!==i&&(a.tokenName=i),this.fetchTokenList(a)}async buildFetchRequest(e,t,o){this.validateGetTokenListOptions(t);const n={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},i=Po(o.includeType?{...n,type:"all"!==t.type&&t.type?t.type:"DEFI"}:n,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),r=await this.http.get(e,i);if(!r)throw new I("No response from user service","response","NO_RESPONSE");oo(r,o.errorMessage,!0);const a=(s=r.data)?Array.isArray(s)?s:s.token:[];var s;const c=eo(r,{page:t.page||wo.DEFAULT_PAGE,limit:t.limit||wo.DEFAULT_LIMIT}),l=to(c.page,c.totalPages);return{tokens:a,...c,...l}}validateGetTokenListOptions(e){if(G(e.page,e.limit,Uo),void 0!==e.address&&!Mo(e.address))throw new I("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>=Uo.SEARCH.MIN_LENGTH&&t.length<=Uo.SEARCH.MAX_LENGTH))throw new I(`Search query must be between ${Uo.SEARCH.MIN_LENGTH} and ${Uo.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,o;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((o=e.tokenName)&&"string"==typeof o&&o.length>=Uo.TOKEN_NAME.MIN_LENGTH&&o.length<=Uo.TOKEN_NAME.MAX_LENGTH))throw new I(`Token name must be between ${Uo.TOKEN_NAME.MIN_LENGTH} and ${Uo.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!Mo(e.address))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=Uo.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=Uo.PROFILE.FULL_NAME.MAX_LENGTH&&Uo.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new I(`Full name must be between ${Uo.PROFILE.FULL_NAME.MIN_LENGTH} and ${Uo.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!Mo(e.address))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Ko extends Error{constructor(e,t,o){super(e),this.filename=t,this.mimeType=o,this.name="FileValidationError"}}function Go(e,t,o){if(!e)throw new Ko("File is required",t,o);if("undefined"!=typeof File&&e instanceof File){const t=Be.safeParse(e);if(!t.success){const o=t.error.errors.map(e=>e.message).join("; ");throw new Ko(o,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Ko("Filename is required when uploading Buffer objects",t,o);const n=Ue.safeParse(e);if(!n.success){const e=n.error.errors.map(e=>e.message).join("; ");throw new Ko(e,t,o)}if(t.length>255)throw new Ko(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,o);const i=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!i.includes(o))throw new Ko(`Invalid file type "${o}" is not allowed. Allowed types: ${i.join(", ")}`,t,o);const r=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),a=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!a.includes(r))throw new Ko(`File extension "${r}" is not allowed. Allowed extensions: ${a.join(", ")}`,t,o);const s=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"}}(r);if(s!==o&&"application/octet-stream"!==s)throw new Ko(`File extension "${r}" does not match MIME type "${o}"`,t,o);return}throw new Ko("File must be a File object (browser) or Buffer (Node.js)",t,o)}class zo extends ko{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:o}=e;jt(t);const n=`${t}.png`;Go(o.file,n,"image/png");try{const e=`${o.tokenName??t}.png`,n=Bo(o.file,"image",e),i=await this.http.request({method:"POST",url:`${no}?tokenName=${encodeURIComponent(o.tokenName??t)}`,data:n,headers:{}});if(!i)throw q("No response from image upload service","response");return oo(i,"Image upload failed"),"string"==typeof i.data?i.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw q("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class Wo extends ko{constructor(e,t=!1){super(e,t)}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount},o=await this.http.post(yo,t);if(!o)throw new I("No response from faucet service","response","NO_RESPONSE");oo(o,"Faucet transfer failed")}validateTransferFaucetsData(e){if(!Mo(e.walletAddress))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!Uo.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new I("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class jo{constructor(e,t=!1){this.http=e,this.poolService=new Io(e,t),this.tradeService=new xo(e,t),this.commentService=new $o(e,this.poolService,t),this.userService=new qo(e,t),this.imageService=new zo(e,t),this.faucetService=new Wo(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 fetchComments(e){return this.commentService.fetchComments(e)}async postComment(e){return this.commentService.postComment(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)}async transferFaucets(e){return this.faucetService.transferFaucets(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return jt(e)}}const Ho={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var Vo;!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"}(Vo||(Vo={}));class Qo extends Error{constructor(e,t,o){super(e),this.type=t,this.details=o,this.name="TransferError"}}function Xo(e,t="0"){return new i(null==e||""===e?t:e)}function Zo(e){return r.tickToSqrtPrice(e)}function Yo(e){const t=Xo(e),o=Math.log(1.0001),n=t.toNumber();return Math.log(n)/o}function Jo(e,t=!1){const o=Xo(e),n=new i(1).dividedBy(o);return t?n.toFixed():n}function en(...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 tn(e,t,o){if(e.isNaN())throw new Error(`${t} must be a valid number, got: NaN`);if(!e.isFinite()){const n=o?`${t} must be finite ${o}, got: ${e.toString()}`:`${t} must be finite, got: ${e.toString()}`;throw new Error(n)}if(e.isLessThanOrEqualTo(0)){const n=o?`${t} must be positive ${o}, got: ${e.toString()}`:`${t} must be positive, got: ${e.toString()}`;throw new Error(n)}}class on{static validateAmount(e){const t=new i(e);try{tn(t,"amount","for transfer")}catch(t){throw new Qo(t.message,Vo.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(e){if(e.length>Ho.MAX_UNIQUE_KEY_LENGTH)throw new I(`Unique key too long. Maximum length: ${Ho.MAX_UNIQUE_KEY_LENGTH}`);if(!Ho.UNIQUE_KEY_PATTERN.test(e))throw new Qo('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Vo.INVALID_AMOUNT,{uniqueKey:e})}}}class nn{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 rn(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function an(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[o,n,i,...r]=t;if(!o||!n||!i)throw new Error("Collection, category, and type must be non-empty");const a=r.join("$");if(!a)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:n,type:i,additionalKey:a}}catch(t){throw new I(`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 sn extends o.ChainCallDTO{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,o,n,i){let r;if("string"==typeof n){r={...an(n),instance:"0"}}else r={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new sn({from:e,to:t,quantity:o,tokenInstance:r,uniqueKey:i||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,o,n){return new sn({from:e,to:t,quantity:o,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:n||`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 cn extends o.ChainCallDTO{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,o,n,i){let r;if("string"==typeof n){r={...an(n),instance:"0"}}else r={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new cn({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:o,tokenInstanceKey:r}],...void 0!==i?.expires&&{expires:i.expires},...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,o,n){return new cn({lockAuthority:t||e,tokenInstances:[{owner:e,quantity:o,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==n?.expires&&{expires:n.expires},...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{lockAuthority:this.lockAuthority,tokenInstances:this.tokenInstances,...void 0!==this.expires&&{expires:this.expires},...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class ln extends o.ChainCallDTO{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,o,n){let i;if("string"==typeof o){i={...an(o),instance:"0"}}else i={collection:o.collection,category:o.category,type:o.type,additionalKey:o.additionalKey,instance:"0"};return new ln({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:i}],...void 0!==n?.name&&{name:n.name},uniqueKey:n?.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,o){return new ln({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==o?.name&&{name:o.name},uniqueKey:o?.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 un{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},o={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,o,e),domain:t,types:o,signerPublicKey:this.wallet.signingKey.publicKey}}async signLockToken(e){const t={name:"GalaChain",chainId:1},o={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"}]},n={lockAuthority:e.lockAuthority,tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.expires&&(n.expires=e.expires),void 0!==e.name&&(n.name=e.name);return{signature:await this.wallet.signTypedData(t,o,n),domain:t,types:o,signerPublicKey:this.wallet.signingKey.publicKey}}async signUnlockToken(e){const t={name:"GalaChain",chainId:1},o={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"}]},n={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.name&&(n.name=e.name);return{signature:await this.wallet.signTypedData(t,o,n),domain:t,types:o,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const o=e.replace("0x","");return`eth|${t.ethers.getAddress(`0x${o}`).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{...an(e),instance:"0"}}}function dn(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new I(`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 I(`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 I("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 I(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function hn(e){try{const[t,o]=e.split("|");if(!o)throw new Error("Missing token part after service");const n=o.split("$");if(n.length<4)throw new Error(`Invalid vault address format. Expected at least 4 parts separated by $, got ${n.length}`);if(!(n[0]&&n[1]&&n[2]&&n[3]))throw new Error("All vault address components (collection, category, type, additionalKey) must be non-empty");const i=n.slice(3,-1),r=i.length>0?i.join("$"):n[3];return{collection:n[0],category:n[1],type:n[2],additionalKey:r}}catch(t){throw new I(`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 gn(e){return{...hn(e),instance:"0"}}function pn(e){return hn(e).type}var mn,fn=Object.freeze({__proto__:null,extractTokenSymbolFromVault:pn,normalizeToTokenInstanceKey:dn,parseVaultAddressToTokenClassKey:hn,parseVaultAddressToTokenInstance:gn});function yn(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 wn(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)}exports.LockErrorType=void 0,(mn=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",mn.INVALID_AMOUNT="INVALID_AMOUNT",mn.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",mn.SIGNATURE_FAILED="SIGNATURE_FAILED",mn.NETWORK_ERROR="NETWORK_ERROR",mn.WALLET_REQUIRED="WALLET_REQUIRED",mn.LOCK_NOT_FOUND="LOCK_NOT_FOUND",mn.LOCK_EXPIRED="LOCK_EXPIRED",mn.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",mn.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",mn.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class kn extends Error{constructor(e,t,o){super(e),this.type=t,this.details=o,this.name="LockError"}}const vn="gala-transfer-successful",Tn="token-transfer-successful",Sn="transfer-successful-no-id";class bn extends ko{constructor(e,t,o,n=!1,i){super(e,n),this.wallet=t,this.tokenResolver=o,this.publicAxios=i,this.signatureHelper=t?new un(t):void 0}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw R("No response from GalaChain service",500);if(1!==t.Status)throw R(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const o=t.Data.reverseBondingCurveConfiguration,n=o?.minFeePortion??"0",i=o?.maxFeePortion??"0",r=(await import("bignumber.js")).default,a=!new r(n).isZero()||!new r(i).isZero(),s=t.Data;return s.reverseBondingCurveMinFeePortion=n,s.reverseBondingCurveMaxFeePortion=i,s.hasReverseBondingCurveFee=a,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(!e)throw R("No response from GalaChain service",500);if(1!==e.Status)throw R(`Failed to fetch launch token fee: Status ${e.Status}`,e.Status);return e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.vaultAddress)throw new I("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new I("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new I("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e){try{const t=await this.http.post("/api/asset/token-contract/FetchBalances",e);if(!t)return null;if(1!==t.Status||!t.Data||0===t.Data.length)return null;const o=t.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 n=`${o.collection}|${o.category}|${o.additionalKey}|${o.type}`;return{quantity:o.quantity,collection:o.collection,category:o.category,tokenId:n}}catch(e){throw R(`Failed to fetch token balance from GalaChain: ${Oo(e)}`,void 0,Lo(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?dn(e):e,o={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]},n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",o)).data;if(1!==n.Status)throw R(`Failed to fetch token class from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw R(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return n.Data[0]}catch(e){if(_o(e)&&404===e.response?.status)throw R("Token not found on GalaChain",404,Lo(e)?e:void 0);const t=Oo(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw R(`Failed to fetch token class from GalaChain: ${t}`,void 0,Lo(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw new I("tokenClasses array must not be empty");const t={tokenClasses:e},o=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(1!==o.Status)throw R(`Failed to fetch token classes with supply from GalaChain: Status ${o.Status}${o.Message?` - ${o.Message}`:""}`,o.Status);if(!o.Data||0===o.Data.length)throw R("No token supply data found for requested token classes",404);return o.Data}catch(e){if(_o(e)&&404===e.response?.status)throw R("Token supply data not found on GalaChain",404,Lo(e)?e:void 0);const t=Oo(e);if(t.includes("Token")||t.includes("Status")||t.includes("tokenClasses"))throw e;throw R(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,Lo(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new Qo("Wallet required for GALA transfer operations",Vo.WALLET_REQUIRED);try{const t=H(e.recipientAddress),o=H(this.wallet.address),n=sn.forGALA(o,t,e.amount,e.uniqueKey),i=await this.signatureHelper.signTransferToken(n.toSigningPayload()),r=new sn({...n.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(r,null,2));const a=await this.http.post("/api/asset/token-contract/TransferToken",r);if(!a)throw new Qo("No response from GalaChain transfer service",Vo.NETWORK_ERROR);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(a,null,2)),this.extractTransactionIdFromResponse(a,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new Qo("Wallet required for token transfer operations",Vo.WALLET_REQUIRED);try{const t=H(e.to),o=H(this.wallet.address);let n;if(e.tokenId)n=dn(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",JSON.stringify(n,null,2));else{if(!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const i=new sn({from:o,to:t,quantity:e.amount,tokenInstance:n,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),r=await this.signatureHelper.signTransferToken(i.toSigningPayload()),a=new sn({...i.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(a,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",a);if(!s)throw new Qo("No response from GalaChain transfer service",Vo.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"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 Qo)throw t;throw new Qo(`Failed to resolve token class key for '${e}': ${Oo(t)}`,Vo.TOKEN_NOT_FOUND,{tokenName:e})}}async lockToken(e){if(this.validateLockTokenData(e),!this.wallet||!this.signatureHelper)throw new Qo("Wallet required for token lock operations",Vo.WALLET_REQUIRED);try{const t=H(this.wallet.address),o=e.lockAuthority?H(e.lockAuthority):t;let n;if(e.tokenId)n=dn(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId);else{if(!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const i=new cn({lockAuthority:o,tokenInstances:[{owner:t,quantity:e.amount,tokenInstanceKey:n}],...void 0!==e.expires&&{expires:e.expires},...void 0!==e.name&&{name:e.name},uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),r=await this.signatureHelper.signLockToken(i.toSigningPayload()),a=new cn({...i.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full Lock Request Payload:",JSON.stringify(a,null,2));const s=await this.http.post("/api/asset/token-contract/LockToken",a);if(!s)throw new Qo("No response from GalaChain lock service",Vo.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token lock response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"token")}catch(t){throw this.handleTransferError(t,"Token lock failed",e)}}async unlockToken(e){if(this.validateUnlockTokenData(e),!this.wallet||!this.signatureHelper)throw new Qo("Wallet required for token unlock operations",Vo.WALLET_REQUIRED);try{const t=H(this.wallet.address);let o;if(e.tokenId)o=dn(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId);else{if(!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);o=await this.resolveTokenInstance(e.tokenName)}const n=new ln({tokenInstances:[{owner:t,quantity:e.amount,tokenInstanceKey:o}],...void 0!==e.name&&{name:e.name},uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),i=await this.signatureHelper.signUnlockToken(n.toSigningPayload()),r=new ln({...n.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full Unlock Request Payload:",JSON.stringify(r,null,2));const a=await this.http.post("/api/asset/token-contract/UnlockToken",r);if(!a)throw new Qo("No response from GalaChain unlock service",Vo.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token unlock response:",JSON.stringify(a,null,2)),this.extractTransactionIdFromResponse(a,"token")}catch(t){throw this.handleTransferError(t,"Token unlock failed",e)}}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 I("Invalid GALA transfer data: missing required fields");if(!j(e.recipientAddress))throw new Qo("Invalid recipient address format",Vo.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});on.validateAmount(e.amount),on.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 I("Invalid token transfer data: missing required fields");if(!j(e.to))throw new Qo("Invalid recipient address format",Vo.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);if(e.tokenName&&!Ho.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Qo("Invalid token name format",Vo.TOKEN_NOT_FOUND,{tokenName:e.tokenName});on.validateAmount(e.amount),on.validateUniqueKey(e.uniqueKey)}validateLockTokenData(e){if(!yn(e))throw new I("Invalid lock token data: missing required fields");if(e.lockAuthority&&!j(e.lockAuthority))throw new Qo("Invalid lock authority address format",Vo.INVALID_RECIPIENT,{recipientAddress:e.lockAuthority});if(!e.tokenId&&!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);if(e.tokenName&&!Ho.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Qo("Invalid token name format",Vo.TOKEN_NOT_FOUND,{tokenName:e.tokenName});if(void 0!==e.expires&&(e.expires<=0||!Number.isInteger(e.expires)))throw new I("Expires must be a positive integer (epoch milliseconds)");on.validateAmount(e.amount),on.validateUniqueKey(e.uniqueKey)}validateUnlockTokenData(e){if(!wn(e))throw new I("Invalid unlock token data: missing required fields");if(!e.tokenId&&!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Vo.TOKEN_NOT_FOUND);if(e.tokenName&&!Ho.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Qo("Invalid token name format",Vo.TOKEN_NOT_FOUND,{tokenName:e.tokenName});on.validateAmount(e.amount),on.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Qo(`Token '${e}' not found or not available for transfer`,Vo.TOKEN_NOT_FOUND,{tokenName:e});const o=this.resolveTokenInstanceFromVaultAddress(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}':\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(o,null,2)}`),o}catch(t){if(t instanceof Qo)throw t;throw new Qo(`Failed to resolve token '${e}': ${Oo(t)}`,Vo.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){try{return gn(e)}catch(e){if(e instanceof I)throw new Qo(`Invalid vault address format: ${e.message}`,Vo.TOKEN_NOT_FOUND);throw new Qo(`Failed to parse vault address: ${e instanceof Error?e.message:String(e)}`,Vo.TOKEN_NOT_FOUND)}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const o=e;return Array.isArray(o.Data)&&o.Data.length>0?"gala"===t?vn:Tn:Sn}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Qo("Transfer succeeded but transaction ID could not be extracted",Vo.NETWORK_ERROR)}handleTransferError(e,t,o){if(e instanceof Qo)return e;if(e instanceof I)return new Qo(e.message,Vo.INVALID_AMOUNT);if(_o(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t)return new Qo(("string"==typeof n?.message?n.message:void 0)||"Invalid transfer request",Vo.INVALID_AMOUNT);if(403===t)return new Qo("Insufficient balance for transfer",Vo.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in o&&(e.tokenName=o.tokenName),new Qo("Token not found",Vo.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new Qo("Transfer request timed out",Vo.NETWORK_ERROR);const n=Oo(e);return new Qo(n||t,Vo.NETWORK_ERROR)}}class An{constructor(e,t,o,n=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=o,this.logger=new T({debug:n,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:o}=e;if(!t&&!o)throw U("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&o)throw new I("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS");if(o)return this.logger.debug(`Fetching spot price by tokenId: ${o}`),this._fetchDexTokenSpotPrice(o);throw new I("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw U("tokenId","Token ID");try{const t=dn(e),o=rn(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${o}`),!this.dexBackendHttp)throw R("DEX Backend API client not configured");const n=await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:o}});if(!n.data||"string"!=typeof n.data)throw new I("Invalid price response: data must be a string, got "+typeof n.data,"data","INVALID_RESPONSE");const i=parseFloat(n.data);if(isNaN(i))throw new I(`Invalid price value: could not parse "${n.data}" as number`,"data","INVALID_CALCULATION");const r=`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`;let a;try{if(this.cache){const e=this.cache.getByTokenId(r);if(e?.symbol)return a=e.symbol,this.logger.debug(`DEX spot price for ${a} (cached): $${i}`),{symbol:a,price:i}}this.logger.debug(`Symbol cache miss for ${r}, fetching from API`);a=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(r,{symbol:a}),this.logger.debug(`Cached symbol for ${r}: ${a}`)),this.logger.debug(`DEX spot price for ${a}: $${i}`)}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)}`),a=("Token"===t.collection?t.type:t.collection).toUpperCase(),this.logger.debug(`DEX spot price for ${a} (fallback): $${i}`)}return{symbol:a,price:i}}catch(e){if(e instanceof I)throw e;throw R(`Failed to fetch DEX spot price: ${Oo(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,o){if(!e||"string"!=typeof e)throw new Error(A);try{if(o)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await o(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const o=`${t.sellingToken.collection}|${t.sellingToken.category}|${t.sellingToken.type}|${t.sellingToken.additionalKey}`;return this._fetchDexTokenSpotPrice(o)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Oo(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),i=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(!i)throw R("GALA price not available");const r=Number(n.amount)/1e18;if(r<=0)throw new I(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const a=i.price/r;return{symbol:e.toUpperCase(),price:a}}catch(t){if(t instanceof Error)throw R(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw R(`Failed to calculate launchpad token spot price for ${e}: ${Oo(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw R("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),o={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`),o}catch(t){if((t instanceof I||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw R(`Failed to fetch token details from GalaChain for ${e}: ${Oo(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw R("DEX Backend API client not configured");const e=(await this.dexBackendHttp.request({method:"GET",url:"/leaderboard/seasons"})).data.map(e=>({id:e.id,name:e.name,start:new Date(e.start),end:new Date(e.end),rulesId:e.rules_id}));return this.logger.debug(`Fetched ${e.length} DEX seasons`),e}catch(e){if(e instanceof Error&&e.message.includes("not configured"))throw e;throw R(`Failed to fetch DEX seasons: ${Oo(e)}`)}}async fetchCurrentDexSeason(){const e=await this.fetchAllDexSeasons(),t=new Date,o=e.find(e=>t>=e.start&&t<=e.end);return o?this.logger.debug(`Current DEX season: ${o.name} (ID: ${o.id})`):this.logger.debug("No active DEX season found"),o||null}async fetchDexLeaderboardBySeasonId(e){if(!e||"number"!=typeof e||e<1)throw U("seasonId","Season ID must be a positive number");try{if(!this.dexBackendHttp)throw R("DEX Backend API client not configured");const t=(await this.dexBackendHttp.request({method:"GET",url:"/leaderboard",params:{seasonId:e.toString()}})).data.leaderboard.map(e=>({wallet:e.wallet,rank:e.rank,totalXp:e.total_xp,distributionPercent:e.distribution_percent,liquidityXp:e.liquidity_xp,tradingXp:e.trading_xp,masteryTitles:e.mastery_titles.map(e=>({name:e.name,type:e.type,order:e.order}))}));return this.logger.debug(`Fetched leaderboard for season ${e} with ${t.length} entries`),{entries:t,seasonId:e,totalEntries:t.length}}catch(t){if(t instanceof Error&&t.message.includes("must be a positive number"))throw t;throw R(`Failed to fetch DEX leaderboard for season ${e}: ${Oo(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 R("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 R(`Failed to fetch DEX volume summary: ${Oo(e)}`)}}}function En(e,t=18){const o=parseFloat(e);if(0===o)return"0";return o.toFixed(t).replace(/\.?0+$/,"")}function In(e){return En(e,8)}function Pn(e){return En(e,18)}function Nn(e){return{maxAcceptableReverseBondingCurveFee:In(e.maxAcceptableReverseBondingCurveFee)}}new T({debug:!1,context:"NumberUtils"});class xn extends o.ChainCallDTO{constructor(e,t,o="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=In(t),this.expectedToken=Pn(o),this.extraFees=Nn(n)}}class Dn extends o.ChainCallDTO{constructor(e,t,o,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Pn(t),this.expectedNativeToken=In(o),this.extraFees=Nn(n)}}class Cn extends o.ChainCallDTO{constructor(e,t,o="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Pn(t),this.expectedNativeToken=In(o),this.extraFees=Nn(n)}}class Fn extends o.ChainCallDTO{constructor(e,t,o,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=In(t),this.expectedToken=Pn(o),this.extraFees=Nn(n)}}const $n={BuyNativeDto:xn,BuyExactDto:Dn,SellExactDto:Cn,SellNativeDto:Fn};class Ln extends vo{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),i=o.calculatePersonalSignPrefix(e),r={...e,prefix:i},{signature:a,domain:s}=await this.signWithEthersWallet(n,r),c={...e,signature:a,types:n,domain:s};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(c),signatureLength:a.length}),c}catch(e){this.logger.error("❌ Signature generation failed:",e);throw K(`Failed to sign DTO: ${Oo(e)}`)}}async signWithEthersWallet(e,t){try{let o,n;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)o={name:"ethereum",chainId:1},n=await this.walletProvider.signTypedData(o,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw q("Wallet provider does not support typed data signing","walletProvider");{const i=await this.walletProvider.getNetwork();o={name:i.name,chainId:Number(i.chainId)},n=await this.walletProvider.signTypedData(o,e,t)}}return{signature:n,domain:o}}catch(e){throw K(`Ethers.js signing failed: ${Oo(e)}`)}}generateEIP712Types(e,t){const o={};o[e]=[];const n=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),i=(e,t,n,r=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const a=i(e,t[0],n,!0);return r||o[n].push({name:e,type:(a??e)+"[]"}),a?a+"[]":void 0}if("object"==typeof t&&null!==t){if(o[e])throw new I(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return o[e]=[],Object.entries(t).forEach(([t,o])=>{i(t,o,e)}),r||o[n].push({name:e,type:e}),e}{let i;switch(typeof t){case"string":i="string";break;case"number":i="uint256";break;case"boolean":i="bool";break;default:throw new I(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return r||o[n].push({name:e,type:i}),i}}};return Object.entries(n).forEach(([t,o])=>{i(t,o,e)}),this.logger.debug("📝 Generated EIP-712 types:",o),o}}class On extends vo{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),o=this.createTokenInstance(t),n=this.createGalaInstance(),i=`$service$${o.toStringKey()}$launchpad`,r=`$tokenBalance$${o.toStringKey()}$${e}`,a=`$tokenBalance$${o.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,c=[i,r,a,s,`$tokenBalance$${n.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Oo(e);throw new I(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new a.TokenClassKey;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 a.TokenClassKey;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 U("vaultAddress","Vault address");try{const t=pn(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof I)throw M("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!e||"string"!=typeof e)throw U("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw M("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw M("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw M("vaultAddress",'having at least 5 parts separated by "$"');const o=t[2];if(!o||!/^[A-Za-z]{1,10}$/.test(o))throw M("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,o,n){return`${e}$${t}$${o}$${n}`}parseTokenClassKeyString(e){try{return an(e)}catch(e){if(e instanceof I)throw M("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function _n(e,t,o){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 n=new i(e);if(n.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const r=n.multipliedBy(t);let a;switch(o){case"buy-native":case"sell-exact":a=n.minus(r);break;case"buy-exact":case"sell-native":a=n.plus(r);break;default:throw new Error(`Unknown operation type: ${o}`)}return a.isLessThan(0)&&(a=new i(0)),a.toFixed()}class Bn extends ko{constructor(e,t,o=!1,n,i,r=.05,a=.01){super(e,o),this.tokenResolver=t,this.walletProvider=n,this.userAddress=i,this.defaultSlippageToleranceFactor=r,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.bundleEndpoint="/bundle",n&&i&&(this.signatureService=new Ln(n,o),this.tokenKeyService=new On(o))}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 o=await this.http.post(this.bundleEndpoint,t);return o?(this.logger.debug("📥 Bundle API response:",{success:o.success,hasData:!!o.data,error:o.error}),this.handleBundleResponse(o)):{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 U("bundleData","Bundle data");if(!e.signedDto)throw U("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw U("method","Method name");if(!Array.isArray(e.stringsInstructions))throw M("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new I("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw M("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new I(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new I(`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(_o(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 Oo(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw U("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 U("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:o,type:n,expectedAmount:i}=e,{effectiveSlippageFactor:r,effectiveMaxFee:a,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===n){if(!i)throw new I("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=_n(i,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:r,adjustedMinTokens:e});const t=new $n.BuyNativeDto(s,o,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyWithNative",s)}{if(!i)throw new I("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=_n(i,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:r,adjustedMaxGalaCost:e});const t=new $n.BuyExactDto(s,o,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyExactToken",s)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:o,type:n,expectedAmount:i}=e,{effectiveSlippageFactor:r,effectiveMaxFee:a,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===n){if(!i)throw new I("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=_n(i,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:r,adjustedMinGala:e});const t=new $n.SellExactDto(s,o,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"SellExactToken",s)}{if(!i)throw new I("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=_n(i,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:r,adjustedMaxTokensToSell:e});const t=new $n.SellNativeDto(s,o,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"SellWithNative",s)}}async prepareTradingOperation(e,t,o,n){const{effectiveSlippageFactor:i,effectiveMaxFee:r}=this.calculateEffectiveSlippage(t,o,n),a=await this.resolveTokenNameToVault(e);if(!a)throw B(e);return{effectiveSlippageFactor:i,effectiveMaxFee:r,vaultAddress:a}}calculateEffectiveSlippage(e,t,o){const n=o??this.defaultSlippageToleranceFactor,i=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let r=e||"0";return e&&(r=_n(e,i,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:i,adjustedMaxFee:r})),{effectiveSlippageFactor:n,effectiveFeeSlippageFactor:i,effectiveMaxFee:r}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw q("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw U("userAddress","User address")}async executeBundleTransaction(e,t,o){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${s.v4()}-${Date.now()}-${this.userAddress}`;const n=await this.signatureService.signDTO(e,t,this.userAddress),i=this.tokenKeyService.generateStringsInstructions(o),r={stringsInstructions:i,method:t,signedDto:n};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:i,dtoKeys:Object.keys(n)});const a=await this.submitTransaction(r);if(a.success&&a.data)return this.logger.debug("✅ Bundle transaction submitted:",a.data),{success:!0,data:{transactionId:a.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(a.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 Un,Mn;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Un||(Un={})),exports.SDKTransactionStatus=void 0,(Mn=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",Mn.PROCESSING="processing",Mn.COMPLETED="completed",Mn.FAILED="failed",Mn.TIMEOUT="timeout";const Rn={[Un.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[Un.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[Un.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[Un.FAILED]:exports.SDKTransactionStatus.FAILED,[Un.ERROR]:exports.SDKTransactionStatus.FAILED,[Un.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[Un.PENDING]:exports.SDKTransactionStatus.PENDING};class qn extends vo{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 c.io||(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=c.io(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 o=t[0],n=o.status||o.Status;if(n&&"string"==typeof n){if(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${n}`),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,o);const t=this.eventBufferTimeouts.get(e);t&&clearTimeout(t);const i=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,i)}}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 o=this.eventBuffer.get(e);if(o){this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,o,t)});const n=this.eventBufferTimeouts.get(e);n&&(clearTimeout(n),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e)}const n=this.config.timeout||3e5,i=setTimeout(()=>{if(this.listeners.has(e)){const o=Math.round(n/1e3),i={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${o} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${o}s)`),t(i),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},n);if(this.timeouts.set(e,i),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,o=>{this.processTransactionEvent(e,o,t)});else{const o={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(o),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,o){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const n=t,i=n?.data,r=n?.status||n?.Status||i?.status||i?.Status;let a=n?.message||n?.Message||i?.message||i?.Message||n?.error||i?.error;a&&"string"==typeof a||(a=r===Un.FAILED||r===Un.ERROR?"Transaction failed - check transaction details":r===Un.COMPLETED||r===Un.PROCESSED||r===Un.SUCCESS?"Transaction completed successfully":r?`Transaction status: ${r}`:"Unknown transaction status");const s=n?.blockHash||i?.blockHash,c=n?.gasUsed||i?.gasUsed,l=n?.Data||i?.Data,u={transactionId:e,status:this.mapSocketStatus(r),message:"string"==typeof a?a:"Transaction update received",timestamp:Date.now(),...s&&{blockHash:s},...c&&{gasUsed:c},...l&&{data:l}};if(this.logger.debug(`📡 Mapped status for ${e}: ${r} -> ${u.status}`),this.logger.debug(`📡 Final message: "${a}"`),o(u),u.status===exports.SDKTransactionStatus.COMPLETED||u.status===exports.SDKTransactionStatus.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} (${u.status})`)}}async waitForTransaction(e){return new Promise((t,o)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||o(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Rn[t]||exports.SDKTransactionStatus.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 Kn extends vo{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!W(e))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");const t=e.trim().toLowerCase(),o=this.get(t);if(o)return o;try{const o=await this.poolService.resolveTokenNameToVault(e);return o&&this.set(t,o),o}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw B(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:o}of e)this.set(t,o)}parseVaultAddressToTokenClassKey(e){try{return hn(e)}catch(e){if(e instanceof I)throw M("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}async function Gn(e,t={}){const{maxPages:o=1e4,logger:n,pageSize:i=20}=t,r=[];let a=1,s=!0,c=0;for(;s&&a<=o;){n&&n.debug(`Auto-pagination: fetching page ${a} with limit ${i}`);const t=await e(a,i);if(!t||!Array.isArray(t.items)){n&&n.warn("Auto-pagination: received invalid result structure, stopping");break}if(r.push(...t.items),c=t.total,n&&n.debug(`Auto-pagination: page ${a} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){n&&n.debug(`Auto-pagination: no items returned on page ${a}, exiting loop`);break}s=t.hasNext,a++}return a>o&&n&&n.warn(`Auto-pagination: exceeded maxPages limit of ${o}, stopping iteration`),n&&n.debug(`Auto-pagination: completed with total items: ${r.length}, total count: ${c}`),{items:r,total:c}}function zn(e,t=e.length,o="items"){return{...{page:1,limit:e.length||0,total:t,totalPages:Math.ceil(t/(e.length||1))||1,hasNext:!1,hasPrevious:!1},[o]:e}}class Wn extends ko{constructor(e,t=!1,o){super(e,t),this.tokenResolverService=o}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw q("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 q("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 q(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const o=hn(t),n=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`;return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(t instanceof Error&&t.message.includes("ConfigurationError"))throw t;throw R(`Failed to resolve token name '${e}': ${Oo(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 o=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=o,this.logger.debug(`Resolved to token ID: ${o}`)}if(!t)throw q("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:o}=await Promise.resolve().then(function(){return fn}),n=o(t),i=rn(`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`),{from:r,to:a,sortOrder:s="DESC",page:c=1,limit:l=10}=e,u={token:i,page:String(c),limit:String(l)};r&&(u.from=r.toISOString()),a&&(u.to=a.toISOString());const d=function(e){if(e)return e.toLowerCase()}(s);d&&(u.order=d),this.logger.debug(`Querying price snapshots for token ${i}, page ${c}, limit ${l}`);const h=await this.http.get("/price-oracle/fetch-price",u);if(!h)throw R("No response from price history service",500);const g=this.transformApiResponseToPriceHistory(h);return this.logger.debug(`Found ${g.snapshots.length} price snapshots, total ${g.total}`),g}catch(e){if(e instanceof Error&&(e.message.includes("ConfigurationError")||e.message.includes("NetworkError")))throw e;throw R(`Failed to fetch price history: ${Oo(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw R("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw R("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}`})),o=e.data.meta,n=o.currentPage??1,i=o.totalPages??1;return{snapshots:t,page:n,limit:o.pageSize??50,total:o.totalItems??0,totalPages:i,hasNext:n<i,hasPrevious:n>1}}async fetchAllPriceHistory(e){this.logger.debug("Fetching all price history with options:",e);const t=await Gn((t,o)=>this.fetchPriceHistory({...e,page:t,limit:o}).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 zn(t.items,t.total,"snapshots")}validateOptions(e){const{from:t,to:o,sortOrder:n,page:i=1,limit:r=10}=e;if(function(e,t,o,n={}){const{description:i="parameter",treatEmptyAsNull:r=!0}=n,a=e[t],s=e[o],c=null!=a&&(!r||""!==a),l=null!=s&&(!r||""!==s);if(!c&&!l)throw q(`Either ${t} or ${o} must be provided (${i})`,o);if(c&&l)throw q(`Cannot provide both ${t} and ${o}. Provide exactly one (${i}).`,o)}(e,"tokenName","tokenId",{description:"token identifier"}),t&&!(t instanceof Date)&&isNaN(new Date(t).getTime()))throw q("from must be a valid Date","from");if(o&&!(o instanceof Date)&&isNaN(new Date(o).getTime()))throw q("to must be a valid Date","to");if(n&&"ASC"!==n&&"DESC"!==n)throw q('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(i)||i<1)throw q("page must be a positive integer","page");if(!Number.isInteger(r)||r<1||r>50)throw q("limit must be between 1 and 50","limit")}}function jn(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new I("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:o,type:n,additionalKey:i}=e;if(!t||"string"!=typeof t)throw new I("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!o||"string"!=typeof o)throw new I("Token.category must be a non-empty string, got "+typeof o,"token.category","MISSING_OR_INVALID_CATEGORY");if(!n||"string"!=typeof n)throw new I("Token.type must be a non-empty string, got "+typeof n,"token.type","MISSING_OR_INVALID_TYPE");if(!i||"string"!=typeof i)throw new I("Token.additionalKey must be a non-empty string, got "+typeof i,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:o,type:n,additionalKey:i}}(e);if(!e)throw new I(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new I("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[o,n,i,...r]=t;if(!o||!n||!i)throw new Error("Collection, category, and type must be non-empty");const a=r.join("|");if(!a)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:n,type:i,additionalKey:a}}catch(t){const o=e.split("|");throw new I(`Invalid pipe-delimited token: "${e}" (${o.length} parts). Expected format: "collection|category|type|additionalKey" (4 parts minimum). Received: [${o.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 o=t[t.length-1],n=t[t.length-2],i=t[t.length-3],r=t.slice(0,t.length-3).join("$");if(!(r&&i&&n&&o))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:r,category:i,type:n,additionalKey:o}}catch(t){const o=e.split("$");throw new I(`Invalid dollar-delimited token: "${e}" (${o.length} parts). Expected format: "collection$category$type$additionalKey" (4 parts minimum). Received: [${o.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e);throw new I(`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 Hn extends Error{constructor(e,t,o){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=o,this.name="ApiError"}}function Vn(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 Qn(e){return"object"==typeof e&&null!==e&&"positionId"in e&&"owner"in e&&"token0"in e&&"token1"in e&&"fee"in e&&"liquidity"in e&&"string"==typeof e.positionId&&"string"==typeof e.owner&&"number"==typeof e.fee}class Xn{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 o=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&&Vn(t.token0ClassKey)&&Vn(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}(o))throw new Hn(t.status,"Invalid pool data response format",o);return o}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 o=t.data.Data;if(!Array.isArray(o.positions))throw new Hn(t.status,"Invalid positions response format: positions must be an array",o);for(const e of o.positions)if(!Qn(e))throw new Hn(t.status,"Invalid position in response",e);return o}catch(e){throw this.handleError(e,"getPositions")}}async getPositionById(e,t,o,n,i,r,a){try{let s,c;if(void 0!==t&&void 0!==o&&void 0!==n&&void 0!==i&&void 0!==r){s={owner:e,token0:"string"==typeof t?{collection:t,category:"Unit",type:"none",additionalKey:"none"}:t,token1:"string"==typeof o?{collection:o,category:"Unit",type:"none",additionalKey:"none"}:o,fee:n,tickLower:i,tickUpper:r},a&&(s.positionId=a),c=`${e}/${t}/${o}/${n}`}else s={positionId:e},c=e;const l=await this.client.post("/api/asset/dexv3-contract/GetPositions",s);this.validateResponse(l.data);const u=l.data.Data;let d;if(u&&"object"==typeof u&&"positionId"in u&&!("positions"in u))d=u;else{if(!(u&&Array.isArray(u.positions)&&u.positions.length>0))throw new Hn(404,`Position not found: ${c}`);d=u.positions[0]}const h={Data:d,Status:l.status};return void 0!==l.data.Message&&(h.Message=l.data.Message),h}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 o=t.data.Data;if("string"!=typeof o.amount0||"string"!=typeof o.amount1||"string"!=typeof o.fee0||"string"!=typeof o.fee1)throw new Hn(t.status,"Invalid removal estimation response format",o);return o}catch(e){throw this.handleError(e,"getRemoveLiquidityEstimation")}}validateResponse(e){if(!e||"object"!=typeof e)throw new Hn(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new Hn(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new Hn(e.Status,e.Message??"Gateway error",e.Data)}handleError(t,o){if(t instanceof Hn)return t;if(e.isAxiosError(t)){const e=t.response?.status??500,n=t.response?.data?.Message??t.message,i=t.response?.data?.Data??void 0;return new Hn(e,`${o}: ${n}`,i)}return new Hn(500,`${o}: ${t instanceof Error?t.message:String(t)}`)}}class Zn{constructor(e){this.http=e}async getUserAssets(e,t=20,o=0){try{if(!e||"string"!=typeof e)throw new Hn(400,"Invalid wallet address");const n=Math.max(1,Math.floor(o/t)+1),i={};i.address=e,i.page=n,i.limit=t;const r=await this.http.get("/user/assets",i);if(!r||"object"!=typeof r)throw new Hn(500,"Invalid response format: not an object");const a=r.data;if(!a||"object"!=typeof a)throw new Hn(500,"Invalid response format: missing data wrapper");const s=a.token;if(!Array.isArray(s))throw new Hn(500,"Invalid response format: token array must be an array");const c=[];for(const e of s){if("object"!=typeof e||null===e)throw new Hn(500,"Invalid asset in response: asset must be an object");const t=e;if("string"!=typeof t.symbol||"string"!=typeof t.name)throw new Hn(500,"Invalid asset in response: missing symbol or name",t);const o="number"==typeof t.decimals?t.decimals:"string"==typeof t.decimals?parseInt(t.decimals,10):void 0;if("number"!=typeof o||isNaN(o))throw new Hn(500,"Invalid asset in response: decimals must be a number",t);const n={tokenId:t.compositeKey||`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:o,balance:t.quantity||"0"};t.image&&(n.imageUrl=t.image),t.verify&&(n.verified=t.verify),c.push(n)}const l={tokens:c,count:a.count??c.length};return void 0!==a.totalValue&&(l.totalValue=a.totalValue),l}catch(t){throw this.handleError(t,`getUserAssets(${e})`)}}handleError(e,t){if(e instanceof Hn)return e;if(e instanceof Error&&e instanceof Error&&"response"in e){const o=e,n=o.response?.status??500,i=o.response?.data?.message??o.response?.data?.Message??o.message,r=o.response?.data?.Data??o.response?.data?.data??void 0;return o.response,new Hn(n,`${t}: ${i}`,r)}return new Hn(500,`${t}: ${e instanceof Error?e.message:String(e)}`)}}const Yn=10;class Jn extends vo{constructor(e,t,o){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new nn,this.webSocketService=t,this.dexQuoteService=o,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 Xn({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new Zn(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 i(e.amount).isLessThanOrEqualTo(0))throw new D("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new D("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),o=this.tokenConverter.toLaunchpadFormat(e.toToken),n=[3e3,500,1e4];let r;for(const a of n)try{const n=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:o,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),r=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:n,fromToken:t,toToken:o,amount:e.amount}),s=new i(r.currentSqrtPrice),c=new i(r.newSqrtPrice),l=s.gt(c)?s.minus(c).dividedBy(s):new i(0),u=new i(r.amount0),d=new i(r.amount1),h=u.isNegative(),g=d.isNegative();this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":r.amount0,"quoteResult.amount1":r.amount1,"amount0BN.isNegative()":h,"amount1BN.isNegative()":g});const p=h?u:d;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:h,selectedAmount:p.toFixed(),selectedAmountAbs:p.absoluteValue().toFixed()});const m=p.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:r.currentSqrtPrice,newSqrtPrice:r.newSqrtPrice}}catch(e){r=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e instanceof Error?e.message:"Unknown error"})}throw r||new D("No available fee tiers for quote",{feeTiers:n,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",D,e)}}async getSwapQuoteExactOutput(e){try{if(new i(e.amount).isLessThanOrEqualTo(0))throw new D("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new D("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),o=this.tokenConverter.toLaunchpadFormat(e.toToken),n=[3e3,500,1e4];let r;for(const a of n)try{const n=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:o,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),r=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:n,fromToken:t,toToken:o,amount:e.amount}),s=new i(r.currentSqrtPrice),c=new i(r.newSqrtPrice),l=s.gt(c)?s.minus(c).dividedBy(s):new i(0),u=n.pool.token0,d="string"==typeof u?u.split("|")[0]:"object"==typeof u&&null!==u&&"tokenName"in u?u.tokenName:String(u),h=o.split("|")[0]===d?r.amount1:r.amount0;return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:h,estimatedOutput:e.amount,feeTier:a,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(h,e.amount),currentSqrtPrice:r.currentSqrtPrice,newSqrtPrice:r.newSqrtPrice}}catch(e){r=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e instanceof Error?e.message:"Unknown error"})}throw r||new D("No available fee tiers for quote",{feeTiers:n,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",D,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:o}=this.convertTokenPair(e.fromToken,e.toToken),n=function(e,t=.01){const o=Xo(e),n=new i(1).minus(t);return o.multipliedBy(n)}(e.estimatedOutput,e.slippageTolerance||.01),r=this.getWalletAddress();if(!r)throw new Error("Wallet address required for swap execution");let a;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});a=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:a,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:o,inputAmount:e.inputAmount,minOutput:n.toFixed(),feeTier:e.feeTier,walletAddress:r,slippageTolerance:e.slippageTolerance||.01};void 0!==a&&(s.currentSqrtPrice=a);const c=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:c,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const l=await this.webSocketService.waitForTransaction(c);return{transactionId:l.transactionId,status:l.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(l.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(c)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",C,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,o=20){try{this.logger.debug("Fetching user assets",{walletAddress:e,page:t,limit:o});const n=await this.dexBackendClient.getUserAssets(e,o,(t-1)*o);return(Array.isArray(n)?n:n?.tokens||[]).map(e=>{const t=e.symbol||"UNKNOWN";try{return{tokenId:jn(`${t}|Unit|none|none`),symbol:t,balance:(o=e.quantity||e.balance||0,void 0!==n?Xo(o).toFixed(n):Xo(o).toFixed()),decimals:e.decimals||18}}catch(o){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:o instanceof Error?o.message:String(o),assetData:{symbol:t,quantity:e.quantity,balance:e.balance,decimals:e.decimals}}),null}var o,n}).filter(e=>null!==e)}catch(n){this.handleGSwapError("Failed to fetch user assets",$,n,{walletAddress:e,page:t,limit:o})}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets (auto-paginated)",{walletAddress:e});const t=await Gn((t,o)=>this.getUserAssets(e,t,o).then(e=>({items:e,page:t,limit:o,total:e.length,totalPages:1,hasNext:e.length===o,hasPrevious:t>1})),{maxPages:1e4,logger:this.logger,pageSize:20});return this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:t.items.length}),t.items}catch(t){this.handleGSwapError("Failed to fetch all user assets",$,t,{walletAddress:e})}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:o,gswapToken1:n}=this.convertTokenPair(e,t),r=[500,3e3,1e4];let a=new i(0),s=0;for(const c of r)try{const e="string"==typeof o?jn(o):o,t="string"==typeof n?jn(n):n,r=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:c});r&&(a=a.plus(new i(r.liquidity||0)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:c})}return{tokenA:e,tokenB:t,liquidity:a.toFixed(),feeTiers:r,swapCount:s}}catch(o){this.logger.warn("Failed to fetch pool info",o);const n=o;return this.logger.debug("Pool error details",{error:new F(`Failed to fetch pool info: ${n?.message||String(o)}`,o,e,t,this.extractGSwapErrorCode(o))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const o=[];for(let n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const o=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;o.has(e)||o.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const n=Array.from(o.values()),i=this.chunkArray(n,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:o.size,chunks:i.length,concurrency:t});const r=new Map;for(let e=0;e<i.length;e++){const t=i[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?r.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return r}normalizePositionResponse(e,t){const o=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""};return{positionId:e.positionId||e.id||"",ownerAddress:t||e.ownerAddress||e.owner||"",token0:e.token0Symbol||o(e.token0)||o(e.tokenA)||e.tokenSymbol0||"",token1:e.token1Symbol||o(e.token1)||o(e.tokenB)||e.tokenSymbol1||"",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 jn(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}}async getUserLiquidityPositions(t,o=10,n,i){try{this.logger.debug("Fetching user liquidity positions",{ownerAddress:t,limit:o,bookmark:n});const r=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,a={user:t,limit:o,bookmark:n||""};this.logger.debug("Sending position query request",{endpoint:r,payload:a});const s=await e.post(r,a,{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==s.status||1!==s.data?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:s.status,apiStatus:s.data?.Status}),{items:[]};const c=s.data.Data||{},l=c.positions||[],u=c.nextBookMark,d=l.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(e=>this.normalizePositionResponse(e,t));let h;this.logger.debug("Retrieved liquidity positions",{count:d.length,hasNextBookmark:!!u,nextBookmark:u}),i?.withPrices&&d.length>0&&(h=await this.fetchPositionPrices(d));const g={items:d};return void 0!==u&&(g.nextBookmark=u),void 0!==h&&(g.prices=h),g}catch(e){if(e&&"object"==typeof e&&"response"in e){const o=e;this.logger.error("Position query failed with HTTP error",{status:o.response?.status,statusText:o.response?.statusText,data:o.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:t})}this.handleGSwapError("Failed to fetch user liquidity positions",L,e)}}async getAllSwapUserLiquidityPositions(e,t){try{this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const o=async t=>{const o=await this.getUserLiquidityPositions(e,Yn,t,void 0);return{items:o.items,nextBookmark:o.nextBookmark}},n=await async function(e,t={}){const{maxPages:o=1e4,logger:n,pageSize:i=20}=t,r=[];let a,s=0;for(;s<o;){n&&n.debug(`Auto-pagination (bookmark): fetching page ${s+1} with pageSize ${i}`,{bookmark:a});const t=await e(a,i);let o,c,l;if(Array.isArray(t))o=t,c=void 0,l=!1;else{if(!t||"object"!=typeof t||!("items"in t)){n&&n.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}o=t.items,c=t.nextBookmark,l=!0}if(!Array.isArray(o)){n&&n.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===o.length){n&&n.debug(`Auto-pagination (bookmark): no items returned on page ${s+1}, exiting loop`);break}r.push(...o),s++,n&&n.debug(`Auto-pagination (bookmark): page ${s} returned ${o.length} items`,{hasNextBookmark:!!c,format:l?"BookmarkPaginationResult":"legacy-array"});const u=o.length<i;if(l&&(""===c||void 0===c)){n&&n.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(u){n&&n.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:o.length,pageSize:i,format:l?"BookmarkPaginationResult":"legacy-array"});break}a=c}return s>=o&&n&&n.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${o}, stopping iteration`),n&&n.debug(`Auto-pagination (bookmark): completed with total items: ${r.length}`,{pageCount:s}),{items:r,total:r.length}}(o,{maxPages:1e4,logger:this.logger,pageSize:Yn}),i=n.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:i.length}),t?.withPrices&&i.length>0){return{items:i,prices:await this.fetchPositionPrices(i)}}return i}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",L,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t});const{gswapToken0:o,gswapToken1:n}=this.convertTokenPair(t.token0,t.token1),i=(await this.gatewayClient.getPositions({owner:e,tokenA:o,tokenB:n,feeTier:t.fee})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!i||"object"!=typeof i||!("positionId"in i)&&!("id"in i))throw new Error("Invalid position data returned from API");const r=this.normalizePositionResponse(i,e);return this.logger.debug("Retrieved liquidity position",{positionId:r.positionId}),r}catch(e){this.handleGSwapError("Failed to fetch liquidity position",L,e)}}async getLiquidityPositionById(e,t,o,n,i,r,a){try{let s;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:!!o,hasToken1:!!n,hasFee:!!i,hasTickLower:void 0!==r,hasTickUpper:void 0!==a});let c=null;const l=5,u=2e3;for(let d=1;d<=l;d++)try{if(o&&n&&void 0!==i&&void 0!==r&&void 0!==a)try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:o,token1:n,feeTier:i,tickLower:r,tickUpper:a});if(s=(await this.gatewayClient.getPositionById(e,o,n,i,r,a,t)).Data,s&&"object"==typeof s&&("positionId"in s||"id"in s)){this.logger.debug("Successfully fetched position via compound key",{attempt:d,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:d,error:e instanceof Error?e.message:e})}try{if(s=(await this.gatewayClient.getPositionById(t)).Data,s&&"object"==typeof s&&("positionId"in s||"id"in s)){this.logger.debug("Successfully fetched position on attempt",{attempt:d,positionId:t});break}throw new Error("Invalid position data from direct lookup")}catch(o){this.logger.debug("Direct position lookup failed, trying fallback via GetUserPositions",{attempt:d,positionId:t,error:o instanceof Error?o.message:o});const n=await this.getUserLiquidityPositions(e,10);if(Array.isArray(n.items)&&n.items.length>0){const e=n.items.find(e=>(e.positionId||e.id||"").toLowerCase()===t.toLowerCase());if(e){s=e,this.logger.debug("Found position via fallback (GetUserPositions)",{attempt:d,positionId:t});break}}if(c=new Error("Position not found in owner positions"),d<l){this.logger.warn("Fallback query did not find position, retrying",{attempt:d,positionId:t,ownerAddress:e,foundCount:Array.isArray(n?.items)?n.items.length:0}),await new Promise(e=>setTimeout(e,u));continue}}}catch(e){if(d<l){this.logger.warn("Error fetching position, retrying",{attempt:d,positionId:t,error:e instanceof Error?e.message:e}),await new Promise(e=>setTimeout(e,u));continue}c=e instanceof Error?e:new Error(String(e))}if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw this.logger.error("Invalid position data returned from API after retries",{positionId:t,resultType:typeof s,resultKeys:s?Object.keys(s):"null",resultValue:JSON.stringify(s),lastError:c?.message}),c||new Error("Invalid position data returned from API");const d=this.normalizePositionResponse(s,e);return this.logger.debug("Retrieved liquidity position by ID",{positionId:d.positionId}),d}catch(e){this.handleGSwapError("Failed to fetch liquidity position by ID",L,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,o={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},n=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetPositions`;this.logger.debug("Calling position endpoint via compound key",{url:n});const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(o)});if(!i.ok){if(404===i.status)throw new Error("Position not found (HTTP 404): No position exists for this compound key");if(400===i.status)throw new Error("Invalid parameters (HTTP 400): Check token format, fee (500|3000|10000), and tick ranges");throw new Error(`HTTP ${i.status}: ${i.statusText}`)}const r=await i.json();if(1!==r.Status||!r.Data)throw new Error(`Position not found: ${r.Message||"API returned no position data"}`);const a=this.normalizePositionResponse(r.Data,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:a.positionId,token0:a.token0,token1:a.token1}),a}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",L,e)}}async estimateRemoveLiquidity(e){try{this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1});const{gswapToken0:t,gswapToken1:o}=this.convertTokenPair(e.token0,e.token1),n=await this.gatewayClient.getRemoveLiquidityEstimation({tokenA:t,tokenB:o,fee:e.fee,liquidity:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper});return this.logger.debug("Estimated removal",{result:n}),n}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",L,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:o}=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 n=jn(t),r=jn(o),a=(await this.gatewayClient.getPoolData({token0:n,token1:r,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:a,fee:e.fee});const s=new i(e.minPrice),c=new i(e.maxPrice),l=Math.floor(Yo(s)),u=Math.ceil(Yo(c)),d=Math.floor(l/a)*a,h=Math.ceil(u/a)*a;this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:d,tickUpper:h,tickSpacing:a});const g=this.getWalletAddress();if(!g)throw new Error("GSwapService: No wallet address available - cannot create position");const p="string"==typeof e.token0?jn(e.token0):e.token0,m="string"==typeof e.token1?jn(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${d}-${h}`,walletAddress:g});const f=await this.sendAddLiquidityToBundler({token0:p,token1:m,fee:e.fee,tickLower:d,tickUpper:h,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:g}),y={transactionId:f};if(y.positionId&&f){this.logger.debug("Position ID returned directly from backend",{transactionId:f,positionId:y.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(f);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:f,status:e.status});const t=this.getWalletAddress();if(t&&y.positionId)try{const o=await this.getLiquidityPositionById(t,y.positionId),{createdAt:n,updatedAt:i,...r}=o,a=n instanceof Date?n.getTime():"number"==typeof n?n:void 0,s={...y,...r,positionId:y.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}};return void 0!==a&&(s.createdAt=a),s}catch(t){return{...y,positionId:y.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}}}}if(f){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:f}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(f);let o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:f,status:t.status});let n=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");const i=(await this.getUserLiquidityPositions(t,10)).items;if(i&&i.length>0){const t=e.token0.split("|")[0].toUpperCase(),r=e.token1.split("|")[0].toUpperCase(),a=[];for(const o of i){if(!o||!o.positionId)continue;const n=o.token0?.toUpperCase(),i=o.token1?.toUpperCase();if(!n||!i)continue;const s=n===t&&i===r||n===r&&i===t,c=o.feeTier===e.fee;s&&c&&a.push(o)}a.length>0&&(n=a[a.length-1],o=n.positionId,this.logger.debug("Found newly created position",{positionId:o,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:i.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}let i=n;if(o)try{i=await this.getLiquidityPositionById(g,o)}catch(e){}return{...y,...i,positionId:o,status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),y}catch(e){Error,this.handleGSwapError("Failed to add liquidity by price",L,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 o="string"==typeof e.token0?jn(e.token0):e.token0,n="string"==typeof e.token1?jn(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendAddLiquidityToBundler({token0:o,token1:n,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:i});const r=this.webSocketService.waitForTransaction(i),a={transactionId:i};if(a.positionId&&i){this.logger.info("Position ID returned directly from backend",{transactionId:i,positionId:a.positionId});const e=await r;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:e.status});const t=this.getWalletAddress();if(t&&a.positionId)try{this.logger.debug("Fetching full position details",{positionId:a.positionId});const o=await this.getLiquidityPositionById(t,a.positionId);this.logger.debug("Fetched full position data",{positionId:o.positionId,liquidity:o.liquidity,amount0:o.amount0,amount1:o.amount1});const{createdAt:n,updatedAt:r,...s}=o,c=n instanceof Date?n.getTime():"number"==typeof n?n:void 0,l={...a,...s,positionId:a.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}};return void 0!==c&&(l.createdAt=c),l}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:a.positionId,error:t instanceof Error?t.message:String(t)}),{...a,positionId:a.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}}if(i){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:i});const o=await r;let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:o.status});let s=null;const c="string"==typeof e.token0?e.token0:e.token0.type,l="string"==typeof e.token1?e.token1:e.token1.type;this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:l,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:Yn});const o=3,i=5e3,r=3e3;let a=[];for(let c=1;c<=o;c++){const l=1===c?i:r;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:o,delayMs:l}),await new Promise(e=>setTimeout(e,l)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:Yn});if(a=(await this.getUserLiquidityPositions(t,Yn)).items,this.logger.debug("Got positions from API",{count:a?.length||0}),a&&a.length>0){const t=("string"==typeof e.token0?e.token0.split("|")[0]:e.token0.collection).toUpperCase(),o=("string"==typeof e.token1?e.token1.split("|")[0]:e.token1.collection).toUpperCase(),i=[];for(const n of a){if(!n||!n.positionId)continue;const r=n.token0?.toUpperCase(),a=n.token1?.toUpperCase();if(!r||!a){this.logger.debug("Skipping position with empty tokens",{positionId:n.positionId});continue}const s=r===t&&a===o||r===o&&a===t,c=n.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:n.positionId,tokens:`${r}/${a}`,tokensMatch:s,fee:n.feeTier,feeMatches:c}),s&&c&&i.push(n)}if(i.length>0){s=i[i.length-1],n=s.positionId,this.logger.info("Found newly created position",{positionId:n,liquidity:s.liquidity,amount0:s.amount0,amount1:s.amount1,fee:s.feeTier}),this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:a.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:n||"not found",found:!!n}),this.logger.debug("Matched position data",{positionId:s?.positionId,liquidity:s?.liquidity,amount0:s?.amount0,amount1:s?.amount1,feeAmount0:s?.feeAmount0,feeAmount1:s?.feeAmount1,token0:s?.token0,token1:s?.token1,feeTier:s?.feeTier});let u=s;if(n)try{this.logger.debug("Fetching full position details",{positionId:n}),u=await this.getLiquidityPositionById(t,n),this.logger.debug("Fetched full position data",{positionId:u.positionId,liquidity:u.liquidity,amount0:u.amount0,amount1:u.amount1,feeAmount0:u.feeAmount0,feeAmount1:u.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:n,error:e instanceof Error?e.message:String(e)})}return{...a,...u,positionId:n,status:o.status,transactionId:o.transactionId,timestamp:new Date(o.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),a}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",L,e)}}async monitorBundlerTransaction(e,t,o="bundler"){let n;try{const i=await t;n={status:i.status,transactionId:i.transactionId||e,timestamp:i.timestamp||Date.now(),data:i.data},this.logger.debug(`${o} transaction confirmed on-chain`,{transactionId:e,status:n.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${o} 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:n.transactionId,status:n.status,timestamp:new Date(n.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?jn(e.token0):e.token0,o="string"==typeof e.token1?jn(e.token1):e.token1;await this.ensureWebSocketConnected();const n=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,o,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||"");this.logger.debug("Liquidity removal submitted to bundler",{transactionId:n});const i=this.webSocketService.waitForTransaction(n);return this.monitorBundlerTransaction(n,i,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",L,e)}}async collectPositionFees(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0.type,token1:"string"==typeof e.token1?e.token1:e.token1.type,tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?jn(e.token0):e.token0,o="string"==typeof e.token1?jn(e.token1):e.token1;await this.ensureWebSocketConnected();const n=await this.sendCollectPositionFeesToBundler(t,o,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||"");this.logger.debug("Fee collection submitted to bundler",{transactionId:n});const i=this.webSocketService.waitForTransaction(n);return this.monitorBundlerTransaction(n,i,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",L,e)}}async getPoolData(e,t,o){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:o});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),a=jn(n),s=jn(r),c=await this.gatewayClient.getPoolData({token0:a,token1:s,fee:o}),l=this.calculatePriceFromSqrtPriceX96(new i(c.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:o,liquidity:c.liquidity.toString(),sqrtPriceX96:c.sqrtPrice.toString(),tick:c.tick,feeGrowthGlobal0X128:c.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:c.feeGrowthGlobal1.toString(),currentPrice:l.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",F,e)}}async calculateDexPoolSpotPrice(e,t,o){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:o});const n=await this.getPoolData(e,t,o),i=Xo(n.currentPrice);return{tokenA:e,tokenB:t,feeTier:o,price:i.toFixed(),invertedPrice:Jo(i,!0),tick:n.tick,liquidity:n.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",F,e)}}async calculateOptimalPositionSize(e,t,o,n,a,s,c){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:n,desiredAmount1:a});const l=(await this.getPoolData(e,t,o)).tick,u=r.tickToSqrtPrice(s),d=r.tickToSqrtPrice(l),h=r.tickToSqrtPrice(c),g=r.getLiquidityForAmounts(new i(n),new i(a),u,d,h),p=r.getAmountsForLiquidity(g,d,u,h),m=p[0],f=p[1],y=new i(n),w=new i(a);return{amount0:m.toFixed(),amount1:f.toFixed(),liquidity:g.toFixed(),ratio:m.dividedBy(f).toFixed(),utilizationPercent:{amount0:m.dividedBy(y).multipliedBy(100).toFixed(2),amount1:f.dividedBy(w).multipliedBy(100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",L,e)}}async validatePositionParameters(e,t,o,n,r,a,s){const c=[],l=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:n,tickUpper:r});const u=[500,3e3,1e4];u.includes(o)||c.push(`Invalid fee tier: ${o}. Must be one of: ${u.join(", ")}`);const d=this.getTickSpacing(o);let h;n%d!==0&&c.push(`tickLower must be multiple of ${d}`),r%d!==0&&c.push(`tickUpper must be multiple of ${d}`),n>=r&&c.push(`tickLower (${n}) must be less than tickUpper (${r})`);try{h=await this.getPoolData(e,t,o)}catch{return c.push(`Pool not found for ${e}/${t} at fee tier ${o}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}const g=new i(a),p=new i(s);if(g.isNaN()||p.isNaN())c.push("Amounts must be valid numbers");else try{en(g,p)}catch(e){c.push(`Liquidity amounts must be non-negative: ${e.message}`)}const m=h.tick;(m<n||m>r)&&l.push("Position is out of current price range - will not earn fees until price moves into range");new i(h.liquidity||"0").lt("1000000")&&l.push("Low pool liquidity - consider higher slippage tolerance");const f=0===c.length?35e4:0;return{valid:0===c.length,errors:c,warnings:l,gasEstimate:f,tickSpacing:d,currentTick:m,poolLiquidity:h.liquidity}}catch(e){const t=e;return c.includes(t?.message||"")||c.push(`Validation failed: ${t?.message||String(e)}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}}async calculateTicksForPrice(e,t,o,n,r){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:o,maxPrice:n});const a=this.getTickSpacing(r),s=new i(o),c=new i(n);if(s.gte(c))throw new Error("minPrice must be less than maxPrice");const l=Math.floor(Yo(s)),u=Math.ceil(Yo(c)),d=Math.floor(l/a)*a,h=Math.ceil(u/a)*a,g=Math.pow(1.0001,d),p=Math.pow(1.0001,h),m=new i(g),f=new i(p);return{tokenA:e,tokenB:t,feeTier:r,tickLower:d,tickUpper:h,tickSpacing:a,requestedMinPrice:o,requestedMaxPrice:n,actualMinPrice:m.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:m.minus(s).dividedBy(s).multipliedBy(100).toFixed(4),maxPriceDeviation:f.minus(c).dividedBy(c).multipliedBy(100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",L,e)}}async calculatePriceForTicks(e,t,o,n){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:o,tickUpper:n});const r=Math.pow(1.0001,o),a=Math.pow(1.0001,n);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const c=new i(r),l=new i(a),u={tokenA:e,tokenB:t,tickLower:o,tickUpper:n,minPrice:c.toFixed(8),maxPrice:l.toFixed(8),priceRange:`${c.toFixed(4)} - ${l.toFixed(4)}`,tickSpread:n-o};return void 0!==s&&(u.currentPrice=s),u}catch(e){this.handleGSwapError("Failed to calculate price for ticks",L,e)}}calculateExecutionPrice(e,t){try{const o=new i(e),n=new i(t);return o.isZero()?"0":n.dividedBy(o).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}`)}}calculatePriceFromSqrtPriceX96(e){try{const t=new i(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new i(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return new i(0)}}async getPoolSlot0(t,o,n){try{this.logger.debug("Fetching pool slot0 data",{token0:t,token1:o,fee:n});const i="string"==typeof t?jn(t):t,r="string"==typeof o?jn(o):o,a=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetSlot0`,s=await e.post(a,{token0:i,token1:r,fee:n},{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==s.status||1!==s.data?.Status)throw this.logger.warn("Unexpected GetSlot0 API response",{httpStatus:s.status,apiStatus:s.data?.Status}),new F("GetSlot0 API returned unexpected status",{httpStatus:s.status,apiStatus:s.data?.Status});const c=s.data.Data||{},l={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:l.sqrtPrice,tick:l.tick,liquidity:l.liquidity}),l}catch(e){this.handleGSwapError("Failed to fetch pool slot0 data",F,e,{token0:t,token1:o,fee:n})}}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),o=new i(t.sqrtPrice),n={price:this.calculatePriceFromSqrtPriceDecimal(o).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:n.price,tick:n.tick}),n}catch(t){this.handleGSwapError("Failed to fetch position current price",F,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,o){try{const n=Zo(t),i=Zo(o);return r.liquidity0(e,n,i)}catch{return new i(0)}}calculateLiquidityFromAmount1(e,t,o){try{const n=Zo(t),i=Zo(o);return r.liquidity1(e,n,i)}catch{return new i(0)}}calculateAmount0FromLiquidity(e,t,o){try{const n=Zo(t),i=Zo(o);return r.getAmount0Delta(n,i,e)}catch{return new i(0)}}calculateAmount1FromLiquidity(e,t,o){try{const n=Zo(t),i=Zo(o);return r.getAmount1Delta(n,i,e)}catch{return new i(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(o){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:o.token0.type,token1:o.token1.type,fee:o.fee,tickRange:`${o.tickLower}-${o.tickUpper}`});const n=`galaswap - operation - ${s.v4()}-${Date.now()}-${o.owner}`,i={token0:o.token0,token1:o.token1,fee:o.fee,owner:o.owner,tickLower:o.tickLower,tickUpper:o.tickUpper,amount0Desired:o.amount0Desired,amount1Desired:o.amount1Desired,amount0Min:o.amount0Min,amount1Min:o.amount1Min,positionId:"",uniqueKey:n},r=new t.ethers.Wallet(this.privateKey),a={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"}]},c={name:"ethereum",chainId:1},l=this.calculatePersonalSignPrefix(i),u={...i,prefix:l},d=await r.signTypedData(c,a,u),h={...u,signature:d,types:a,domain:c};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:h.signature?.substring(0,20)+"...",prefix:h.prefix,tickLower:i.tickLower,tickUpper:i.tickUpper});const g=this.buildLiquidityStringsInstructions(o.token0,o.token1,o.fee,o.owner),p=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),m=await p.post("/bundle",{method:"AddLiquidity",signedDto:h,stringsInstructions:g}),f=m.data?.data||m.data?.transactionId||m.data?.id;if(!f)throw this.logger.error("Bundler response structure",{status:m.status,data:m.data,dataType:typeof m.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(m.data)}`);return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:f}),f}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(o,n,i,r,a,c,l,u,d){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const h=new t.ethers.Wallet(this.privateKey),g=await h.getAddress(),p=`galaswap - operation - ${s.v4()}-${Date.now()}-${g}`,m={tickLower:o,tickUpper:n,amount:i,token0:r,token1:a,fee:c,amount0Min:l,amount1Min:u,positionId:d,uniqueKey:p},f={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"}]},y={name:"ethereum",chainId:1},w=this.calculatePersonalSignPrefix(m),k={...m,prefix:w},v=await h.signTypedData(y,f,k),T={...k,signature:v,types:f,domain:y},S=this.buildLiquidityStringsInstructions(r,a,c,g);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:o,tickUpper:n,amount:i,fee:c,positionId:d,transactionId:p});const b=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),A=await b.post("/bundle",{method:"RemoveLiquidity",signedDto:T,stringsInstructions:S}),E=A.data?.data||A.data?.transactionId||A.data?.id;if(!E)throw this.logger.error("Bundler response structure",{status:A.status,data:A.data,dataType:typeof A.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(A.data)}`);return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:E}),E}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(o,n,i,r,a,c,l,u){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const d=new t.ethers.Wallet(this.privateKey),h=await d.getAddress(),g=`galaswap - operation - ${s.v4()}-${Date.now()}-${h}`,p={token0:o,token1:n,fee:i,amount0Requested:r,amount1Requested:a,tickLower:c,tickUpper:l,positionId:u,uniqueKey:g},m={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"}]},f={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},k=await d.signTypedData(f,m,w),v={...w,signature:k,types:m,domain:f},T=this.buildLiquidityStringsInstructions(o,n,i,h);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:i,amount0Requested:r,amount1Requested:a,tickLower:c,tickUpper:l,positionId:u,transactionId:g});const S=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),b=await S.post("/bundle",{method:"CollectPositionFees",signedDto:v,stringsInstructions:T}),A=b.data?.data||b.data?.transactionId||b.data?.id;if(!A)throw this.logger.error("Bundler response structure",{status:b.status,data:b.data,dataType:typeof b.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(b.data)}`);return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:A}),A}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(o){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 n=[500,3e3,1e4];if(!n.includes(o.feeTier))throw new Error(`GSwapService: Invalid fee tier ${o.feeTier}. Must be one of: ${n.join(", ")} (basis points)`);try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof o.fromToken?o.fromToken:o.fromToken.type,toToken:"string"==typeof o.toToken?o.toToken:o.toToken.type,inputAmount:o.inputAmount,minOutput:o.minOutput,feeTier:o.feeTier});let n=o.fromToken,r=o.toToken;"string"==typeof n&&(n=jn(n)),"string"==typeof r&&(r=jn(r));const a=`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`,c=`${r.collection}|${r.category}|${r.type}|${r.additionalKey}`,l=a<c?[n,r,a,c]:[r,n,c,a],[u,d,h,g]=l,p="string"==typeof o.fromToken?jn(o.fromToken):o.fromToken,m=`${p.collection}|${p.category}|${p.type}|${p.additionalKey}`,f=m===h,y=`galaswap - operation - ${s.v4()}-${Date.now()}-${o.walletAddress}`;let w;if(!o.currentSqrtPrice)throw new Error("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation");const k=new i(o.currentSqrtPrice),v=o.slippageTolerance??.01;if(f){const e=new i(1).minus(v);w=k.multipliedBy(e).toString()}else{const e=new i(1).plus(v);w=k.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:o.currentSqrtPrice,slippageTolerance:100*v+"%",zeroForOne:f,sqrtPriceLimit:w,direction:f?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const T={token0:u,token1:d,fee:o.feeTier,amount:new i(o.inputAmount).toFixed(),zeroForOne:f,sqrtPriceLimit:w,recipient:o.walletAddress,amountOutMinimum:new i(o.minOutput).multipliedBy(-1).toFixed(),uniqueKey:y};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:h,orderedToken1String:g,fromTokenStr:m,zeroForOne:f?`TRUE (${h} → ${g})`:`FALSE (${g} → ${h})`,inputAmount:o.inputAmount,expectedOutput:o.minOutput,slippageTolerance:100*(o.slippageTolerance||.01)+"%",currentSqrtPrice:o.currentSqrtPrice,swapDto:{amount:T.amount,zeroForOne:T.zeroForOne,sqrtPriceLimit:T.sqrtPriceLimit,amountOutMinimum:T.amountOutMinimum}});const S=new t.ethers.Wallet(this.privateKey),b={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"}]},A={name:"ethereum",chainId:1},E=this.calculatePersonalSignPrefix(T),I={...T,prefix:E},P=await S.signTypedData(A,b,I),N={...I,signature:P,types:b,domain:A};this.logger.debug("Swap DTO signed",{signature:N.signature?.substring(0,20)+"...",prefix:N.prefix,zeroForOne:T.zeroForOne});const x=this.buildLiquidityStringsInstructions(u,d,o.feeTier,o.walletAddress),D=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),C=await D.post("/bundle",{method:"Swap",signedDto:N,stringsInstructions:x}),F=C.data?.data||C.data?.transactionId||C.data?.id;if(!F)throw this.logger.error("Bundler response structure",{status:C.status,data:C.data,dataType:typeof C.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(C.data)}`);return this.logger.debug("Swap transaction sent to bundler",{transactionId:F,inputAmount:o.inputAmount,minOutput:o.minOutput}),F}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,o,n){const i=`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`,r=`$${t.collection}$${t.category}$${t.type}$${t.additionalKey}`,a=`$pool${i}${r}$${o}`;return[a,`$userPosition${n}`,`$tokenBalance${i}${n}`,`$tokenBalance${r}${n}`,`$tokenBalance${i}${a}`,`$tokenBalance${r}${a}`]}handleGSwapError(e,t,o,n){this.logger.error(e,o);const i=this.extractGSwapErrorCode(o),r=o,a=[`${e}: ${r?.message||String(o)}`,o];throw n&&("GSwapSwapError"===t.name&&n.transactionHash&&a.push(n.transactionHash),"GSwapPoolError"===t.name&&(n.tokenA&&a.push(n.tokenA),n.tokenB&&a.push(n.tokenB)),"GSwapAssetError"===t.name&&n.walletAddress&&a.push(n.walletAddress)),i&&a.push(i),new t(...a)}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 ei{}ei.BASE_PRICE=1650667151e-14,ei.PRICE_SCALING_FACTOR=1166069e-12,ei.TRADING_FEE_FACTOR=.001,ei.GAS_FEE="1",ei.MIN_UNBONDING_FEE_FACTOR=0,ei.MAX_UNBONDING_FEE_FACTOR=.5,ei.NET_UNBONDING_FEE_FACTOR=.5,ei.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class ti extends vo{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 o=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=ti.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...o||{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const o=this.normalizeTokenName(e);this.updateCacheEntry(o,t)}set(e,t){const o=this.normalizeTokenName(e);this.updateCacheEntry(o,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),o=this.cache.get(t);return o?.maxSupply||ei.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,o)=>{e[o]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((o,n)=>{o.lastUpdated<e&&(e=o.lastUpdated);let i=0;i+=2*n.length,void 0!==o.reverseBondingCurveMinFeeFactor&&(i+=8),void 0!==o.reverseBondingCurveMaxFeeFactor&&(i+=8),void 0!==o.reverseBondingCurveNetFeeFactor&&(i+=8),i+=8,o.vaultAddress&&(i+=2*o.vaultAddress.length),o.maxSupply&&(i+=2*o.maxSupply.length),o.symbol&&(i+=2*o.symbol.length),i+=32,t+=i}),{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 o=`token:${e.toLowerCase().trim()}`;this.updateCacheEntry(o,t)}hasByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.has(t)}}ti.MAX_CACHE_SIZE=1e4;class oi extends ko{constructor(e,t,o=void 0,n=5,i=!1){super(e,i),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=o,this.pricingConcurrency=n}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 o=0;o<e.length;o++){const n=e[o];t.push({poolIndex:o,token:n.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:n.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${n.token0}`,{error:e.message})})}),t.push({poolIndex:o,token:n.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:n.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${n.token1}`,{error:e.message})})})}const o=new Map;for(let t=0;t<e.length;t++)o.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const n=t.slice(e,e+this.pricingConcurrency),i=await Promise.allSettled(n.map(e=>e.task));for(let e=0;e<n.length;e++){const t=n[e],r=i[e],a=o.get(t.poolIndex)||{};"fulfilled"===r.status&&r.value&&(t.isToken0?a.token0Price=r.value:a.token1Price=r.value),o.set(t.poolIndex,a)}}const n=e.map((e,t)=>{const n=o.get(t)||{},i={...e};return void 0!==n.token0Price&&(i.token0Price=n.token0Price),void 0!==n.token1Price&&(i.token1Price=n.token1Price),i}),i=n.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:i,failed:e.length-i}),n}async fetchDexPools(e={}){const{search:t,sortBy:o="tvl",sortOrder:n="desc",page:i=wo.DEFAULT_PAGE,limit:r=wo.DEFAULT_LIMIT,withPrices:a=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:o,sortOrder:n,page:i,limit:r,withPrices:a});const s=new URLSearchParams({page:i.toString(),limit:Math.min(r,20).toString(),sortBy:o,sortOrder:n});t&&s.append("search",t);const c=`${this.dexBackendBaseUrl}/explore/pools?${s}`;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 o=e.data.count,n=Math.min(r,20),s=Math.ceil(o/n);return a&&(t=await this.enrichPoolsWithPricing(t)),this.logger.debug("DEX pools fetched successfully",{poolCount:t.length,total:o,totalPages:s,withPrices:a}),{pools:t,page:i,limit:n,total:o,totalPages:s,hasNext:i<s,hasPrevious:i>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 Gn((t,o)=>this.fetchDexPools({...e,page:t,limit:o}).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 zn(t.items,t.total,"pools")}}function ni(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[o,n,i,...r]=t;if(!o||!n||!i)throw new Error("Collection, category, and type must be non-empty");const a=r.join("|");if(!a)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:n,type:i,additionalKey:a}}catch(t){throw new I(`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")}}class ii extends ko{constructor(e,t,o=!1,n=3e4){super(e,o),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=n}validateFetchCompositePoolDataInput(e,t,o){if(!e||"string"!=typeof e)throw new O("token0 must be a non-empty string",{token0:e});if(!t||"string"!=typeof t)throw new O("token1 must be a non-empty string",{token1:t});const n=e.split("|"),i=t.split("|");if(4!==n.length)throw new O("token0 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token0:e});if(4!==i.length)throw new O("token1 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token1:t});const r=[500,3e3,1e4];if(!Number.isInteger(o)||!r.includes(o))throw new O(`fee must be one of: ${r.join(", ")} (got ${o})`,{fee:o})}validateQuoteAmount(e){if(!e||"string"!=typeof e)throw new O("amount must be a non-empty string",{amount:e});const t=new i(e);try{tn(t,"amount","for quote calculation")}catch(t){throw new O(t.message,{amount:e})}}convertTokenClassKey(e){const t=new a.TokenClassKey;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:o,fee:n,gatewayBaseUrl:s}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:o,fee:n}),this.validateFetchCompositePoolDataInput(t,o,n);try{const e=ni(t),c=ni(o),l=this.convertTokenClassKey(e),u=this.convertTokenClassKey(c),d=new r.GetCompositePoolDto(l,u,n),h=`${s||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,g=await this.http.post(h,d);if(!g||1!==g.Status)throw new _(`Pool not found: ${t}/${o} with fee ${n}`);const p=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 r.Pool(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,new i(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=new i(e.pool.grossPoolLiquidity),t.liquidity=new i(e.pool.liquidity),t.feeGrowthGlobal0=new i(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=new i(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=new i(e.pool.protocolFeesToken0),t.protocolFeesToken1=new i(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=new i(e.pool.maxLiquidityPerTick);const o={};Object.keys(e.tickDataMap).forEach(t=>{const n=e.tickDataMap[t],a=new r.TickData(n.poolHash,n.tick);a.initialised=n.initialised,a.liquidityNet=new i(n.liquidityNet),a.liquidityGross=new i(n.liquidityGross),a.feeGrowthOutside0=new i(n.feeGrowthOutside0),a.feeGrowthOutside1=new i(n.feeGrowthOutside1),o[t]=a});const n={...e.token0Balance},s=new a.TokenBalance(n);s.quantity=new i(e.token0Balance.quantity);const c={...e.token1Balance},l=new a.TokenBalance(c);return l.quantity=new i(e.token1Balance.quantity),new r.CompositePoolDto(t,o,s,l,e.token0Decimals,e.token1Decimals)}(g.Data),g.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:o,fee:n,liquidity:p.pool.liquidity.toString()}),p}catch(e){if(e instanceof _)throw e;const i=e instanceof Error?e.message:String(e);throw this.logger.error("Failed to fetch composite pool data",e),new O(`Failed to fetch composite pool data: ${i}`,{token0:t,token1:o,fee:n})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:o,toToken:n,amount:a}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:o,toToken:n,amount:a}),this.validateQuoteAmount(a),!t)throw new O("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=o===t.pool.token0.replace(/\$/g,"|"),s=ni(o),c=ni(n),l=this.convertTokenClassKey(s),u=this.convertTokenClassKey(c),d=new r.QuoteExactAmountDto(l,u,t.pool.fee,new i(a),e,t.compositePoolDto),h=await r.quoteExactAmount(void 0,d);return this.logger.debug("Local quote calculated",{amount0:h.amount0,amount1:h.amount1}),{amount0:h.amount0.toString(),amount1:h.amount1.toString(),currentSqrtPrice:h.currentSqrtPrice.toString(),newSqrtPrice:h.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("Local quote calculation failed",e),new O(`Local quote calculation failed: ${t}`,{fromToken:o,toToken:n,amount:a})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:o,toToken:n,amount:a}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:o,toToken:n,amount:a}),this.validateQuoteAmount(a),!t)throw new O("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=o===t.pool.token0.replace(/\$/g,"|"),s=ni(o),c=ni(n),l=this.convertTokenClassKey(s),u=this.convertTokenClassKey(c),d=new r.QuoteExactAmountDto(l,u,t.pool.fee,new i(a),e,void 0),h=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,g=await this.http.post(h,d);if(!g||1!==g.Status)throw new O("External quote failed: "+(g?.Message||"Unknown error"));const p=g.Data;return this.logger.debug("External quote calculated",{amount0:p.amount0,amount1:p.amount1}),{amount0:p.amount0.toString(),amount1:p.amount1.toString(),currentSqrtPrice:p.currentSqrtPrice.toString(),newSqrtPrice:p.newSqrtPrice.toString()}}catch(e){const t=e instanceof Error?e.message:String(e);throw this.logger.error("External quote calculation failed",e),new O(`External quote calculation failed: ${t}`,{fromToken:o,toToken:n,amount:a})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class ri{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 o=this.getPoolMetrics(e);o.cacheHits++,o.eventsProcessed++,o.totalLatency+=t,o.lastEventTime=new Date}recordPoolCacheMiss(e,t){const o=this.getPoolMetrics(e);o.cacheMisses++,o.eventsProcessed++,o.totalLatency+=t,o.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),o=Math.floor(.95*e.length),n=Math.floor(.99*e.length);return{p50:e[t]??0,p95:e[o]??0,p99:e[n]??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 o=t.cacheHits+t.cacheMisses;return 0===o?0:t.cacheHits/o*100}getHealthMetrics(e,t,o,n,i){const r=this.getLatencyPercentiles(),a=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:r.p50,latencyP95:r.p95,latencyP99:r.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:Math.round(10*a)/10,maxMB:i,percentUsed:Math.round(a/i*1e3)/10},pools:{totalMonitored:e,hotCacheSize:t,warmCacheSize:o,coldCacheSize:n}}}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 ai{static createPoolKey(e,t,o){return`${e}/${t}/${o}`}static parsePoolKey(e){if(!e||"string"!=typeof e)return null;const t=e.split("/");if(3!==t.length)return null;const o=t[0]?.trim(),n=t[1]?.trim(),i=t[2]?.trim();if(!o||!n||!i)return null;const r=Number.parseInt(i,10);return Number.isNaN(r)?null:{token0:o,token1:n,feeTier:r}}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 o=this.parsePoolKey(e);return!!o&&(o.token0===t||o.token1===t)}static containsTokenPair(e,t,o){const n=this.parsePoolKey(e);if(!n)return!1;const i=n.token0===t||n.token1===t,r=n.token0===o||n.token1===o;return i&&r&&t!==o}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 si{constructor(e){this.logger=e||new T({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const o=[],n=new WeakSet,i=(e,r=0)=>{if(r>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(n.has(e))return;n.add(e);const a=this.extractSwapFromObject(e);a&&!t.has(a.transactionId)&&(o.push(a),t.add(a.transactionId));for(const t of Object.values(e))i(t,r+1)}};return i(e,0),o}extractSwapFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const o=e.Data,n=o&&"object"==typeof o&&!Array.isArray(o)?o:e,i=this.extractToken(n,"token0","fromToken","source"),r=this.extractToken(n,"token1","toToken","destination");if(!i||!r)return null;const a=this.extractAmount(n,"amount0","amountIn","inputAmount"),s=this.extractAmount(n,"amount1","amountOut","outputAmount");if(!a||!s)return null;const c=this.extractFeeTier(n);if(null===c)return null;const l=this.extractTimestamp(n),u=this.buildPoolKey(i,r,c),d=this.determineDirection(n,i,r),h={transactionId:t,poolKey:u,token0:i,token1:r,amount0:a,amount1:s,feeTier:c,direction:d,timestamp:l,exactInput:this.determineExactInput(n,d)},g=this.extractUser(n);return void 0!==g&&(h.user=g),h}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractToken(e,...t){for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractAmount(e,...t){for(const o of t){const t=e[o];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 o of t){const t=e[o],n=this.normalizeFee(t);if(null!==n)return n}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 o of t){const t=e[o];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 o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}}determineDirection(e,t,o){const n=e.zeroForOne||e.direction;if("boolean"==typeof n)return n?"zeroForOne":"oneForZero";if("string"==typeof n){if("zerotoone"===n.toLowerCase()||"0to1"===n)return"zeroForOne";if("onetozero"===n.toLowerCase()||"1to0"===n)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===o||e.inputToken===o)return"oneForZero";const i=this.extractAmount(e,"amount0","amountIn");return i&&Number(i),"zeroForOne"}determineExactInput(e,t){if("boolean"==typeof e.exactInput)return e.exactInput;if("boolean"==typeof e.exactOutput)return!e.exactOutput;const o=void 0!==e.amountIn&&null!==e.amountIn,n=void 0!==e.amountOut&&null!==e.amountOut,i=void 0!==e.inputAmount&&null!==e.inputAmount,r=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!o||n)||!(n&&!o)&&(!(!i||r)||!(r&&!i))}buildPoolKey(e,t,o){return`${e}/${t}/${o}`}}class ci{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,new i(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,o=Array.from(this.CACHE.keys());for(let e=0;e<t;e++)this.CACHE.delete(o[e])}}}ci.CACHE=new Map,ci.ZERO=new i(0),ci.ONE=new i(1),ci.FEE_PIPS=new i(1e6),ci.MIN_SQRT_RATIO=new i("4295128739"),ci.MAX_SQRT_RATIO=new i("1461446703485210103287273052203988822378723970342");const li={maxIterations:100,enableBigNumberCache:!0,roundingMode:i.ROUND_DOWN,debugLogging:!1};class ui{static calculateSwapDelta(e,t,o={}){const n=Date.now(),r={...li,...o};try{const o=this.initializeSwapState(e,t,r);r.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:o.sqrtPrice.toString(),liquidity:o.liquidity.toString(),tick:o.tick,zeroForOne:t.zeroForOne});const a=this.computeSwapLoop(o,e,t,r);r.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:a.stepCount,ticksCrossed:a.ticksCrossed.length,priceHitLimit:a.priceHitLimit});const s=this.createUpdatedPool(e.pool,a.state,t,r),c=this.calculateFinalAmounts(o,a.state,t);let l;if(t.actualSqrtPrice){const e=new i(s.sqrtPrice),o=new i(t.actualSqrtPrice);l=e.minus(o).abs().div(o).times(100).toNumber()}const u=Date.now()-n;r.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:u,amount0:c.amount0.toString(),amount1:c.amount1.toString(),driftPercentage:l}),u>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:u,stepCount:a.stepCount,ticksCrossed:a.ticksCrossed.length}),a.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:a.stepCount}),a.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:a.stepCount,ticksCrossed:a.ticksCrossed.length});return{updatedPool:s,updatedTicks:a.updatedTicks,amount0:c.amount0,amount1:c.amount1,feeAmount0:c.feeAmount0,feeAmount1:c.feeAmount1,ticksCrossed:a.ticksCrossed,metadata:{calculationTimeMs:u,swapSteps:a.stepCount,priceHitLimit:a.priceHitLimit,...void 0!==l&&{driftPercentage:l}}}}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,o){const{pool:n}=e;if(!n.sqrtPrice||!n.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const a=o.enableBigNumberCache?ci.getCached.bind(ci):e=>new i(e),s="string"==typeof n.sqrtPrice?n.sqrtPrice:new i(n.sqrtPrice).toFixed(0),c="string"==typeof n.liquidity?n.liquidity:new i(n.liquidity).toFixed(0),l=a(s),u=a(c),d=n.tick??0,h=r.sqrtPriceToTick(new i(s)),g=Math.abs(h-d);g>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:d,calculatedTick:h,drift:g,threshold:100});const p=a(t.amountSpecified);tn(p,"amountSpecified","for swap operation");const m="string"==typeof n.feeGrowthGlobal1?n.feeGrowthGlobal1:new i(n.feeGrowthGlobal1).toFixed(0),f="string"==typeof n.feeGrowthGlobal0?n.feeGrowthGlobal0:new i(n.feeGrowthGlobal0).toFixed(0),y=t.zeroForOne?a(m):a(f);return{sqrtPrice:l,liquidity:u,tick:d,amountSpecifiedRemaining:p,amountCalculated:ci.ZERO,feeGrowthGlobalX:y,protocolFee:ci.ZERO}}static computeSwapLoop(e,t,o,n){const{pool:a,tickDataMap:s}=t,c=[],l={};let u=0;const d=o.zeroForOne?ci.MIN_SQRT_RATIO:ci.MAX_SQRT_RATIO,h=new i("0.000001");for(;e.amountSpecifiedRemaining.gt(h)&&!e.sqrtPrice.eq(d)&&u<n.maxIterations;){u++;const[t,h]=this.findNextInitializedTick(s,e.tick,a.tickSpacing,o.zeroForOne);let g;if(n.debugLogging&&this.logger.debug(`Swap step ${u}`,{currentTick:e.tick,tickNext:t,initialized:h,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),h&&t>=-887272&&t<=887272){const e=r.tickToSqrtPrice(t);g=e instanceof i?e:new i(String(e))}else g=d;const p=o.zeroForOne?i.max(g,d):i.min(g,d),m=this.executeSwapStep(e.sqrtPrice,p,e.liquidity,e.amountSpecifiedRemaining,a.fee,o.exactInput);if(e.sqrtPrice=m.sqrtPriceNext,o.exactInput){const t=m.amountIn.plus(m.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=ci.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=ci.ZERO)),e.amountCalculated=e.amountCalculated.minus(m.amountOut)}else{m.amountOut.lte(0)?e.amountSpecifiedRemaining=ci.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(m.amountOut),e.amountCalculated=e.amountCalculated.plus(m.amountIn.plus(m.feeAmount))}if(e.liquidity.gt(0)){const t=m.feeAmount.div(e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(g)&&h){const r=s[t.toString()];if(!r)throw new Error(`Missing tick data for initialized tick ${t}`);const a=o.zeroForOne?new i(r.liquidityNet).negated():new i(r.liquidityNet);if(e.liquidity=e.liquidity.plus(a),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);c.push(t),l[t.toString()]=r,n.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:a.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(g))e.tick=o.zeroForOne?t-1:t;else{const t=r.sqrtPriceToTick(new i(e.sqrtPrice.toString()));e.tick=t}}if(u>=n.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${n.maxIterations}). Possible infinite loop or very complex swap.`);const g=e.sqrtPrice.eq(d);return{state:e,ticksCrossed:c,priceHitLimit:g,stepCount:u,updatedTicks:l}}static createUpdatedPool(e,t,o,n){const r=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(r.sqrtPrice=t.sqrtPrice.toFixed(0),r.liquidity=t.liquidity.toFixed(0),r.tick=t.tick,o.zeroForOne?r.feeGrowthGlobal1=t.feeGrowthGlobalX.toFixed(0):r.feeGrowthGlobal0=t.feeGrowthGlobalX.toFixed(0),o.zeroForOne){const o=new i(e.protocolFeesToken0);r.protocolFeesToken0=o.plus(t.protocolFee).toFixed(0)}else{const o=new i(e.protocolFeesToken1);r.protocolFeesToken1=o.plus(t.protocolFee).toFixed(0)}return r}static calculateFinalAmounts(e,t,o){let n,r,a,s;if(o.exactInput){const e=new i(o.amountSpecified),c=t.amountCalculated.abs();o.zeroForOne?(n=e.negated(),r=c,a=ci.ZERO,s=ci.ZERO):(n=c,r=e.negated(),a=ci.ZERO,s=ci.ZERO)}else{const e=new i(o.amountSpecified),c=t.amountCalculated.abs();o.zeroForOne?(n=c.negated(),r=e,a=ci.ZERO,s=ci.ZERO):(n=e,r=c.negated(),a=ci.ZERO,s=ci.ZERO)}const c=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return o.zeroForOne?s=c:a=c,{amount0:n,amount1:r,feeAmount0:a,feeAmount1:s}}static findNextInitializedTick(e,t,o,n){const i=Object.keys(e).map(e=>parseInt(e,10)).sort((e,t)=>e-t);if(0===i.length){return[n?-887272:887272,!1]}if(n){const e=i.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=i.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,o,n,a,s){en(o),tn(n,"amountRemaining","for swap step");const c=[500,3e3,1e4];if(!c.includes(a))throw new Error(`Invalid fee tier: ${a}. Must be one of: ${c.join(", ")}`);const l=r.computeSwapStep(e,t,o,n,a,t.lt(e)),u=l[0],d=l[1],h=l[2],g=l[3],p=i.isBigNumber(u)?u:new i(String(u)),m=i.isBigNumber(d)?d:new i(String(d)),f=i.isBigNumber(h)?h:new i(String(h)),y=i.isBigNumber(g)?g:new i(String(g));return{sqrtPriceStart:e,tickNext:r.sqrtPriceToTick(p),sqrtPriceNext:p,initialised:!1,amountIn:m,amountOut:f,feeAmount:y}}}ui.logger=new T({debug:!1,context:"SwapDeltaCalculator"});class di{constructor(e,t,o,n){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=o,this.logger=n||new T({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),o=this.determineTier(),n={poolData:t,tier:o,lastAccessTime:Date.now(),expiresAt:Date.now()+this.tierTTLs[o],swapsSinceRefetch:0,cumulativeDrift:0,lastDeltaAppliedTime:Date.now()};return this.cache.set(e,n),this.cache.size>this.config.maxPools&&this.evictLRU(),this.logger.debug(`Fetched pool ${e} (tier: ${o})`),t}catch(t){throw this.logger.error(`Failed to fetch pool ${e}:`,t),t}}updatePoolWithSwapDelta(e,t,o,n,i){const r=this.cache.get(e);if(!r)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(i){const a="zeroForOne"===t,s=a?o:n,c={transactionId:i.transactionId,timestamp:i.timestamp,amountSpecified:s,zeroForOne:a,exactInput:i.exactInput},l=ui.calculateSwapDelta(r.poolData,c);r.poolData={...r.poolData,pool:l.updatedPool},r.swapsSinceRefetch++,r.lastDeltaAppliedTime=Date.now(),void 0!==l.metadata.driftPercentage?(r.cumulativeDrift+=l.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${l.metadata.driftPercentage.toFixed(4)}%, cumulative=${r.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${l.ticksCrossed.length} ticks crossed`)}else r.swapsSinceRefetch++,r.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(r)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${r.swapsSinceRefetch}, drift=${(100*r.cumulativeDrift).toFixed(2)}%`),r.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),r.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 o={succeeded:0,failed:0,total:e.length};let n=0;const i=new Set;for(;n<e.length||i.size>0;){for(;n<e.length&&i.size<t;){const t=e[n];n++;const r=this.warmCache(t).then(e=>{e?o.succeeded++:o.failed++});i.add(r),r.finally(()=>i.delete(r))}i.size>0&&await Promise.race(i)}return this.logger.debug(`Cache warming complete: ${o.succeeded}/${o.total} succeeded`),o}clear(){this.cache.clear(),this.logger.debug("Cache cleared")}clearExpired(){const e=Date.now();let t=0;for(const[o,n]of this.cache)e>n.expiresAt&&(this.cache.delete(o),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(o=>{t&&(t.poolData=o,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)})),o=new Promise(e=>setTimeout(()=>e(),5e3));await Promise.race([Promise.all(t),o])}}class hi{constructor(e,t,o){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=o||new T({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 o=()=>{0!==this.queue.length||0!==this.currentConcurrency?setTimeout(o,10):t()};e&&setTimeout(()=>t(),e),o()})}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 o=0;o<e.length;o++){const n=e[o];this.eventsProcessedCount++,"rejected"===n.status&&this.logger.error(`Failed to process event ${t[o].transactionId}:`,n.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 o=Date.now()-t;this.metrics.recordEventLatency(o)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class gi{constructor(e,t,o,n={},i){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=i||new T({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 ri,this.config=this.applyDefaults(n),this.eventExtractor=new si(this.logger),this.quoteService=o,this.cacheManager=new di(t,this.config,this.metrics,this.logger),this.eventQueue=new hi(this.config,this.metrics,this.logger),this.seenTransactions=new pi(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 o=this;return()=>{o.listeners=o.listeners.filter(e=>e!==t),e.onError&&(o.onErrorCallbacks=o.onErrorCallbacks.filter(t=>t!==e.onError)),0===o.listeners.length&&0===o.onErrorCallbacks.length&&o.unsubscribe()}}getHealth(){const e=this.cacheManager.getStats(),t=this.eventQueue.getStats(),o=this.metrics.getHealthMetrics(e.totalCached,e.hotCacheSize,e.warmCacheSize,e.coldCacheSize,this.getMaxMemoryMB()),n=this.determineHealthStatus(t,e),i={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectAttempts};this.socket?.connected&&(i.lastConnectionTime=new Date);const r=t.queueSize/this.config.maxQueueSize*100,a=e.totalCached/this.config.maxPools*100,s=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(n,r,a,s,o.metrics.cacheHitRate);return{...o,status:n,websocket:i,recommendations:c,detailedMetrics:{eventQueueUtilization:r,cacheUtilization:a,memoryUtilization:s}}}generateHealthRecommendations(e,t,o,n,i){const r=[];return"failed"===e&&(r.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||r.push("Reconnect WebSocket - connection lost"),t>90&&r.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(r.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&r.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),n>80&&r.push(`Memory usage ${n.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(i<50&&r.push(`Cache hit rate ${i.toFixed(1)}% is low - consider warming more pools`),n>50&&r.push("Memory usage is moderate - monitor for growth trends"),t>50&&r.push("Queue utilization is elevated - monitor for bottlenecks")),r}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=(o,...n)=>{try{const o=Date.now(),i=n[0],r=t.eventExtractor.walkPayloadForSwaps(i,t.seenTransactions);if(0===r.length)return;t.logger.debug(`Extracted ${r.length} swaps from payload`);for(const o of r){if(t.filterSwap(o,e)){t.eventQueue.enqueue(o)||t.logger.debug(`Swap dropped due to queue overflow: ${o.transactionId}`)}}const a=Date.now()-o;t.metrics.recordEventLatency(a)}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(!ai.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[o,n]=t.pairTokens;if(!ai.containsTokenPair(e.poolKey,o,n))return!1}if(t.feeTierFilter){if(ai.normalizeFee(t.feeTierFilter)!==e.feeTier)return!1}return!t.userFilter||e.user===t.userFilter}async processSwapEvent(e){const t=Date.now();try{const o=this.cacheManager.updatePoolWithSwapDelta(e.poolKey,e.direction,e.amount0,e.amount1,e);e.poolStateUpdated=o;const n=Date.now()-t;this.metrics.recordEventLatency(n);for(const t of this.listeners)try{const o=t(e);o instanceof Promise&&await o}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 pi{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}}function mi(e){const t=function(e){const t=Pt(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 fi="/api/asset/launchpad-contract/CallNativeTokenIn",yi="/api/asset/launchpad-contract/CallNativeTokenOut",wi="/api/asset/launchpad-contract/CallMemeTokenIn",ki="/api/asset/launchpad-contract/CallMemeTokenOut";class vi extends o.ChainCallDTO{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 Ti(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 Si={NATIVE:"native",EXACT:"exact"},bi={LOCAL:"local",EXTERNAL:"external"};class Ai{static calculateBuyWithExact(e,t){const o=parseFloat(e),n=parseFloat(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:a,TRADING_FEE_FACTOR:s,GAS_FEE:c}=ei,l=this.roundUp(r*(Math.exp((n+o)*a)-Math.exp(n*a))/a,8),u=new i(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateBuyWithNative(e,t){const o=parseFloat(e),n=parseFloat(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:a,TRADING_FEE_FACTOR:s,GAS_FEE:c}=ei,l=Math.log(o*a/r+Math.exp(n*a))/a-n,u=new i(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateSellWithExact(e,t,o,n,r){const a=parseFloat(e),s=parseFloat(t),c=parseFloat(o),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=ei,g=l*(Math.exp(s*u)-Math.exp((s-a)*u))/u,p=new i(g),m=n+s/c*(r-n),f=p.multipliedBy(m).toFixed(8,i.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,o,n,r){const a=parseFloat(e),s=parseFloat(t),c=parseFloat(o),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=ei,g=s-Math.log(Math.exp(s*u)-a*u/l)/u,p=new i(a),m=n+s/c*(r-n),f=p.multipliedBy(m).toFixed(8,i.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static roundUp(e,t){const o=Math.pow(10,t);return Math.ceil(e*o)/o}}class Ei{constructor(e,t,o,n,i,r,a="local"){this.http=e,this.tokenResolver=t,this.logger=o,this.bundleHttp=n,this.galaChainHttp=i,this.dexApiHttp=r,this.defaultCalculateAmountMode=a,this.metadataCache=new ti}addIfDefined(e,t,o){return void 0!==o&&(e[t]=o),e}async uploadImageByTokenName(e){const{tokenName:t,options:o}=e;jt(t);const n=`${t}.png`;Go(o.file,n,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&o.file instanceof File)e.append("image",o.file);else{if(!Buffer.isBuffer(o.file))throw M("file","a File object (browser) or Buffer (Node.js)");{const n=`${o.tokenName||t}.png`,i=new Blob([o.file],{type:"image/png"});e.append("image",i,n)}}const n=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(o.tokenName||t)}`,data:e,headers:{}});if(!0===n.error||200!==n.status||!n.data?.imageUrl)throw R(n.message||"Image upload failed - no URL returned",n.status);return n.data.imageUrl}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw q("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){Ht(e),e.tokenName&&jt(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 o=S(t),n=await this.http.get("/launchpad/fetch-pool",o);if(!0===n.error||200!==n.status||!n.data)throw R(n.message||"Failed to fetch pools",n.status);let i=[];const r=(await import("bignumber.js")).default;if(n.data.tokens)if(Array.isArray(n.data.tokens))i=n.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",o=e.reverseBondingCurveMaxFeePortion??"0",n=!new r(t).isZero()||!new r(o).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}});else{const e=n.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",o=e.reverseBondingCurveMaxFeePortion??"0",a=!new r(t).isZero()||!new r(o).isZero();i=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:a,createdAt:e.created_at||e.createdAt||""}]}else n.data.pools&&Array.isArray(n.data.pools)&&(i=n.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",o=e.reverseBondingCurveMaxFeePortion??"0",n=!new r(t).isZero()||!new r(o).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:a,isValidPoolForCaching:s}=await Promise.resolve().then(function(){return Mi});i.forEach(e=>{if(!s(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=a(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=n.data.count??n.data.total??0,l=n.data.page??e.page??1,u=n.data.limit??e.limit??10,d=u>0?Math.ceil(c/u):1;return{pools:i,page:l,limit:u,total:c,totalPages:d,hasNext:l<d,hasPrevious:l>1}}async _getAmount(e){if(Qt(e),!this.galaChainHttp)throw q("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:o}=((e,t,o,n)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:fi,body:{vaultAddress:o,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:yi,body:{vaultAddress:o,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:wi,body:{vaultAddress:o,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:ki,body:{vaultAddress:o,nativeTokenQuantity:n,IsPreMint:!1}};throw M("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,o);if(!Ti(e))throw R("Malformed response data from GalaChain gateway");if(1!==e.Status)throw R(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:n,extraFees:i}=e.Data;return{amount:n,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(n){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:o,error:n instanceof Error?n.message:n}),n}}async checkPool(e){Vt(e),e.tokenName&&jt(e.tokenName);const t=S(e),o=await this.http.get("/launchpad/check-pool",t);if(!0===o.error||200!==o.status)throw R(o.message||"Failed to check pool",o.status);const n=o.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.exists??!1}async fetchVolumeData(e){if(!Eo(e))throw new I("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:o,to:n,resolution:i}=e;if(jt(t),!o||!n||!i)throw new I("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:o,to:n,resolution:i};Xt(r);const a=S(r),s=await this.http.get("/launchpad/get-graph-data",a);if(!0===s.error||200!==s.status||!s.data)throw R(s.message||"Failed to fetch graph data",s.status);return{dataPoints:s.data}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const o={page:e.page||1,limit:e.limit||10};return e.search&&(o.search=e.search),e.tokenName&&(o.tokenName=e.tokenName),t&&(o.type=t),this.fetchPoolsFromAPI(o)}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 I("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:o,type:n,currentSupply:i}=e,r=e.mode??this.defaultCalculateAmountMode;if("local"!==r&&"external"!==r)throw new I(`Invalid calculation mode "${r}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new I("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Si.NATIVE&&n!==Si.EXACT)throw new I('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===r?this.calculateBuyAmountExternal({tokenName:t,amount:o,type:n}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:o,type:n},"currentSupply",i))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:o,type:n}=e,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw new I(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Si.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:i,amount:o}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:i,amount:o})}async calculateSellAmount(e){const{tokenName:t,amount:o,type:n,currentSupply:i,maxSupply:r,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:s}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new I(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new I("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Si.EXACT&&n!==Si.NATIVE)throw new I('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:o,type:n});{const e={tokenName:t,amount:o,type:n,...void 0!==i&&{currentSupply:i},...void 0!==r&&{maxSupply:r},...void 0!==a&&{reverseBondingCurveMaxFeeFactor:a},...void 0!==s&&{reverseBondingCurveMinFeeFactor:s}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:o,type:n}=e,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw new I(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Si.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:i,amount:o}):this._getAmount({type:"MEME",method:"IN",vaultAddress:i,amount:o})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:o,type:n,currentSupply:i}=e;if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Si.NATIVE&&n!==Si.EXACT)throw new I('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==i&&Yt(i,"currentSupply");const r=!i;if(r&&!t)throw new I("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&jt(t);let a=i;if(r){a=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return n===Si.EXACT?Ai.calculateBuyWithExact(o,a):Ai.calculateBuyWithNative(o,a)}async calculateSellAmountLocal(e){const{tokenName:t,amount:o,type:n,currentSupply:i,maxSupply:r,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:s}=e;if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Si.EXACT&&n!==Si.NATIVE)throw new I('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==i&&Yt(i,"currentSupply");const c=!i||!r||void 0===a||void 0===s;if(c&&!t)throw new I("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&jt(t);let l=i,u=r,d=a,h=s;if(c&&t){const e=this.metadataCache.get(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,l||(l=await this.fetchCurrentSupply(t));if(void 0===d||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);d=d??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return n===Si.EXACT?Ai.calculateSellWithExact(o,l,u,h,d):Ai.calculateSellWithNative(o,l,u,h,d)}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 To(t,"tokenName")&&Ao(t)&&So(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:o,calculateAmountMode:n,currentSupply:i}=t;jt(o);const r=await this.tokenResolver.resolveTokenToVault(o);if(!r)throw new I(E(o),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw q("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:r});if(1!==a.Status)throw R(`Failed to fetch pool details: Status ${a.Status}`,a.Status);const s=a.Data,c=(await import("bignumber.js")).default,l=i??new c(s.maxSupply).minus(s.sellingTokenQuantity).toFixed(),u=s.sellingTokenQuantity;if("0"===u)throw new I(`Token ${o} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const d={tokenName:o,amount:u,type:"exact",currentSupply:l,...void 0!==n&&{mode:n}};return await this.calculateBuyAmount(d)}async launchToken(e){if(!this.bundleHttp)throw q("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");mi(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new I("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:o}=e.reverseBondingCurveConfiguration,n=Number(t),i=Number(o);if(isNaN(n)||isNaN(i)||n<=0||i<=0||n>=i)throw new I("Reverse bonding curve configuration must have valid min/max fee portions with min < max","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 R("Image upload failed: No URL returned");n=t}else"string"==typeof e.tokenImage&&(n=e.tokenImage);const i=`galaswap - operation - ${s.v4()}-${Date.now()}-${this.http.getAddress()}`,r={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:i};e.websiteUrl?.trim()&&(r.websiteUrl=e.websiteUrl.trim()),e.telegramUrl?.trim()&&(r.telegramUrl=e.telegramUrl.trim()),e.twitterUrl?.trim()&&(r.twitterUrl=e.twitterUrl.trim()),e.reverseBondingCurveConfiguration&&(r.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const a=new vi(r),c=await this.http.signWithGalaChain("CreateSale",a,o.SigningType.SIGN_TYPED_DATA),{signature:l,types:u,domain:d,prefix:h}=c,g={tokenName:a.tokenName,tokenSymbol:a.tokenSymbol,tokenDescription:a.tokenDescription,tokenImage:a.tokenImage,preBuyQuantity:a.preBuyQuantity,...a.websiteUrl&&{websiteUrl:a.websiteUrl},...a.telegramUrl&&{telegramUrl:a.telegramUrl},...a.twitterUrl&&{twitterUrl:a.twitterUrl},tokenCategory:a.tokenCategory,tokenCollection:a.tokenCollection,uniqueKey:a.uniqueKey,signature:l,types:u,domain:d,...h&&{prefix:h},...a.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:a.reverseBondingCurveConfiguration}},p=`${e.tokenName.trim()}$Unit$none$none`,m="GALA$Unit$none$none";let f;if(parseFloat(t)>0){const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`]}else{const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`]}const y={signedDto:g,stringsInstructions:f,method:"CreateSale"},w=await this.bundleHttp.post("/bundle",y);if(w.error||!w.data)throw R(w.message||"Token launch failed");return w.data}async fetchTokenDistribution(e){if(!e)throw U("tokenName","Token name");jt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new I(E(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const o=encodeURIComponent(t),n=await this.http.get(`/holders/${o}`);if(!0===n.error||200!==n.status||!n.data)throw R(n.message||"Failed to fetch token distribution",n.status);const r=n.data;if(!Array.isArray(r))throw R("Invalid API response: expected array of holders",n.status);for(const e of r){if(!e.owner||"string"!=typeof e.owner)throw R("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw R("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw R(`Invalid holder quantity: "${e.quantity}"`,n.status)}const a=r.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:r.map(e=>{const t=new i(e.quantity),o=a.isZero()?0:t.dividedBy(a).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:o}}),totalSupply:a.toFixed(),totalHolders:r.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw U("tokenName","Token name");jt(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw R(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:o,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const i=("volume"===o?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return i?.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 I("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw q("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},o=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!Ti(o))throw R("Malformed response data from GalaChain gateway");if(1!==o.Status)throw R(`GalaChain calculation failed with status ${o.Status}`,o.Status);const{calculatedQuantity:n,extraFees:i}=o.Data;return{amount:n,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.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 I(E(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw q("GalaChain HTTP client not configured");const o=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==o.Status)throw R(`Failed to fetch pool details: Status ${o.Status}`,o.Status);const n=o.Data,i=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),r=n.sellingTokenQuantity,a=n.maxSupply;let s=.5,c=0;n.reverseBondingCurveConfiguration?(s=parseFloat(n.reverseBondingCurveConfiguration.maxFeePortion),c=parseFloat(n.reverseBondingCurveConfiguration.minFeePortion)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const l=s-c;return this.metadataCache.set(e,{maxSupply:a,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}),{currentSupply:i,remainingTokens:r,maxSupply:a,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}}async fetchCurrentSupply(e){jt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new I(E(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw q("GalaChain HTTP client not configured");const o=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==o.Status)throw R(`Failed to fetch pool details: Status ${o.Status}`,o.Status);const n=o.Data,i=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),r=n.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),i}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Zt(e)}validateTokenName(e){return jt(e)}validatePagination(e){return Ht(e)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw q("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw U("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}}),o=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&o.push({symbol:e.symbol,price:e.currentPrices.usd})}),o}catch(e){throw R(`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 To(t,"tokenName")&&Ao(t)&&So(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:o,calculateAmountMode:n,currentSupply:i}=t;if(!o||"string"!=typeof o)throw U("tokenName","Token name (string)");try{const e={tokenName:o,amount:"1",type:"native",...void 0!==n&&{mode:n},...void 0!==i&&{currentSupply:i}},t=await this.calculateBuyAmount(e),r=(await this.fetchTokenPrice("GALA"))[0];if(!r)throw R("GALA price not available");const a=Number(t.amount);if(a<=0)throw new I(`Invalid token amount calculation: ${a}`,"amount","INVALID_CALCULATION");const s=r.price/a;return{symbol:o.toUpperCase(),price:s}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${o}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${o}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}const Ii={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 Pi(e){return Ii[e]}class Ni extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class xi extends Error{constructor(e,t,o){super(`Transaction ${e} failed with status: ${t}${o?` - ${o}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function Di(e,t){if(!e)throw new Ni(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Ni(`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 Ni(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Ci(e,t,o,n){Di(e,t);const i=e,r=i.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)}(r))throw new Ni(`Invalid trade data received for transaction ${t}`);const a={transactionId:t,type:o,method:"native"===n.type?"native":"exact",inputAmount:r.inputQuantity||n.amount,outputAmount:r.outputQuantity||n.expectedAmount||"0",totalFees:r.totalFees||"0",tokenName:n.tokenName,vaultAddress:r.vaultAddress||"",timestamp:Date.now()};return void 0!==i.blockHash&&(a.blockHash=i.blockHash),void 0!==i.gasUsed&&(a.gasUsed=i.gasUsed),void 0!==n.slippageToleranceFactor&&(a.slippageTolerance=n.slippageToleranceFactor),a}const Fi="4.0.1-beta.3";class $i{constructor(e){this.logger=e||new T({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const o=[],n=new WeakSet,i=(e,r=0)=>{if(r>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(e&&"string"!=typeof e&&"object"==typeof e){if(n.has(e))return;n.add(e);const a=this.extractLiquidityFromObject(e);a&&!t.has(a.transactionId)&&(o.push(a),t.add(a.transactionId));for(const t of Object.values(e))i(t,r+1)}};return i(e,0),o}extractLiquidityFromObject(e){const t=this.extractTransactionId(e);if(!t)return null;const o=e.Data,n=o&&"object"==typeof o&&!Array.isArray(o)?o:e,i=this.extractPositionId(n),r=this.extractPoolHash(n),a=this.extractAmounts(n),s=this.extractUserAddress(n),c=this.extractPoolFee(n);if(!(i&&r&&a&&s&&null!==c))return null;const l=this.extractPoolAlias(n),u=this.extractUserBalanceDelta(n),d=this.extractTimestamp(n),h=u?.token0Balance?.collection,g=u?.token1Balance?.collection,p={transactionId:t,positionId:i,poolHash:r,poolFee:c,amounts:a,userAddress:s};return void 0!==h&&(p.token0=h),void 0!==g&&(p.token1=g),void 0!==d&&(p.timestamp=d),void 0!==l&&(p.poolAlias=l),void 0!==u&&(p.userBalanceDelta=u),p}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","poolId","pool"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const o of t){const t=e[o];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(),o=String(t[1]).trim();if(e&&o)return[e,o]}const o=e.amount0||e.amount0Desired,n=e.amount1||e.amount1Desired;return void 0!==o&&void 0!==n?[String(o),String(n)]:null}extractUserAddress(e){const t=["userAddress","user","owner","from","sender","wallet","address"];for(const o of t){const t=e[o];if("string"==typeof t&&t.trim())return t}return null}extractPoolFee(e){const t=["poolFee","fee","feeTier","feeTierBps"];for(const o of t){const t=e[o];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 o of t){const t=e[o];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 o=t,n=this.extractBalanceObject(o.token0Balance),i=this.extractBalanceObject(o.token1Balance);if(!n&&!i)return;const r={};return void 0!==n&&(r.token0Balance=n),void 0!==i&&(r.token1Balance=i),r}extractBalanceObject(e){if(!e||"object"!=typeof e)return;const t=e,o=t.collection,n=t.category,i=t.type,r=t.additionalKey,a=t.quantity,s=t.owner;return"string"==typeof o&&"string"==typeof n&&"string"==typeof i&&"string"==typeof r&&"string"==typeof a&&"string"==typeof s?{collection:o,category:n,type:i,additionalKey:r,quantity:a,owner:s}:void 0}}class Li{constructor(t){this.wallet=t.wallet;let o=null,n="STAGE";t.env?(n=t.env,o=Pi(t.env)):t.baseUrl?.includes("prod")?(n="PROD",o=Pi("PROD")):(n="STAGE",o=Pi("STAGE")),this.environment=n,this.config={baseUrl:o.launchpadBaseUrl,galaChainBaseUrl:o.galaChainBaseUrl,bundleBaseUrl:o.bundleBaseUrl,webSocketUrl:o.webSocketUrl,dexApiBaseUrl:o.dexApiBaseUrl,dexBackendBaseUrl:o.dexBackendBaseUrl,launchpadFrontendUrl:o.launchpadFrontendUrl,timeout:3e4,debug:!1,...t},this.logger=new T({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===t.slippageToleranceFactor?Li.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(t.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===t.maxAcceptableReverseBondingCurveFeeSlippageFactor?Li.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(t.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=t.calculateAmountMode||Li.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=t.pricingConcurrency||5,this.auth=new v({wallet:t.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new b(this.auth,this.config),this.galaChainHttp=new b(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new b(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new b(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new b(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 ti(t.debug||!1),this.launchpadService=new jo(this.http),this.tokenResolverService=new Kn(this.launchpadService.poolService),this.launchpadAPI=new Ei(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new bn(this.galaChainHttp,t.wallet,this.tokenResolverService,t.debug||!1,this.galaChainPublicAxios),this.dexService=new An(this.dexBackendHttp,this.cache,this.galaChainService,t.debug||!1),this.bundleService=new Bn(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,t.wallet,t.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new qn({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new Wn(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new ii(this.galaChainHttp,this.config.galaChainBaseUrl,t.debug||!1,t.dexQuoteNetworkTimeout||3e4),this.gswapService=new Jn({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 oi(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,t.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw q("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw q('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const o=new t.Wallet(e),n={...this.config,wallet:o};return new Li(n)}getAddress(){return this.validateWallet(),this.auth.getAddress()}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw new I("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 I("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}}getVersion(){return Fi}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw q("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:o,currentSupply:n,calculateAmountMode:i}=e;if(t&&!o){const e={tokenName:t};return n&&(e.currentSupply=n),i&&(e.calculateAmountMode=i),this.fetchLaunchpadTokenSpotPrice(e)}if(o&&!t)try{return await this.dexService.fetchTokenPrice({tokenId:o})}catch(e){const t=function(e){if(_o(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(o)).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 r={tokenName:t};return n&&(r.currentSupply=n),i&&(r.calculateAmountMode=i),this.fetchLaunchpadTokenSpotPrice(r)}catch(t){throw this.logger.error(`Launchpad fallback failed: ${Oo(t)}`),e}}throw e}if(!t&&!o)throw U("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");throw new I("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(E(e));const o=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return o.currentSupply=n.currentSupply,o.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,o.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,o.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,o.tokenName=e,o}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 Jt}),o=t(e)||this.getAddress();return this.galaChainService.fetchGalaBalance({owner:o,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return fn}),n=t(e.tokenId),{collection:i,category:r,type:a,additionalKey:s}=n;return this.galaChainService.fetchTokenBalance({owner:o,collection:i,category:r,additionalKey:s,type:a,instance:"0"})}if(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...o&&{address:o}})).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 U("tokenId or tokenName","Either tokenId or tokenName")}async fetchComments(e){return this.launchpadService.fetchComments(e)}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:o,maxAcceptableReverseBondingCurveFeeSlippageFactor:n,privateKey:i,calculateAmountMode:r,currentSupply:a}=e;let s=t;void 0===r&&void 0===a||(s={tokenName:t,...void 0!==r&&{calculateAmountMode:r},...void 0!==a&&{currentSupply:a}});const c=await this.calculateBuyAmountForGraduation(s),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==o&&(l.slippageToleranceFactor=o),void 0!==n&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=n),void 0!==i&&(l.privateKey=i),await this.buy(l)}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:o,...n}=e;return t.buy(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,o=t?.transactionId;if(!o)throw K("No transaction ID returned from buy operation");return this.waitForConfirmation(o,t=>Ci(t,o,"buy",e))}async sell(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.sell(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,o=t?.transactionId;if(!o)throw K("No transaction ID returned from sell operation");return this.waitForConfirmation(o,t=>Ci(t,o,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async postComment(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.postComment(n)}return this.validateWallet(),this.launchpadService.postComment(e)}async launchToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.launchToken(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,o=>{Di(o,t);const n=o?.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)}(n))throw new Ni(`Invalid launch data received for transaction ${t}`);const i={transactionId:t,vaultAddress:n.vaultAddress||"",tokenStringKey:n.tokenStringKey||"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:n.creatorAddress||this.getAddress(),timestamp:Date.now(),...o.blockHash&&{blockHash:o.blockHash},...o.gasUsed&&{gasUsed:o.gasUsed}};return"string"==typeof e.tokenImage&&(i.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(i.preBuyQuantity=e.preBuyQuantity),i.vaultAddress&&this.tokenResolverService.set(e.tokenName,i.vaultAddress),i})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.uploadTokenImage(n)}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 Jt}),o=t(e)||this.getAddress();return this.launchpadService.fetchProfile(o)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,address:t(e.address)};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.updateProfile(n)}return this.validateWallet(),this.launchpadService.updateProfile(o)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,address:t(e.address)||this.getAddress()};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.uploadProfileImage(n)}return this.validateWallet(),this.launchpadService.uploadProfileImage(o)}async retrieveGalaFromFaucet(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={walletAddress:t(e)||this.getAddress(),amount:"5"};return this.launchpadService.transferFaucets(o)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o=t(e?.address)||this.getAddress(),n={page:e?.page||1,limit:e?.limit||10,address:o};return e?.tokenName&&(n.tokenName=e.tokenName),e?.search&&(n.search=e.search),this.launchpadService.fetchTokensHeld(n)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(o.tokenName=e.tokenName),e?.search&&(o.search=e.search),this.launchpadService.fetchTokenList(o)}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 Jt}),o={...e,recipientAddress:t(e.recipientAddress)};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.transferGala(n)}return this.validateWallet(),this.galaChainService.transferGala(o)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,to:t(e.to)};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.transferToken(n)}return this.validateWallet(),this.galaChainService.transferToken(o)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async lockToken(e){if(e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt});e={...e,lockAuthority:t(e.lockAuthority)}}if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.lockToken(n)}return this.validateWallet(),this.galaChainService.lockToken(e)}async unlockToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.unlockToken(n)}return this.validateWallet(),this.galaChainService.unlockToken(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}getCacheInfo(){return this.launchpadAPI.getCacheStats()}clearCache(e){this.launchpadAPI.clearCache(e)}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 q("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw q("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw q(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw q(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw q(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw q(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw q(`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: ${Li.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Li.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: ${Li.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Li.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 o=await this.websocketService.waitForTransaction(e);if("completed"!==o.status)throw new xi(e,o.status,o.message);let n;try{n=t(o)}catch(t){if(t instanceof Ni)throw t;throw new Ni(`Failed to transform WebSocket response for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,n),n}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof xi||t instanceof Ni)throw t;throw new Ni(`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:o}=await Promise.resolve().then(function(){return Mi});e.forEach(e=>{if(!o(e))return;const n=t(e,this.logger);n&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,n)})}async getSwapQuoteExactInput(e,t,o){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:o})}async getSwapQuoteExactOutput(e,t,o){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:o})}async executeSwap(e,t,o,n,i,r=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:o,estimatedOutput:n,feeTier:i,slippageTolerance:r})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,o){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:o})}async getSwapUserLiquidityPositions(e,t,o,n){let i,r;"string"==typeof o?(i=o,r=n):"object"==typeof o?r=o:n&&(r=n);return await this.gswapService.getUserLiquidityPositions(e,t,i,r)}async getAllSwapUserLiquidityPositions(e,t){const o=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(o))return o;if(o&&"items"in o)return o.items}return o}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t,o,n,i,r,a){return this.gswapService.getLiquidityPositionById(e,t,o,n,i,r,a)}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={...e,fee:e.feeTier??e.fee};return 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 o=this.websocketService.getSocket();return o?(o.on(e,t),()=>{o.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 o=1e3,n=Math.max(t?.intervalMs??3e4,o);t?.intervalMs&&t.intervalMs<o&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const i=t?.minTVL,r=t?.tokens,a=new Map;let s=!0,c=null;let l=0;const u=async()=>{if(s){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.pools.forEach(t=>{const o=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!a.has(o)){if((e=>{if(a.set(e,!0),a.size>1e3){const e=a.keys().next().value;void 0!==e&&a.delete(e)}})(o),i){if((t.token0Tvl+t.token1Tvl)/2<i)return}if(r&&r.length>0){if(!(r.includes(t.token0)||r.includes(t.token1)))return}e(t)}})}catch(e){l++;const t=e instanceof Error?e.message:String(e);l>=5?this.logger.error(`Polling for new DEX pools failed ${l} consecutive times. Last error: ${t}. Continuing to retry...`):l>1?this.logger.warn(`Error polling for new DEX pools (attempt ${l}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(s){const e=Math.min(Math.max(l-1,0),2),t=n*Math.pow(2,e);c=setTimeout(u,t)}}};return u(),()=>{s=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const o=1e3,n=Math.max(t?.intervalMs??3e4,o);t?.intervalMs&&t.intervalMs<o&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const i=t?.creatorAddress,r=new Map;let a=!0,s=null;let c=0;const l=async()=>{if(a){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=>{r.has(t.tokenName)||((e=>{if(r.set(e,!0),r.size>1e3){const e=r.keys().next().value;void 0!==e&&r.delete(e)}})(t.tokenName),i&&t.creatorAddress!==i||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(a){const e=Math.min(Math.max(c-1,0),2),t=n*Math.pow(2,e);s=setTimeout(l,t)}}};return l(),()=>{a=!1,s&&clearTimeout(s),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 o=e;for(const e of t)if(o[e])return String(o[e]);return""}looksLikePoolPair(e){if("string"!=typeof e)return null;const t=e.trim();if(!t.includes("/"))return null;const o=t.split("/");return 3!==o.length?null:o[0]&&o[1]&&o[2]?t:null}buildPoolPairFromObject(e){if("object"!=typeof e||null===e)return null;const t=e,o=this.extractField(t,"token0ClassKey","token0Class","token0","token0Symbol")||"",n=this.extractField(t,"token1ClassKey","token1Class","token1","token1Symbol")||"",i=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return o&&n&&null!==i?`${o}/${n}/${i}`:null}parsePoolPairString(e){const t=e.split("/");if(3!==t.length)return null;const o=t[0].split("|")[0],n=t[1].split("|")[0],i=t[2];return o&&n&&i?{token0:o,token1:n,fee:i,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,o=t.userBalanceDelta??t.balanceDelta??t.delta;if(!o||"object"!=typeof o||null===o)return null;const n=o,i=n.token0Balance??n.token0??n.baseBalance??n.primaryBalance,r=n.token1Balance??n.token1??n.quoteBalance??n.secondaryBalance,a=this.serializeBalanceToken(i),s=this.serializeBalanceToken(r),c=this.normalizeFee(t.poolFee??t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps);return a&&s&&null!==c?`${a}/${s}/${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,o=this.looksLikePoolPair(t.poolPair);if(o)return this.parsePoolPairString(o);const n=this.buildPoolPairFromBalances(t);if(n)return this.parsePoolPairString(n);const i=this.buildPoolPairFromObject(t);if(i)return this.parsePoolPairString(i);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[o,n]=t.pairTokens,i=e.token0===o||e.token1===o,r=e.token0===n||e.token1===n;if(!i||!r||o===n)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 o=!1,n=null;const i=(o,...n)=>{try{if(n.length>0&&"object"==typeof n[0]&&null!==n[0]){const o=n[0].data;if(o&&o.Data&&"object"==typeof o.Data){const n=o.Data;if("CreateSale"===n.functionName){const o={tokenName:n.tokenName||"",symbol:n.symbol||"",creatorAddress:n.creatorAddress||"",description:n.description||"",image:n.image||"",vaultAddress:n.vaultAddress||"",tokenStringKey:n.tokenStringKey||"",preBuyQuantity:n.initialBuyQuantity||"0",websiteUrl:n.websiteUrl||"",telegramUrl:n.telegramUrl||"",twitterUrl:n.twitterUrl||"",isFinalized:n.isFinalized||!1};this.matchesCreatorFilter(o,t?.creatorFilter)&&e(o)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${e instanceof Error?e.message:String(e)}`)}};let r=this.websocketService.getSocket();if(r)r.onAny(i),o=!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 o=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(o)});let e=0;const a=()=>{if(r=this.websocketService.getSocket(),!r&&e<Li.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(n=setTimeout(()=>a(),Li.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!r&&e>=Li.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Li.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Li.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}r&&(r.onAny(i),o=!0,this.logger.debug("Token creation broadcast listener registered"))};a()}return()=>{try{if(null!==n&&(clearTimeout(n),n=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!o)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(i),o=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}walkPayloadForPools(e,t,o=new WeakSet){const n=[];if("string"==typeof e){const o=this.looksLikePoolPair(e);if(o){const e=this.parsePoolPairString(o);e&&!t.has(e.poolPair)&&(t.add(e.poolPair),n.push(e))}return n}if("object"!=typeof e||null===e)return n;if(o.has(e))return n;o.add(e);const i=this.extractPoolDataFromPayload(e);i&&!t.has(i.poolPair)&&(t.add(i.poolPair),n.push(i));for(const i of Object.values(e)){const e=this.walkPayloadForPools(i,t,o);n.push(...e)}return n}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 o=!1,n=null;const i=new Set,r=(o,...n)=>{try{for(const o of n){const n=this.walkPayloadForPools(o,i);for(const o of n)this.matchesPoolFilter(o,t)&&e(o)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${e instanceof Error?e.message:String(e)}`)}};let a=this.websocketService.getSocket();if(a)a.onAny(r),o=!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 o=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(o)});let e=0;const i=()=>{if(a=this.websocketService.getSocket(),!a&&e<Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(n=setTimeout(()=>i(),Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX pool subscription timeout:",e.message),void(t?.onError&&t.onError(e))}a&&(a.onAny(r),o=!0,this.logger.debug("DEX pool broadcast listener registered"))};i()}return()=>{try{if(null!==n&&(clearTimeout(n),n=null,this.logger.debug("Cleared DEX pool polling timeout")),!o)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(r),o=!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 o=null,n=null,i=null,r=!1;const a=async e=>{const t=ai.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})},s=()=>{const c=this.websocketService.getSocket();if(!c)return this.logger.debug("WebSocket not yet ready for swap monitoring, polling..."),void(o=setTimeout(()=>s(),100));r=!0,n=new gi(c,a,this.dexQuoteService,t||{},this.logger),i=n.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 o=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(o)})),s(),()=>{try{o&&clearTimeout(o),i&&r&&i(),n&&n.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 o=!1,n=null;const i=new Set,r=new $i(this.logger),a=(o,...n)=>{try{for(const o of n){const n=r.walkPayloadForLiquidityEvents(o,i);for(const o of n)if(this.matchesLiquidityFilter(o,t))try{const t=e(o);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 s=this.websocketService.getSocket();if(s)s.onAny(a),o=!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 o=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(o)});let e=0;const i=()=>{if(s=this.websocketService.getSocket(),!s&&e<Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(n=setTimeout(()=>i(),Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS*Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX liquidity subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(a),o=!0,this.logger.debug("DEX liquidity broadcast listener registered"))};i()}return async()=>{try{if(null!==n&&(clearTimeout(n),n=null,this.logger.debug("Cleared DEX liquidity polling timeout")),!o)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(a),o=!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 o=this.normalizeFeeTier(t.feeTierFilter);if(e.poolFee!==o)return!1}if(t.userFilter&&e.userAddress!==t.userFilter)return!1;if(t.tokenFilter){const o=e.token0?.toLowerCase().includes(t.tokenFilter.toLowerCase()),n=e.token1?.toLowerCase().includes(t.tokenFilter.toLowerCase());if(!o&&!n)return!1}if(t.pairTokens){const[o,n]=t.pairTokens.map(e=>e.toLowerCase()),i=e.token0?.toLowerCase()||"",r=e.token1?.toLowerCase()||"",a=i.includes(o)&&r.includes(n),s=i.includes(n)&&r.includes(o);if(!a&&!s)return!1}if(t.minAmount){const o=parseFloat(t.minAmount),n=parseFloat(e.amounts[0])||0,i=parseFloat(e.amounts[1])||0;if(Math.abs(n)<o&&Math.abs(i)<o)return!1}return!0}normalizeFeeTier(e){if("number"==typeof e)return e>=100?e:Math.round(1e4*e);const t=e.replace("%","").trim(),o=parseFloat(t);return o>=100?o:Math.round(1e4*o)}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 T({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:o}=require("./services/WebSocketService");o.cleanupAll(e),t.debug("Global cleanup completed")}}Li.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Li.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Li.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=ei.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Li.DEFAULT_CALCULATE_AMOUNT_MODE=bi.LOCAL,Li.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Li.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,Li.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,Li.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class Oi{static generateWallet(){try{const e=t.Wallet.createRandom();if(!e.mnemonic?.phrase)throw new Error("Failed to generate wallet with mnemonic phrase");const o=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:o,mnemonic:e.mnemonic.phrase,wallet:new t.Wallet(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,o="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),n=new t.Wallet(o),i=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:i,mnemonic:"test test test test test test test test test test test junk",wallet:n}}throw e}}static fromPrivateKey(e){const o=new t.Wallet(e),n=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:n,mnemonic:"",wallet:o}}static fromMnemonic(e,o=0){try{const n=t.Mnemonic.fromPhrase(e),i=t.HDNodeWallet.fromMnemonic(n,`m/44'/60'/0'/0/${o}`),r=new t.Wallet(i.privateKey),a=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:a,mnemonic:e,wallet:r}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${o}-${e}`,i="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),r=new t.Wallet(i),a=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:a,mnemonic:e,wallet:r}}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 o=0;o<e;o++){const e=`test-multi-${o}-${Date.now()}-${++this.testCounter}`,n="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(n))}else for(let o=0;o<e;o++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const o=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${e.mnemonic||"Not available"}`];return t?o.splice(3,0,`🔑 Private Key: ${e.privateKey}`):o.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),o.push("═".repeat(50)),o.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),o.push("This is your backup to recover the wallet."),o.join("\n")}}function _i(e){if(void 0===e)return Oi.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 Oi.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 Oi.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?"...":""}"`)}Oi.testCounter=0;class Bi{static fastValidation(e,t,o,n=Bi.DEFAULT_CONFIG){const r=Date.now();let a=!0;try{const s=new i(e.sqrtPrice),c=new i(t.sqrtPrice);o.zeroForOne?c.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:c.toString(),zeroForOne:o.zeroForOne}),a=!1):c.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:c.toString(),zeroForOne:o.zeroForOne}),a=!1);const l=new i(e.liquidity),u=new i(t.liquidity);if(!l.isZero()){const e=u.minus(l).abs().div(l);e.gt(n.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:l.toString(),updatedLiquidity:u.toString(),changePct:e.times(100).toFixed(2)})}const d=new i(e.feeGrowthGlobal0),h=new i(t.feeGrowthGlobal0),g=new i(e.feeGrowthGlobal1),p=new i(t.feeGrowthGlobal1);o.zeroForOne?p.lt(g)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:g.toString(),updatedFeeGrowth1:p.toString()}),a=!1):h.lt(d)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:d.toString(),updatedFeeGrowth0:h.toString()}),a=!1);const m=new i(e.protocolFeesToken0),f=new i(t.protocolFeesToken0),y=new i(e.protocolFeesToken1),w=new i(t.protocolFeesToken1);f.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:m.toString(),updatedProtocolFees0:f.toString()}),a=!1),w.lt(y)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:y.toString(),updatedProtocolFees1:w.toString()}),a=!1);const k=Date.now()-r;return this.logger.debug("Fast validation completed",{passed:a,elapsedMs:k}),a}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,o=Bi.DEFAULT_CONFIG){const n=Date.now(),a=[];let s=0;try{if(t.actualSqrtPrice){const n=new i(e.sqrtPrice),r=new i(t.actualSqrtPrice),c=this.calculateDriftPercentage(n,r);s=c,c>100*o.maxDriftThreshold&&a.push(`Price drift detected: ${c.toFixed(4)}% (threshold: ${(100*o.maxDriftThreshold).toFixed(4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:n.toString(),actualSqrtPrice:r.toString(),driftPct:c.toFixed(4)})}const c=new i(e.sqrtPrice),l=new i(2).pow(96),u=c.dividedBy(l),d=r.sqrtPriceToTick(u),h=e.tick??0,g=Math.abs(d-h);g>o.maxTickDrift&&a.push(`Tick/price mismatch: tick=${h}, calculated=${d}, drift=${g}`);const p=new i(e.feeGrowthGlobal0),m=new i(e.feeGrowthGlobal1),f=new i(e.liquidity);try{en(p,m,f)}catch(e){a.push(e.message)}const y=0===a.length,w=!y||s>100*o.maxDriftThreshold,k=Date.now()-n;return this.logger.debug("Moderate validation completed",{isValid:y,shouldRefetch:w,driftPercentage:s,errorCount:a.length,elapsedMs:k}),this.buildValidationResult(y,s,w,a)}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,o){const n=Date.now(),r=[];let a=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await o(),c=new i(t.pool.sqrtPrice),l=new i(s.pool.sqrtPrice),u=this.calculateDriftPercentage(c,l);a=Math.max(a,u),u>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&r.push(`Price drift: ${u.toFixed(4)}% (cached: ${c.toString()}, fresh: ${l.toString()})`);const d=new i(t.pool.liquidity),h=new i(s.pool.liquidity),g=this.calculateDriftPercentage(d,h);a=Math.max(a,g),g>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&r.push(`Liquidity drift: ${g.toFixed(4)}% (cached: ${d.toString()}, fresh: ${h.toString()})`);const p=Object.keys(t.tickDataMap).length,m=Object.keys(s.tickDataMap).length;if(m>0){const e=Math.abs(m-p)/m;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&r.push(`Tick data incomplete: cached has ${p} ticks, fresh has ${m} ticks (${(100*e).toFixed(2)}% difference)`)}const f=0===r.length,y=!f,w=Date.now()-n;return this.logger.debug("Full validation completed",{poolKey:e,isValid:f,shouldRefetch:y,maxDriftPercentage:a,priceDrift:u,liquidityDrift:g,cachedTickCount:p,freshTickCount:m,errorCount:r.length,elapsedMs:w}),this.buildValidationResult(f,a,y,r)}catch(t){this.logger.error("Full validation exception",{poolKey:e,error:t});const o=t instanceof Error?t.message:String(t);return this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${o}`])}}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,o,n=[]){let i;if(o&&n.length>0){const e=n.join(" ").toLowerCase();i=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const r={isValid:e,driftPercentage:t,shouldRefetch:o,validationErrors:n};return void 0!==i&&(r.refetchReason=i),r}}Bi.logger=new T({debug:!1,context:"PoolStateValidator"}),Bi.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class Ui{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return h.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){this.logger=new T({debug:t?.debug??!1,context:"PoolStateManager"});const o={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??i.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={...o,...t?.onRefetchNeeded?{onRefetchNeeded:t.onRefetchNeeded}:{}},this.validationConfig=Bi.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:Ui.calculatePoolStateHash(this.pool)};if(!Bi.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},o={maxIterations:this.config.maxIterations,enableBigNumberCache:this.config.enableBigNumberCache,roundingMode:this.config.roundingMode,debugLogging:this.config.debug},n=ui.calculateSwapDelta(t,e,o);this.lastSwapMetrics={calculationTimeMs:n.metadata.calculationTimeMs,swapSteps:n.metadata.swapSteps,timestamp:Date.now()},this.config.enablePerformanceWarnings&&n.metadata.calculationTimeMs>this.config.performanceWarningThreshold&&this.logger.warn("Slow swap calculation",{calculationTimeMs:n.metadata.calculationTimeMs,swapSteps:n.metadata.swapSteps,threshold:this.config.performanceWarningThreshold});if(!Bi.fastValidation(t.pool,n.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new Error("Swap validation failed");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=new i(e.actualAmount0),o=new i(e.actualAmount1),r=n.amount0.minus(t).abs(),a=n.amount1.minus(o).abs(),s=t.isZero()?0:r.div(t.abs()).times(100).toNumber(),c=o.isZero()?0:a.div(o.abs()).times(100).toNumber(),l=Math.max(s,c);l>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:l.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=l)}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=Ui.calculatePoolStateHash(this.pool),this.logger.info("Full refetch completed",{sqrtPrice:this.pool.sqrtPrice.toString()})}return this.pool=n.updatedPool,Object.assign(this.tickDataMap,n.updatedTicks),this.metadata.swapsSinceRefetch++,this.metadata.stateHash=Ui.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:n.amount0.toString(),amount1:n.amount1.toString(),sqrtPriceNew:this.pool.sqrtPrice.toString()}),n}catch(o){const n=o instanceof Error?o.message:String(o);if(this.logger.error("Failed to apply swap delta",{transactionId:e.transactionId,error:n}),this.config.strictValidation)throw o;return{updatedPool:this.pool,updatedTicks:{},amount0:new i(0),amount1:new i(0),feeAmount0:new i(0),feeAmount1:new i(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:Ui.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}"undefined"!=typeof process&&process.env&&(process.env.CORE_CHAINCODE_LOGGING_LEVEL=process.env.CORE_CHAINCODE_LOGGING_LEVEL||"ERROR");var Mi=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const o={};if(e.vaultAddress&&(o.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const n=parseFloat(e.reverseBondingCurveMinFeePortion);isNaN(n)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):o.reverseBondingCurveMinFeeFactor=n}if(void 0!==e.reverseBondingCurveMaxFeePortion){const n=parseFloat(e.reverseBondingCurveMaxFeePortion);isNaN(n)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):o.reverseBondingCurveMaxFeeFactor=n}return void 0!==o.reverseBondingCurveMaxFeeFactor&&void 0!==o.reverseBondingCurveMinFeeFactor&&(o.reverseBondingCurveNetFeeFactor=o.reverseBondingCurveMaxFeeFactor-o.reverseBondingCurveMinFeeFactor),Object.keys(o).length>0?o: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}});exports.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),o=this.setupWallet(e.privateKey),n={wallet:o.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{}},i=new Li(n),r={sdk:i,wallet:o,config:n};if(!1!==e.autoValidate){const e=await this.validateSetup(i,o);return{...r,validation:e}}return r}static async readOnlySetup(e={}){const t=e.environment||this.detectEnvironment(),o={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||{}};return{sdk:new Li(o),config:o}}static async validateSetup(e,t){const o=[],n=[],i={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(i.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);i.hasBalance=e>0,i.canTrade=e>=.1,i.canCreateTokens=e>=100,0===e?n.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?n.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&n.push("GALA balance too low for token creation (minimum 100 GALA)")}else o.push("Failed to fetch GALA balance: No balance returned")}catch(e){o.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||n.push("Pool listing not accessible - some features may be limited")}catch(e){n.push(`Pool access test failed: ${e instanceof Error?e.message:String(e)}`)}return{ready:0===o.length&&i.connectionHealthy,sdk:e,wallet:t||Oi.generateWallet(),issues:o,warnings:n,capabilities:i}}static getRecommendedConfig(e,t="general"){const o={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(o,{debug:!1,timeout:3e4});break;case"development":Object.assign(o,{debug:!0,timeout:45e3});break;case"testing":Object.assign(o,{debug:!0,timeout:6e4})}switch(t){case"trading":o.timeout=1.5*(o.timeout||3e4);break;case"creation":o.timeout=2*(o.timeout||3e4);break;case"monitoring":o.timeout=.5*(o.timeout||3e4)}return o}static async multiWalletSetup(e,t="development"){const o={};for(const[n,i]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:i,agentId:`multi-wallet-${n}`,autoValidate:!1});o[n]=e}return o}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?Oi.fromPrivateKey(e):Oi.generateWallet()}return"generate"===e?Oi.generateWallet():Oi.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}},exports.CALCULATION_MODES=bi,exports.COMPOSITE_POOL_FETCH_CONCURRENCY=5,exports.ConfigurationError=N,exports.DexPoolNotFoundError=_,exports.DexQuoteError=O,exports.FileValidationError=Ko,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.GSwapAssetError=$,exports.GSwapPoolError=F,exports.GSwapQuoteError=D,exports.GSwapSwapError=C,exports.IMAGE_EXTENSIONS=Oe,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LaunchpadSDK=Li,exports.LockError=kn,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.NetworkError=P,exports.PAGINATION_DEFAULTS=wo,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PoolStateManager=Ui,exports.QUERY_FIELD_NAMES={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"},exports.SDK_VERSION=Fi,exports.TRADING_TYPES=Si,exports.TokenMetadataService=class extends vo{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}async resolveTokenMetadata(e){const t=this.getCacheKey(e),o=this.cache[t];if(o&&!this.isCacheExpired(o.timestamp))return this.logger.debug(`Using cached metadata for token: ${t}`),o.data;const n=this.extractMetadata(e);return this.cache[t]={data:n,timestamp:Date.now()},n}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,o,n="Token",i="Unit",r="none";if("string"==typeof e)if(e.includes("|")){const a=e.split("|");"Token"===a[0]&&a[2]?(n=a[0],i=a[1]||"Unit",t=a[2],r=a[3]||"none",o=t):(t=a[0],o=t,i=a[1]||"Unit",r=a[3]||"none")}else t=e,o=e;else t=e.type||"unknown",n=e.collection||"Token",i=e.category||"Unit",r=e.additionalKey||"none",o=e.symbol||("Token"===n?t:n)||"unknown";const a=this.getDecimalsForToken(o);return{symbol:o.toUpperCase(),decimals:a,collection:n,category:i,type:t.toUpperCase(),additionalKey:r,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`)}},exports.TransactionError=x,exports.TransactionFailedError=xi,exports.ValidationError=I,exports.WebSocketError=Ni,exports.WebSocketTimeoutError=class extends Ni{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.addressFormatSchema=ee,exports.amountMethodSchema=Fe,exports.amountTypeSchema=Ce,exports.browserFileSchema=Be,exports.bufferFileSchema=Ue,exports.buyTokensDataSchema=at,exports.calculatePreMintDataSchema=gt,exports.checkPoolOptionsSchema=De,exports.commentMessageSchema=ye,exports.commentPaginationSchema=We,exports.createLaunchpadSDK=function(e){e||(e={});const{wallet:o,env:n,config:i={},...r}=e,a={...r,...i},{wallet:s,env:c,config:l,...u}=a;let d;if(o)if("string"==typeof o){d=_i(o).wallet}else{if(!(o instanceof t.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");d=o}else{d=_i().wallet}const h={wallet:d,...n&&{env:n},debug:!1,timeout:3e4,...u};return new Li(h)},exports.createLimitSchema=ue,exports.createPaginatedResultSchema=function(e){return n.z.object({data:n.z.array(e),page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()})},exports.createPoolStateManager=function(e,t){return new Ui(e,t)},exports.createTradeDataSchema=rt,exports.createWallet=_i,exports.ethereumAddressSchema=te,exports.faucetAmountSchema=ae,exports.fetchGalaBalanceOptionsSchema=Je,exports.fetchPoolDetailsDataSchema=pt,exports.fetchTokenBalanceOptionsSchema=ot,exports.fileSizeSchema=pe,exports.fileUploadSchema=_e,exports.filenameSchema=me,exports.filterByFeeTier=function(e,t){return e.filter(e=>e.feeTier===t)},exports.filterByLiquidity=function(e){return e.filter(e=>new i(e.liquidity).isGreaterThan(0))},exports.filterByMinLiquidity=function(e,t){const o=new i(t);return e.filter(e=>new i(e.liquidity).isGreaterThanOrEqualTo(o))},exports.filterByPoolKey=function(e,t,o,n){const i=t.toUpperCase(),r=o.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),o=e.token1.toUpperCase();return(t===i&&o===r||t===r&&o===i)&&e.feeTier===n})},exports.filterByToken=function(e,t){const o=t.toUpperCase();return e.filter(e=>e.token0.toUpperCase()===o||e.token1.toUpperCase()===o)},exports.filterByTokenPair=function(e,t,o){const n=t.toUpperCase(),i=o.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),o=e.token1.toUpperCase();return t===n&&o===i||t===i&&o===n})},exports.flexibleAddressSchema=oe,exports.flexibleFileSchema=Me,exports.formatGalaForDTO=In,exports.formatLaunchpadTokenForDTO=Pn,exports.fullNameSchema=J,exports.getAmountOptionsSchema=ht,exports.getEnv=function(e,t){return process.env[e]??t},exports.getEnvOrThrow=function(e,t){const o=process.env[e];if(!o){throw new Error(t?`${e} not set in root or local .env (${t})`:`${e} not set in root or local .env`)}return o},exports.getTradeOptionsSchema=ct,exports.graduateTokenOptionsSchema=Le,exports.graphDataOptionsSchema=$e,exports.groupByFeeTier=function(e){const t=new Map;return e.forEach(e=>{t.has(e.feeTier)||t.set(e.feeTier,[]),t.get(e.feeTier).push(e)}),t},exports.groupByPoolKey=function(e){const t=new Map;return e.forEach(e=>{const o=`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`;t.has(o)||t.set(o,[]),t.get(o).push(e)}),t},exports.groupByTokenPair=function(e){const t=new Map;return e.forEach(e=>{const o=`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`;t.has(o)||t.set(o,[]),t.get(o).push(e)}),t},exports.imageExtensionSchema=Re,exports.imageFilenameSchema=qe,exports.imageMimeTypeSchema=fe,exports.imageUploadOptionsSchema=Ne,exports.isLockTokenData=yn,exports.isUnlockTokenData=wn,exports.isoDateStringSchema=we,exports.launchTokenDataSchema=Pe,exports.loadEnvWithFallback=function(){const e=f.join(process.cwd(),"..","..",".env");y.existsSync(e)&&w.config({path:e});const t=f.join(process.cwd(),".env");y.existsSync(t)&&w.config({path:t})},exports.nonNegativeDecimalStringSchema=re,exports.optionalUrlSchema=ce,exports.pageNumberSchema=le,exports.paginationResultMetaSchema=Qe,exports.poolFetchTypeSchema=xe,exports.poolPaginationSchema=je,exports.positiveDecimalStringSchema=ie,exports.privateKeySchema=ve,exports.requireNonNegative=en,exports.requirePositive=function(...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()}`)})},exports.requirePositiveWithContext=tn,exports.reverseBondingCurveConfigSchema=Ie,exports.reverseBondingCurveConfigurationSchema=mt,exports.searchQuerySchema=Y,exports.sellTokensDataSchema=st,exports.sortByLiquidity=function(e,t="desc"){return[...e].sort((e,o)=>{const n=new i(e.liquidity),r=new i(o.liquidity);return"desc"===t?r.minus(n).toNumber():n.minus(r).toNumber()})},exports.standardLimitSchema=de,exports.standardPaginationSchema=Ke,exports.timestampSchema=ke,exports.tokenCategorySchema=Ae,exports.tokenCollectionSchema=Ee,exports.tokenDescriptionSchema=X,exports.tokenListOptionsSchema=Ze,exports.tokenNameSchema=V,exports.tokenSymbolSchema=Q,exports.tokenUrlsSchema=be,exports.tradeCalculationMethodSchema=dt,exports.tradeCalculationTypeSchema=ut,exports.tradeLimitSchema=ge,exports.tradeListParamsSchema=lt,exports.tradePaginationSchema=ze,exports.tradePaginationWithFiltersSchema=Ve,exports.tradeTypeBackendSchema=it,exports.tradeTypeSchema=nt,exports.transactionIdSchema=Te,exports.transferFaucetsDataSchema=Ye,exports.uniqueKeySchema=Se,exports.updateProfileDataSchema=et,exports.uploadProfileImageOptionsSchema=tt,exports.urlSchema=se,exports.userLimitSchema=he,exports.userPaginationSchema=Ge,exports.userTokenNameSchema=Z,exports.userTokenTypeSchema=Xe,exports.userTokensPaginationSchema=He,exports.validateAddress=vt,exports.validateAmountString=St,exports.validateBuyTokensData=Ut,exports.validateCalculatePreMintData=Gt,exports.validateCheckPoolOptions=Dt,exports.validateCreateTradeData=Bt,exports.validateFaucetAmount=bt,exports.validateFetchGalaBalanceOptions=$t,exports.validateFetchPoolDetailsData=zt,exports.validateFetchTokenBalanceOptions=_t,exports.validateFullName=At,exports.validateGetAmountOptions=Kt,exports.validateGetTradeOptions=Rt,exports.validateImageUploadOptions=xt,exports.validateLaunchTokenData=Pt,exports.validateSearchQuery=Et,exports.validateSellTokensData=Mt,exports.validateTokenDescription=kt,exports.validateTokenListOptions=Ct,exports.validateTokenName=yt,exports.validateTokenSymbol=wt,exports.validateTokenUrls=Nt,exports.validateTradeListParams=qt,exports.validateTransferFaucetsData=Ft,exports.validateUpdateProfileData=Lt,exports.validateUploadProfileImageOptions=Ot,exports.validateUserTokenName=It,exports.validateVaultAddress=Tt,exports.vaultAddressSchema=ne;