@gala-chain/launchpad-sdk 3.12.3 โ†’ 3.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("ethers"),require("axios"),require("@gala-chain/connect"),require("zod"),require("bignumber.js"),require("@gala-chain/api"),require("uuid"),require("socket.io-client")):"function"==typeof define&&define.amd?define(["exports","ethers","axios","@gala-chain/connect","zod","bignumber.js","@gala-chain/api","uuid","socket.io-client"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GalaLaunchpadSDK={},e.ethers,e.axios,e.GalaChainConnect,e.z,e.BigNumber,e.GalaChainAPI,e.uuid,e.io)}(this,function(e,t,a,n,r,o,s,i,c){"use strict";var l,u;!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"}(l||(l={}));class d extends Error{constructor(e,t,a){super(t),this.type=e,this.originalError=a,this.name="AuthError"}}class h{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new d(l.SIGNATURE_FAILED,"Message prefix cannot be empty");this.validateWallet()}async generateSignature(){try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,a=await this.wallet.signMessage(t);return{message:t,signature:a,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){throw new d(l.SIGNATURE_FAILED,"Failed to generate signature for authentication",e instanceof Error?e:new Error(String(e)))}}getAddress(){return this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.wallet.address}getPrivateKey(){if(!this.wallet.privateKey)throw new d(l.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 d(l.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`);return`eth|${t}`}async signMessage(e){try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){const t=e instanceof Error?e.message:String(e);throw new d(l.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){try{const a=Date.now(),n=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${a}`,r=await this.wallet.signMessage(n);return{"x-signature":r,"x-address":this.formatAddress(this.wallet.address),"x-message":n,"x-timestamp":a.toString()}}catch(e){throw new d(l.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(e)))}}async signTypedData(e,t,a){try{return await this.wallet.signTypedData(e,t,a)}catch(e){throw new d(l.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 d(l.SIGNATURE_FAILED,"Custom message must be a non-empty string");try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){throw new d(l.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new d(l.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new d(l.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new d(l.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"}(u||(u={}));class g{constructor(e){this.levelPriority={[u.DEBUG]:0,[u.INFO]:1,[u.WARN]:2,[u.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?u.DEBUG:u.INFO)}debug(e,t){this.log(u.DEBUG,e,t)}info(e,t){this.log(u.INFO,e,t)}warn(e,t){this.log(u.WARN,e,t)}error(e,t){this.log(u.ERROR,e,t)}log(e,t,a){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===u.DEBUG&&!this.debugEnabled)return;const n=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,r=this.getConsoleMethod(e);void 0!==a?a instanceof Error?r(`${n} ${t}`,a.message,a.stack):r(`${n} ${t}`,a):r(`${n} ${t}`)}getConsoleMethod(e){switch(e){case u.DEBUG:return console.debug;case u.INFO:return console.info;case u.WARN:return console.warn;case u.ERROR:return console.error;default:return console.log}}child(e){return new g({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[u.DEBUG]>=this.levelPriority[this.minLevel]}}function m(e){if(!e||"object"!=typeof e)return{};const t={};for(const[a,n]of Object.entries(e))null!=n&&("string"==typeof n?t[a]=n:"number"==typeof n||"boolean"==typeof n?t[a]=n.toString():Array.isArray(n)?t[a]=n.join(","):t[a]="object"==typeof n?JSON.stringify(n):String(n));return t}class p{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new g({debug:this.debug,context:"HttpClient"}),this.axios=a.create({baseURL:t.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:t.timeout||3e4,headers:{Accept:"application/json",...t.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:m(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};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 a=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:a,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,a){return this.request({method:"GET",url:e,...t&&{params:t},...a&&{headers:a}})}async post(e,t,a){return this.request({method:"POST",url:e,data:t,...a&&{headers:a}})}async put(e,t,a){return this.request({method:"PUT",url:e,data:t,...a&&{headers:a}})}async delete(e,t,a){return this.request({method:"DELETE",url:e,...t&&{params:t},...a&&{headers:a}})}async patch(e,t,a){return this.request({method:"PATCH",url:e,data:t,...a&&{headers:a}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,a){return await this.auth.signTypedData(e,t,a)}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,a=n.SigningType.SIGN_TYPED_DATA){const r=this.auth.getPrivateKey(),o=new n.SigningClient(r);return await o.sign(e,t,a)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{try{const t=await this.auth.generateSignature();return e.headers||(e.headers={}),e.headers.Sign=t.signature,e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp}),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 f="Token name is required and must be a string",y=e=>`Could not find vault address for token: ${e}`;class v extends Error{constructor(e,t,a){super(e),this.field=t,this.code=a,this.name="ValidationError"}}class A extends Error{constructor(e,t,a){super(e),this.statusCode=t,this.originalError=a,this.name="NetworkError"}}class w extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class T extends Error{constructor(e,t,a){super(e),this.transactionId=t,this.code=a,this.name="TransactionError"}}function k(e,t,a){const{MIN_PAGE:n,MAX_PAGE:r,MIN_LIMIT:o,MAX_LIMIT:s}=a.PAGINATION;if("number"!=typeof e||e<n||e>r)throw new v(`Page must be a number between ${n} and ${r}`,"page","INVALID_PAGE");if("number"!=typeof t||t<o||t>s)throw new v(`Limit must be a number between ${o} and ${s}`,"limit","INVALID_LIMIT")}const N={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function E(e){return"string"==typeof e&&e.trim().length>0}function S(e){return!(!e||"string"!=typeof e)&&(N.ETH_ADDRESS.test(e)||N.BACKEND_ADDRESS.test(e))}function b(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const I=r.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"),F=r.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"),C=r.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),D=r.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),P=r.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),_=r.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"),x=r.z.string().regex(N.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),L=r.z.string().regex(N.ETH_ADDRESS,"Invalid Ethereum address format"),O=r.z.string().refine(e=>N.BACKEND_ADDRESS.test(e)||N.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),$=r.z.string().refine(e=>N.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),U=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),B=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),M=r.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),R=r.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),K=r.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),G=r.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 z(e=100){return r.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 V=z(100),q=z(20),j=z(20),W=r.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"),H=r.z.string().max(255,"Filename must be at most 255 characters"),Q=r.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),X=r.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),Y=r.z.string().datetime("Must be a valid ISO 8601 date string"),Z=r.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),J=r.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),ee=r.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"),te=r.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),ae=r.z.object({websiteUrl:K,telegramUrl:K,twitterUrl:K}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),ne=r.z.string().min(1,"Token category must not be empty").default("Unit"),re=r.z.string().min(1,"Token collection must not be empty").default("Token"),oe=r.z.object({minFeePortion:U,maxFeePortion:U}),se=r.z.object({tokenName:I,tokenSymbol:F,tokenDescription:C,tokenImage:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer),r.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:B.default("0"),websiteUrl:K,telegramUrl:K,twitterUrl:K,tokenCategory:ne,tokenCollection:re,reverseBondingCurveConfiguration:oe.optional(),privateKey:J.optional()}),ie=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),tokenName:I}),ce=r.z.enum(["recent","popular"]),le=r.z.object({tokenName:I.optional(),symbol:F.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),ue=r.z.enum(["NATIVE","MEME"]),de=r.z.enum(["IN","OUT"]),he=r.z.object({from:r.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:r.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:r.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:I}),ge=r.z.object({tokenName:I,slippageToleranceFactor:r.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:r.z.number().min(0).max(1).optional(),privateKey:J.optional()}),me=[".png",".jpg",".jpeg",".gif",".webp",".svg"];function pe(){return r.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")}const fe=r.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");let ye=null,ve=null,Ae=null;function we(){return ye||"undefined"==typeof File||(ye=pe()),ye}function Te(){return ve||(ve="undefined"!=typeof File?r.z.union([pe(),fe]):fe),ve}function ke(){return Ae||(Ae=function(){const e="undefined"!=typeof File?r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]):r.z.instanceof(Buffer);return r.z.object({file:e,name:H,size:W,type:Q})}()),Ae}const Ne={safeParse:e=>{const t=we();return t?t.safeParse(e):{success:!1,error:new Error("File schema not available in Node.js")}},parse:e=>{const t=we();if(!t)throw new Error("File schema not available in Node.js");return t.parse(e)}},Ee={safeParse:e=>Te().safeParse(e),parse:e=>Te().parse(e)},Se={safeParse:e=>ke().safeParse(e),parse:e=>ke().parse(e)},be=r.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Ie=H.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return me.includes(t)},`Filename must end with one of: ${me.join(", ")}`),Fe=r.z.object({page:G,limit:V}),Ce=r.z.object({page:G,limit:q}),De=r.z.object({page:G,limit:j}),Pe=r.z.object({page:G,limit:z(50)}),_e=Fe.extend({type:r.z.enum(["recent","popular"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),xe=Ce.extend({tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),Le=De.extend({tradeType:r.z.enum(["BUY","SELL"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),userAddress:r.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:r.z.string().datetime().optional(),endDate:r.z.string().datetime().optional(),sortOrder:r.z.enum(["ASC","DESC"]).default("DESC")}),Oe=r.z.object({page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()});const $e=r.z.enum(["all","DEFI","ASSET"]),Ue=Ce.extend({type:$e.optional(),address:O.optional(),search:P.optional(),tokenName:D.optional()}),Be=r.z.object({walletAddress:O,amount:M}),Me=r.z.object({address:O.optional(),refresh:r.z.boolean().optional()}),Re=r.z.object({profileImage:r.z.string(),fullName:_,address:O,privateKey:J.optional()}),Ke=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),address:O.optional(),privateKey:J.optional()}),Ge=r.z.object({address:O,tokenId:r.z.union([r.z.string(),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string()}),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string(),instance:r.z.string()})]).optional(),tokenClassKey:r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string()}).optional(),tokenName:D.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),ze=r.z.enum(["buy","sell"]),Ve=r.z.enum(["BUY","SELL"]),qe=r.z.object({tradeType:ze,tokenAmount:U,vaultAddress:$,userAddress:O,slippageTolerance:U.optional(),deadline:r.z.number().int().positive().optional()}),je=r.z.object({tokenSymbol:F,nativeTokenQuantity:U,expectedToken:U,maxAcceptableReverseBondingCurveFee:B.default("0").optional()}),We=r.z.object({tokenSymbol:F,tokenQuantity:U,expectedNativeToken:U,maxAcceptableReverseBondingCurveFee:B.default("0").optional()}),He=De.extend({tokenName:D.optional()}),Qe=r.z.object({page:r.z.number().int().min(1).max(1e3).default(1).optional(),limit:r.z.number().int().min(1).max(20).default(10).optional()}),Xe=r.z.enum(["NATIVE","MEME"]),Ye=r.z.enum(["IN","OUT"]),Ze=r.z.object({type:Xe,method:Ye,vaultAddress:$,amount:U}),Je=r.z.object({nativeTokenQuantity:U}),et=r.z.object({vaultAddress:$}),tt=r.z.object({minFeePortion:U,maxFeePortion:U});function at(e){return t=>{const a=e.safeParse(t);return{success:a.success,data:a.success?a.data:void 0,errors:a.success?void 0:a.error.errors.map(e=>e.message)}}}const nt=at(I),rt=at(F),ot=at(C),st=at(O),it=at($),ct=at(U),lt=at(M),ut=at(_),dt=at(P),ht=at(D),gt=at(se),mt=at(ae),pt=at(ie),ft=at(le),yt=at(Ue),vt=at(Be),At=at(Me),wt=at(Re),Tt=at(Ke),kt=at(Ge),Nt=at(qe),Et=at(je),St=at(We),bt=at(He),It=at(Qe),Ft=at(Ze),Ct=at(Je),Dt=at(et);function Pt(e,t){throw new v(e.join("; "),t,"VALIDATION_ERROR")}function _t(e){const t=nt(e);!t.success&&t.errors&&Pt(t.errors,"tokenName")}function xt(e){const t=_e.safeParse(e);t.success||Pt(t.error.errors.map(e=>e.message),"pagination")}function Lt(e){const t=ft(e);!t.success&&t.errors&&Pt(t.errors,"options")}function Ot(e){const t=Ft(e);!t.success&&t.errors&&Pt(t.errors,"options")}function $t(e){const t=he.safeParse(e);t.success||Pt(t.error.errors.map(e=>e.message),"options")}function Ut(e){const t=O.safeParse(e);if(!t.success)throw new v("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Bt(e,t,a=!0){if(!e||""===e.trim())throw new v(`${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 v(`${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 v(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(n))throw new v(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(n<0)throw new v(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!a&&0===n)throw new v(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var Mt=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=O.safeParse(e);if(!t.success)throw new v(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:Ut,validateCheckPoolOptions:Lt,validateGetAmountOptions:Ot,validateGetGraphOptions:$t,validateNumericString:Bt,validatePagination:xt,validateTokenName:_t});function Rt(e,t){return new v(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Kt(e,t){const a=t||e.charAt(0).toUpperCase()+e.slice(1);return new v(`${a} is required`,e,"REQUIRED_FIELD")}function Gt(e,t,a){const n=a||e.charAt(0).toUpperCase()+e.slice(1);return new v(`${n} must be ${t}`,e,"INVALID_FORMAT")}function zt(e,t,a){return new A(e,t,a)}function Vt(e,t){return new w(e,t)}function qt(e,t,a){return new T(e,t,a)}function jt(e,t){const a=e,n=Number(a.page)||t.page,r=Number(a.limit)||t.limit,o=a.data,s=Number(a.total)||Number(o?.count)||0;return{page:n,limit:r,total:s,totalPages:Math.ceil(s/r)}}function Wt(e,t){return{hasNext:e<t,hasPrevious:e>1}}function Ht(e,t,a=!1){const n=!0===e.error||200!==e.status,r=a&&!e.data;if(n||r)throw new Error(e.message||t)}const Qt="/launchpad/upload-image",Xt="/launchpad/fetch-pool",Yt="/launchpad/check-pool",Zt="/launchpad/get-graph-data",Jt="/holders",ea="/launchpad/get-badge/",ta="/trade/",aa="/token/commment",na="/token/commment",ra="/user/profile",oa="/user/profile",sa="/user/token-list",ia="/user/token-hold",ca="/user/transfer-faucets";function la(e,t){return"string"==typeof e[t]}function ua(e,t){return void 0===e[t]||"string"==typeof e[t]}function da(e,t){return void 0===e[t]||"number"==typeof e[t]}function ha(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function ga(e){if(!e||"object"!=typeof e)return!1;const t=e;return la(t,"tokenName")&&da(t,"from")&&da(t,"to")&&da(t,"resolution")}class ma{constructor(e,t=!1){this.http=e,this.logger=new g({debug:t,context:"PoolService"})}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 a=m(t),n=await this.http.get(Xt,a);Ht(n,"Failed to fetch pools",!0);const r=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 a=e.tokens;t=[{...a,createdAt:a.created_at||a.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(n.data),o=n.data.count??n.data.total??0;return{pools:r,total:o,totalPages:e.limit>0?Math.ceil(o/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:a,pageSize:n,...r}=e,o=[];if(a&&a>=t){const e=[];for(let n=t;n<=a;n++)e.push(n);for(let t=0;t<e.length;t+=5){const a=e.slice(t,t+5).map(e=>this.fetchSinglePage({...r,page:e,limit:n}));(await Promise.all(a)).forEach(e=>{o.push(...e.pools)})}return o}let s=t,i=!0;for(;i;){const e=[];for(let t=0;t<5&&i;t++)e.push(s+t);const t=e.map(e=>this.fetchSinglePage({...r,page:e,limit:n})),a=await Promise.all(t);for(const e of a){if(0===e.pools.length){i=!1;break}o.push(...e.pools)}s+=e.length,s>100&&(i=!1)}return o}async fetchPools(e={}){const t=e.page||1,a=e.limit??10;let n;if(0!==a&&xt({page:t,limit:a}),e.tokenName&&_t(e.tokenName),"recent"===e.type?n="RECENT":"popular"===e.type&&(n="POPULAR"),a>0&&a<=20){const r=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:a});return{pools:r.pools,page:t,limit:a,total:r.total,totalPages:r.totalPages,hasNext:t<r.totalPages,hasPrevious:t>1}}if(0===a){const t=20,a=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:1,limit:t}),r=[...a.pools];if(a.pools.length>0){const o=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:2,totalPages:a.totalPages>1?a.totalPages:null,pageSize:t});r.push(...o)}return{pools:r,page:1,limit:r.length,total:a.total||r.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const r=Math.ceil(a/20),o=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:20}),s=[...o.pools],i=Math.min(r,o.totalPages-t+1);if(i>1){const a=t+i-1,r=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:t+1,totalPages:a,pageSize:20});s.push(...r)}const c=s.slice(0,a);return{pools:c,page:t,limit:a,total:o.total,totalPages:o.totalPages,hasNext:t<o.totalPages&&c.length<o.total,hasPrevious:t>1}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){Lt(e),e.tokenName&&_t(e.tokenName);const t=m(e),a=await this.http.get(Yt,t);Ht(a,"Failed to check pool");const n=a.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(!ga(e))throw new v("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:a,to:n,resolution:r}=e;if(_t(t),!a||!n||!r)throw new v("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:a,to:n,resolution:r};$t(o);const s=m(o),i=await this.http.get(Zt,s);return Ht(i,"Failed to fetch graph data",!0),{dataPoints:i.data}}async fetchTokenDistribution(e){if(!e)throw Kt("tokenName","Token name");_t(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw new v(y(e),"tokenName","VAULT_NOT_FOUND");const a=encodeURIComponent(t),n=await this.http.get(`${Jt}/${a}`);Ht(n,"Failed to fetch token distribution",!0);const r=n.data;if(!Array.isArray(r))throw zt("Invalid API response: expected array of holders",n.status);for(const e of r){if(!e.owner||"string"!=typeof e.owner)throw zt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw zt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw zt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const s=r.reduce((e,t)=>e.plus(t.quantity),new o(0));return{holders:r.map(e=>{const t=new o(e.quantity),a=s.isZero()?0:t.dividedBy(s).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:a}}),totalSupply:s.toFixed(),totalHolders:r.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Kt("tokenName","Token name");_t(e);const t=await this.http.get(ea,{tokenName:e});return Ht(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:a,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const r=("volume"===a?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return r?.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 pa(e,t={}){const{stringifyFields:a=[],optionalFields:n=[],fieldMappings:r={}}=t,o={};for(const[t,s]of Object.entries(e)){const e=t;if(n.includes(e)&&void 0===s)continue;if(n.includes(e)&&"string"==typeof s&&0===s.trim().length)continue;const i=r[e],c=i?String(i):t;a.includes(e)?o[c]=String(s):o[c]=s}return m(o)}const fa={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class ya{constructor(e,t=!1){this.http=e,this.logger=new g({debug:t,context:"TradeService"})}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return la(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&ua(t,"userAddress")&&da(t,"page")&&da(t,"limit")}(e))throw new v("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:a,userAddress:n,page:r=1,limit:o=10,startDate:s,endDate:i,sortOrder:c}=e;if(!E(t))throw new v("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");k(r,o,fa);const l=function(e,t,a){return pa({tokenName:e,page:t,limit:a},{stringifyFields:["page","limit"]})}(t,r,o),u=await this.http.get(ta,l),d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const g=jt(u,{page:r,limit:o}),m=Wt(g.page,g.totalPages);return{trades:d,...g,...m}}}const va=new g({debug:!1,context:"DateUtils"});function Aa(e,t){if(!e)return t||new Date;if(e instanceof Date)return isNaN(e.getTime())?t||new Date:e;try{const a=new Date(e);return isNaN(a.getTime())?(va.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):a}catch(a){return va.warn(`Date parsing error for "${e}":`,a),t||new Date}}const wa={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class Ta{constructor(e,t,a=!1){this.http=e,this.poolService=t,this.logger=new g({debug:a,context:"CommentService"})}async fetchComments(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return la(t,"tokenName")&&da(t,"page")&&da(t,"limit")}(e))throw new v("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:a=1,limit:n=10}=e;if(!E(t))throw new v("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");k(a,n,wa);const r=await this.poolService.resolveTokenNameToVault(t);if(!r)throw Rt(t);const o=pa({vaultAddress:r,page:a,limit:n},{stringifyFields:["page","limit"]}),s=await this.http.get(aa,o);Ht(s,"Failed to fetch comments");return{comments:s.data.comments.map(e=>({...e,createdAt:Aa(e.createdAt)})),total:s.data.count}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return la(t,"tokenName")&&la(t,"content")}(e))throw new v("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:a}=e;if(!E(t))throw new v("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>=wa.CONTENT.MIN_LENGTH&&t.length<=wa.CONTENT.MAX_LENGTH}(a))throw new v(`Comment content must be between ${wa.CONTENT.MIN_LENGTH} and ${wa.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const n=await this.poolService.resolveTokenNameToVault(t);if(!n)throw Rt(t);const r={userAddress:this.http.getAddress(),vaultAddress:n,content:a};Ht(await this.http.post(na,r),"Failed to create comment")}}function ka(e,t="image",a){const n=new FormData;if("undefined"!=typeof File&&e instanceof File)n.append(t,e);else{if(!Buffer.isBuffer(e))throw Gt("file","a File object (browser) or Buffer (Node.js)");{const r=new Blob([e],{type:"image/png"});n.append(t,r,a)}}return n}const Na={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 Ea(e){return!(!e||"string"!=typeof e)&&Na.USER_ADDRESS.PATTERN.test(e)}const Sa="Update profile";class ba{constructor(e){this.http=e}async fetchProfile(e){const t=e??this.http.getAddress();if(!Ea(t))throw new v("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const a={userAddress:t};return await this.http.get(ra,a)}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!t||""===t.trim())try{const a=await this.fetchProfile(e.address);t=a.data?.profileImage||""}catch{t=""}const a={profileImage:t,fullName:e.fullName,userAddress:e.address},n=await this.http.signCustomMessage(Sa),r={address:n.address,message:Sa,publickey:n.ethereumAddress,sign:n.signature};Ht(await this.http.put(oa,a,r),"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();try{const a=`profile-image-${t}.png`,n=ka(e.file,"image",a),r=await this.http.request({method:"POST",url:`${Qt}?tokenName=${encodeURIComponent(t)}`,data:n,headers:{}});return Ht(r,"Image upload failed"),"string"==typeof r.data?r.data:""}catch(e){if(e instanceof v)throw e;throw new v(`Profile image upload failed: ${e instanceof Error?e.message:"Unknown error"}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(sa,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(ia,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=1,limit:a=10,search:n,tokenName:r}=e,o={type:"DEFI",address:this.http.getAddress(),page:t,limit:a};return void 0!==n&&(o.search=n),void 0!==r&&(o.tokenName=r),this.fetchTokenList(o)}async buildFetchRequest(e,t,a){this.validateGetTokenListOptions(t);const n={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},r=pa(a.includeType?{...n,type:"all"!==t.type&&t.type?t.type:"DEFI"}:n,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),o=await this.http.get(e,r);Ht(o,a.errorMessage,!0);const s=(i=o.data)?Array.isArray(i)?i:i.token:[];var i;const c=jt(o,{page:t.page||1,limit:t.limit||10}),l=Wt(c.page,c.totalPages);return{tokens:s,...c,...l}}validateGetTokenListOptions(e){if(k(e.page,e.limit,Na),void 0!==e.address&&!Ea(e.address))throw new v("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>=Na.SEARCH.MIN_LENGTH&&t.length<=Na.SEARCH.MAX_LENGTH))throw new v(`Search query must be between ${Na.SEARCH.MIN_LENGTH} and ${Na.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,a;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((a=e.tokenName)&&"string"==typeof a&&a.length>=Na.TOKEN_NAME.MIN_LENGTH&&a.length<=Na.TOKEN_NAME.MAX_LENGTH))throw new v(`Token name must be between ${Na.TOKEN_NAME.MIN_LENGTH} and ${Na.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!Ea(e.address))throw new v("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=Na.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=Na.PROFILE.FULL_NAME.MAX_LENGTH&&Na.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new v(`Full name must be between ${Na.PROFILE.FULL_NAME.MIN_LENGTH} and ${Na.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!Ea(e.address))throw new v("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Ia extends Error{constructor(e,t,a){super(e),this.filename=t,this.mimeType=a,this.name="FileValidationError"}}function Fa(e,t,a){if(!e)throw new Ia("File is required",t,a);if("undefined"!=typeof File&&e instanceof File){const t=we();if(t){const a=t.safeParse(e);if(!a.success){const t=a.error.errors.map(e=>e.message).join("; ");throw new Ia(t,e.name,e.type)}}return}if(Buffer.isBuffer(e)){if(!t)throw new Ia("Filename is required when uploading Buffer objects",t,a);const n=fe.safeParse(e);if(!n.success){const e=n.error.errors.map(e=>e.message).join("; ");throw new Ia(e,t,a)}if(t.length>255)throw new Ia(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,a);const r=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!r.includes(a))throw new Ia(`Invalid file type "${a}" is not allowed. Allowed types: ${r.join(", ")}`,t,a);const o=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),s=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!s.includes(o))throw new Ia(`File extension "${o}" is not allowed. Allowed extensions: ${s.join(", ")}`,t,a);const i=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"}}(o);if(i!==a&&"application/octet-stream"!==i)throw new Ia(`File extension "${o}" does not match MIME type "${a}"`,t,a);return}throw new Ia("File must be a File object (browser) or Buffer (Node.js)",t,a)}class Ca{constructor(e,t=!1){this.http=e,this.logger=new g({debug:t,context:"ImageService"})}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;_t(t);const n=`${t}.png`;Fa(a.file,n,"image/png");try{const e=`${a.tokenName??t}.png`,n=ka(a.file,"image",e),r=await this.http.request({method:"POST",url:`${Qt}?tokenName=${encodeURIComponent(a.tokenName??t)}`,data:n,headers:{}});return Ht(r,"Image upload failed"),"string"==typeof r.data?r.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw Vt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class Da{constructor(e,t=!1){this.http=e,this.logger=new g({debug:t,context:"FaucetService"})}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount};Ht(await this.http.post(ca,t),"Faucet transfer failed")}validateTransferFaucetsData(e){if(!Ea(e.walletAddress))throw new v("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!Na.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new v("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class Pa{constructor(e,t=!1){this.http=e,this.poolService=new ma(e,t),this.tradeService=new ya(e,t),this.commentService=new Ta(e,this.poolService,t),this.userService=new ba(e),this.imageService=new Ca(e,t),this.faucetService=new Da(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 _t(e)}}const _a={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var xa;!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"}(xa||(xa={}));class La extends Error{constructor(e,t,a){super(e),this.type=t,this.details=a,this.name="TransferError"}}class Oa{static validateAmount(e){if(parseFloat(e)<=0)throw new La("Transfer amount must be positive",xa.INVALID_AMOUNT,{amount:e})}static validateUniqueKey(e){if(e){if(e.length>_a.MAX_UNIQUE_KEY_LENGTH)throw new v(`Unique key too long. Maximum length: ${_a.MAX_UNIQUE_KEY_LENGTH}`);if(!_a.UNIQUE_KEY_PATTERN.test(e))throw new La('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',xa.INVALID_AMOUNT,{uniqueKey:e})}}}class $a extends n.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,a,n,r){let o;if("string"==typeof n){const e=n.split("$");if(4!==e.length)throw new Error(`Invalid token class key format: ${n}. Expected format: collection$category$type$additionalKey`);o={collection:e[0],category:e[1],type:e[2],additionalKey:e[3],instance:"0"}}else o={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new $a({from:e,to:t,quantity:a,tokenInstance:o,uniqueKey:r||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,a,n){return new $a({from:e,to:t,quantity:a,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 Ua{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},a={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,a,e),domain:t,types:a,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const a=e.replace("0x","");return`eth|${t.ethers.getAddress(`0x${a}`).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){const t=e.split("$");if(4!==t.length)throw new Error(`Invalid token class key format: ${e}. Expected format: collection$category$type$additionalKey`);return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3],instance:"0"}}}function Ba(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new v(`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 v(`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 v("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 v(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}var Ma=Object.freeze({__proto__:null,normalizeToTokenInstanceKey:Ba});function Ra(e){return e instanceof Error}function Ka(e){return Ra(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 Ga(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}const za="gala-transfer-successful",Va="token-transfer-successful",qa="transfer-successful-no-id";class ja{constructor(e,t,a,n=!1){this.http=e,this.wallet=t,this.tokenResolver=a,this.signatureHelper=new Ua(t),this.logger=new g({debug:n,context:"GalaChainService"})}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(1!==t.Status)throw zt(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const a=t.Data.reverseBondingCurveConfiguration,n=a?.minFeePortion??"0",r=a?.maxFeePortion??"0",o=(await import("bignumber.js")).default,s=!new o(n).isZero()||!new o(r).isZero(),i=t.Data;return i.reverseBondingCurveMinFeePortion=n,i.reverseBondingCurveMaxFeePortion=r,i.hasReverseBondingCurveFee=s,i.isGraduated="Completed"===t.Data.saleStatus,delete i.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(1!==e.Status)throw zt(`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 v("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new v("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new v("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(1!==t.Status||!t.Data||0===t.Data.length)return null;const a=t.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!a||"0"===a.quantity)return null;const n=`${a.collection}|${a.category}|${a.additionalKey}|${a.type}`;return{quantity:a.quantity,collection:a.collection,category:a.category,tokenId:n}}catch(e){throw zt(`Failed to fetch token balance from GalaChain: ${Ka(e)}`,void 0,Ra(e)?e:void 0)}}async transferGala(e){this.validateTransferGalaData(e);try{const t=b(e.recipientAddress),a=b(this.wallet.address),n=$a.forGALA(a,t,e.amount,e.uniqueKey),r=await this.signatureHelper.signTransferToken(n.toSigningPayload()),o=new $a({...n.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(o,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",o);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){this.validateTransferTokenData(e);try{const t=b(e.to),a=b(this.wallet.address);let n;if(e.tokenId)n=Ba(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 La("Must provide either tokenId or tokenName for token identification",xa.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const r=new $a({from:a,to:t,quantity:e.amount,tokenInstance:n,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),o=await this.signatureHelper.signTransferToken(r.toSigningPayload()),s=new $a({...r.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(s,null,2));const i=await this.http.post("/api/asset/token-contract/TransferToken",s);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(i,null,2)),this.extractTransactionIdFromResponse(i,"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 La)throw t;throw new La(`Failed to resolve token class key for '${e}': ${t instanceof Error?t.message:String(t)}`,xa.TOKEN_NOT_FOUND,{tokenName: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 v("Invalid GALA transfer data: missing required fields");if(!S(e.recipientAddress))throw new La("Invalid recipient address format",xa.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Oa.validateAmount(e.amount),Oa.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 v("Invalid token transfer data: missing required fields");if(!S(e.to))throw new La("Invalid recipient address format",xa.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new La("Must provide either tokenId or tokenName for token identification",xa.TOKEN_NOT_FOUND);if(e.tokenName&&!_a.TOKEN_NAME_PATTERN.test(e.tokenName))throw new La("Invalid token name format",xa.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Oa.validateAmount(e.amount),Oa.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new La(`Token '${e}' not found or not available for transfer`,xa.TOKEN_NOT_FOUND,{tokenName:e});const a=this.resolveTokenInstanceFromVaultAddress(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}':\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(a,null,2)}`),a}catch(t){if(t instanceof La)throw t;throw new La(`Failed to resolve token '${e}': ${t instanceof Error?t.message:String(t)}`,xa.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){const[t,a]=e.split("|");if(!a)throw new La(`Invalid vault address format: missing token components. Address: ${e}`,xa.TOKEN_NOT_FOUND);const n=a.split("$");if(n.length<4)throw new La(`Invalid vault address format: insufficient token components. Expected 4+, got ${n.length}. Address: ${e}`,xa.TOKEN_NOT_FOUND);return{collection:n[0],category:n[1],type:n[2],additionalKey:n[3],instance:"0"}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const a=e;return Array.isArray(a.Data)&&a.Data.length>0?"gala"===t?za:Va:qa}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new La("Transfer succeeded but transaction ID could not be extracted",xa.NETWORK_ERROR)}handleTransferError(e,t,a){if(e instanceof La)return e;if(e instanceof v)return new La(e.message,xa.INVALID_AMOUNT);if(Ga(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t)return new La(("string"==typeof n?.message?n.message:void 0)||"Invalid transfer request",xa.INVALID_AMOUNT);if(403===t)return new La("Insufficient balance for transfer",xa.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in a&&(e.tokenName=a.tokenName),new La("Token not found",xa.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new La("Transfer request timed out",xa.NETWORK_ERROR);const n=Ka(e);return new La(n||t,xa.NETWORK_ERROR)}}class Wa{constructor(e,t=!1){this.http=e,this.logger=new g({debug:t,context:"DexService"})}async fetchTokenSpotPrice(e){if(!e||Array.isArray(e)&&0===e.length)throw Kt("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.http.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),a=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&a.push({symbol:e.symbol,price:e.currentPrices.usd})}),a}catch(e){throw zt(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`)}}async fetchLaunchpadTokenSpotPrice(e,t){if(!e||"string"!=typeof e)throw new Error(f);try{const a=await t({tokenName:e,amount:"1",type:"native"}),n=(await this.fetchTokenSpotPrice("GALA"))[0];if(!n)throw zt("GALA price not available");const r=Number(a.amount)/1e18;if(r<=0)throw new v(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const o=n.price/r;return{symbol:e.toUpperCase(),price:o}}catch(t){if(t instanceof Error)throw zt(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw zt(`Failed to calculate launchpad token spot price for ${e}: ${String(t)}`)}}}function Ha(e,t=18){const a=parseFloat(e);if(0===a)return"0";return a.toFixed(t).replace(/\.?0+$/,"")}function Qa(e){return Ha(e,8)}function Xa(e){return Ha(e,18)}function Ya(e){return{maxAcceptableReverseBondingCurveFee:Qa(e.maxAcceptableReverseBondingCurveFee)}}new g({debug:!1,context:"NumberUtils"});class Za extends n.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Qa(t),this.expectedToken=Xa(a),this.extraFees=Ya(n)}}class Ja extends n.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Xa(t),this.expectedNativeToken=Qa(a),this.extraFees=Ya(n)}}class en extends n.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Xa(t),this.expectedNativeToken=Qa(a),this.extraFees=Ya(n)}}class tn extends n.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Qa(t),this.expectedToken=Xa(a),this.extraFees=Ya(n)}}const an={BuyNativeDto:Za,BuyExactDto:Ja,SellExactDto:en,SellNativeDto:tn};var nn,rn,on;!function(e){e[e.METAMASK=0]="METAMASK",e[e.TRUST_WALLET=1]="TRUST_WALLET",e[e.GALA_WALLET=2]="GALA_WALLET"}(nn||(nn={}));class sn{constructor(e,t=!1){this.walletProvider=e,this.debug=t,this.logger=new g({debug:t,context:"SignatureService"})}async signDTO(e,t,a,r=nn.METAMASK){try{this.logger.debug("๐Ÿ” Signing DTO:",{methodName:t,walletPreference:r,dtoKeys:Object.keys(e)});const o=this.generateEIP712Types(t,e),s=n.calculatePersonalSignPrefix(e),i={...e,prefix:s};let c,l,u;switch(r){case nn.GALA_WALLET:({signature:c,domain:l}=await this.signWithGalaWallet(o,i,t,a));break;case nn.TRUST_WALLET:c=await this.signWithTrustWallet(i),l={name:"ethereum",chainId:1};break;case nn.METAMASK:default:({signature:c,domain:l}=await this.signWithMetaMask(o,i))}return u=r===nn.TRUST_WALLET?{...i,signature:c}:{...e,signature:c,types:o,domain:l},this.logger.debug("โœ… DTO signed successfully:",{payloadKeys:Object.keys(u),signatureLength:c.length}),u}catch(e){this.logger.error("โŒ Signature generation failed:",e);throw qt(`Failed to sign DTO: ${Ka(e)}`)}}async signWithMetaMask(e,t){try{let a,n;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)a={name:"ethereum",chainId:1},n=await this.walletProvider.signTypedData(a,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw Vt("Wallet provider does not support typed data signing","walletProvider");{const r=await this.walletProvider.getNetwork();a={name:r.name,chainId:Number(r.chainId)},n=await this.walletProvider.signTypedData(a,e,t)}}return{signature:n,domain:a}}catch(e){throw qt(`MetaMask/ethers signing failed: ${Ka(e)}`)}}async signWithTrustWallet(e){try{const a=(t=e,JSON.stringify(t));let n;if(!this.walletProvider.signMessage)throw Vt("Wallet provider does not support signMessage","walletProvider");return n=await this.walletProvider.signMessage(a),n}catch(e){throw qt(`TrustWallet signing failed: ${Ka(e)}`)}var t}async signWithGalaWallet(e,t,a,n){try{const r={name:"ethereum",chainId:1};if("undefined"==typeof window)return this.logger.warn("โš ๏ธ GalaWallet not available in Node.js environment, falling back to ethers.js signing"),await this.signWithMetaMask(e,t);const o={domain:r,types:e,message:t,Primary_type:a},s=window;if(!s.gala)throw Vt("GalaWallet not found in window object","galaWallet");await s.gala.setAddress(n);return{signature:await s.gala.request({method:"eth_signTypedData",params:[JSON.stringify(o),n]}),domain:r}}catch(e){throw qt(`GalaWallet signing failed: ${Ka(e)}`)}}generateEIP712Types(e,t){const a={};a[e]=[];const n=(e,t,r,o=!1)=>{if(void 0!==t){if(Array.isArray(t)){const s=n(e,t[0],r,!0);return o||a[r].push({name:e,type:(s??e)+"[]"}),s?s+"[]":void 0}if("object"==typeof t&&null!==t){if(a[e])throw new v(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return a[e]=[],Object.entries(t).forEach(([t,a])=>{n(t,a,e)}),o||a[r].push({name:e,type:e}),e}{let n;switch(typeof t){case"string":n="string";break;case"number":n="uint256";break;case"boolean":n="bool";break;default:throw new v(`Unsupported type for fieldName ${e}: ${typeof t}, value: ${t}`,"fieldValue","UNSUPPORTED_TYPE")}return o||a[r].push({name:e,type:n}),n}}};return Object.entries(t).forEach(([t,a])=>{n(t,a,e)}),this.logger.debug("๐Ÿ“ Generated EIP-712 types:",a),a}detectWalletPreference(){if("undefined"==typeof window)return nn.METAMASK;const e=window;return e.gala?nn.GALA_WALLET:e.trustWallet?.isTrust?nn.TRUST_WALLET:(e.ethereum,nn.METAMASK)}}class cn{constructor(e=!1){this.debug=e,this.logger=new g({debug:e,context:"TokenClassKeyService"})}generateStringsInstructions(e){try{this.logger.debug("๐Ÿ”ง Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),a=this.createTokenInstance(t),n=this.createGalaInstance(),r=`$service$${a.toStringKey()}$launchpad`,o=`$tokenBalance$${a.toStringKey()}$${e}`,s=`$tokenBalance$${a.toStringKey()}$${e}`,i=`$tokenBalance$${n.toStringKey()}$${e}`,c=[r,o,s,i,`$tokenBalance$${n.toStringKey()}$${e}`];return this.logger.debug("โœ… Generated stringsInstructions:",c),c}catch(e){this.logger.error("โŒ Failed to generate stringsInstructions:",e);const t=Ka(e);throw new v(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new s.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 s.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 Kt("vaultAddress","Vault address");const t=e.split("$");if(t.length<3)throw Gt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");const a=t[2];if(!a||0===a.trim().length)throw new v(`Empty token symbol in vault address: ${e}`,"vaultAddress","EMPTY_TOKEN_SYMBOL");return this.logger.debug("๐Ÿ” Extracted token symbol:",{vaultAddress:e,tokenSymbol:a,parts:t.slice(0,4)}),a}validateVaultAddress(e){if(!e||"string"!=typeof e)throw Kt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Gt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Gt("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw Gt("vaultAddress",'having at least 5 parts separated by "$"');const a=t[2];if(!a||!/^[A-Za-z]{1,10}$/.test(a))throw Gt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("โœ… Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,a,n){return`${e}$${t}$${a}$${n}`}parseTokenClassKeyString(e){const t=e.split("$");if(4!==t.length)throw Gt("stringKey","format: collection$category$type$additionalKey (4 parts)");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}}function ln(e,t,a){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 o(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 s;switch(a){case"buy-native":case"sell-exact":s=n.minus(r);break;case"buy-exact":case"sell-native":s=n.plus(r);break;default:throw new Error(`Unknown operation type: ${a}`)}return s.isLessThan(0)&&(s=new o(0)),s.toFixed()}class un{constructor(e,t,a=!1,n,r,o=.05,s=.01){this.httpClient=e,this.tokenResolver=t,this.walletProvider=n,this.userAddress=r,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=s,this.bundleEndpoint="/bundle",this.logger=new g({debug:a,context:"BundleService"}),n&&r&&(this.signatureService=new sn(n,a),this.tokenKeyService=new cn(a))}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 a=await this.httpClient.post(this.bundleEndpoint,t);return this.logger.debug("๐Ÿ“ฅ Bundle API response:",{success:a.success,hasData:!!a.data,error:a.error}),this.handleBundleResponse(a)}catch(e){return this.logger.error("โŒ Bundle transaction submission failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}validateBundleData(e){if(!e)throw Kt("bundleData","Bundle data");if(!e.signedDto)throw Kt("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw Kt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Gt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new v("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Gt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new v(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new v(`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(Ga(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 Ka(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw Kt("transactionId","Transaction ID");this.logger.debug("๐Ÿ” Checking bundler transaction result:",e);const t=await this.httpClient.get(`${this.bundleEndpoint}?id=${e}`);return this.logger.debug("๐Ÿ“Š Bundler transaction result:",t),{success:!0,data:t}}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 Kt("transactionId","Transaction ID");this.logger.debug("๐Ÿšซ Cancelling transaction:",e);const t=await this.httpClient.delete(`${this.bundleEndpoint}/${e}`);return this.logger.debug("๐Ÿ—‘๏ธ Transaction cancellation response:",t),{success:!0,data:t}}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.httpClient.get(`${this.bundleEndpoint}/health`);return this.logger.debug("๐Ÿ’š Bundle service health:",e),{success:!0,data:e}}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:a,type:n,expectedAmount:r}=e,{effectiveSlippageFactor:o,effectiveMaxFee:s,vaultAddress:i}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===n){if(!r)throw new v("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ln(r,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:r,slippageFactor:o,adjustedMinTokens:e});const t=new an.BuyNativeDto(i,a,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",i)}{if(!r)throw new v("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ln(r,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:r,slippageFactor:o,adjustedMaxGalaCost:e});const t=new an.BuyExactDto(i,a,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyExactToken",i)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:a,type:n,expectedAmount:r}=e,{effectiveSlippageFactor:o,effectiveMaxFee:s,vaultAddress:i}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===n){if(!r)throw new v("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ln(r,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:r,slippageFactor:o,adjustedMinGala:e});const t=new an.SellExactDto(i,a,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",i)}{if(!r)throw new v("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ln(r,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:r,slippageFactor:o,adjustedMaxTokensToSell:e});const t=new an.SellNativeDto(i,a,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellWithNative",i)}}async prepareTradingOperation(e,t,a,n){const{effectiveSlippageFactor:r,effectiveMaxFee:o}=this.calculateEffectiveSlippage(t,a,n),s=await this.resolveTokenNameToVault(e);if(!s)throw Rt(e);return{effectiveSlippageFactor:r,effectiveMaxFee:o,vaultAddress:s}}calculateEffectiveSlippage(e,t,a){const n=a??this.defaultSlippageToleranceFactor,r=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let o=e||"0";return e&&(o=ln(e,r,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:r,adjustedMaxFee:o})),{effectiveSlippageFactor:n,effectiveFeeSlippageFactor:r,effectiveMaxFee:o}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw Vt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw Kt("userAddress","User address")}async executeBundleTransaction(e,t,a){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${i.v4()}-${Date.now()}-${this.userAddress}`;const n=await this.signatureService.signDTO(e,t,this.userAddress),r=this.tokenKeyService.generateStringsInstructions(a),o={stringsInstructions:r,method:t,signedDto:n};this.logger.debug("๐Ÿ“ฆ Bundle transaction data:",{method:t,stringsInstructions:r,dtoKeys:Object.keys(n)});const s=await this.submitTransaction(o);if(s.success&&s.data)return this.logger.debug("โœ… Bundle transaction submitted:",s.data),{success:!0,data:{transactionId:s.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(s.error||"Bundle transaction failed"))}catch(e){throw this.logger.error("โŒ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(rn||(rn={})),e.SDKTransactionStatus=void 0,(on=e.SDKTransactionStatus||(e.SDKTransactionStatus={})).PENDING="pending",on.PROCESSING="processing",on.COMPLETED="completed",on.FAILED="failed",on.TIMEOUT="timeout";const dn={[rn.PROCESSED]:e.SDKTransactionStatus.COMPLETED,[rn.COMPLETED]:e.SDKTransactionStatus.COMPLETED,[rn.SUCCESS]:e.SDKTransactionStatus.COMPLETED,[rn.FAILED]:e.SDKTransactionStatus.FAILED,[rn.ERROR]:e.SDKTransactionStatus.FAILED,[rn.PROCESSING]:e.SDKTransactionStatus.PROCESSING,[rn.PENDING]:e.SDKTransactionStatus.PENDING};class hn{constructor(e,t=!1){this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.reconnectCount=0,this.hasOnAnyListener=!1,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.logger=new g({debug:t,context:"WebSocketService"}),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.debug&&(this.socket.onAny((e,...t)=>{this.logger.debug(`๐Ÿ“ก [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0)}catch(e){t(e)}})}async monitorTransaction(t,a){this.listeners.set(t,a),this.logger.debug(`๐Ÿ“ก Starting to monitor transaction: ${t}`),this.logger.debug(`๐Ÿ“ก WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=setTimeout(()=>{if(this.listeners.has(t)){const n={transactionId:t,status:e.SDKTransactionStatus.TIMEOUT,message:"Transaction monitoring timeout - no response after 60 seconds",timestamp:Date.now()};this.logger.debug(`๐Ÿ“ก Transaction timeout for ${t}`),a(n),this.listeners.delete(t),this.timeouts.delete(t),this.socket?.off(t)}},6e4);if(this.timeouts.set(t,n),this.socket&&this.socket.connected)this.socket.off(t),this.logger.debug(`๐Ÿ“ก Listening for transaction updates: ${t}`),this.logger.debug(`๐Ÿ“ก WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`๐Ÿ“ก WebSocket URL: ${this.config.url}`),this.socket.on(t,n=>{this.logger.debug(`๐Ÿ“ก Socket.IO transaction update for ${t}:`,JSON.stringify(n,null,2));const r=n,o=r?.data,s=r?.status||r?.Status||o?.status||o?.Status;let i=r?.message||r?.Message||o?.message||o?.Message||r?.error||o?.error;i&&"string"==typeof i||(i=s===rn.FAILED||s===rn.ERROR?"Transaction failed - check transaction details":s===rn.COMPLETED||s===rn.PROCESSED||s===rn.SUCCESS?"Transaction completed successfully":s?`Transaction status: ${s}`:"Unknown transaction status");const c=r?.blockHash||o?.blockHash,l=r?.gasUsed||o?.gasUsed,u={transactionId:t,status:this.mapSocketStatus(s),message:"string"==typeof i?i:"Transaction update received",timestamp:Date.now(),...c&&{blockHash:c},...l&&{gasUsed:l}};if(this.logger.debug(`๐Ÿ“ก Mapped status for ${t}: ${s} -> ${u.status}`),this.logger.debug(`๐Ÿ“ก Final message: "${i}"`),a(u),u.status===e.SDKTransactionStatus.COMPLETED||u.status===e.SDKTransactionStatus.FAILED){this.listeners.delete(t);const e=this.timeouts.get(t);e&&(clearTimeout(e),this.timeouts.delete(t)),this.socket?.off(t),this.logger.debug(`๐Ÿ“ก Cleaned up listener for ${t} (${u.status})`)}});else{const n={transactionId:t,status:e.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};a(n),this.listeners.delete(t),this.timeouts.delete(t)}}async waitForTransaction(t){return new Promise((a,n)=>{this.monitorTransaction(t,t=>{t.status===e.SDKTransactionStatus.COMPLETED?a(t):t.status!==e.SDKTransactionStatus.FAILED&&t.status!==e.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${t.status}: ${t.message}`))})})}mapSocketStatus(t){const a=t?.toUpperCase();return dn[a]||e.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.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}}class gn{constructor(e,t=!1){this.poolService=e,this.cache=new Map,this.logger=new g({debug:t,context:"TokenResolverService"})}async resolveTokenToVault(e){if(!E(e))throw new v("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");const t=e.trim().toLowerCase(),a=this.get(t);if(a)return a;try{const a=await this.poolService.resolveTokenNameToVault(e);return a&&this.set(t,a),a}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw Rt(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:a}of e)this.set(t,a)}parseVaultAddressToTokenClassKey(e){const t=e.split("|");if(2!==t.length)throw Gt("vaultAddress","format: service|Token$Unit$...$launchpad","Vault address");const a=t[1].split("$");if(a.length<4)throw Gt("vaultAddress","at least 4 parts after service|","Vault address");return{collection:a[0],category:a[1],type:a[2],additionalKey:a[3]}}}class mn{}mn.BASE_PRICE=1650667151e-14,mn.PRICE_SCALING_FACTOR=1166069e-12,mn.TRADING_FEE_FACTOR=.001,mn.GAS_FEE="1",mn.MIN_UNBONDING_FEE_FACTOR=0,mn.MAX_UNBONDING_FEE_FACTOR=.5,mn.NET_UNBONDING_FEE_FACTOR=.5,mn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class pn{constructor(e=!1){this.cache=new Map,this.logger=new g({debug:e,context:"TokenMetadataCache"})}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 a=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=pn.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...a||{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const a=this.normalizeTokenName(e);this.updateCacheEntry(a,t)}set(e,t){const a=this.normalizeTokenName(e);this.updateCacheEntry(a,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),a=this.cache.get(t);return a?.maxSupply||mn.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,a)=>{e[a]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((a,n)=>{a.lastUpdated<e&&(e=a.lastUpdated);let r=0;r+=2*n.length,void 0!==a.reverseBondingCurveMinFeeFactor&&(r+=8),void 0!==a.reverseBondingCurveMaxFeeFactor&&(r+=8),void 0!==a.reverseBondingCurveNetFeeFactor&&(r+=8),r+=8,a.vaultAddress&&(r+=2*a.vaultAddress.length),a.maxSupply&&(r+=2*a.maxSupply.length),r+=32,t+=r}),{totalTokens:this.cache.size,cacheSize:t,oldestEntry:this.cache.size>0?e:0}}}function fn(e){const t=function(e){const t=gt(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")}`)}pn.MAX_CACHE_SIZE=1e4;const yn="/api/asset/launchpad-contract/CallNativeTokenIn",vn="/api/asset/launchpad-contract/CallNativeTokenOut",An="/api/asset/launchpad-contract/CallMemeTokenIn",wn="/api/asset/launchpad-contract/CallMemeTokenOut";class Tn extends n.ChainCallDTO{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,this.websiteUrl=e.websiteUrl,this.telegramUrl=e.telegramUrl,this.twitterUrl=e.twitterUrl,this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function kn(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 Nn={NATIVE:"native",EXACT:"exact"},En={LOCAL:"local",EXTERNAL:"external"};class Sn{static calculateBuyWithExact(e,t){const a=parseFloat(e),n=parseFloat(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:s,TRADING_FEE_FACTOR:i,GAS_FEE:c}=mn,l=this.roundUp(r*(Math.exp((n+a)*s)-Math.exp(n*s))/s,8),u=new o(l).multipliedBy(i).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateBuyWithNative(e,t){const a=parseFloat(e),n=parseFloat(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:s,TRADING_FEE_FACTOR:i,GAS_FEE:c}=mn,l=Math.log(a*s/r+Math.exp(n*s))/s-n,u=new o(l).multipliedBy(i).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateSellWithExact(e,t,a,n,r){const s=parseFloat(e),i=parseFloat(t),c=parseFloat(a),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=mn,g=l*(Math.exp(i*u)-Math.exp((i-s)*u))/u,m=new o(g),p=n+i/c*(r-n),f=m.multipliedBy(p).toFixed(8,o.ROUND_UP),y=m.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,a,n,r){const s=parseFloat(e),i=parseFloat(t),c=parseFloat(a),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=mn,g=i-Math.log(Math.exp(i*u)-s*u/l)/u,m=new o(s),p=n+i/c*(r-n),f=m.multipliedBy(p).toFixed(8,o.ROUND_UP),y=m.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static roundUp(e,t){const a=Math.pow(10,t);return Math.ceil(e*a)/a}}class bn{constructor(e,t,a,n,r,o,s="local"){this.http=e,this.tokenResolver=t,this.logger=a,this.bundleHttp=n,this.galaChainHttp=r,this.dexApiHttp=o,this.defaultCalculateAmountMode=s,this.metadataCache=new pn}addIfDefined(e,t,a){return void 0!==a&&(e[t]=a),e}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;_t(t);const n=`${t}.png`;Fa(a.file,n,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&a.file instanceof File)e.append("image",a.file);else{if(!Buffer.isBuffer(a.file))throw Gt("file","a File object (browser) or Buffer (Node.js)");{const n=`${a.tokenName||t}.png`,r=new Blob([a.file],{type:"image/png"});e.append("image",r,n)}}const n=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(a.tokenName||t)}`,data:e,headers:{}});if(!0===n.error||200!==n.status||!n.data?.imageUrl)throw zt(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 Vt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){xt(e),e.tokenName&&_t(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 a=m(t),n=await this.http.get("/launchpad/fetch-pool",a);if(!0===n.error||200!==n.status||!n.data)throw zt(n.message||"Failed to fetch pools",n.status);let r=[];const o=(await import("bignumber.js")).default;if(n.data.tokens)if(Array.isArray(n.data.tokens))r=n.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",a=e.reverseBondingCurveMaxFeePortion??"0",n=!new o(t).isZero()||!new o(a).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:a,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}});else{const e=n.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",a=e.reverseBondingCurveMaxFeePortion??"0",s=!new o(t).isZero()||!new o(a).isZero();r=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:a,hasReverseBondingCurveFee:s,createdAt:e.created_at||e.createdAt||""}]}else n.data.pools&&Array.isArray(n.data.pools)&&(r=n.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",a=e.reverseBondingCurveMaxFeePortion??"0",n=!new o(t).isZero()||!new o(a).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:a,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:s,isValidPoolForCaching:i}=await Promise.resolve().then(function(){return Bn});r.forEach(e=>{if(!i(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=s(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=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:r,page:l,limit:u,total:c,totalPages:d,hasNext:l<d,hasPrevious:l>1}}async _getAmount(e){if(Ot(e),!this.galaChainHttp)throw Vt("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:a}=((e,t,a,n)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:yn,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:vn,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:An,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:wn,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};throw Gt("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,a);if(!kn(e))throw zt("Malformed response data from GalaChain gateway");if(1!==e.Status)throw zt(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:n,extraFees:r}=e.Data;return{amount:n,reverseBondingCurveFee:r.reverseBondingCurve,transactionFee:r.transactionFees,gasFee:"1"}}catch(n){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:a,error:n instanceof Error?n.message:n}),n}}async checkPool(e){Lt(e),e.tokenName&&_t(e.tokenName);const t=m(e),a=await this.http.get("/launchpad/check-pool",t);if(!0===a.error||200!==a.status)throw zt(a.message||"Failed to check pool",a.status);const n=a.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.exists??!1}async fetchVolumeData(e){if(!ga(e))throw new v("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:a,to:n,resolution:r}=e;if(_t(t),!a||!n||!r)throw new v("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:a,to:n,resolution:r};$t(o);const s=m(o),i=await this.http.get("/launchpad/get-graph-data",s);if(!0===i.error||200!==i.status||!i.data)throw zt(i.message||"Failed to fetch graph data",i.status);return{dataPoints:i.data}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const a={page:e.page||1,limit:e.limit||10};return e.search&&(a.search=e.search),e.tokenName&&(a.tokenName=e.tokenName),t&&(a.type=t),this.fetchPoolsFromAPI(a)}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 v("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:a,type:n,currentSupply:r}=e,o=e.mode??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw new v(`Invalid calculation mode "${o}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new v("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!a||"string"!=typeof a)throw new v("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Nn.NATIVE&&n!==Nn.EXACT)throw new v('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===o?this.calculateBuyAmountExternal({tokenName:t,amount:a,type:n}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:a,type:n},"currentSupply",r))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:a,type:n}=e,r=await this.tokenResolver.resolveTokenToVault(t);if(!r)throw new v(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Nn.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:r,amount:a}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:r,amount:a})}async calculateSellAmount(e){const{tokenName:t,amount:a,type:n,currentSupply:r,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:i}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new v(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new v("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!a||"string"!=typeof a)throw new v("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Nn.EXACT&&n!==Nn.NATIVE)throw new v('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:a,type:n});{const e={tokenName:t,amount:a,type:n,...void 0!==r&&{currentSupply:r},...void 0!==o&&{maxSupply:o},...void 0!==s&&{reverseBondingCurveMaxFeeFactor:s},...void 0!==i&&{reverseBondingCurveMinFeeFactor:i}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:a,type:n}=e,r=await this.tokenResolver.resolveTokenToVault(t);if(!r)throw new v(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Nn.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:r,amount:a}):this._getAmount({type:"MEME",method:"IN",vaultAddress:r,amount:a})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:a,type:n,currentSupply:r}=e;if(!a||"string"!=typeof a)throw new v("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Nn.NATIVE&&n!==Nn.EXACT)throw new v('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==r&&Bt(r,"currentSupply");const o=!r;if(o&&!t)throw new v("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&_t(t);let s=r;if(o){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return n===Nn.EXACT?Sn.calculateBuyWithExact(a,s):Sn.calculateBuyWithNative(a,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:a,type:n,currentSupply:r,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:i}=e;if(!a||"string"!=typeof a)throw new v("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Nn.EXACT&&n!==Nn.NATIVE)throw new v('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==r&&Bt(r,"currentSupply");const c=!r||!o||void 0===s||void 0===i;if(c&&!t)throw new v("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&_t(t);let l=r,u=o,d=s,h=i;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===Nn.EXACT?Sn.calculateSellWithExact(a,l,u,h,d):Sn.calculateSellWithNative(a,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 la(t,"tokenName")&&ha(t)&&ua(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:a,calculateAmountMode:n,currentSupply:r}=t;_t(a);const o=await this.tokenResolver.resolveTokenToVault(a);if(!o)throw new v(y(a),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw Vt("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:o});if(1!==s.Status)throw zt(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const i=s.Data,c=(await import("bignumber.js")).default,l=r??new c(i.maxSupply).minus(i.sellingTokenQuantity).toFixed(),u=i.sellingTokenQuantity;if("0"===u)throw new v(`Token ${a} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const d={tokenName:a,amount:u,type:"exact",currentSupply:l,...void 0!==n&&{mode:n}};return await this.calculateBuyAmount(d)}async launchToken(e){if(!this.bundleHttp)throw Vt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");fn(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new v("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:a}=e.reverseBondingCurveConfiguration,n=Number(t),r=Number(a);if(isNaN(n)||isNaN(r)||n<=0||r<=0||n>=r)throw new v("Reverse bonding curve configuration must have valid min/max fee portions with min < max","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG")}let a="";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 zt("Image upload failed: No URL returned");a=t}else"string"==typeof e.tokenImage&&(a=e.tokenImage);const r=`galaswap - operation - ${i.v4()}-${Date.now()}-${this.http.getAddress()}`,o={tokenName:e.tokenName.trim(),tokenSymbol:e.tokenSymbol.trim().toUpperCase(),tokenDescription:e.tokenDescription.trim(),tokenImage:a.trim(),preBuyQuantity:t.toString(),websiteUrl:e.websiteUrl||"",telegramUrl:e.telegramUrl||"",twitterUrl:e.twitterUrl||"",tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:r};e.reverseBondingCurveConfiguration&&(o.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const s=new Tn(o),c=await this.http.signWithGalaChain("CreateSale",s,n.SigningType.SIGN_TYPED_DATA),{signature:l,types:u,domain:d,prefix:h}=c,g={tokenName:s.tokenName,tokenSymbol:s.tokenSymbol,tokenDescription:s.tokenDescription,tokenImage:s.tokenImage,preBuyQuantity:s.preBuyQuantity,websiteUrl:s.websiteUrl,telegramUrl:s.telegramUrl,twitterUrl:s.twitterUrl,tokenCategory:s.tokenCategory,tokenCollection:s.tokenCollection,uniqueKey:s.uniqueKey,signature:l,types:u,domain:d,...h&&{prefix:h},...s.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:s.reverseBondingCurveConfiguration}},m=`${e.tokenName.trim()}$Unit$none$none`,p="GALA$Unit$none$none";let f;if(parseFloat(t)>0){const e=`$service$${m}$launchpad`;f=[e,`$token$${m}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`]}else{const e=`$service$${m}$launchpad`;f=[e,`$token$${m}$${e}`,`$tokenBalance$${m}$${e}`]}const y={signedDto:g,stringsInstructions:f,method:"CreateSale"},A=await this.bundleHttp.post("/bundle",y);if(A.error||!A.data)throw zt(A.message||"Token launch failed");return A.data}async fetchTokenDistribution(e){if(!e)throw Kt("tokenName","Token name");_t(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new v(y(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const a=encodeURIComponent(t),n=await this.http.get(`/holders/${a}`);if(!0===n.error||200!==n.status||!n.data)throw zt(n.message||"Failed to fetch token distribution",n.status);const r=n.data;if(!Array.isArray(r))throw zt("Invalid API response: expected array of holders",n.status);for(const e of r){if(!e.owner||"string"!=typeof e.owner)throw zt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw zt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw zt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const s=r.reduce((e,t)=>e.plus(t.quantity),new o(0));return{holders:r.map(e=>{const t=new o(e.quantity),a=s.isZero()?0:t.dividedBy(s).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:a}}),totalSupply:s.toFixed(),totalHolders:r.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Kt("tokenName","Token name");_t(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw zt(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:a,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const r=("volume"===a?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return r?.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 v("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw Vt("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},a=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!kn(a))throw zt("Malformed response data from GalaChain gateway");if(1!==a.Status)throw zt(`GalaChain calculation failed with status ${a.Status}`,a.Status);const{calculatedQuantity:n,extraFees:r}=a.Data;return{amount:n,reverseBondingCurveFee:r.reverseBondingCurve,transactionFee:r.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 v(y(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw Vt("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==a.Status)throw zt(`Failed to fetch pool details: Status ${a.Status}`,a.Status);const n=a.Data,r=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),o=n.sellingTokenQuantity,s=n.maxSupply;let i=.5,c=0;n.reverseBondingCurveConfiguration?(i=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=i-c;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}),{currentSupply:r,remainingTokens:o,maxSupply:s,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}}async fetchCurrentSupply(e){_t(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new v(y(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw Vt("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==a.Status)throw zt(`Failed to fetch pool details: Status ${a.Status}`,a.Status);const n=a.Data,r=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),o=n.maxSupply;return this.metadataCache.set(e,{maxSupply:o}),r}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Ut(e)}validateTokenName(e){return _t(e)}validatePagination(e){return xt(e)}async fetchTokenSpotPrice(e){if(!this.dexApiHttp)throw Vt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw Kt("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}}),a=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&a.push({symbol:e.symbol,price:e.currentPrices.usd})}),a}catch(e){throw zt(`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 la(t,"tokenName")&&ha(t)&&ua(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:a,calculateAmountMode:n,currentSupply:r}=t;if(!a||"string"!=typeof a)throw Kt("tokenName","Token name (string)");try{const e={tokenName:a,amount:"1",type:"native",...void 0!==n&&{mode:n},...void 0!==r&&{currentSupply:r}},t=await this.calculateBuyAmount(e),o=(await this.fetchTokenSpotPrice("GALA"))[0];if(!o)throw zt("GALA price not available");const s=Number(t.amount);if(s<=0)throw new v(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");const i=o.price/s;return{symbol:a.toUpperCase(),price:i}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${a}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${a}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}const In={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",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",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function Fn(e){return In[e]}class Cn extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Dn extends Error{constructor(e,t,a){super(`Transaction ${e} failed with status: ${t}${a?` - ${a}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function Pn(e,t){if(!e)throw new Cn(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Cn(`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 Cn(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function _n(e,t,a,n){Pn(e,t);const r=e,o=r.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)}(o))throw new Cn(`Invalid trade data received for transaction ${t}`);const s={transactionId:t,type:a,method:"native"===n.type?"native":"exact",inputAmount:o.inputQuantity||n.amount,outputAmount:o.outputQuantity||n.expectedAmount||"0",totalFees:o.totalFees||"0",tokenName:n.tokenName,vaultAddress:o.vaultAddress||"",timestamp:Date.now()};return void 0!==r.blockHash&&(s.blockHash=r.blockHash),void 0!==r.gasUsed&&(s.gasUsed=r.gasUsed),void 0!==n.slippageToleranceFactor&&(s.slippageTolerance=n.slippageToleranceFactor),s}let xn="";const Ln=function(){if(xn)return xn;try{const e=require("../../package.json");xn=e.version||"unknown"}catch{xn="unknown"}return xn}();class On{constructor(e){let t=null;t=e.env?Fn(e.env):e.baseUrl?.includes("prod")?Fn("PROD"):Fn("STAGE"),this.config={baseUrl:t.launchpadBaseUrl,galaChainBaseUrl:t.galaChainBaseUrl,bundleBaseUrl:t.bundleBaseUrl,webSocketUrl:t.webSocketUrl,dexApiBaseUrl:t.dexApiBaseUrl,launchpadFrontendUrl:t.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new g({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?On.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?On.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||On.DEFAULT_CALCULATE_AMOUNT_MODE,this.auth=new h({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new p(this.auth,this.config),this.galaChainHttp=new p(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new p(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new p(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.launchpadService=new Pa(this.http),this.tokenResolverService=new gn(this.launchpadService.poolService),this.launchpadAPI=new bn(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new ja(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1),this.dexService=new Wa(this.dexApiHttp),this.bundleService=new un(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,this.getAddress(),this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new hn({url:this.config.webSocketUrl},this.config.debug)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw Vt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Vt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const a=new t.Wallet(e),n={...this.config,wallet:a};return new On(n)}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.config.wallet.address}getConfig(){const{wallet:e,...t}=this.config;return{...t,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode}}getVersion(){return Ln}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw Vt("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 fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenSpotPrice(e){return this.dexService.fetchTokenSpotPrice(e)}async fetchGalaSpotPrice(){const e=await this.dexService.fetchTokenSpotPrice("GALA");if(0===e.length)throw zt("Failed to fetch GALA price - no price data returned");const t=e.find(e=>"GALA"===e.symbol);if(!t)throw zt("GALA price not found in response");return t}async fetchLaunchpadTokenSpotPrice(e){return this.launchpadAPI.fetchLaunchpadTokenSpotPrice(e)}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(!t)throw new Error(y(e));const a=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return a.currentSupply=n.currentSupply,a.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,a.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,a.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,a.tokenName=e,a}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 Mt}),a=t(e)||this.getAddress();return this.galaChainService.fetchGalaBalance({owner:a,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Ma}),n=t(e.tokenId),{collection:r,category:o,type:s,additionalKey:i}=n;return this.galaChainService.fetchTokenBalance({owner:a,collection:r,category:o,additionalKey:i,type:s,instance:"0"})}if(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...a&&{address:a}})).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 Kt("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:a,maxAcceptableReverseBondingCurveFeeSlippageFactor:n,privateKey:r,calculateAmountMode:o,currentSupply:s}=e;let i=t;void 0===o&&void 0===s||(i={tokenName:t,...void 0!==o&&{calculateAmountMode:o},...void 0!==s&&{currentSupply:s}});const c=await this.calculateBuyAmountForGraduation(i),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==a&&(l.slippageToleranceFactor=a),void 0!==n&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=n),void 0!==r&&(l.privateKey=r),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:a,...n}=e;return t.buy(n)}await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,a=t?.transactionId;if(!a)throw qt("No transaction ID returned from buy operation");return this.waitForConfirmation(a,t=>_n(t,a,"buy",e))}async sell(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:a,...n}=e;return t.sell(n)}await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,a=t?.transactionId;if(!a)throw qt("No transaction ID returned from sell operation");return this.waitForConfirmation(a,t=>_n(t,a,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async postComment(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:a,...n}=e;return t.postComment(n)}return this.launchpadService.postComment(e)}async launchToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:a,...n}=e;return t.launchToken(n)}await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,a=>{Pn(a,t);const n=a?.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 Cn(`Invalid launch data received for transaction ${t}`);const r={transactionId:t,vaultAddress:n.vaultAddress||"",tokenStringKey:n.tokenStringKey||"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:n.creatorAddress||this.getAddress(),timestamp:Date.now(),...a.blockHash&&{blockHash:a.blockHash},...a.gasUsed&&{gasUsed:a.gasUsed}};return"string"==typeof e.tokenImage&&(r.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(r.preBuyQuantity=e.preBuyQuantity),r.vaultAddress&&this.tokenResolverService.set(e.tokenName,r.vaultAddress),r})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:a,...n}=e;return t.uploadTokenImage(n)}return 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 Mt}),a=t(e)||this.getAddress();return this.launchpadService.fetchProfile(a)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={...e,address:t(e.address)};if(a.privateKey){const e=this.createOverrideSdk(a.privateKey),{privateKey:t,...n}=a;return e.updateProfile(n)}return this.launchpadService.updateProfile(a)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={...e,address:t(e.address)||this.getAddress()};if(a.privateKey){const e=this.createOverrideSdk(a.privateKey),{privateKey:t,...n}=a;return e.uploadProfileImage(n)}return this.launchpadService.uploadProfileImage(a)}async retrieveGalaFromFaucet(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={walletAddress:t(e)||this.getAddress(),amount:"5"};return this.launchpadService.transferFaucets(a)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a=t(e?.address)||this.getAddress(),n={page:e?.page||1,limit:e?.limit||10,address:a};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 Mt}),a={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(a.tokenName=e.tokenName),e?.search&&(a.search=e.search),this.launchpadService.fetchTokenList(a)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={...e,recipientAddress:t(e.recipientAddress)};if(a.privateKey){const e=this.createOverrideSdk(a.privateKey),{privateKey:t,...n}=a;return e.transferGala(n)}return this.galaChainService.transferGala(a)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={...e,to:t(e.to)};if(a.privateKey){const e=this.createOverrideSdk(a.privateKey),{privateKey:t,...n}=a;return e.transferToken(n)}return this.galaChainService.transferToken(a)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(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 Vt("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw Vt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Vt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Vt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw Vt(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Vt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Vt(`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: ${On.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),On.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: ${On.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),On.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 a=await this.websocketService.waitForTransaction(e);if("completed"!==a.status)throw new Dn(e,a.status,a.message);let n;try{n=t(a)}catch(t){if(t instanceof Cn)throw t;throw new Cn(`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 Dn||t instanceof Cn)throw t;throw new Cn(`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:a}=await Promise.resolve().then(function(){return Bn});e.forEach(e=>{if(!a(e))return;const n=t(e,this.logger);n&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,n)})}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),this.websocketService&&this.websocketService.disconnect(),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new g({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:a}=require("./services/WebSocketService");a.cleanupAll(e),t.debug("Global cleanup completed")}}On.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,On.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,On.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=mn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,On.DEFAULT_CALCULATE_AMOUNT_MODE=En.LOCAL;class $n{static generateWallet(){try{const e=t.Wallet.createRandom();if(!e.mnemonic?.phrase)throw new Error("Failed to generate wallet with mnemonic phrase");const a=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:a,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}`,a="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),n=new t.Wallet(a),r=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"test test test test test test test test test test test junk",wallet:n}}throw e}}static fromPrivateKey(e){const a=new t.Wallet(e),n=this.toGalaAddress(a.address);return{privateKey:a.privateKey,address:a.address,galaAddress:n,mnemonic:"",wallet:a}}static fromMnemonic(e,a=0){try{const n=t.Mnemonic.fromPhrase(e),r=t.HDNodeWallet.fromMnemonic(n,`m/44'/60'/0'/0/${a}`),o=new t.Wallet(r.privateKey),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:e,wallet:o}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${a}-${e}`,r="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),o=new t.Wallet(r),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:e,wallet:o}}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 a=0;a<e;a++){const e=`test-multi-${a}-${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 a=0;a<e;a++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const a=["๐Ÿ” Wallet Information","โ•".repeat(50),`๐Ÿ“ Address: ${e.address}`,`๐ŸŽฎ Gala Address: ${e.galaAddress}`,`๐ŸŒฑ Mnemonic: ${e.mnemonic||"Not available"}`];return t?a.splice(3,0,`๐Ÿ”‘ Private Key: ${e.privateKey}`):a.splice(3,0,"๐Ÿ”‘ Private Key: [HIDDEN - use includeSensitive=true to show]"),a.push("โ•".repeat(50)),a.push("๐Ÿ’พ IMPORTANT: Save your mnemonic phrase securely!"),a.push("This is your backup to recover the wallet."),a.join("\n")}}function Un(e){if(void 0===e)return $n.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 $n.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 $n.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?"...":""}"`)}$n.testCounter=0;var Bn=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const a={};if(e.vaultAddress&&(a.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}"`):a.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}"`):a.reverseBondingCurveMaxFeeFactor=n}return void 0!==a.reverseBondingCurveMaxFeeFactor&&void 0!==a.reverseBondingCurveMinFeeFactor&&(a.reverseBondingCurveNetFeeFactor=a.reverseBondingCurveMaxFeeFactor-a.reverseBondingCurveMinFeeFactor),Object.keys(a).length>0?a: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}});e.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),a=this.setupWallet(e.privateKey),n={wallet:a.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t)},r=new On(n),o={sdk:r,wallet:a,config:n};if(!1!==e.autoValidate){const e=await this.validateSetup(r,a);return{...o,validation:e}}return o}static async validateSetup(e,t){const a=[],n=[],r={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(r.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);r.hasBalance=e>0,r.canTrade=e>=.1,r.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 a.push("Failed to fetch GALA balance: No balance returned")}catch(e){a.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===a.length&&r.connectionHealthy,sdk:e,wallet:t||$n.generateWallet(),issues:a,warnings:n,capabilities:r}}static getRecommendedConfig(e,t="general"){const a={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(a,{debug:!1,timeout:3e4});break;case"development":Object.assign(a,{debug:!0,timeout:45e3});break;case"testing":Object.assign(a,{debug:!0,timeout:6e4})}switch(t){case"trading":a.timeout=1.5*(a.timeout||3e4);break;case"creation":a.timeout=2*(a.timeout||3e4);break;case"monitoring":a.timeout=.5*(a.timeout||3e4)}return a}static async multiWalletSetup(e,t="development"){const a={};for(const[n,r]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:r,agentId:`multi-wallet-${n}`,autoValidate:!1});a[n]=e}return a}static detectEnvironment(){const e=process.env.NODE_ENV?.toLowerCase();return"production"===e?"production":"test"===e||"testing"===e?"testing":"development"}static setupWallet(e){if(!e){const e=process.env.PRIVATE_KEY;return e?$n.fromPrivateKey(e):$n.generateWallet()}return"generate"===e?$n.generateWallet():$n.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}},e.CALCULATION_MODES=En,e.FileValidationError=Ia,e.GALA_DECIMALS=8,e.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},e.IMAGE_EXTENSIONS=me,e.LAUNCHPAD_TOKEN_DECIMALS=18,e.LaunchpadSDK=On,e.MAX_CONCURRENT_POOL_FETCHES=5,e.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},e.SDK_VERSION=Ln,e.TRADING_TYPES=Nn,e.TransactionFailedError=Dn,e.ValidationError=v,e.WebSocketError=Cn,e.WebSocketTimeoutError=class extends Cn{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},e.addressFormatSchema=x,e.amountMethodSchema=de,e.amountTypeSchema=ue,e.browserFileSchema=Ne,e.bufferFileSchema=fe,e.buyTokensDataSchema=je,e.calculatePreMintDataSchema=Je,e.checkPoolOptionsSchema=le,e.commentMessageSchema=X,e.commentPaginationSchema=Pe,e.createLaunchpadSDK=function(e){const{wallet:a,env:n,config:r={}}=e||{};let o;if(a)if("string"==typeof a){o=Un(a).wallet}else{if(!(a instanceof t.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");o=a}else{o=Un().wallet}const s={wallet:o,...n&&{env:n},debug:!1,timeout:3e4,...r};return new On(s)},e.createLimitSchema=z,e.createPaginatedResultSchema=function(e){return r.z.object({data:r.z.array(e),page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()})},e.createTradeDataSchema=qe,e.createWallet=Un,e.ethereumAddressSchema=L,e.faucetAmountSchema=M,e.fetchGalaBalanceOptionsSchema=Me,e.fetchPoolDetailsDataSchema=et,e.fetchTokenBalanceOptionsSchema=Ge,e.fileSizeSchema=W,e.fileUploadSchema=Se,e.filenameSchema=H,e.flexibleAddressSchema=O,e.flexibleFileSchema=Ee,e.formatGalaForDTO=Qa,e.formatLaunchpadTokenForDTO=Xa,e.fullNameSchema=_,e.getAmountOptionsSchema=Ze,e.getBrowserFileSchema=we,e.getFileUploadSchema=ke,e.getFlexibleFileSchema=Te,e.getTradeOptionsSchema=He,e.graduateTokenOptionsSchema=ge,e.graphDataOptionsSchema=he,e.imageExtensionSchema=be,e.imageFilenameSchema=Ie,e.imageMimeTypeSchema=Q,e.imageUploadOptionsSchema=ie,e.isoDateStringSchema=Y,e.launchTokenDataSchema=se,e.nonNegativeDecimalStringSchema=B,e.optionalUrlSchema=K,e.pageNumberSchema=G,e.paginationResultMetaSchema=Oe,e.poolFetchTypeSchema=ce,e.poolPaginationSchema=_e,e.positiveDecimalStringSchema=U,e.privateKeySchema=J,e.reverseBondingCurveConfigSchema=oe,e.reverseBondingCurveConfigurationSchema=tt,e.searchQuerySchema=P,e.sellTokensDataSchema=We,e.standardLimitSchema=V,e.standardPaginationSchema=Fe,e.timestampSchema=Z,e.tokenCategorySchema=ne,e.tokenCollectionSchema=re,e.tokenDescriptionSchema=C,e.tokenListOptionsSchema=Ue,e.tokenNameSchema=I,e.tokenSymbolSchema=F,e.tokenUrlsSchema=ae,e.tradeCalculationMethodSchema=Ye,e.tradeCalculationTypeSchema=Xe,e.tradeLimitSchema=j,e.tradeListParamsSchema=Qe,e.tradePaginationSchema=De,e.tradePaginationWithFiltersSchema=Le,e.tradeTypeBackendSchema=Ve,e.tradeTypeSchema=ze,e.transactionIdSchema=ee,e.transferFaucetsDataSchema=Be,e.uniqueKeySchema=te,e.updateProfileDataSchema=Re,e.uploadProfileImageOptionsSchema=Ke,e.urlSchema=R,e.userLimitSchema=q,e.userPaginationSchema=Ce,e.userTokenNameSchema=D,e.userTokenTypeSchema=$e,e.userTokensPaginationSchema=xe,e.validateAddress=st,e.validateAmountString=ct,e.validateBuyTokensData=Et,e.validateCalculatePreMintData=Ct,e.validateCheckPoolOptions=ft,e.validateCreateTradeData=Nt,e.validateFaucetAmount=lt,e.validateFetchGalaBalanceOptions=At,e.validateFetchPoolDetailsData=Dt,e.validateFetchTokenBalanceOptions=kt,e.validateFullName=ut,e.validateGetAmountOptions=Ft,e.validateGetTradeOptions=bt,e.validateImageUploadOptions=pt,e.validateLaunchTokenData=gt,e.validateSearchQuery=dt,e.validateSellTokensData=St,e.validateTokenDescription=ot,e.validateTokenListOptions=yt,e.validateTokenName=nt,e.validateTokenSymbol=rt,e.validateTokenUrls=mt,e.validateTradeListParams=It,e.validateTransferFaucetsData=vt,e.validateUpdateProfileData=wt,e.validateUploadProfileImageOptions=Tt,e.validateUserTokenName=ht,e.validateVaultAddress=it,e.vaultAddressSchema=$});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("util"),require("ethers"),require("axios"),require("@gala-chain/connect"),require("zod"),require("bignumber.js"),require("@gala-chain/api"),require("uuid"),require("socket.io-client")):"function"==typeof define&&define.amd?define(["exports","util","ethers","axios","@gala-chain/connect","zod","bignumber.js","@gala-chain/api","uuid","socket.io-client"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GalaLaunchpadSDK={},null,e.ethers,e.axios,e.GalaChainConnect,e.z,e.BigNumber,e.GalaChainAPI,e.uuid,e.io)}(this,function(e,t,r,n,a,o,i,s,l,c){"use strict";var u="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function d(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var h,p={exports:{}};var f=(h||(h=1,function(e,t){!function(e){var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(e){return"Symbol("+e+")"};function r(){}var n="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==u?u:void 0,a=Number.isNaN||function(e){return e!=e},o=r;function i(e){return"object"==typeof e&&null!==e||"function"==typeof e}function s(e){return e.slice()}function l(e){return!1!==function(e){return!("number"!=typeof e||a(e)||e<0)}(e)&&e!==1/0}function c(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function d(e,t,r,n){var a=e[t];if(void 0!==a){if("function"!=typeof a)throw new TypeError(a+" is not a method");switch(r){case 0:return function(){return p(a,e,n)};case 1:return function(t){var r=[t].concat(n);return p(a,e,r)}}}return function(){return A(void 0)}}function h(e,t,r){var n=e[t];if(void 0!==n)return c(n,e,r)}function p(e,t,r){try{return A(c(e,t,r))}catch(e){return _(e)}}function f(e){if(e=Number(e),a(e)||e<0)throw new RangeError("highWaterMark property of a queuing strategy must be non-negative and non-NaN");return e}function m(e){if(void 0===e)return function(){return 1};if("function"!=typeof e)throw new TypeError("size property of a queuing strategy must be a function");return function(t){return e(t)}}var g=Promise,y=Promise.prototype.then,v=Promise.resolve.bind(g),b=Promise.reject.bind(g);function w(e){return new g(e)}function A(e){return v(e)}function _(e){return b(e)}function T(e,t,r){return y.call(e,t,r)}function S(e,t,r){T(T(e,t,r),void 0,o)}function k(e,t){S(e,t)}function E(e,t){S(e,void 0,t)}function N(e,t,r){return T(e,t,r)}function I(e){T(e,void 0,o)}var C=function(){function e(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!0,configurable:!0}),e.prototype.push=function(e){var t=this._back,r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size},e.prototype.shift=function(){var e=this._front,t=e,r=this._cursor,n=r+1,a=e._elements,o=a[r];return 16384===n&&(t=e._next,n=0),--this._size,this._cursor=n,e!==t&&(this._front=t),a[r]=void 0,o},e.prototype.forEach=function(e){for(var t=this._cursor,r=this._front,n=r._elements;!(t===n.length&&void 0===r._next||t===n.length&&(t=0,0===(n=(r=r._next)._elements).length));)e(n[t]),++t},e.prototype.peek=function(){var e=this._front,t=this._cursor;return e._elements[t]},e}();function F(e,t,r){var n=null;!0===r&&(n=Object.prototype);var a=Object.create(n);return a.value=e,a.done=t,a}function P(e,t){e._forAuthorCode=!0,e._ownerReadableStream=t,t._reader=e,"readable"===t._state?L(e):"closed"===t._state?function(e){L(e),$(e)}(e):B(e,t._storedError)}function D(e,t){return Kt(e._ownerReadableStream,t)}function R(e){"readable"===e._ownerReadableStream._state?x(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e){B(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness"))}(e),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function O(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function L(e){e._closedPromise=w(function(t,r){e._closedPromise_resolve=t,e._closedPromise_reject=r})}function B(e,t){L(e),x(e,t)}function x(e,t){I(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}function $(e){e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}var U=t("[[CancelSteps]]"),M=t("[[PullSteps]]");function q(e,t){void 0===t&&(t=!1);var r=new H(e);return r._forAuthorCode=t,r}function K(e){return w(function(t,r){var n={_resolve:t,_reject:r};e._reader._readRequests.push(n)})}function G(e,t,r){var n=e._reader;n._readRequests.shift()._resolve(F(t,r,n._forAuthorCode))}function z(e){return e._reader._readRequests.length}function j(e){var t=e._reader;return void 0!==t&&!!Q(t)}var W,V,H=function(){function e(e){if(!1===Mt(e))throw new TypeError("ReadableStreamDefaultReader can only be constructed with a ReadableStream instance");if(!0===qt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");P(this,e),this._readRequests=new C}return Object.defineProperty(e.prototype,"closed",{get:function(){return Q(this)?this._closedPromise:_(Y("closed"))},enumerable:!0,configurable:!0}),e.prototype.cancel=function(e){return Q(this)?void 0===this._ownerReadableStream?_(O("cancel")):D(this,e):_(Y("cancel"))},e.prototype.read=function(){return Q(this)?void 0===this._ownerReadableStream?_(O("read from")):X(this):_(Y("read"))},e.prototype.releaseLock=function(){if(!Q(this))throw Y("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");R(this)}},e}();function Q(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")}function X(e){var t=e._ownerReadableStream;return t._disturbed=!0,"closed"===t._state?A(F(void 0,!0,e._forAuthorCode)):"errored"===t._state?_(t._storedError):t._readableStreamController[M]()}function Y(e){return new TypeError("ReadableStreamDefaultReader.prototype."+e+" can only be used on a ReadableStreamDefaultReader")}"symbol"==typeof t.asyncIterator&&((W={})[t.asyncIterator]=function(){return this},V=W,Object.defineProperty(V,t.asyncIterator,{enumerable:!1}));var Z={next:function(){if(!1===J(this))return _(ee("next"));var e=this._asyncIteratorReader;return void 0===e._ownerReadableStream?_(O("iterate")):N(X(e),function(t){var r=t.done;return r&&R(e),F(t.value,r,!0)})},return:function(e){if(!1===J(this))return _(ee("next"));var t=this._asyncIteratorReader;if(void 0===t._ownerReadableStream)return _(O("finish iterating"));if(t._readRequests.length>0)return _(new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled"));if(!1===this._preventCancel){var r=D(t,e);return R(t),N(r,function(){return F(e,!0,!0)})}return R(t),A(F(e,!0,!0))}};function J(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorReader")}function ee(e){return new TypeError("ReadableStreamAsyncIterator."+e+" can only be used on a ReadableSteamAsyncIterator")}function te(e){var t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function re(e,t,r){if(!l(r=Number(r)))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ne(e){e._queue=new C,e._queueTotalSize=0}void 0!==V&&Object.setPrototypeOf(Z,V),Object.defineProperty(Z,"next",{enumerable:!1}),Object.defineProperty(Z,"return",{enumerable:!1});var ae=t("[[AbortSteps]]"),oe=t("[[ErrorSteps]]"),ie=function(){function e(e,t){void 0===e&&(e={}),void 0===t&&(t={}),le(this);var r=t.size,n=t.highWaterMark;if(void 0!==e.type)throw new RangeError("Invalid type is specified");var a=m(r);void 0===n&&(n=1),function(e,t,r,n){var a=Object.create(Ee.prototype),o=d(t,"write",1,[a]),i=d(t,"close",0,[]),s=d(t,"abort",1,[]);Ne(e,a,function(){return h(t,"start",[a])},o,i,s,r,n)}(this,e,n=f(n),a)}return Object.defineProperty(e.prototype,"locked",{get:function(){if(!1===ce(this))throw Oe("locked");return ue(this)},enumerable:!0,configurable:!0}),e.prototype.abort=function(e){return!1===ce(this)?_(Oe("abort")):!0===ue(this)?_(new TypeError("Cannot abort a stream that already has a writer")):de(this,e)},e.prototype.close=function(){return!1===ce(this)?_(Oe("close")):!0===ue(this)?_(new TypeError("Cannot close a stream that already has a writer")):!0===ge(this)?_(new TypeError("Cannot close an already-closing stream")):he(this)},e.prototype.getWriter=function(){if(!1===ce(this))throw Oe("getWriter");return se(this)},e}();function se(e){return new be(e)}function le(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new C,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function ce(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")}function ue(e){return void 0!==e._writer}function de(e,t){var r=e._state;if("closed"===r||"errored"===r)return A(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;var n=!1;"erroring"===r&&(n=!0,t=void 0);var a=w(function(r,a){e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:a,_reason:t,_wasAlreadyErroring:n}});return e._pendingAbortRequest._promise=a,!1===n&&fe(e,t),a}function he(e){var t=e._state;if("closed"===t||"errored"===t)return _(new TypeError("The stream (in "+t+" state) is not in the writable state and cannot be closed"));var r,n=w(function(t,r){var n={_resolve:t,_reject:r};e._closeRequest=n}),a=e._writer;return void 0!==a&&!0===e._backpressure&&"writable"===t&&je(a),re(r=e._writableStreamController,"close",0),Fe(r),n}function pe(e,t){"writable"!==e._state?me(e):fe(e,t)}function fe(e,t){var r=e._writableStreamController;e._state="erroring",e._storedError=t;var n=e._writer;void 0!==n&&Te(n,t),!1===function(e){return void 0!==e._inFlightWriteRequest||void 0!==e._inFlightCloseRequest}(e)&&!0===r._started&&me(e)}function me(e){e._state="errored",e._writableStreamController[oe]();var t=e._storedError;if(e._writeRequests.forEach(function(e){e._reject(t)}),e._writeRequests=new C,void 0!==e._pendingAbortRequest){var r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,!0===r._wasAlreadyErroring)return r._reject(t),void ye(e);S(e._writableStreamController[ae](r._reason),function(){r._resolve(),ye(e)},function(t){r._reject(t),ye(e)})}else ye(e)}function ge(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ye(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);var t=e._writer;void 0!==t&&Ue(t,e._storedError)}function ve(e,t){var r=e._writer;void 0!==r&&t!==e._backpressure&&(!0===t?function(e){qe(e)}(r):je(r)),e._backpressure=t}var be=function(){function e(e){if(!1===ce(e))throw new TypeError("WritableStreamDefaultWriter can only be constructed with a WritableStream instance");if(!0===ue(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var t,r=e._state;if("writable"===r)!1===ge(e)&&!0===e._backpressure?qe(this):Ge(this),xe(this);else if("erroring"===r)Ke(this,e._storedError),xe(this);else if("closed"===r)Ge(this),xe(t=this),Me(t);else{var n=e._storedError;Ke(this,n),$e(this,n)}}return Object.defineProperty(e.prototype,"closed",{get:function(){return!1===we(this)?_(Le("closed")):this._closedPromise},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"desiredSize",{get:function(){if(!1===we(this))throw Le("desiredSize");if(void 0===this._ownerWritableStream)throw Be("desiredSize");return function(e){var t=e._ownerWritableStream,r=t._state;return"errored"===r||"erroring"===r?null:"closed"===r?0:Ce(t._writableStreamController)}(this)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ready",{get:function(){return!1===we(this)?_(Le("ready")):this._readyPromise},enumerable:!0,configurable:!0}),e.prototype.abort=function(e){return!1===we(this)?_(Le("abort")):void 0===this._ownerWritableStream?_(Be("abort")):function(e,t){return de(e._ownerWritableStream,t)}(this,e)},e.prototype.close=function(){if(!1===we(this))return _(Le("close"));var e=this._ownerWritableStream;return void 0===e?_(Be("close")):!0===ge(e)?_(new TypeError("Cannot close an already-closing stream")):Ae(this)},e.prototype.releaseLock=function(){if(!1===we(this))throw Le("releaseLock");void 0!==this._ownerWritableStream&&Se(this)},e.prototype.write=function(e){return!1===we(this)?_(Le("write")):void 0===this._ownerWritableStream?_(Be("write to")):ke(this,e)},e}();function we(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")}function Ae(e){return he(e._ownerWritableStream)}function _e(e,t){"pending"===e._closedPromiseState?Ue(e,t):function(e,t){$e(e,t)}(e,t)}function Te(e,t){"pending"===e._readyPromiseState?ze(e,t):function(e,t){Ke(e,t)}(e,t)}function Se(e){var t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Te(e,r),_e(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function ke(e,t){var r=e._ownerWritableStream,n=r._writableStreamController,a=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Pe(e,t),1}}(n,t);if(r!==e._ownerWritableStream)return _(Be("write to"));var o=r._state;if("errored"===o)return _(r._storedError);if(!0===ge(r)||"closed"===o)return _(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===o)return _(r._storedError);var i=function(e){return w(function(t,r){var n={_resolve:t,_reject:r};e._writeRequests.push(n)})}(r);return function(e,t,r){var n={chunk:t};try{re(e,n,r)}catch(t){return void Pe(e,t)}var a=e._controlledWritableStream;!1===ge(a)&&"writable"===a._state&&ve(a,De(e)),Fe(e)}(n,t,a),i}var Ee=function(){function e(){throw new TypeError("WritableStreamDefaultController cannot be constructed explicitly")}return e.prototype.error=function(e){if(!1===function(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")}(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&Re(this,e)},e.prototype[ae]=function(e){var t=this._abortAlgorithm(e);return Ie(this),t},e.prototype[oe]=function(){ne(this)},e}();function Ne(e,t,r,n,a,o,i,s){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ne(t),t._started=!1,t._strategySizeAlgorithm=s,t._strategyHWM=i,t._writeAlgorithm=n,t._closeAlgorithm=a,t._abortAlgorithm=o;var l=De(t);ve(e,l),S(A(r()),function(){t._started=!0,Fe(t)},function(r){t._started=!0,pe(e,r)})}function Ie(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ce(e){return e._strategyHWM-e._queueTotalSize}function Fe(e){var t=e._controlledWritableStream;if(!1!==e._started&&void 0===t._inFlightWriteRequest)if("erroring"!==t._state){if(0!==e._queue.length){var r=e._queue.peek().value;"close"===r?function(e){var t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),te(e);var r=e._closeAlgorithm();Ie(e),S(r,function(){!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";var t=e._writer;void 0!==t&&Me(t)}(t)},function(e){!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),pe(e,t)}(t,e)})}(e):function(e,t){var r=e._controlledWritableStream;(function(e){e._inFlightWriteRequest=e._writeRequests.shift()})(r),S(e._writeAlgorithm(t),function(){!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);var t=r._state;if(te(e),!1===ge(r)&&"writable"===t){var n=De(e);ve(r,n)}Fe(e)},function(t){"writable"===r._state&&Ie(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,pe(e,t)}(r,t)})}(e,r.chunk)}}else me(t)}function Pe(e,t){"writable"===e._controlledWritableStream._state&&Re(e,t)}function De(e){return Ce(e)<=0}function Re(e,t){var r=e._controlledWritableStream;Ie(e),fe(r,t)}function Oe(e){return new TypeError("WritableStream.prototype."+e+" can only be used on a WritableStream")}function Le(e){return new TypeError("WritableStreamDefaultWriter.prototype."+e+" can only be used on a WritableStreamDefaultWriter")}function Be(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function xe(e){e._closedPromise=w(function(t,r){e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"})}function $e(e,t){xe(e),Ue(e,t)}function Ue(e,t){I(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected"}function Me(e){e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved"}function qe(e){e._readyPromise=w(function(t,r){e._readyPromise_resolve=t,e._readyPromise_reject=r}),e._readyPromiseState="pending"}function Ke(e,t){qe(e),ze(e,t)}function Ge(e){qe(e),je(e)}function ze(e,t){I(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected"}function je(e){e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled"}function We(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}var Ve,He="undefined"!=typeof DOMException?DOMException:void 0,Qe=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(He)?He:((Ve=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}).prototype=Object.create(Error.prototype),Object.defineProperty(Ve.prototype,"constructor",{value:Ve,writable:!0,configurable:!0}),Ve);function Xe(e,t,n,a,o,i){var s=q(e),l=se(t);e._disturbed=!0;var c=!1,u=A(void 0);return w(function(d,h){var p,f,m,g;if(void 0!==i){if(p=function(){var r=new Qe("Aborted","AbortError"),n=[];!1===a&&n.push(function(){return"writable"===t._state?de(t,r):A(void 0)}),!1===o&&n.push(function(){return"readable"===e._state?Kt(e,r):A(void 0)}),N(function(){return Promise.all(n.map(function(e){return e()}))},!0,r)},!0===i.aborted)return void p();i.addEventListener("abort",p)}if(b(e,s._closedPromise,function(e){!1===a?N(function(){return de(t,e)},!0,e):C(!0,e)}),b(t,l._closedPromise,function(t){!1===o?N(function(){return Kt(e,t)},!0,t):C(!0,t)}),f=e,m=s._closedPromise,g=function(){!1===n?N(function(){return function(e){var t=e._ownerWritableStream,r=t._state;return!0===ge(t)||"closed"===r?A(void 0):"errored"===r?_(t._storedError):Ae(e)}(l)}):C()},"closed"===f._state?g():k(m,g),!0===ge(t)||"closed"===t._state){var y=new TypeError("the destination writable stream closed before all data could be piped to it");!1===o?N(function(){return Kt(e,y)},!0,y):C(!0,y)}function v(){var e=u;return T(u,function(){return e!==u?v():void 0})}function b(e,t,r){"errored"===e._state?r(e._storedError):E(t,r)}function N(e,r,n){function a(){S(e(),function(){return F(r,n)},function(e){return F(!0,e)})}!0!==c&&(c=!0,"writable"===t._state&&!1===ge(t)?k(v(),a):a())}function C(e,r){!0!==c&&(c=!0,"writable"===t._state&&!1===ge(t)?k(v(),function(){return F(e,r)}):F(e,r))}function F(e,t){Se(l),R(s),void 0!==i&&i.removeEventListener("abort",p),e?h(t):d(void 0)}I(w(function(e,t){!function n(a){a?e():T(!0===c?A(!0):T(l._readyPromise,function(){return T(X(s),function(e){return!0===e.done||(u=T(ke(l,e.value),void 0,r),!1)})}),n,t)}(!1)}))})}var Ye=function(){function e(){throw new TypeError}return Object.defineProperty(e.prototype,"desiredSize",{get:function(){if(!1===Ze(this))throw lt("desiredSize");return ot(this)},enumerable:!0,configurable:!0}),e.prototype.close=function(){if(!1===Ze(this))throw lt("close");if(!1===it(this))throw new TypeError("The stream is not in a state that permits close");rt(this)},e.prototype.enqueue=function(e){if(!1===Ze(this))throw lt("enqueue");if(!1===it(this))throw new TypeError("The stream is not in a state that permits enqueue");return nt(this,e)},e.prototype.error=function(e){if(!1===Ze(this))throw lt("error");at(this,e)},e.prototype[U]=function(e){ne(this);var t=this._cancelAlgorithm(e);return tt(this),t},e.prototype[M]=function(){var e=this._controlledReadableStream;if(this._queue.length>0){var t=te(this);return!0===this._closeRequested&&0===this._queue.length?(tt(this),Gt(e)):Je(this),A(F(t,!1,e._reader._forAuthorCode))}var r=K(e);return Je(this),r},e}();function Ze(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")}function Je(e){!1!==et(e)&&(!0!==e._pulling?(e._pulling=!0,S(e._pullAlgorithm(),function(){e._pulling=!1,!0===e._pullAgain&&(e._pullAgain=!1,Je(e))},function(t){at(e,t)})):e._pullAgain=!0)}function et(e){var t=e._controlledReadableStream;return!1!==it(e)&&!1!==e._started&&(!0===qt(t)&&z(t)>0||ot(e)>0)}function tt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function rt(e){var t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(tt(e),Gt(t))}function nt(e,t){var r=e._controlledReadableStream;if(!0===qt(r)&&z(r)>0)G(r,t,!1);else{var n=void 0;try{n=e._strategySizeAlgorithm(t)}catch(t){throw at(e,t),t}try{re(e,t,n)}catch(t){throw at(e,t),t}}Je(e)}function at(e,t){var r=e._controlledReadableStream;"readable"===r._state&&(ne(e),tt(e),zt(r,t))}function ot(e){var t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function it(e){var t=e._controlledReadableStream._state;return!1===e._closeRequested&&"readable"===t}function st(e,t,r,n,a,o,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ne(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=o,t._pullAlgorithm=n,t._cancelAlgorithm=a,e._readableStreamController=t,S(A(r()),function(){t._started=!0,Je(t)},function(e){at(t,e)})}function lt(e){return new TypeError("ReadableStreamDefaultController.prototype."+e+" can only be used on a ReadableStreamDefaultController")}var ct=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},ut=function(){function e(){throw new TypeError("ReadableStreamBYOBRequest cannot be used directly")}return Object.defineProperty(e.prototype,"view",{get:function(){if(!1===pt(this))throw Ct("view");return this._view},enumerable:!0,configurable:!0}),e.prototype.respond=function(e){if(!1===pt(this))throw Ct("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){if(!1===l(t=Number(t)))throw new RangeError("bytesWritten must be a finite");Tt(e,t)}(this._associatedReadableByteStreamController,e)},e.prototype.respondWithNewView=function(e){if(!1===pt(this))throw Ct("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");e.buffer,function(e,t){var r=e._pendingPullIntos.peek();if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==t.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=t.buffer,Tt(e,t.byteLength)}(this._associatedReadableByteStreamController,e)},e}(),dt=function(){function e(){throw new TypeError("ReadableByteStreamController constructor cannot be used directly")}return Object.defineProperty(e.prototype,"byobRequest",{get:function(){if(!1===ht(this))throw Ft("byobRequest");if(void 0===this._byobRequest&&this._pendingPullIntos.length>0){var e=this._pendingPullIntos.peek(),t=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled),r=Object.create(ut.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(r,this,t),this._byobRequest=r}return this._byobRequest},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"desiredSize",{get:function(){if(!1===ht(this))throw Ft("desiredSize");return Nt(this)},enumerable:!0,configurable:!0}),e.prototype.close=function(){if(!1===ht(this))throw Ft("close");if(!0===this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");!function(e){var t=e._controlledReadableByteStream;if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0&&e._pendingPullIntos.peek().bytesFilled>0){var r=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Et(e,r),r}kt(e),Gt(t)}}(this)},e.prototype.enqueue=function(e){if(!1===ht(this))throw Ft("enqueue");if(!0===this._closeRequested)throw new TypeError("stream is closed or draining");var t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError("The stream (in "+t+" state) is not in the readable state and cannot be enqueued to");if(!ArrayBuffer.isView(e))throw new TypeError("You can only enqueue array buffer views when using a ReadableByteStreamController");e.buffer,function(e,t){var r=e._controlledReadableByteStream,n=t.buffer,a=t.byteOffset,o=t.byteLength,i=n;!0===j(r)?0===z(r)?yt(e,i,a,o):G(r,new Uint8Array(i,a,o),!1):!0===Rt(r)?(yt(e,i,a,o),_t(e)):yt(e,i,a,o),ft(e)}(this,e)},e.prototype.error=function(e){if(!1===ht(this))throw Ft("error");Et(this,e)},e.prototype[U]=function(e){this._pendingPullIntos.length>0&&(this._pendingPullIntos.peek().bytesFilled=0),ne(this);var t=this._cancelAlgorithm(e);return kt(this),t},e.prototype[M]=function(){var e=this._controlledReadableByteStream;if(this._queueTotalSize>0){var t=this._queue.shift();this._queueTotalSize-=t.byteLength,wt(this);var r=void 0;try{r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}catch(e){return _(e)}return A(F(r,!1,e._reader._forAuthorCode))}var n=this._autoAllocateChunkSize;if(void 0!==n){var a=void 0;try{a=new ArrayBuffer(n)}catch(e){return _(e)}var o={buffer:a,byteOffset:0,byteLength:n,bytesFilled:0,elementSize:1,ctor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}var i=K(e);return ft(this),i},e}();function ht(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")}function pt(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")}function ft(e){!1!==function(e){var t=e._controlledReadableByteStream;return"readable"===t._state&&!0!==e._closeRequested&&!1!==e._started&&(!0===j(t)&&z(t)>0||!0===Rt(t)&&Dt(t)>0||Nt(e)>0)}(e)&&(!0!==e._pulling?(e._pulling=!0,S(e._pullAlgorithm(),function(){e._pulling=!1,!0===e._pullAgain&&(e._pullAgain=!1,ft(e))},function(t){Et(e,t)})):e._pullAgain=!0)}function mt(e,t){var r=!1;"closed"===e._state&&(r=!0);var n=gt(t);"default"===t.readerType?G(e,n,r):function(e,t,r){var n=e._reader;n._readIntoRequests.shift()._resolve(F(t,r,n._forAuthorCode))}(e,n,r)}function gt(e){var t=e.bytesFilled,r=e.elementSize;return new e.ctor(e.buffer,e.byteOffset,t/r)}function yt(e,t,r,n){e._queue.push({buffer:t,byteOffset:r,byteLength:n}),e._queueTotalSize+=n}function vt(e,t){var r=t.elementSize,n=t.bytesFilled-t.bytesFilled%r,a=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),o=t.bytesFilled+a,i=o-o%r,s=a,l=!1;i>n&&(s=i-t.bytesFilled,l=!0);for(var c,u,d,h,p,f=e._queue;s>0;){var m=f.peek(),g=Math.min(s,m.byteLength),y=t.byteOffset+t.bytesFilled;c=t.buffer,u=y,d=m.buffer,h=m.byteOffset,p=g,new Uint8Array(c).set(new Uint8Array(d,h,p),u),m.byteLength===g?f.shift():(m.byteOffset+=g,m.byteLength-=g),e._queueTotalSize-=g,bt(e,g,t),s-=g}return l}function bt(e,t,r){At(e),r.bytesFilled+=t}function wt(e){0===e._queueTotalSize&&!0===e._closeRequested?(kt(e),Gt(e._controlledReadableByteStream)):ft(e)}function At(e){void 0!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=void 0,e._byobRequest=void 0)}function _t(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;var t=e._pendingPullIntos.peek();!0===vt(e,t)&&(St(e),mt(e._controlledReadableByteStream,t))}}function Tt(e,t){var r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");!function(e,t){t.buffer=t.buffer;var r=e._controlledReadableByteStream;if(!0===Rt(r))for(;Dt(r)>0;)mt(r,St(e))}(e,r)}else!function(e,t,r){if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range");if(bt(e,t,r),!(r.bytesFilled<r.elementSize)){St(e);var n=r.bytesFilled%r.elementSize;if(n>0){var a=r.byteOffset+r.bytesFilled,o=r.buffer.slice(a-n,a);yt(e,o,0,o.byteLength)}r.buffer=r.buffer,r.bytesFilled-=n,mt(e._controlledReadableByteStream,r),_t(e)}}(e,t,r);ft(e)}function St(e){var t=e._pendingPullIntos.shift();return At(e),t}function kt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Et(e,t){var r=e._controlledReadableByteStream;"readable"===r._state&&(function(e){At(e),e._pendingPullIntos=new C}(e),ne(e),kt(e),zt(r,t))}function Nt(e){var t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function It(e,t,r){var n=Object.create(dt.prototype),a=d(t,"pull",0,[n]),o=d(t,"cancel",1,[]),i=t.autoAllocateChunkSize;if(void 0!==i&&(i=Number(i),!1===ct(i)||i<=0))throw new RangeError("autoAllocateChunkSize must be a positive integer");!function(e,t,r,n,a,o,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=void 0,t._queue=t._queueTotalSize=void 0,ne(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=f(o),t._pullAlgorithm=n,t._cancelAlgorithm=a,t._autoAllocateChunkSize=i,t._pendingPullIntos=new C,e._readableStreamController=t,S(A(r()),function(){t._started=!0,ft(t)},function(e){Et(t,e)})}(e,n,function(){return h(t,"start",[n])},a,o,r,i)}function Ct(e){return new TypeError("ReadableStreamBYOBRequest.prototype."+e+" can only be used on a ReadableStreamBYOBRequest")}function Ft(e){return new TypeError("ReadableByteStreamController.prototype."+e+" can only be used on a ReadableByteStreamController")}function Pt(e){return w(function(t,r){var n={_resolve:t,_reject:r};e._reader._readIntoRequests.push(n)})}function Dt(e){return e._reader._readIntoRequests.length}function Rt(e){var t=e._reader;return void 0!==t&&!!Lt(t)}var Ot=function(){function e(e){if(!Mt(e))throw new TypeError("ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a byte source");if(!1===ht(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");if(qt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");P(this,e),this._readIntoRequests=new C}return Object.defineProperty(e.prototype,"closed",{get:function(){return Lt(this)?this._closedPromise:_(Bt("closed"))},enumerable:!0,configurable:!0}),e.prototype.cancel=function(e){return Lt(this)?void 0===this._ownerReadableStream?_(O("cancel")):D(this,e):_(Bt("cancel"))},e.prototype.read=function(e){return Lt(this)?void 0===this._ownerReadableStream?_(O("read from")):ArrayBuffer.isView(e)?(e.buffer,0===e.byteLength?_(new TypeError("view must have non-zero byteLength")):function(e,t){var r=e._ownerReadableStream;return r._disturbed=!0,"errored"===r._state?_(r._storedError):function(e,t){var r=e._controlledReadableByteStream,n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);var a=t.constructor,o={buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,ctor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(o),Pt(r);if("closed"===r._state)return A(F(new a(o.buffer,o.byteOffset,0),!0,r._reader._forAuthorCode));if(e._queueTotalSize>0){if(!0===vt(e,o)){var i=gt(o);return wt(e),A(F(i,!1,r._reader._forAuthorCode))}if(!0===e._closeRequested){var s=new TypeError("Insufficient bytes to fill elements in the given buffer");return Et(e,s),_(s)}}e._pendingPullIntos.push(o);var l=Pt(r);return ft(e),l}(r._readableStreamController,t)}(this,e)):_(new TypeError("view must be an array buffer view")):_(Bt("read"))},e.prototype.releaseLock=function(){if(!Lt(this))throw Bt("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");R(this)}},e}();function Lt(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")}function Bt(e){return new TypeError("ReadableStreamBYOBReader.prototype."+e+" can only be used on a ReadableStreamBYOBReader")}var xt=function(){function e(e,t){void 0===e&&(e={}),void 0===t&&(t={}),Ut(this);var r=t.size,n=t.highWaterMark,a=e.type;if("bytes"===String(a)){if(void 0!==r)throw new RangeError("The strategy for a byte stream cannot have a size function");void 0===n&&(n=0),It(this,e,n=f(n))}else{if(void 0!==a)throw new RangeError("Invalid type is specified");var o=m(r);void 0===n&&(n=1),function(e,t,r,n){var a=Object.create(Ye.prototype),o=d(t,"pull",0,[a]),i=d(t,"cancel",1,[]);st(e,a,function(){return h(t,"start",[a])},o,i,r,n)}(this,e,n=f(n),o)}}return Object.defineProperty(e.prototype,"locked",{get:function(){if(!1===Mt(this))throw jt("locked");return qt(this)},enumerable:!0,configurable:!0}),e.prototype.cancel=function(e){return!1===Mt(this)?_(jt("cancel")):!0===qt(this)?_(new TypeError("Cannot cancel a stream that already has a reader")):Kt(this,e)},e.prototype.getReader=function(e){var t=(void 0===e?{}:e).mode;if(!1===Mt(this))throw jt("getReader");if(void 0===t)return q(this,!0);if("byob"===(t=String(t)))return function(e,t){var r=new Ot(e);return r._forAuthorCode=t,r}(this,!0);throw new RangeError("Invalid mode is specified")},e.prototype.pipeThrough=function(e,t){var r=e.writable,n=e.readable,a=void 0===t?{}:t,o=a.preventClose,i=a.preventAbort,s=a.preventCancel,l=a.signal;if(!1===Mt(this))throw jt("pipeThrough");if(!1===ce(r))throw new TypeError("writable argument to pipeThrough must be a WritableStream");if(!1===Mt(n))throw new TypeError("readable argument to pipeThrough must be a ReadableStream");if(o=Boolean(o),i=Boolean(i),s=Boolean(s),void 0!==l&&!We(l))throw new TypeError("ReadableStream.prototype.pipeThrough's signal option must be an AbortSignal");if(!0===qt(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(!0===ue(r))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return I(Xe(this,r,o,i,s,l)),n},e.prototype.pipeTo=function(e,t){var r=void 0===t?{}:t,n=r.preventClose,a=r.preventAbort,o=r.preventCancel,i=r.signal;return!1===Mt(this)?_(jt("pipeTo")):!1===ce(e)?_(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")):(n=Boolean(n),a=Boolean(a),o=Boolean(o),void 0===i||We(i)?!0===qt(this)?_(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):!0===ue(e)?_(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Xe(this,e,n,a,o,i):_(new TypeError("ReadableStream.prototype.pipeTo's signal option must be an AbortSignal")))},e.prototype.tee=function(){if(!1===Mt(this))throw jt("tee");var e=function(e){var t,r,n,a,o,i=q(e),l=!1,c=!1,u=!1,d=w(function(e){o=e});function h(){return!0===l||(l=!0,I(N(X(i),function(e){if(l=!1,!0===e.done)return!1===c&&rt(n._readableStreamController),void(!1===u&&rt(a._readableStreamController));var t=e.value,r=t,o=t;!1===c&&nt(n._readableStreamController,r),!1===u&&nt(a._readableStreamController,o)}))),A(void 0)}function p(){}return n=$t(p,h,function(n){if(c=!0,t=n,!0===u){var a=s([t,r]),i=Kt(e,a);o(i)}return d}),a=$t(p,h,function(n){if(u=!0,r=n,!0===c){var a=s([t,r]),i=Kt(e,a);o(i)}return d}),E(i._closedPromise,function(e){at(n._readableStreamController,e),at(a._readableStreamController,e)}),[n,a]}(this);return s(e)},e.prototype.getIterator=function(e){var t=(void 0===e?{}:e).preventCancel,r=void 0!==t&&t;if(!1===Mt(this))throw jt("getIterator");return function(e,t){void 0===t&&(t=!1);var r=q(e),n=Object.create(Z);return n._asyncIteratorReader=r,n._preventCancel=Boolean(t),n}(this,r)},e}();function $t(e,t,r,n,a){void 0===n&&(n=1),void 0===a&&(a=function(){return 1});var o=Object.create(xt.prototype);return Ut(o),st(o,Object.create(Ye.prototype),e,t,r,n,a),o}function Ut(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Mt(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")}function qt(e){return void 0!==e._reader}function Kt(e,t){return e._disturbed=!0,"closed"===e._state?A(void 0):"errored"===e._state?_(e._storedError):(Gt(e),N(e._readableStreamController[U](t),r))}function Gt(e){e._state="closed";var t=e._reader;void 0!==t&&(Q(t)&&(t._readRequests.forEach(function(e){e._resolve(F(void 0,!0,t._forAuthorCode))}),t._readRequests=new C),$(t))}function zt(e,t){e._state="errored",e._storedError=t;var r=e._reader;void 0!==r&&(Q(r)?(r._readRequests.forEach(function(e){e._reject(t)}),r._readRequests=new C):(r._readIntoRequests.forEach(function(e){e._reject(t)}),r._readIntoRequests=new C),x(r,t))}function jt(e){return new TypeError("ReadableStream.prototype."+e+" can only be used on a ReadableStream")}"symbol"==typeof t.asyncIterator&&Object.defineProperty(xt.prototype,t.asyncIterator,{value:xt.prototype.getIterator,enumerable:!1,writable:!0,configurable:!0});var Wt=function(){function e(e){var t=e.highWaterMark;this.highWaterMark=t}return e.prototype.size=function(e){return e.byteLength},e}(),Vt=function(){function e(e){var t=e.highWaterMark;this.highWaterMark=t}return e.prototype.size=function(){return 1},e}(),Ht=function(){function e(e,t,r){void 0===e&&(e={}),void 0===t&&(t={}),void 0===r&&(r={});var n=t.size,a=t.highWaterMark,o=r.size,i=r.highWaterMark;if(void 0!==e.writableType)throw new RangeError("Invalid writable type specified");var s=m(n);if(void 0===a&&(a=1),a=f(a),void 0!==e.readableType)throw new RangeError("Invalid readable type specified");var l,c=m(o);void 0===i&&(i=0),i=f(i),function(e,t,r,n,a,o){function i(){return t}e._writable=function(e,t,r,n,a,o){void 0===a&&(a=1),void 0===o&&(o=function(){return 1});var i=Object.create(ie.prototype);return le(i),Ne(i,Object.create(Ee.prototype),e,t,r,n,a,o),i}(i,function(t){return function(e,t){var r=e._transformStreamController;return!0===e._backpressure?N(e._backpressureChangePromise,function(){var n=e._writable;if("erroring"===n._state)throw n._storedError;return nr(r,t)}):nr(r,t)}(e,t)},function(){return function(e){var t=e._readable,r=e._transformStreamController,n=r._flushAlgorithm();return tr(r),N(n,function(){if("errored"===t._state)throw t._storedError;var e=t._readableStreamController;!0===it(e)&&rt(e)},function(r){throw Xt(e,r),t._storedError})}(e)},function(t){return function(e,t){return Xt(e,t),A(void 0)}(e,t)},r,n),e._readable=$t(i,function(){return function(e){return Zt(e,!1),e._backpressureChangePromise}(e)},function(t){return Yt(e,t),A(void 0)},a,o),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Zt(e,!0),e._transformStreamController=void 0}(this,w(function(e){l=e}),a,s,i,c),function(e,t){var r=Object.create(Jt.prototype),n=function(e){try{return rr(r,e),A(void 0)}catch(e){return _(e)}},a=t.transform;if(void 0!==a){if("function"!=typeof a)throw new TypeError("transform is not a method");n=function(e){return p(a,t,[e,r])}}var o=d(t,"flush",0,[r]);!function(e,t,r,n){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=n}(e,r,n,o)}(this,e);var u=h(e,"start",[this._transformStreamController]);l(u)}return Object.defineProperty(e.prototype,"readable",{get:function(){if(!1===Qt(this))throw or("readable");return this._readable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"writable",{get:function(){if(!1===Qt(this))throw or("writable");return this._writable},enumerable:!0,configurable:!0}),e}();function Qt(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")}function Xt(e,t){at(e._readable._readableStreamController,t),Yt(e,t)}function Yt(e,t){tr(e._transformStreamController),Pe(e._writable._writableStreamController,t),!0===e._backpressure&&Zt(e,!1)}function Zt(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=w(function(t){e._backpressureChangePromise_resolve=t}),e._backpressure=t}var Jt=function(){function e(){throw new TypeError("TransformStreamDefaultController instances cannot be created directly")}return Object.defineProperty(e.prototype,"desiredSize",{get:function(){if(!1===er(this))throw ar("desiredSize");return ot(this._controlledTransformStream._readable._readableStreamController)},enumerable:!0,configurable:!0}),e.prototype.enqueue=function(e){if(!1===er(this))throw ar("enqueue");rr(this,e)},e.prototype.error=function(e){if(!1===er(this))throw ar("error");var t;t=e,Xt(this._controlledTransformStream,t)},e.prototype.terminate=function(){if(!1===er(this))throw ar("terminate");!function(e){var t=e._controlledTransformStream,r=t._readable._readableStreamController;!0===it(r)&&rt(r),Yt(t,new TypeError("TransformStream terminated"))}(this)},e}();function er(e){return!!i(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")}function tr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function rr(e,t){var r=e._controlledTransformStream,n=r._readable._readableStreamController;if(!1===it(n))throw new TypeError("Readable side is not in a state that permits enqueue");try{nt(n,t)}catch(e){throw Yt(r,e),r._readable._storedError}(function(e){return!0!==et(e)})(n)!==r._backpressure&&Zt(r,!0)}function nr(e,t){return N(e._transformAlgorithm(t),void 0,function(t){throw Xt(e._controlledTransformStream,t),t})}function ar(e){return new TypeError("TransformStreamDefaultController.prototype."+e+" can only be used on a TransformStreamDefaultController")}function or(e){return new TypeError("TransformStream.prototype."+e+" can only be used on a TransformStream")}var ir=Object.assign||function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];for(var n=Object(e),a=0,o=t;a<o.length;a++){var i=o[a];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])}return n};void 0!==n&&ir(n,{ReadableStream:xt,WritableStream:ie,ByteLengthQueuingStrategy:Wt,CountQueuingStrategy:Vt,TransformStream:Ht}),e.ByteLengthQueuingStrategy=Wt,e.CountQueuingStrategy=Vt,e.ReadableStream=xt,e.TransformStream=Ht,e.WritableStream=ie,Object.defineProperty(e,"__esModule",{value:!0})}(t)}(0,p.exports)),p.exports),m=d(f);const{ReadableStream:g}=m;var y,v;!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"}(y||(y={}));class b extends Error{constructor(e,t,r){super(t),this.type=e,this.originalError=r,this.name="AuthError"}}class w{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new b(y.SIGNATURE_FAILED,"Message prefix cannot be empty");this.validateWallet()}async generateSignature(){try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,r=await this.wallet.signMessage(t);return{message:t,signature:r,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){throw new b(y.SIGNATURE_FAILED,"Failed to generate signature for authentication",e instanceof Error?e:new Error(String(e)))}}getAddress(){return this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.wallet.address}getPrivateKey(){if(!this.wallet.privateKey)throw new b(y.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 b(y.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`);return`eth|${t}`}async signMessage(e){try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){const t=e instanceof Error?e.message:String(e);throw new b(y.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){try{const r=Date.now(),n=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${r}`,a=await this.wallet.signMessage(n);return{"x-signature":a,"x-address":this.formatAddress(this.wallet.address),"x-message":n,"x-timestamp":r.toString()}}catch(e){throw new b(y.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(e)))}}async signTypedData(e,t,r){try{return await this.wallet.signTypedData(e,t,r)}catch(e){throw new b(y.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 b(y.SIGNATURE_FAILED,"Custom message must be a non-empty string");try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){throw new b(y.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new b(y.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new b(y.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new b(y.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"}(v||(v={}));class A{constructor(e){this.levelPriority={[v.DEBUG]:0,[v.INFO]:1,[v.WARN]:2,[v.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?v.DEBUG:v.INFO)}debug(e,t){this.log(v.DEBUG,e,t)}info(e,t){this.log(v.INFO,e,t)}warn(e,t){this.log(v.WARN,e,t)}error(e,t){this.log(v.ERROR,e,t)}log(e,t,r){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===v.DEBUG&&!this.debugEnabled)return;const n=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,a=this.getConsoleMethod(e);void 0!==r?r instanceof Error?a(`${n} ${t}`,r.message,r.stack):a(`${n} ${t}`,r):a(`${n} ${t}`)}getConsoleMethod(e){switch(e){case v.DEBUG:return console.debug;case v.INFO:return console.info;case v.WARN:return console.warn;case v.ERROR:return console.error;default:return console.log}}child(e){return new A({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[v.DEBUG]>=this.levelPriority[this.minLevel]}}function _(e){if(!e||"object"!=typeof e)return{};const t={};for(const[r,n]of Object.entries(e))null!=n&&("string"==typeof n?t[r]=n:"number"==typeof n||"boolean"==typeof n?t[r]=n.toString():Array.isArray(n)?t[r]=n.join(","):t[r]="object"==typeof n?JSON.stringify(n):String(n));return t}class T{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new A({debug:this.debug,context:"HttpClient"}),this.axios=n.create({baseURL:t.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:t.timeout||3e4,headers:{Accept:"application/json",...t.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:_(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};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 r=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:r,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,r){return this.request({method:"GET",url:e,...t&&{params:t},...r&&{headers:r}})}async post(e,t,r){return this.request({method:"POST",url:e,data:t,...r&&{headers:r}})}async put(e,t,r){return this.request({method:"PUT",url:e,data:t,...r&&{headers:r}})}async delete(e,t,r){return this.request({method:"DELETE",url:e,...t&&{params:t},...r&&{headers:r}})}async patch(e,t,r){return this.request({method:"PATCH",url:e,data:t,...r&&{headers:r}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,r){return await this.auth.signTypedData(e,t,r)}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,r=a.SigningType.SIGN_TYPED_DATA){const n=this.auth.getPrivateKey(),o=new a.SigningClient(n);return await o.sign(e,t,r)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{try{const t=await this.auth.generateSignature();return e.headers||(e.headers={}),e.headers.Sign=t.signature,e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp}),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 S="Token name is required and must be a string",k=e=>`Could not find vault address for token: ${e}`;class E extends Error{constructor(e,t,r){super(e),this.field=t,this.code=r,this.name="ValidationError"}}class N extends Error{constructor(e,t,r){super(e),this.statusCode=t,this.originalError=r,this.name="NetworkError"}}class I extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class C extends Error{constructor(e,t,r){super(e),this.transactionId=t,this.code=r,this.name="TransactionError"}}function F(e,t,r){const{MIN_PAGE:n,MAX_PAGE:a,MIN_LIMIT:o,MAX_LIMIT:i}=r.PAGINATION;if("number"!=typeof e||e<n||e>a)throw new E(`Page must be a number between ${n} and ${a}`,"page","INVALID_PAGE");if("number"!=typeof t||t<o||t>i)throw new E(`Limit must be a number between ${o} and ${i}`,"limit","INVALID_LIMIT")}const P={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function D(e){return"string"==typeof e&&e.trim().length>0}function R(e){return!(!e||"string"!=typeof e)&&(P.ETH_ADDRESS.test(e)||P.BACKEND_ADDRESS.test(e))}function O(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const L=o.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"),B=o.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=o.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),$=o.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),U=o.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),M=o.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"),q=o.z.string().regex(P.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),K=o.z.string().regex(P.ETH_ADDRESS,"Invalid Ethereum address format"),G=o.z.string().refine(e=>P.BACKEND_ADDRESS.test(e)||P.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),z=o.z.string().refine(e=>P.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),j=o.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),W=o.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),V=o.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),H=o.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Q=o.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),X=o.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 Y(e=100){return o.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 Z=Y(100),J=Y(20),ee=Y(20),te=o.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"),re=o.z.string().max(255,"Filename must be at most 255 characters"),ne=o.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),ae=o.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),oe=o.z.string().datetime("Must be a valid ISO 8601 date string"),ie=o.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),se=o.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),le=o.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"),ce=o.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),ue=o.z.object({websiteUrl:Q,telegramUrl:Q,twitterUrl:Q}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),de=o.z.string().min(1,"Token category must not be empty").default("Unit"),he=o.z.string().min(1,"Token collection must not be empty").default("Token"),pe=o.z.object({minFeePortion:j,maxFeePortion:j}),fe=o.z.object({tokenName:L,tokenSymbol:B,tokenDescription:x,tokenImage:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer),o.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:W.default("0"),websiteUrl:Q,telegramUrl:Q,twitterUrl:Q,tokenCategory:de,tokenCollection:he,reverseBondingCurveConfiguration:pe.optional(),privateKey:se.optional()}),me=o.z.object({file:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer)]),tokenName:L}),ge=o.z.enum(["recent","popular"]),ye=o.z.object({tokenName:L.optional(),symbol:B.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),ve=o.z.enum(["NATIVE","MEME"]),be=o.z.enum(["IN","OUT"]),we=o.z.object({from:o.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:o.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:o.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:L}),Ae=o.z.object({tokenName:L,slippageToleranceFactor:o.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:o.z.number().min(0).max(1).optional(),privateKey:se.optional()}),_e=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Te=o.z.object({file:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer)]),name:re,size:te,type:ne}),Se=o.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"),ke=o.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Ee=o.z.union([Se,ke]),Ne=o.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Ie=re.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return _e.includes(t)},`Filename must end with one of: ${_e.join(", ")}`),Ce=o.z.object({page:X,limit:Z}),Fe=o.z.object({page:X,limit:J}),Pe=o.z.object({page:X,limit:ee}),De=o.z.object({page:X,limit:Y(50)}),Re=Ce.extend({type:o.z.enum(["recent","popular"]).optional(),tokenName:o.z.string().min(1).max(50).optional(),search:o.z.string().min(1).max(100).optional()}),Oe=Fe.extend({tokenName:o.z.string().min(1).max(50).optional(),search:o.z.string().min(1).max(100).optional()}),Le=Pe.extend({tradeType:o.z.enum(["BUY","SELL"]).optional(),tokenName:o.z.string().min(1).max(50).optional(),userAddress:o.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:o.z.string().datetime().optional(),endDate:o.z.string().datetime().optional(),sortOrder:o.z.enum(["ASC","DESC"]).default("DESC")}),Be=o.z.object({page:o.z.number().int().min(1),limit:o.z.number().int().min(1),total:o.z.number().int().min(0),totalPages:o.z.number().int().min(0),hasNext:o.z.boolean(),hasPrevious:o.z.boolean()});const xe=o.z.enum(["all","DEFI","ASSET"]),$e=Fe.extend({type:xe.optional(),address:G.optional(),search:U.optional(),tokenName:$.optional()}),Ue=o.z.object({walletAddress:G,amount:V}),Me=o.z.object({address:G.optional(),refresh:o.z.boolean().optional()}),qe=o.z.object({profileImage:o.z.string(),fullName:M,address:G,privateKey:se.optional()}),Ke=o.z.object({file:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer)]),address:G.optional(),privateKey:se.optional()}),Ge=o.z.object({address:G,tokenId:o.z.union([o.z.string(),o.z.object({collection:o.z.string(),category:o.z.string(),type:o.z.string(),additionalKey:o.z.string()}),o.z.object({collection:o.z.string(),category:o.z.string(),type:o.z.string(),additionalKey:o.z.string(),instance:o.z.string()})]).optional(),tokenClassKey:o.z.object({collection:o.z.string(),category:o.z.string(),type:o.z.string(),additionalKey:o.z.string()}).optional(),tokenName:$.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),ze=o.z.enum(["buy","sell"]),je=o.z.enum(["BUY","SELL"]),We=o.z.object({tradeType:ze,tokenAmount:j,vaultAddress:z,userAddress:G,slippageTolerance:j.optional(),deadline:o.z.number().int().positive().optional()}),Ve=o.z.object({tokenSymbol:B,nativeTokenQuantity:j,expectedToken:j,maxAcceptableReverseBondingCurveFee:W.default("0").optional()}),He=o.z.object({tokenSymbol:B,tokenQuantity:j,expectedNativeToken:j,maxAcceptableReverseBondingCurveFee:W.default("0").optional()}),Qe=Pe.extend({tokenName:$.optional()}),Xe=o.z.object({page:o.z.number().int().min(1).max(1e3).default(1).optional(),limit:o.z.number().int().min(1).max(20).default(10).optional()}),Ye=o.z.enum(["NATIVE","MEME"]),Ze=o.z.enum(["IN","OUT"]),Je=o.z.object({type:Ye,method:Ze,vaultAddress:z,amount:j}),et=o.z.object({nativeTokenQuantity:j}),tt=o.z.object({vaultAddress:z}),rt=o.z.object({minFeePortion:j,maxFeePortion:j});function nt(e){return t=>{const r=e.safeParse(t);return{success:r.success,data:r.success?r.data:void 0,errors:r.success?void 0:r.error.errors.map(e=>e.message)}}}const at=nt(L),ot=nt(B),it=nt(x),st=nt(G),lt=nt(z),ct=nt(j),ut=nt(V),dt=nt(M),ht=nt(U),pt=nt($),ft=nt(fe),mt=nt(ue),gt=nt(me),yt=nt(ye),vt=nt($e),bt=nt(Ue),wt=nt(Me),At=nt(qe),_t=nt(Ke),Tt=nt(Ge),St=nt(We),kt=nt(Ve),Et=nt(He),Nt=nt(Qe),It=nt(Xe),Ct=nt(Je),Ft=nt(et),Pt=nt(tt);function Dt(e,t){throw new E(e.join("; "),t,"VALIDATION_ERROR")}function Rt(e){const t=at(e);!t.success&&t.errors&&Dt(t.errors,"tokenName")}function Ot(e){const t=Re.safeParse(e);t.success||Dt(t.error.errors.map(e=>e.message),"pagination")}function Lt(e){const t=yt(e);!t.success&&t.errors&&Dt(t.errors,"options")}function Bt(e){const t=Ct(e);!t.success&&t.errors&&Dt(t.errors,"options")}function xt(e){const t=we.safeParse(e);t.success||Dt(t.error.errors.map(e=>e.message),"options")}function $t(e){const t=G.safeParse(e);if(!t.success)throw new E("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Ut(e,t,r=!0){if(!e||""===e.trim())throw new E(`${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 E(`${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 E(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(n))throw new E(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(n<0)throw new E(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!r&&0===n)throw new E(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var Mt=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=G.safeParse(e);if(!t.success)throw new E(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:$t,validateCheckPoolOptions:Lt,validateGetAmountOptions:Bt,validateGetGraphOptions:xt,validateNumericString:Ut,validatePagination:Ot,validateTokenName:Rt});function qt(e,t){return new E(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Kt(e,t){const r=t||e.charAt(0).toUpperCase()+e.slice(1);return new E(`${r} is required`,e,"REQUIRED_FIELD")}function Gt(e,t,r){const n=r||e.charAt(0).toUpperCase()+e.slice(1);return new E(`${n} must be ${t}`,e,"INVALID_FORMAT")}function zt(e,t,r){return new N(e,t,r)}function jt(e,t){return new I(e,t)}function Wt(e,t,r){return new C(e,t,r)}function Vt(e,t){const r=e,n=Number(r.page)||t.page,a=Number(r.limit)||t.limit,o=r.data,i=Number(r.total)||Number(o?.count)||0;return{page:n,limit:a,total:i,totalPages:Math.ceil(i/a)}}function Ht(e,t){return{hasNext:e<t,hasPrevious:e>1}}function Qt(e,t,r=!1){const n=!0===e.error||200!==e.status,a=r&&!e.data;if(n||a)throw new Error(e.message||t)}const Xt="/launchpad/upload-image",Yt="/launchpad/fetch-pool",Zt="/launchpad/check-pool",Jt="/launchpad/get-graph-data",er="/holders",tr="/launchpad/get-badge/",rr="/trade/",nr="/token/commment",ar="/token/commment",or="/user/profile",ir="/user/profile",sr="/user/token-list",lr="/user/token-hold",cr="/user/transfer-faucets";function ur(e,t){return"string"==typeof e[t]}function dr(e,t){return void 0===e[t]||"string"==typeof e[t]}function hr(e,t){return void 0===e[t]||"number"==typeof e[t]}function pr(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function fr(e){if(!e||"object"!=typeof e)return!1;const t=e;return ur(t,"tokenName")&&hr(t,"from")&&hr(t,"to")&&hr(t,"resolution")}class mr{constructor(e,t=!1){this.http=e,this.logger=new A({debug:t,context:"PoolService"})}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 r=_(t),n=await this.http.get(Yt,r);Qt(n,"Failed to fetch pools",!0);const a=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 r=e.tokens;t=[{...r,createdAt:r.created_at||r.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(n.data),o=n.data.count??n.data.total??0;return{pools:a,total:o,totalPages:e.limit>0?Math.ceil(o/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:r,pageSize:n,...a}=e,o=[];if(r&&r>=t){const e=[];for(let n=t;n<=r;n++)e.push(n);for(let t=0;t<e.length;t+=5){const r=e.slice(t,t+5).map(e=>this.fetchSinglePage({...a,page:e,limit:n}));(await Promise.all(r)).forEach(e=>{o.push(...e.pools)})}return o}let i=t,s=!0;for(;s;){const e=[];for(let t=0;t<5&&s;t++)e.push(i+t);const t=e.map(e=>this.fetchSinglePage({...a,page:e,limit:n})),r=await Promise.all(t);for(const e of r){if(0===e.pools.length){s=!1;break}o.push(...e.pools)}i+=e.length,i>100&&(s=!1)}return o}async fetchPools(e={}){const t=e.page||1,r=e.limit??10;let n;if(0!==r&&Ot({page:t,limit:r}),e.tokenName&&Rt(e.tokenName),"recent"===e.type?n="RECENT":"popular"===e.type&&(n="POPULAR"),r>0&&r<=20){const a=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:r});return{pools:a.pools,page:t,limit:r,total:a.total,totalPages:a.totalPages,hasNext:t<a.totalPages,hasPrevious:t>1}}if(0===r){const t=20,r=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:1,limit:t}),a=[...r.pools];if(r.pools.length>0){const o=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:2,totalPages:r.totalPages>1?r.totalPages:null,pageSize:t});a.push(...o)}return{pools:a,page:1,limit:a.length,total:r.total||a.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const a=Math.ceil(r/20),o=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:20}),i=[...o.pools],s=Math.min(a,o.totalPages-t+1);if(s>1){const r=t+s-1,a=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:t+1,totalPages:r,pageSize:20});i.push(...a)}const l=i.slice(0,r);return{pools:l,page:t,limit:r,total:o.total,totalPages:o.totalPages,hasNext:t<o.totalPages&&l.length<o.total,hasPrevious:t>1}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){Lt(e),e.tokenName&&Rt(e.tokenName);const t=_(e),r=await this.http.get(Zt,t);Qt(r,"Failed to check pool");const n=r.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(!fr(e))throw new E("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:r,to:n,resolution:a}=e;if(Rt(t),!r||!n||!a)throw new E("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:r,to:n,resolution:a};xt(o);const i=_(o),s=await this.http.get(Jt,i);return Qt(s,"Failed to fetch graph data",!0),{dataPoints:s.data}}async fetchTokenDistribution(e){if(!e)throw Kt("tokenName","Token name");Rt(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw new E(k(e),"tokenName","VAULT_NOT_FOUND");const r=encodeURIComponent(t),n=await this.http.get(`${er}/${r}`);Qt(n,"Failed to fetch token distribution",!0);const a=n.data;if(!Array.isArray(a))throw zt("Invalid API response: expected array of holders",n.status);for(const e of a){if(!e.owner||"string"!=typeof e.owner)throw zt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw zt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw zt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const o=a.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:a.map(e=>{const t=new i(e.quantity),r=o.isZero()?0:t.dividedBy(o).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:r}}),totalSupply:o.toFixed(),totalHolders:a.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Kt("tokenName","Token name");Rt(e);const t=await this.http.get(tr,{tokenName:e});return Qt(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:r,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const a=("volume"===r?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return a?.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 gr(e,t={}){const{stringifyFields:r=[],optionalFields:n=[],fieldMappings:a={}}=t,o={};for(const[t,i]of Object.entries(e)){const e=t;if(n.includes(e)&&void 0===i)continue;if(n.includes(e)&&"string"==typeof i&&0===i.trim().length)continue;const s=a[e],l=s?String(s):t;r.includes(e)?o[l]=String(i):o[l]=i}return _(o)}const yr={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class vr{constructor(e,t=!1){this.http=e,this.logger=new A({debug:t,context:"TradeService"})}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ur(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&dr(t,"userAddress")&&hr(t,"page")&&hr(t,"limit")}(e))throw new E("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:r,userAddress:n,page:a=1,limit:o=10,startDate:i,endDate:s,sortOrder:l}=e;if(!D(t))throw new E("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");F(a,o,yr);const c=function(e,t,r){return gr({tokenName:e,page:t,limit:r},{stringifyFields:["page","limit"]})}(t,a,o),u=await this.http.get(rr,c),d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const p=Vt(u,{page:a,limit:o}),f=Ht(p.page,p.totalPages);return{trades:d,...p,...f}}}const br=new A({debug:!1,context:"DateUtils"});function wr(e,t){if(!e)return t||new Date;if(e instanceof Date)return isNaN(e.getTime())?t||new Date:e;try{const r=new Date(e);return isNaN(r.getTime())?(br.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):r}catch(r){return br.warn(`Date parsing error for "${e}":`,r),t||new Date}}const Ar={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class _r{constructor(e,t,r=!1){this.http=e,this.poolService=t,this.logger=new A({debug:r,context:"CommentService"})}async fetchComments(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ur(t,"tokenName")&&hr(t,"page")&&hr(t,"limit")}(e))throw new E("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:r=1,limit:n=10}=e;if(!D(t))throw new E("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");F(r,n,Ar);const a=await this.poolService.resolveTokenNameToVault(t);if(!a)throw qt(t);const o=gr({vaultAddress:a,page:r,limit:n},{stringifyFields:["page","limit"]}),i=await this.http.get(nr,o);Qt(i,"Failed to fetch comments");return{comments:i.data.comments.map(e=>({...e,createdAt:wr(e.createdAt)})),total:i.data.count}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ur(t,"tokenName")&&ur(t,"content")}(e))throw new E("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:r}=e;if(!D(t))throw new E("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>=Ar.CONTENT.MIN_LENGTH&&t.length<=Ar.CONTENT.MAX_LENGTH}(r))throw new E(`Comment content must be between ${Ar.CONTENT.MIN_LENGTH} and ${Ar.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const n=await this.poolService.resolveTokenNameToVault(t);if(!n)throw qt(t);const a={userAddress:this.http.getAddress(),vaultAddress:n,content:r};Qt(await this.http.post(ar,a),"Failed to create comment")}}function Tr(e,t="image",r){const n=new FormData;if("undefined"!=typeof File&&e instanceof File)n.append(t,e);else{if(!Buffer.isBuffer(e))throw Gt("file","a File object (browser) or Buffer (Node.js)");{const a=new Blob([e],{type:"image/png"});n.append(t,a,r)}}return n}const Sr={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 kr(e){return!(!e||"string"!=typeof e)&&Sr.USER_ADDRESS.PATTERN.test(e)}const Er="Update profile";class Nr{constructor(e){this.http=e}async fetchProfile(e){const t=e??this.http.getAddress();if(!kr(t))throw new E("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const r={userAddress:t};return await this.http.get(or,r)}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!t||""===t.trim())try{const r=await this.fetchProfile(e.address);t=r.data?.profileImage||""}catch{t=""}const r={profileImage:t,fullName:e.fullName,userAddress:e.address},n=await this.http.signCustomMessage(Er),a={address:n.address,message:Er,publickey:n.ethereumAddress,sign:n.signature};Qt(await this.http.put(ir,r,a),"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();try{const r=`profile-image-${t}.png`,n=Tr(e.file,"image",r),a=await this.http.request({method:"POST",url:`${Xt}?tokenName=${encodeURIComponent(t)}`,data:n,headers:{}});return Qt(a,"Image upload failed"),"string"==typeof a.data?a.data:""}catch(e){if(e instanceof E)throw e;throw new E(`Profile image upload failed: ${e instanceof Error?e.message:"Unknown error"}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(sr,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(lr,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=1,limit:r=10,search:n,tokenName:a}=e,o={type:"DEFI",address:this.http.getAddress(),page:t,limit:r};return void 0!==n&&(o.search=n),void 0!==a&&(o.tokenName=a),this.fetchTokenList(o)}async buildFetchRequest(e,t,r){this.validateGetTokenListOptions(t);const n={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},a=gr(r.includeType?{...n,type:"all"!==t.type&&t.type?t.type:"DEFI"}:n,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),o=await this.http.get(e,a);Qt(o,r.errorMessage,!0);const i=(s=o.data)?Array.isArray(s)?s:s.token:[];var s;const l=Vt(o,{page:t.page||1,limit:t.limit||10}),c=Ht(l.page,l.totalPages);return{tokens:i,...l,...c}}validateGetTokenListOptions(e){if(F(e.page,e.limit,Sr),void 0!==e.address&&!kr(e.address))throw new E("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>=Sr.SEARCH.MIN_LENGTH&&t.length<=Sr.SEARCH.MAX_LENGTH))throw new E(`Search query must be between ${Sr.SEARCH.MIN_LENGTH} and ${Sr.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,r;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((r=e.tokenName)&&"string"==typeof r&&r.length>=Sr.TOKEN_NAME.MIN_LENGTH&&r.length<=Sr.TOKEN_NAME.MAX_LENGTH))throw new E(`Token name must be between ${Sr.TOKEN_NAME.MIN_LENGTH} and ${Sr.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!kr(e.address))throw new E("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=Sr.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=Sr.PROFILE.FULL_NAME.MAX_LENGTH&&Sr.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new E(`Full name must be between ${Sr.PROFILE.FULL_NAME.MIN_LENGTH} and ${Sr.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!kr(e.address))throw new E("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Ir extends Error{constructor(e,t,r){super(e),this.filename=t,this.mimeType=r,this.name="FileValidationError"}}function Cr(e,t,r){if(!e)throw new Ir("File is required",t,r);if("undefined"!=typeof File&&e instanceof File){const t=Se.safeParse(e);if(!t.success){const r=t.error.errors.map(e=>e.message).join("; ");throw new Ir(r,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Ir("Filename is required when uploading Buffer objects",t,r);const n=ke.safeParse(e);if(!n.success){const e=n.error.errors.map(e=>e.message).join("; ");throw new Ir(e,t,r)}if(t.length>255)throw new Ir(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,r);const a=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!a.includes(r))throw new Ir(`Invalid file type "${r}" is not allowed. Allowed types: ${a.join(", ")}`,t,r);const o=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),i=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!i.includes(o))throw new Ir(`File extension "${o}" is not allowed. Allowed extensions: ${i.join(", ")}`,t,r);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"}}(o);if(s!==r&&"application/octet-stream"!==s)throw new Ir(`File extension "${o}" does not match MIME type "${r}"`,t,r);return}throw new Ir("File must be a File object (browser) or Buffer (Node.js)",t,r)}class Fr{constructor(e,t=!1){this.http=e,this.logger=new A({debug:t,context:"ImageService"})}async uploadImageByTokenName(e){const{tokenName:t,options:r}=e;Rt(t);const n=`${t}.png`;Cr(r.file,n,"image/png");try{const e=`${r.tokenName??t}.png`,n=Tr(r.file,"image",e),a=await this.http.request({method:"POST",url:`${Xt}?tokenName=${encodeURIComponent(r.tokenName??t)}`,data:n,headers:{}});return Qt(a,"Image upload failed"),"string"==typeof a.data?a.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw jt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class Pr{constructor(e,t=!1){this.http=e,this.logger=new A({debug:t,context:"FaucetService"})}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount};Qt(await this.http.post(cr,t),"Faucet transfer failed")}validateTransferFaucetsData(e){if(!kr(e.walletAddress))throw new E("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!Sr.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new E("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class Dr{constructor(e,t=!1){this.http=e,this.poolService=new mr(e,t),this.tradeService=new vr(e,t),this.commentService=new _r(e,this.poolService,t),this.userService=new Nr(e),this.imageService=new Fr(e,t),this.faucetService=new Pr(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 Rt(e)}}const Rr={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var Or;!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"}(Or||(Or={}));class Lr extends Error{constructor(e,t,r){super(e),this.type=t,this.details=r,this.name="TransferError"}}class Br{static validateAmount(e){if(parseFloat(e)<=0)throw new Lr("Transfer amount must be positive",Or.INVALID_AMOUNT,{amount:e})}static validateUniqueKey(e){if(e){if(e.length>Rr.MAX_UNIQUE_KEY_LENGTH)throw new E(`Unique key too long. Maximum length: ${Rr.MAX_UNIQUE_KEY_LENGTH}`);if(!Rr.UNIQUE_KEY_PATTERN.test(e))throw new Lr('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Or.INVALID_AMOUNT,{uniqueKey:e})}}}class xr extends a.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,r,n,a){let o;if("string"==typeof n){const e=n.split("$");if(4!==e.length)throw new Error(`Invalid token class key format: ${n}. Expected format: collection$category$type$additionalKey`);o={collection:e[0],category:e[1],type:e[2],additionalKey:e[3],instance:"0"}}else o={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new xr({from:e,to:t,quantity:r,tokenInstance:o,uniqueKey:a||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,r,n){return new xr({from:e,to:t,quantity:r,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 $r{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},r={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,r,e),domain:t,types:r,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const t=e.replace("0x","");return`eth|${r.ethers.getAddress(`0x${t}`).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){const t=e.split("$");if(4!==t.length)throw new Error(`Invalid token class key format: ${e}. Expected format: collection$category$type$additionalKey`);return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3],instance:"0"}}}function Ur(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new E(`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 E(`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 E("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 E(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}var Mr=Object.freeze({__proto__:null,normalizeToTokenInstanceKey:Ur});function qr(e){return e instanceof Error}function Kr(e){return qr(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 Gr(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}const zr="gala-transfer-successful",jr="token-transfer-successful",Wr="transfer-successful-no-id";class Vr{constructor(e,t,r,n=!1){this.http=e,this.wallet=t,this.tokenResolver=r,this.signatureHelper=new $r(t),this.logger=new A({debug:n,context:"GalaChainService"})}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(1!==t.Status)throw zt(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const r=t.Data.reverseBondingCurveConfiguration,n=r?.minFeePortion??"0",a=r?.maxFeePortion??"0",o=(await import("bignumber.js")).default,i=!new o(n).isZero()||!new o(a).isZero(),s=t.Data;return s.reverseBondingCurveMinFeePortion=n,s.reverseBondingCurveMaxFeePortion=a,s.hasReverseBondingCurveFee=i,s.isGraduated="Completed"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(1!==e.Status)throw zt(`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 E("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new E("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new E("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(1!==t.Status||!t.Data||0===t.Data.length)return null;const r=t.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!r||"0"===r.quantity)return null;const n=`${r.collection}|${r.category}|${r.additionalKey}|${r.type}`;return{quantity:r.quantity,collection:r.collection,category:r.category,tokenId:n}}catch(e){throw zt(`Failed to fetch token balance from GalaChain: ${Kr(e)}`,void 0,qr(e)?e:void 0)}}async transferGala(e){this.validateTransferGalaData(e);try{const t=O(e.recipientAddress),r=O(this.wallet.address),n=xr.forGALA(r,t,e.amount,e.uniqueKey),a=await this.signatureHelper.signTransferToken(n.toSigningPayload()),o=new xr({...n.toSigningPayload(),signedPayload:a});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(o,null,2));const i=await this.http.post("/api/asset/token-contract/TransferToken",o);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(i,null,2)),this.extractTransactionIdFromResponse(i,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){this.validateTransferTokenData(e);try{const t=O(e.to),r=O(this.wallet.address);let n;if(e.tokenId)n=Ur(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 Lr("Must provide either tokenId or tokenName for token identification",Or.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const a=new xr({from:r,to:t,quantity:e.amount,tokenInstance:n,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),o=await this.signatureHelper.signTransferToken(a.toSigningPayload()),i=new xr({...a.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(i,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",i);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 Lr)throw t;throw new Lr(`Failed to resolve token class key for '${e}': ${t instanceof Error?t.message:String(t)}`,Or.TOKEN_NOT_FOUND,{tokenName: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 E("Invalid GALA transfer data: missing required fields");if(!R(e.recipientAddress))throw new Lr("Invalid recipient address format",Or.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Br.validateAmount(e.amount),Br.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 E("Invalid token transfer data: missing required fields");if(!R(e.to))throw new Lr("Invalid recipient address format",Or.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Lr("Must provide either tokenId or tokenName for token identification",Or.TOKEN_NOT_FOUND);if(e.tokenName&&!Rr.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Lr("Invalid token name format",Or.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Br.validateAmount(e.amount),Br.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Lr(`Token '${e}' not found or not available for transfer`,Or.TOKEN_NOT_FOUND,{tokenName:e});const r=this.resolveTokenInstanceFromVaultAddress(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}':\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(r,null,2)}`),r}catch(t){if(t instanceof Lr)throw t;throw new Lr(`Failed to resolve token '${e}': ${t instanceof Error?t.message:String(t)}`,Or.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){const[t,r]=e.split("|");if(!r)throw new Lr(`Invalid vault address format: missing token components. Address: ${e}`,Or.TOKEN_NOT_FOUND);const n=r.split("$");if(n.length<4)throw new Lr(`Invalid vault address format: insufficient token components. Expected 4+, got ${n.length}. Address: ${e}`,Or.TOKEN_NOT_FOUND);return{collection:n[0],category:n[1],type:n[2],additionalKey:n[3],instance:"0"}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const r=e;return Array.isArray(r.Data)&&r.Data.length>0?"gala"===t?zr:jr:Wr}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Lr("Transfer succeeded but transaction ID could not be extracted",Or.NETWORK_ERROR)}handleTransferError(e,t,r){if(e instanceof Lr)return e;if(e instanceof E)return new Lr(e.message,Or.INVALID_AMOUNT);if(Gr(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t)return new Lr(("string"==typeof n?.message?n.message:void 0)||"Invalid transfer request",Or.INVALID_AMOUNT);if(403===t)return new Lr("Insufficient balance for transfer",Or.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in r&&(e.tokenName=r.tokenName),new Lr("Token not found",Or.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new Lr("Transfer request timed out",Or.NETWORK_ERROR);const n=Kr(e);return new Lr(n||t,Or.NETWORK_ERROR)}}class Hr{constructor(e,t=!1){this.http=e,this.logger=new A({debug:t,context:"DexService"})}async fetchTokenSpotPrice(e){if(!e||Array.isArray(e)&&0===e.length)throw Kt("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.http.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),r=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&r.push({symbol:e.symbol,price:e.currentPrices.usd})}),r}catch(e){throw zt(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`)}}async fetchLaunchpadTokenSpotPrice(e,t){if(!e||"string"!=typeof e)throw new Error(S);try{const r=await t({tokenName:e,amount:"1",type:"native"}),n=(await this.fetchTokenSpotPrice("GALA"))[0];if(!n)throw zt("GALA price not available");const a=Number(r.amount)/1e18;if(a<=0)throw new E(`Invalid token amount calculation: ${a}`,"amount","INVALID_CALCULATION");const o=n.price/a;return{symbol:e.toUpperCase(),price:o}}catch(t){if(t instanceof Error)throw zt(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw zt(`Failed to calculate launchpad token spot price for ${e}: ${String(t)}`)}}}function Qr(e,t=18){const r=parseFloat(e);if(0===r)return"0";return r.toFixed(t).replace(/\.?0+$/,"")}function Xr(e){return Qr(e,8)}function Yr(e){return Qr(e,18)}function Zr(e){return{maxAcceptableReverseBondingCurveFee:Xr(e.maxAcceptableReverseBondingCurveFee)}}new A({debug:!1,context:"NumberUtils"});class Jr extends a.ChainCallDTO{constructor(e,t,r="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Xr(t),this.expectedToken=Yr(r),this.extraFees=Zr(n)}}class en extends a.ChainCallDTO{constructor(e,t,r,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Yr(t),this.expectedNativeToken=Xr(r),this.extraFees=Zr(n)}}class tn extends a.ChainCallDTO{constructor(e,t,r="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Yr(t),this.expectedNativeToken=Xr(r),this.extraFees=Zr(n)}}class rn extends a.ChainCallDTO{constructor(e,t,r,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Xr(t),this.expectedToken=Yr(r),this.extraFees=Zr(n)}}const nn={BuyNativeDto:Jr,BuyExactDto:en,SellExactDto:tn,SellNativeDto:rn};var an,on,sn;!function(e){e[e.METAMASK=0]="METAMASK",e[e.TRUST_WALLET=1]="TRUST_WALLET",e[e.GALA_WALLET=2]="GALA_WALLET"}(an||(an={}));class ln{constructor(e,t=!1){this.walletProvider=e,this.debug=t,this.logger=new A({debug:t,context:"SignatureService"})}async signDTO(e,t,r,n=an.METAMASK){try{this.logger.debug("๐Ÿ” Signing DTO:",{methodName:t,walletPreference:n,dtoKeys:Object.keys(e)});const o=this.generateEIP712Types(t,e),i=a.calculatePersonalSignPrefix(e),s={...e,prefix:i};let l,c,u;switch(n){case an.GALA_WALLET:({signature:l,domain:c}=await this.signWithGalaWallet(o,s,t,r));break;case an.TRUST_WALLET:l=await this.signWithTrustWallet(s),c={name:"ethereum",chainId:1};break;case an.METAMASK:default:({signature:l,domain:c}=await this.signWithMetaMask(o,s))}return u=n===an.TRUST_WALLET?{...s,signature:l}:{...e,signature:l,types:o,domain:c},this.logger.debug("โœ… DTO signed successfully:",{payloadKeys:Object.keys(u),signatureLength:l.length}),u}catch(e){this.logger.error("โŒ Signature generation failed:",e);throw Wt(`Failed to sign DTO: ${Kr(e)}`)}}async signWithMetaMask(e,t){try{let r,n;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)r={name:"ethereum",chainId:1},n=await this.walletProvider.signTypedData(r,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw jt("Wallet provider does not support typed data signing","walletProvider");{const a=await this.walletProvider.getNetwork();r={name:a.name,chainId:Number(a.chainId)},n=await this.walletProvider.signTypedData(r,e,t)}}return{signature:n,domain:r}}catch(e){throw Wt(`MetaMask/ethers signing failed: ${Kr(e)}`)}}async signWithTrustWallet(e){try{const r=(t=e,JSON.stringify(t));let n;if(!this.walletProvider.signMessage)throw jt("Wallet provider does not support signMessage","walletProvider");return n=await this.walletProvider.signMessage(r),n}catch(e){throw Wt(`TrustWallet signing failed: ${Kr(e)}`)}var t}async signWithGalaWallet(e,t,r,n){try{const a={name:"ethereum",chainId:1};if("undefined"==typeof window)return this.logger.warn("โš ๏ธ GalaWallet not available in Node.js environment, falling back to ethers.js signing"),await this.signWithMetaMask(e,t);const o={domain:a,types:e,message:t,Primary_type:r},i=window;if(!i.gala)throw jt("GalaWallet not found in window object","galaWallet");await i.gala.setAddress(n);return{signature:await i.gala.request({method:"eth_signTypedData",params:[JSON.stringify(o),n]}),domain:a}}catch(e){throw Wt(`GalaWallet signing failed: ${Kr(e)}`)}}generateEIP712Types(e,t){const r={};r[e]=[];const n=(e,t,a,o=!1)=>{if(void 0!==t){if(Array.isArray(t)){const i=n(e,t[0],a,!0);return o||r[a].push({name:e,type:(i??e)+"[]"}),i?i+"[]":void 0}if("object"==typeof t&&null!==t){if(r[e])throw new E(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return r[e]=[],Object.entries(t).forEach(([t,r])=>{n(t,r,e)}),o||r[a].push({name:e,type:e}),e}{let n;switch(typeof t){case"string":n="string";break;case"number":n="uint256";break;case"boolean":n="bool";break;default:throw new E(`Unsupported type for fieldName ${e}: ${typeof t}, value: ${t}`,"fieldValue","UNSUPPORTED_TYPE")}return o||r[a].push({name:e,type:n}),n}}};return Object.entries(t).forEach(([t,r])=>{n(t,r,e)}),this.logger.debug("๐Ÿ“ Generated EIP-712 types:",r),r}detectWalletPreference(){if("undefined"==typeof window)return an.METAMASK;const e=window;return e.gala?an.GALA_WALLET:e.trustWallet?.isTrust?an.TRUST_WALLET:(e.ethereum,an.METAMASK)}}class cn{constructor(e=!1){this.debug=e,this.logger=new A({debug:e,context:"TokenClassKeyService"})}generateStringsInstructions(e){try{this.logger.debug("๐Ÿ”ง Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),r=this.createTokenInstance(t),n=this.createGalaInstance(),a=`$service$${r.toStringKey()}$launchpad`,o=`$tokenBalance$${r.toStringKey()}$${e}`,i=`$tokenBalance$${r.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,l=[a,o,i,s,`$tokenBalance$${n.toStringKey()}$${e}`];return this.logger.debug("โœ… Generated stringsInstructions:",l),l}catch(e){this.logger.error("โŒ Failed to generate stringsInstructions:",e);const t=Kr(e);throw new E(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new s.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 s.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 Kt("vaultAddress","Vault address");const t=e.split("$");if(t.length<3)throw Gt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");const r=t[2];if(!r||0===r.trim().length)throw new E(`Empty token symbol in vault address: ${e}`,"vaultAddress","EMPTY_TOKEN_SYMBOL");return this.logger.debug("๐Ÿ” Extracted token symbol:",{vaultAddress:e,tokenSymbol:r,parts:t.slice(0,4)}),r}validateVaultAddress(e){if(!e||"string"!=typeof e)throw Kt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Gt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Gt("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw Gt("vaultAddress",'having at least 5 parts separated by "$"');const r=t[2];if(!r||!/^[A-Za-z]{1,10}$/.test(r))throw Gt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("โœ… Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,r,n){return`${e}$${t}$${r}$${n}`}parseTokenClassKeyString(e){const t=e.split("$");if(4!==t.length)throw Gt("stringKey","format: collection$category$type$additionalKey (4 parts)");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}}function un(e,t,r){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 a=n.multipliedBy(t);let o;switch(r){case"buy-native":case"sell-exact":o=n.minus(a);break;case"buy-exact":case"sell-native":o=n.plus(a);break;default:throw new Error(`Unknown operation type: ${r}`)}return o.isLessThan(0)&&(o=new i(0)),o.toFixed()}class dn{constructor(e,t,r=!1,n,a,o=.05,i=.01){this.httpClient=e,this.tokenResolver=t,this.walletProvider=n,this.userAddress=a,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=i,this.bundleEndpoint="/bundle",this.logger=new A({debug:r,context:"BundleService"}),n&&a&&(this.signatureService=new ln(n,r),this.tokenKeyService=new cn(r))}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 r=await this.httpClient.post(this.bundleEndpoint,t);return this.logger.debug("๐Ÿ“ฅ Bundle API response:",{success:r.success,hasData:!!r.data,error:r.error}),this.handleBundleResponse(r)}catch(e){return this.logger.error("โŒ Bundle transaction submission failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}validateBundleData(e){if(!e)throw Kt("bundleData","Bundle data");if(!e.signedDto)throw Kt("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw Kt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Gt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new E("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Gt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new E(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new E(`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(Gr(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 Kr(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw Kt("transactionId","Transaction ID");this.logger.debug("๐Ÿ” Checking bundler transaction result:",e);const t=await this.httpClient.get(`${this.bundleEndpoint}?id=${e}`);return this.logger.debug("๐Ÿ“Š Bundler transaction result:",t),{success:!0,data:t}}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 Kt("transactionId","Transaction ID");this.logger.debug("๐Ÿšซ Cancelling transaction:",e);const t=await this.httpClient.delete(`${this.bundleEndpoint}/${e}`);return this.logger.debug("๐Ÿ—‘๏ธ Transaction cancellation response:",t),{success:!0,data:t}}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.httpClient.get(`${this.bundleEndpoint}/health`);return this.logger.debug("๐Ÿ’š Bundle service health:",e),{success:!0,data:e}}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:r,type:n,expectedAmount:a}=e,{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===n){if(!a)throw new E("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=un(a,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:a,slippageFactor:o,adjustedMinTokens:e});const t=new nn.BuyNativeDto(s,r,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",s)}{if(!a)throw new E("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=un(a,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:a,slippageFactor:o,adjustedMaxGalaCost:e});const t=new nn.BuyExactDto(s,r,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyExactToken",s)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:r,type:n,expectedAmount:a}=e,{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===n){if(!a)throw new E("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=un(a,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:a,slippageFactor:o,adjustedMinGala:e});const t=new nn.SellExactDto(s,r,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellExactToken",s)}{if(!a)throw new E("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=un(a,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:a,slippageFactor:o,adjustedMaxTokensToSell:e});const t=new nn.SellNativeDto(s,r,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellWithNative",s)}}async prepareTradingOperation(e,t,r,n){const{effectiveSlippageFactor:a,effectiveMaxFee:o}=this.calculateEffectiveSlippage(t,r,n),i=await this.resolveTokenNameToVault(e);if(!i)throw qt(e);return{effectiveSlippageFactor:a,effectiveMaxFee:o,vaultAddress:i}}calculateEffectiveSlippage(e,t,r){const n=r??this.defaultSlippageToleranceFactor,a=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let o=e||"0";return e&&(o=un(e,a,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:a,adjustedMaxFee:o})),{effectiveSlippageFactor:n,effectiveFeeSlippageFactor:a,effectiveMaxFee:o}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw jt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw Kt("userAddress","User address")}async executeBundleTransaction(e,t,r){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${l.v4()}-${Date.now()}-${this.userAddress}`;const n=await this.signatureService.signDTO(e,t,this.userAddress),a=this.tokenKeyService.generateStringsInstructions(r),o={stringsInstructions:a,method:t,signedDto:n};this.logger.debug("๐Ÿ“ฆ Bundle transaction data:",{method:t,stringsInstructions:a,dtoKeys:Object.keys(n)});const i=await this.submitTransaction(o);if(i.success&&i.data)return this.logger.debug("โœ… Bundle transaction submitted:",i.data),{success:!0,data:{transactionId:i.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(i.error||"Bundle transaction failed"))}catch(e){throw this.logger.error("โŒ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(on||(on={})),e.SDKTransactionStatus=void 0,(sn=e.SDKTransactionStatus||(e.SDKTransactionStatus={})).PENDING="pending",sn.PROCESSING="processing",sn.COMPLETED="completed",sn.FAILED="failed",sn.TIMEOUT="timeout";const hn={[on.PROCESSED]:e.SDKTransactionStatus.COMPLETED,[on.COMPLETED]:e.SDKTransactionStatus.COMPLETED,[on.SUCCESS]:e.SDKTransactionStatus.COMPLETED,[on.FAILED]:e.SDKTransactionStatus.FAILED,[on.ERROR]:e.SDKTransactionStatus.FAILED,[on.PROCESSING]:e.SDKTransactionStatus.PROCESSING,[on.PENDING]:e.SDKTransactionStatus.PENDING};class pn{constructor(e,t=!1){this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.reconnectCount=0,this.hasOnAnyListener=!1,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.logger=new A({debug:t,context:"WebSocketService"}),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.debug&&(this.socket.onAny((e,...t)=>{this.logger.debug(`๐Ÿ“ก [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0)}catch(e){t(e)}})}async monitorTransaction(t,r){this.listeners.set(t,r),this.logger.debug(`๐Ÿ“ก Starting to monitor transaction: ${t}`),this.logger.debug(`๐Ÿ“ก WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=setTimeout(()=>{if(this.listeners.has(t)){const n={transactionId:t,status:e.SDKTransactionStatus.TIMEOUT,message:"Transaction monitoring timeout - no response after 60 seconds",timestamp:Date.now()};this.logger.debug(`๐Ÿ“ก Transaction timeout for ${t}`),r(n),this.listeners.delete(t),this.timeouts.delete(t),this.socket?.off(t)}},6e4);if(this.timeouts.set(t,n),this.socket&&this.socket.connected)this.socket.off(t),this.logger.debug(`๐Ÿ“ก Listening for transaction updates: ${t}`),this.logger.debug(`๐Ÿ“ก WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`๐Ÿ“ก WebSocket URL: ${this.config.url}`),this.socket.on(t,n=>{this.logger.debug(`๐Ÿ“ก Socket.IO transaction update for ${t}:`,JSON.stringify(n,null,2));const a=n,o=a?.data,i=a?.status||a?.Status||o?.status||o?.Status;let s=a?.message||a?.Message||o?.message||o?.Message||a?.error||o?.error;s&&"string"==typeof s||(s=i===on.FAILED||i===on.ERROR?"Transaction failed - check transaction details":i===on.COMPLETED||i===on.PROCESSED||i===on.SUCCESS?"Transaction completed successfully":i?`Transaction status: ${i}`:"Unknown transaction status");const l=a?.blockHash||o?.blockHash,c=a?.gasUsed||o?.gasUsed,u={transactionId:t,status:this.mapSocketStatus(i),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...l&&{blockHash:l},...c&&{gasUsed:c}};if(this.logger.debug(`๐Ÿ“ก Mapped status for ${t}: ${i} -> ${u.status}`),this.logger.debug(`๐Ÿ“ก Final message: "${s}"`),r(u),u.status===e.SDKTransactionStatus.COMPLETED||u.status===e.SDKTransactionStatus.FAILED){this.listeners.delete(t);const e=this.timeouts.get(t);e&&(clearTimeout(e),this.timeouts.delete(t)),this.socket?.off(t),this.logger.debug(`๐Ÿ“ก Cleaned up listener for ${t} (${u.status})`)}});else{const n={transactionId:t,status:e.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};r(n),this.listeners.delete(t),this.timeouts.delete(t)}}async waitForTransaction(t){return new Promise((r,n)=>{this.monitorTransaction(t,t=>{t.status===e.SDKTransactionStatus.COMPLETED?r(t):t.status!==e.SDKTransactionStatus.FAILED&&t.status!==e.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${t.status}: ${t.message}`))})})}mapSocketStatus(t){const r=t?.toUpperCase();return hn[r]||e.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.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}}class fn{constructor(e,t=!1){this.poolService=e,this.cache=new Map,this.logger=new A({debug:t,context:"TokenResolverService"})}async resolveTokenToVault(e){if(!D(e))throw new E("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");const t=e.trim().toLowerCase(),r=this.get(t);if(r)return r;try{const r=await this.poolService.resolveTokenNameToVault(e);return r&&this.set(t,r),r}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw qt(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:r}of e)this.set(t,r)}parseVaultAddressToTokenClassKey(e){const t=e.split("|");if(2!==t.length)throw Gt("vaultAddress","format: service|Token$Unit$...$launchpad","Vault address");const r=t[1].split("$");if(r.length<4)throw Gt("vaultAddress","at least 4 parts after service|","Vault address");return{collection:r[0],category:r[1],type:r[2],additionalKey:r[3]}}}class mn{}mn.BASE_PRICE=1650667151e-14,mn.PRICE_SCALING_FACTOR=1166069e-12,mn.TRADING_FEE_FACTOR=.001,mn.GAS_FEE="1",mn.MIN_UNBONDING_FEE_FACTOR=0,mn.MAX_UNBONDING_FEE_FACTOR=.5,mn.NET_UNBONDING_FEE_FACTOR=.5,mn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class gn{constructor(e=!1){this.cache=new Map,this.logger=new A({debug:e,context:"TokenMetadataCache"})}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 r=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=gn.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...r||{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const r=this.normalizeTokenName(e);this.updateCacheEntry(r,t)}set(e,t){const r=this.normalizeTokenName(e);this.updateCacheEntry(r,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),r=this.cache.get(t);return r?.maxSupply||mn.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,r)=>{e[r]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((r,n)=>{r.lastUpdated<e&&(e=r.lastUpdated);let a=0;a+=2*n.length,void 0!==r.reverseBondingCurveMinFeeFactor&&(a+=8),void 0!==r.reverseBondingCurveMaxFeeFactor&&(a+=8),void 0!==r.reverseBondingCurveNetFeeFactor&&(a+=8),a+=8,r.vaultAddress&&(a+=2*r.vaultAddress.length),r.maxSupply&&(a+=2*r.maxSupply.length),a+=32,t+=a}),{totalTokens:this.cache.size,cacheSize:t,oldestEntry:this.cache.size>0?e:0}}}function yn(e){const t=function(e){const t=ft(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")}`)}gn.MAX_CACHE_SIZE=1e4;const vn="/api/asset/launchpad-contract/CallNativeTokenIn",bn="/api/asset/launchpad-contract/CallNativeTokenOut",wn="/api/asset/launchpad-contract/CallMemeTokenIn",An="/api/asset/launchpad-contract/CallMemeTokenOut";class _n extends a.ChainCallDTO{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,this.websiteUrl=e.websiteUrl,this.telegramUrl=e.telegramUrl,this.twitterUrl=e.twitterUrl,this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function Tn(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 Sn={NATIVE:"native",EXACT:"exact"},kn={LOCAL:"local",EXTERNAL:"external"};class En{static calculateBuyWithExact(e,t){const r=parseFloat(e),n=parseFloat(t),{BASE_PRICE:a,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:l}=mn,c=this.roundUp(a*(Math.exp((n+r)*o)-Math.exp(n*o))/o,8),u=new i(c).multipliedBy(s).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:l}}static calculateBuyWithNative(e,t){const r=parseFloat(e),n=parseFloat(t),{BASE_PRICE:a,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:l}=mn,c=Math.log(r*o/a+Math.exp(n*o))/o-n,u=new i(c).multipliedBy(s).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:l}}static calculateSellWithExact(e,t,r,n,a){const o=parseFloat(e),s=parseFloat(t),l=parseFloat(r),{BASE_PRICE:c,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=mn,p=c*(Math.exp(s*u)-Math.exp((s-o)*u))/u,f=new i(p),m=n+s/l*(a-n),g=f.multipliedBy(m).toFixed(8,i.ROUND_UP),y=f.multipliedBy(d).toFixed();return{amount:p.toString(),reverseBondingCurveFee:g,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,r,n,a){const o=parseFloat(e),s=parseFloat(t),l=parseFloat(r),{BASE_PRICE:c,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=mn,p=s-Math.log(Math.exp(s*u)-o*u/c)/u,f=new i(o),m=n+s/l*(a-n),g=f.multipliedBy(m).toFixed(8,i.ROUND_UP),y=f.multipliedBy(d).toFixed();return{amount:p.toString(),reverseBondingCurveFee:g,transactionFee:y,gasFee:h}}static roundUp(e,t){const r=Math.pow(10,t);return Math.ceil(e*r)/r}}class Nn{constructor(e,t,r,n,a,o,i="local"){this.http=e,this.tokenResolver=t,this.logger=r,this.bundleHttp=n,this.galaChainHttp=a,this.dexApiHttp=o,this.defaultCalculateAmountMode=i,this.metadataCache=new gn}addIfDefined(e,t,r){return void 0!==r&&(e[t]=r),e}async uploadImageByTokenName(e){const{tokenName:t,options:r}=e;Rt(t);const n=`${t}.png`;Cr(r.file,n,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&r.file instanceof File)e.append("image",r.file);else{if(!Buffer.isBuffer(r.file))throw Gt("file","a File object (browser) or Buffer (Node.js)");{const n=`${r.tokenName||t}.png`,a=new Blob([r.file],{type:"image/png"});e.append("image",a,n)}}const n=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(r.tokenName||t)}`,data:e,headers:{}});if(!0===n.error||200!==n.status||!n.data?.imageUrl)throw zt(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 jt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){Ot(e),e.tokenName&&Rt(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 r=_(t),n=await this.http.get("/launchpad/fetch-pool",r);if(!0===n.error||200!==n.status||!n.data)throw zt(n.message||"Failed to fetch pools",n.status);let a=[];const o=(await import("bignumber.js")).default;if(n.data.tokens)if(Array.isArray(n.data.tokens))a=n.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",r=e.reverseBondingCurveMaxFeePortion??"0",n=!new o(t).isZero()||!new o(r).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:r,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}});else{const e=n.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",r=e.reverseBondingCurveMaxFeePortion??"0",i=!new o(t).isZero()||!new o(r).isZero();a=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:r,hasReverseBondingCurveFee:i,createdAt:e.created_at||e.createdAt||""}]}else n.data.pools&&Array.isArray(n.data.pools)&&(a=n.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",r=e.reverseBondingCurveMaxFeePortion??"0",n=!new o(t).isZero()||!new o(r).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:r,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:i,isValidPoolForCaching:s}=await Promise.resolve().then(function(){return Un});a.forEach(e=>{if(!s(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=i(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const l=n.data.count??n.data.total??0,c=n.data.page??e.page??1,u=n.data.limit??e.limit??10,d=u>0?Math.ceil(l/u):1;return{pools:a,page:c,limit:u,total:l,totalPages:d,hasNext:c<d,hasPrevious:c>1}}async _getAmount(e){if(Bt(e),!this.galaChainHttp)throw jt("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:r}=((e,t,r,n)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:vn,body:{vaultAddress:r,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:bn,body:{vaultAddress:r,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:wn,body:{vaultAddress:r,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:An,body:{vaultAddress:r,nativeTokenQuantity:n,IsPreMint:!1}};throw Gt("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,r);if(!Tn(e))throw zt("Malformed response data from GalaChain gateway");if(1!==e.Status)throw zt(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:n,extraFees:a}=e.Data;return{amount:n,reverseBondingCurveFee:a.reverseBondingCurve,transactionFee:a.transactionFees,gasFee:"1"}}catch(n){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:r,error:n instanceof Error?n.message:n}),n}}async checkPool(e){Lt(e),e.tokenName&&Rt(e.tokenName);const t=_(e),r=await this.http.get("/launchpad/check-pool",t);if(!0===r.error||200!==r.status)throw zt(r.message||"Failed to check pool",r.status);const n=r.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.exists??!1}async fetchVolumeData(e){if(!fr(e))throw new E("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:r,to:n,resolution:a}=e;if(Rt(t),!r||!n||!a)throw new E("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:r,to:n,resolution:a};xt(o);const i=_(o),s=await this.http.get("/launchpad/get-graph-data",i);if(!0===s.error||200!==s.status||!s.data)throw zt(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 r={page:e.page||1,limit:e.limit||10};return e.search&&(r.search=e.search),e.tokenName&&(r.tokenName=e.tokenName),t&&(r.type=t),this.fetchPoolsFromAPI(r)}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 E("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:r,type:n,currentSupply:a}=e,o=e.mode??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw new E(`Invalid calculation mode "${o}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new E("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!r||"string"!=typeof r)throw new E("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Sn.NATIVE&&n!==Sn.EXACT)throw new E('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===o?this.calculateBuyAmountExternal({tokenName:t,amount:r,type:n}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:r,type:n},"currentSupply",a))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:r,type:n}=e,a=await this.tokenResolver.resolveTokenToVault(t);if(!a)throw new E(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Sn.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:a,amount:r}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:a,amount:r})}async calculateSellAmount(e){const{tokenName:t,amount:r,type:n,currentSupply:a,maxSupply:o,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:s}=e,l=e.mode??this.defaultCalculateAmountMode;if("local"!==l&&"external"!==l)throw new E(`Invalid calculation mode "${l}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new E("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!r||"string"!=typeof r)throw new E("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Sn.EXACT&&n!==Sn.NATIVE)throw new E('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===l)return this.calculateSellAmountExternal({tokenName:t,amount:r,type:n});{const e={tokenName:t,amount:r,type:n,...void 0!==a&&{currentSupply:a},...void 0!==o&&{maxSupply:o},...void 0!==i&&{reverseBondingCurveMaxFeeFactor:i},...void 0!==s&&{reverseBondingCurveMinFeeFactor:s}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:r,type:n}=e,a=await this.tokenResolver.resolveTokenToVault(t);if(!a)throw new E(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Sn.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:a,amount:r}):this._getAmount({type:"MEME",method:"IN",vaultAddress:a,amount:r})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:r,type:n,currentSupply:a}=e;if(!r||"string"!=typeof r)throw new E("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Sn.NATIVE&&n!==Sn.EXACT)throw new E('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==a&&Ut(a,"currentSupply");const o=!a;if(o&&!t)throw new E("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&Rt(t);let i=a;if(o){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return n===Sn.EXACT?En.calculateBuyWithExact(r,i):En.calculateBuyWithNative(r,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:r,type:n,currentSupply:a,maxSupply:o,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:s}=e;if(!r||"string"!=typeof r)throw new E("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Sn.EXACT&&n!==Sn.NATIVE)throw new E('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==a&&Ut(a,"currentSupply");const l=!a||!o||void 0===i||void 0===s;if(l&&!t)throw new E("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&Rt(t);let c=a,u=o,d=i,h=s;if(l&&t){const e=this.metadataCache.get(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,c||(c=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===Sn.EXACT?En.calculateSellWithExact(r,c,u,h,d):En.calculateSellWithNative(r,c,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 ur(t,"tokenName")&&pr(t)&&dr(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:r,calculateAmountMode:n,currentSupply:a}=t;Rt(r);const o=await this.tokenResolver.resolveTokenToVault(r);if(!o)throw new E(k(r),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw jt("GalaChain HTTP client not configured");const i=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:o});if(1!==i.Status)throw zt(`Failed to fetch pool details: Status ${i.Status}`,i.Status);const s=i.Data,l=(await import("bignumber.js")).default,c=a??new l(s.maxSupply).minus(s.sellingTokenQuantity).toFixed(),u=s.sellingTokenQuantity;if("0"===u)throw new E(`Token ${r} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const d={tokenName:r,amount:u,type:"exact",currentSupply:c,...void 0!==n&&{mode:n}};return await this.calculateBuyAmount(d)}async launchToken(e){if(!this.bundleHttp)throw jt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");yn(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new E("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:r}=e.reverseBondingCurveConfiguration,n=Number(t),a=Number(r);if(isNaN(n)||isNaN(a)||n<=0||a<=0||n>=a)throw new E("Reverse bonding curve configuration must have valid min/max fee portions with min < max","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG")}let r="";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 zt("Image upload failed: No URL returned");r=t}else"string"==typeof e.tokenImage&&(r=e.tokenImage);const n=`galaswap - operation - ${l.v4()}-${Date.now()}-${this.http.getAddress()}`,o={tokenName:e.tokenName.trim(),tokenSymbol:e.tokenSymbol.trim().toUpperCase(),tokenDescription:e.tokenDescription.trim(),tokenImage:r.trim(),preBuyQuantity:t.toString(),websiteUrl:e.websiteUrl||"",telegramUrl:e.telegramUrl||"",twitterUrl:e.twitterUrl||"",tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:n};e.reverseBondingCurveConfiguration&&(o.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const i=new _n(o),s=await this.http.signWithGalaChain("CreateSale",i,a.SigningType.SIGN_TYPED_DATA),{signature:c,types:u,domain:d,prefix:h}=s,p={tokenName:i.tokenName,tokenSymbol:i.tokenSymbol,tokenDescription:i.tokenDescription,tokenImage:i.tokenImage,preBuyQuantity:i.preBuyQuantity,websiteUrl:i.websiteUrl,telegramUrl:i.telegramUrl,twitterUrl:i.twitterUrl,tokenCategory:i.tokenCategory,tokenCollection:i.tokenCollection,uniqueKey:i.uniqueKey,signature:c,types:u,domain:d,...h&&{prefix:h},...i.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:i.reverseBondingCurveConfiguration}},f=`${e.tokenName.trim()}$Unit$none$none`,m="GALA$Unit$none$none";let g;if(parseFloat(t)>0){const e=`$service$${f}$launchpad`;g=[e,`$token$${f}$${e}`,`$tokenBalance$${f}$${e}`,`$tokenBalance$${f}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`]}else{const e=`$service$${f}$launchpad`;g=[e,`$token$${f}$${e}`,`$tokenBalance$${f}$${e}`]}const y={signedDto:p,stringsInstructions:g,method:"CreateSale"},v=await this.bundleHttp.post("/bundle",y);if(v.error||!v.data)throw zt(v.message||"Token launch failed");return v.data}async fetchTokenDistribution(e){if(!e)throw Kt("tokenName","Token name");Rt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new E(k(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const r=encodeURIComponent(t),n=await this.http.get(`/holders/${r}`);if(!0===n.error||200!==n.status||!n.data)throw zt(n.message||"Failed to fetch token distribution",n.status);const a=n.data;if(!Array.isArray(a))throw zt("Invalid API response: expected array of holders",n.status);for(const e of a){if(!e.owner||"string"!=typeof e.owner)throw zt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw zt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw zt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const o=a.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:a.map(e=>{const t=new i(e.quantity),r=o.isZero()?0:t.dividedBy(o).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:r}}),totalSupply:o.toFixed(),totalHolders:a.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Kt("tokenName","Token name");Rt(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw zt(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:r,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const a=("volume"===r?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return a?.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 E("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw jt("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},r=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!Tn(r))throw zt("Malformed response data from GalaChain gateway");if(1!==r.Status)throw zt(`GalaChain calculation failed with status ${r.Status}`,r.Status);const{calculatedQuantity:n,extraFees:a}=r.Data;return{amount:n,reverseBondingCurveFee:a.reverseBondingCurve,transactionFee:a.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 E(k(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw jt("GalaChain HTTP client not configured");const r=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==r.Status)throw zt(`Failed to fetch pool details: Status ${r.Status}`,r.Status);const n=r.Data,a=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),o=n.sellingTokenQuantity,i=n.maxSupply;let s=.5,l=0;n.reverseBondingCurveConfiguration?(s=parseFloat(n.reverseBondingCurveConfiguration.maxFeePortion),l=parseFloat(n.reverseBondingCurveConfiguration.minFeePortion)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const c=s-l;return this.metadataCache.set(e,{maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:l,reverseBondingCurveNetFeeFactor:c}),{currentSupply:a,remainingTokens:o,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:l,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Rt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new E(k(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw jt("GalaChain HTTP client not configured");const r=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==r.Status)throw zt(`Failed to fetch pool details: Status ${r.Status}`,r.Status);const n=r.Data,a=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),o=n.maxSupply;return this.metadataCache.set(e,{maxSupply:o}),a}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return $t(e)}validateTokenName(e){return Rt(e)}validatePagination(e){return Ot(e)}async fetchTokenSpotPrice(e){if(!this.dexApiHttp)throw jt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw Kt("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}}),r=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&r.push({symbol:e.symbol,price:e.currentPrices.usd})}),r}catch(e){throw zt(`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 ur(t,"tokenName")&&pr(t)&&dr(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:r,calculateAmountMode:n,currentSupply:a}=t;if(!r||"string"!=typeof r)throw Kt("tokenName","Token name (string)");try{const e={tokenName:r,amount:"1",type:"native",...void 0!==n&&{mode:n},...void 0!==a&&{currentSupply:a}},t=await this.calculateBuyAmount(e),o=(await this.fetchTokenSpotPrice("GALA"))[0];if(!o)throw zt("GALA price not available");const i=Number(t.amount);if(i<=0)throw new E(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const s=o.price/i;return{symbol:r.toUpperCase(),price:s}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${r}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${r}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}const In={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",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",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function Cn(e){return In[e]}class Fn extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Pn extends Error{constructor(e,t,r){super(`Transaction ${e} failed with status: ${t}${r?` - ${r}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function Dn(e,t){if(!e)throw new Fn(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Fn(`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 Fn(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Rn(e,t,r,n){Dn(e,t);const a=e,o=a.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)}(o))throw new Fn(`Invalid trade data received for transaction ${t}`);const i={transactionId:t,type:r,method:"native"===n.type?"native":"exact",inputAmount:o.inputQuantity||n.amount,outputAmount:o.outputQuantity||n.expectedAmount||"0",totalFees:o.totalFees||"0",tokenName:n.tokenName,vaultAddress:o.vaultAddress||"",timestamp:Date.now()};return void 0!==a.blockHash&&(i.blockHash=a.blockHash),void 0!==a.gasUsed&&(i.gasUsed=a.gasUsed),void 0!==n.slippageToleranceFactor&&(i.slippageTolerance=n.slippageToleranceFactor),i}let On="";const Ln=function(){if(On)return On;try{const e=require("../../package.json");On=e.version||"unknown"}catch{On="unknown"}return On}();class Bn{constructor(e){let t=null;t=e.env?Cn(e.env):e.baseUrl?.includes("prod")?Cn("PROD"):Cn("STAGE"),this.config={baseUrl:t.launchpadBaseUrl,galaChainBaseUrl:t.galaChainBaseUrl,bundleBaseUrl:t.bundleBaseUrl,webSocketUrl:t.webSocketUrl,dexApiBaseUrl:t.dexApiBaseUrl,launchpadFrontendUrl:t.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new A({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Bn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Bn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||Bn.DEFAULT_CALCULATE_AMOUNT_MODE,this.auth=new w({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new T(this.auth,this.config),this.galaChainHttp=new T(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new T(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new T(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.launchpadService=new Dr(this.http),this.tokenResolverService=new fn(this.launchpadService.poolService),this.launchpadAPI=new Nn(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new Vr(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1),this.dexService=new Hr(this.dexApiHttp),this.bundleService=new dn(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,this.getAddress(),this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new pn({url:this.config.webSocketUrl},this.config.debug)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw jt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw jt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new r.Wallet(e),n={...this.config,wallet:t};return new Bn(n)}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.config.wallet.address}getConfig(){const{wallet:e,...t}=this.config;return{...t,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode}}getVersion(){return Ln}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw jt("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 fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenSpotPrice(e){return this.dexService.fetchTokenSpotPrice(e)}async fetchGalaSpotPrice(){const e=await this.dexService.fetchTokenSpotPrice("GALA");if(0===e.length)throw zt("Failed to fetch GALA price - no price data returned");const t=e.find(e=>"GALA"===e.symbol);if(!t)throw zt("GALA price not found in response");return t}async fetchLaunchpadTokenSpotPrice(e){return this.launchpadAPI.fetchLaunchpadTokenSpotPrice(e)}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(!t)throw new Error(k(e));const r=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return r.currentSupply=n.currentSupply,r.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,r.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,r.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,r.tokenName=e,r}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 Mt}),r=t(e)||this.getAddress();return this.galaChainService.fetchGalaBalance({owner:r,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),r=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Mr}),n=t(e.tokenId),{collection:a,category:o,type:i,additionalKey:s}=n;return this.galaChainService.fetchTokenBalance({owner:r,collection:a,category:o,additionalKey:s,type:i,instance:"0"})}if(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...r&&{address:r}})).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 Kt("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:r,maxAcceptableReverseBondingCurveFeeSlippageFactor:n,privateKey:a,calculateAmountMode:o,currentSupply:i}=e;let s=t;void 0===o&&void 0===i||(s={tokenName:t,...void 0!==o&&{calculateAmountMode:o},...void 0!==i&&{currentSupply:i}});const l=await this.calculateBuyAmountForGraduation(s),c={tokenName:t,amount:l.amount,type:"exact",expectedAmount:l.amount,maxAcceptableReverseBondingCurveFee:l.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==r&&(c.slippageToleranceFactor=r),void 0!==n&&(c.maxAcceptableReverseBondingCurveFeeSlippageFactor=n),void 0!==a&&(c.privateKey=a),await this.buy(c)}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:r,...n}=e;return t.buy(n)}await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,r=t?.transactionId;if(!r)throw Wt("No transaction ID returned from buy operation");return this.waitForConfirmation(r,t=>Rn(t,r,"buy",e))}async sell(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:r,...n}=e;return t.sell(n)}await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,r=t?.transactionId;if(!r)throw Wt("No transaction ID returned from sell operation");return this.waitForConfirmation(r,t=>Rn(t,r,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async postComment(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:r,...n}=e;return t.postComment(n)}return this.launchpadService.postComment(e)}async launchToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:r,...n}=e;return t.launchToken(n)}await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,r=>{Dn(r,t);const n=r?.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 Fn(`Invalid launch data received for transaction ${t}`);const a={transactionId:t,vaultAddress:n.vaultAddress||"",tokenStringKey:n.tokenStringKey||"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:n.creatorAddress||this.getAddress(),timestamp:Date.now(),...r.blockHash&&{blockHash:r.blockHash},...r.gasUsed&&{gasUsed:r.gasUsed}};return"string"==typeof e.tokenImage&&(a.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(a.preBuyQuantity=e.preBuyQuantity),a.vaultAddress&&this.tokenResolverService.set(e.tokenName,a.vaultAddress),a})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:r,...n}=e;return t.uploadTokenImage(n)}return 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 Mt}),r=t(e)||this.getAddress();return this.launchpadService.fetchProfile(r)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),r={...e,address:t(e.address)};if(r.privateKey){const e=this.createOverrideSdk(r.privateKey),{privateKey:t,...n}=r;return e.updateProfile(n)}return this.launchpadService.updateProfile(r)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),r={...e,address:t(e.address)||this.getAddress()};if(r.privateKey){const e=this.createOverrideSdk(r.privateKey),{privateKey:t,...n}=r;return e.uploadProfileImage(n)}return this.launchpadService.uploadProfileImage(r)}async retrieveGalaFromFaucet(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),r={walletAddress:t(e)||this.getAddress(),amount:"5"};return this.launchpadService.transferFaucets(r)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),r=t(e?.address)||this.getAddress(),n={page:e?.page||1,limit:e?.limit||10,address:r};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 Mt}),r={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(r.tokenName=e.tokenName),e?.search&&(r.search=e.search),this.launchpadService.fetchTokenList(r)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),r={...e,recipientAddress:t(e.recipientAddress)};if(r.privateKey){const e=this.createOverrideSdk(r.privateKey),{privateKey:t,...n}=r;return e.transferGala(n)}return this.galaChainService.transferGala(r)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),r={...e,to:t(e.to)};if(r.privateKey){const e=this.createOverrideSdk(r.privateKey),{privateKey:t,...n}=r;return e.transferToken(n)}return this.galaChainService.transferToken(r)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(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 jt("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw jt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw jt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw jt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw jt(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw jt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw jt(`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: ${Bn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Bn.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: ${Bn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Bn.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 r=await this.websocketService.waitForTransaction(e);if("completed"!==r.status)throw new Pn(e,r.status,r.message);let n;try{n=t(r)}catch(t){if(t instanceof Fn)throw t;throw new Fn(`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 Pn||t instanceof Fn)throw t;throw new Fn(`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:r}=await Promise.resolve().then(function(){return Un});e.forEach(e=>{if(!r(e))return;const n=t(e,this.logger);n&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,n)})}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),this.websocketService&&this.websocketService.disconnect(),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new A({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:r}=require("./services/WebSocketService");r.cleanupAll(e),t.debug("Global cleanup completed")}}Bn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Bn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Bn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=mn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Bn.DEFAULT_CALCULATE_AMOUNT_MODE=kn.LOCAL;class xn{static generateWallet(){try{const e=r.Wallet.createRandom();if(!e.mnemonic?.phrase)throw new Error("Failed to generate wallet with mnemonic phrase");const t=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:t,mnemonic:e.mnemonic.phrase,wallet:new r.Wallet(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,t="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),n=new r.Wallet(t),a=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:a,mnemonic:"test test test test test test test test test test test junk",wallet:n}}throw e}}static fromPrivateKey(e){const t=new r.Wallet(e),n=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:n,mnemonic:"",wallet:t}}static fromMnemonic(e,t=0){try{const n=r.Mnemonic.fromPhrase(e),a=r.HDNodeWallet.fromMnemonic(n,`m/44'/60'/0'/0/${t}`),o=new r.Wallet(a.privateKey),i=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:i,mnemonic:e,wallet:o}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${t}-${e}`,a="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),o=new r.Wallet(a),i=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:i,mnemonic:e,wallet:o}}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 r=0;r<e;r++){const e=`test-multi-${r}-${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 r=0;r<e;r++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const r=["๐Ÿ” Wallet Information","โ•".repeat(50),`๐Ÿ“ Address: ${e.address}`,`๐ŸŽฎ Gala Address: ${e.galaAddress}`,`๐ŸŒฑ Mnemonic: ${e.mnemonic||"Not available"}`];return t?r.splice(3,0,`๐Ÿ”‘ Private Key: ${e.privateKey}`):r.splice(3,0,"๐Ÿ”‘ Private Key: [HIDDEN - use includeSensitive=true to show]"),r.push("โ•".repeat(50)),r.push("๐Ÿ’พ IMPORTANT: Save your mnemonic phrase securely!"),r.push("This is your backup to recover the wallet."),r.join("\n")}}function $n(e){if(void 0===e)return xn.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 xn.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 xn.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?"...":""}"`)}xn.testCounter=0;var Un=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const r={};if(e.vaultAddress&&(r.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}"`):r.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}"`):r.reverseBondingCurveMaxFeeFactor=n}return void 0!==r.reverseBondingCurveMaxFeeFactor&&void 0!==r.reverseBondingCurveMinFeeFactor&&(r.reverseBondingCurveNetFeeFactor=r.reverseBondingCurveMaxFeeFactor-r.reverseBondingCurveMinFeeFactor),Object.keys(r).length>0?r: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}});e.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),r=this.setupWallet(e.privateKey),n={wallet:r.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t)},a=new Bn(n),o={sdk:a,wallet:r,config:n};if(!1!==e.autoValidate){const e=await this.validateSetup(a,r);return{...o,validation:e}}return o}static async validateSetup(e,t){const r=[],n=[],a={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(a.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);a.hasBalance=e>0,a.canTrade=e>=.1,a.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 r.push("Failed to fetch GALA balance: No balance returned")}catch(e){r.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===r.length&&a.connectionHealthy,sdk:e,wallet:t||xn.generateWallet(),issues:r,warnings:n,capabilities:a}}static getRecommendedConfig(e,t="general"){const r={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(r,{debug:!1,timeout:3e4});break;case"development":Object.assign(r,{debug:!0,timeout:45e3});break;case"testing":Object.assign(r,{debug:!0,timeout:6e4})}switch(t){case"trading":r.timeout=1.5*(r.timeout||3e4);break;case"creation":r.timeout=2*(r.timeout||3e4);break;case"monitoring":r.timeout=.5*(r.timeout||3e4)}return r}static async multiWalletSetup(e,t="development"){const r={};for(const[n,a]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:a,agentId:`multi-wallet-${n}`,autoValidate:!1});r[n]=e}return r}static detectEnvironment(){const e=process.env.NODE_ENV?.toLowerCase();return"production"===e?"production":"test"===e||"testing"===e?"testing":"development"}static setupWallet(e){if(!e){const e=process.env.PRIVATE_KEY;return e?xn.fromPrivateKey(e):xn.generateWallet()}return"generate"===e?xn.generateWallet():xn.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}},e.CALCULATION_MODES=kn,e.FileValidationError=Ir,e.GALA_DECIMALS=8,e.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},e.IMAGE_EXTENSIONS=_e,e.LAUNCHPAD_TOKEN_DECIMALS=18,e.LaunchpadSDK=Bn,e.MAX_CONCURRENT_POOL_FETCHES=5,e.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},e.SDK_VERSION=Ln,e.TRADING_TYPES=Sn,e.TransactionFailedError=Pn,e.ValidationError=E,e.WebSocketError=Fn,e.WebSocketTimeoutError=class extends Fn{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},e.addressFormatSchema=q,e.amountMethodSchema=be,e.amountTypeSchema=ve,e.browserFileSchema=Se,e.bufferFileSchema=ke,e.buyTokensDataSchema=Ve,e.calculatePreMintDataSchema=et,e.checkPoolOptionsSchema=ye,e.commentMessageSchema=ae,e.commentPaginationSchema=De,e.createLaunchpadSDK=function(e){const{wallet:t,env:n,config:a={}}=e||{};let o;if(t)if("string"==typeof t){o=$n(t).wallet}else{if(!(t instanceof r.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");o=t}else{o=$n().wallet}const i={wallet:o,...n&&{env:n},debug:!1,timeout:3e4,...a};return new Bn(i)},e.createLimitSchema=Y,e.createPaginatedResultSchema=function(e){return o.z.object({data:o.z.array(e),page:o.z.number().int().min(1),limit:o.z.number().int().min(1),total:o.z.number().int().min(0),totalPages:o.z.number().int().min(0),hasNext:o.z.boolean(),hasPrevious:o.z.boolean()})},e.createTradeDataSchema=We,e.createWallet=$n,e.ethereumAddressSchema=K,e.faucetAmountSchema=V,e.fetchGalaBalanceOptionsSchema=Me,e.fetchPoolDetailsDataSchema=tt,e.fetchTokenBalanceOptionsSchema=Ge,e.fileSizeSchema=te,e.fileUploadSchema=Te,e.filenameSchema=re,e.flexibleAddressSchema=G,e.flexibleFileSchema=Ee,e.formatGalaForDTO=Xr,e.formatLaunchpadTokenForDTO=Yr,e.fullNameSchema=M,e.getAmountOptionsSchema=Je,e.getTradeOptionsSchema=Qe,e.graduateTokenOptionsSchema=Ae,e.graphDataOptionsSchema=we,e.imageExtensionSchema=Ne,e.imageFilenameSchema=Ie,e.imageMimeTypeSchema=ne,e.imageUploadOptionsSchema=me,e.isoDateStringSchema=oe,e.launchTokenDataSchema=fe,e.nonNegativeDecimalStringSchema=W,e.optionalUrlSchema=Q,e.pageNumberSchema=X,e.paginationResultMetaSchema=Be,e.poolFetchTypeSchema=ge,e.poolPaginationSchema=Re,e.positiveDecimalStringSchema=j,e.privateKeySchema=se,e.reverseBondingCurveConfigSchema=pe,e.reverseBondingCurveConfigurationSchema=rt,e.searchQuerySchema=U,e.sellTokensDataSchema=He,e.standardLimitSchema=Z,e.standardPaginationSchema=Ce,e.timestampSchema=ie,e.tokenCategorySchema=de,e.tokenCollectionSchema=he,e.tokenDescriptionSchema=x,e.tokenListOptionsSchema=$e,e.tokenNameSchema=L,e.tokenSymbolSchema=B,e.tokenUrlsSchema=ue,e.tradeCalculationMethodSchema=Ze,e.tradeCalculationTypeSchema=Ye,e.tradeLimitSchema=ee,e.tradeListParamsSchema=Xe,e.tradePaginationSchema=Pe,e.tradePaginationWithFiltersSchema=Le,e.tradeTypeBackendSchema=je,e.tradeTypeSchema=ze,e.transactionIdSchema=le,e.transferFaucetsDataSchema=Ue,e.uniqueKeySchema=ce,e.updateProfileDataSchema=qe,e.uploadProfileImageOptionsSchema=Ke,e.urlSchema=H,e.userLimitSchema=J,e.userPaginationSchema=Fe,e.userTokenNameSchema=$,e.userTokenTypeSchema=xe,e.userTokensPaginationSchema=Oe,e.validateAddress=st,e.validateAmountString=ct,e.validateBuyTokensData=kt,e.validateCalculatePreMintData=Ft,e.validateCheckPoolOptions=yt,e.validateCreateTradeData=St,e.validateFaucetAmount=ut,e.validateFetchGalaBalanceOptions=wt,e.validateFetchPoolDetailsData=Pt,e.validateFetchTokenBalanceOptions=Tt,e.validateFullName=dt,e.validateGetAmountOptions=Ct,e.validateGetTradeOptions=Nt,e.validateImageUploadOptions=gt,e.validateLaunchTokenData=ft,e.validateSearchQuery=ht,e.validateSellTokensData=Et,e.validateTokenDescription=it,e.validateTokenListOptions=vt,e.validateTokenName=at,e.validateTokenSymbol=ot,e.validateTokenUrls=mt,e.validateTradeListParams=It,e.validateTransferFaucetsData=bt,e.validateUpdateProfileData=At,e.validateUploadProfileImageOptions=_t,e.validateUserTokenName=pt,e.validateVaultAddress=lt,e.vaultAddressSchema=z});