@gala-chain/launchpad-sdk 3.7.7 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t,a=require("ethers"),n=require("axios"),r=require("@gala-chain/connect"),s=require("zod"),o=require("@gala-chain/api"),i=require("bignumber.js"),c=require("uuid"),l=require("socket.io-client");!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"}(e||(e={}));class d extends Error{constructor(e,t,a){super(t),this.type=e,this.originalError=a,this.name="AuthError"}}class u{constructor(t){if(this.wallet=t.wallet,this.messagePrefix=t.messagePrefix||"Create a GalaChain Wallet",""===t.messagePrefix)throw new d(e.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(t){throw new d(e.SIGNATURE_FAILED,"Failed to generate signature for authentication",t instanceof Error?t:new Error(String(t)))}}getAddress(){return this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.wallet.address}formatAddress(t){const a=t.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(a))throw new d(e.INVALID_ADDRESS,`Invalid Ethereum address format: ${t}`);return`eth|${a}`}async signMessage(t){try{return{message:t,signature:await this.wallet.signMessage(t),address:this.wallet.address,timestamp:Date.now()}}catch(t){const a=t instanceof Error?t.message:String(t);throw new d(e.SIGNATURE_FAILED,a,t instanceof Error?t:new Error(String(t)))}}async generateAuthHeaders(t,a){try{const e=Date.now(),n=`${this.messagePrefix} ${a.toUpperCase()} ${t} ${e}`,r=await this.wallet.signMessage(n);return{"x-signature":r,"x-address":this.formatAddress(this.wallet.address),"x-message":n,"x-timestamp":e.toString()}}catch(t){throw new d(e.SIGNATURE_FAILED,"Failed to generate authentication headers",t instanceof Error?t:new Error(String(t)))}}async signTypedData(t,a,n){try{return await this.wallet.signTypedData(t,a,n)}catch(t){throw new d(e.SIGNATURE_FAILED,"Failed to sign typed data",t instanceof Error?t:new Error(String(t)))}}async generateCustomSignature(t){if(!t||"string"!=typeof t||0===t.trim().length)throw new d(e.SIGNATURE_FAILED,"Custom message must be a non-empty string");try{const e=await this.wallet.signMessage(t);return{message:t,signature:e,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(t){throw new d(e.SIGNATURE_FAILED,"Failed to generate custom message signature",t instanceof Error?t:new Error(String(t)))}}validateWallet(){if(!this.wallet)throw new d(e.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new d(e.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new d(e.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"}(t||(t={}));class h{constructor(e){this.levelPriority={[t.DEBUG]:0,[t.INFO]:1,[t.WARN]:2,[t.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?t.DEBUG:t.INFO)}debug(e,a){this.log(t.DEBUG,e,a)}info(e,a){this.log(t.INFO,e,a)}warn(e,a){this.log(t.WARN,e,a)}error(e,a){this.log(t.ERROR,e,a)}log(e,a,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===t.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?n instanceof Error?s(`${r} ${a}`,n.message,n.stack):s(`${r} ${a}`,n):s(`${r} ${a}`)}getConsoleMethod(e){switch(e){case t.DEBUG:return console.debug;case t.INFO:return console.info;case t.WARN:return console.warn;case t.ERROR:return console.error;default:return console.log}}child(e){return new h({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[t.DEBUG]>=this.levelPriority[this.minLevel]}}function p(e){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 g{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new h({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:p(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=r.SigningType.SIGN_TYPED_DATA){const n=this.auth.wallet.privateKey;if(!n)throw new Error("Wallet private key not available for @gala-chain signing");const s=new r.SigningClient(n);return await s.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 m="Token name is required and must be a string",f=e=>`Could not find vault address for token: ${e}`;class y 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 v 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:s,MAX_LIMIT:o}=a.PAGINATION;if("number"!=typeof e||e<n||e>r)throw new y(`Page must be a number between ${n} and ${r}`,"page","INVALID_PAGE");if("number"!=typeof t||t<s||t>o)throw new y(`Limit must be a number between ${s} and ${o}`,"limit","INVALID_LIMIT")}const T={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function b(e){return"string"==typeof e&&e.trim().length>0}function E(e){return!(!e||"string"!=typeof e)&&(T.ETH_ADDRESS.test(e)||T.BACKEND_ADDRESS.test(e))}function N(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const S=s.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"),I=s.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"),D=s.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),x=s.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),F=s.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),C=s.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"),$=s.z.string().regex(T.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),_=s.z.string().regex(T.ETH_ADDRESS,"Invalid Ethereum address format"),P=s.z.string().refine(e=>T.BACKEND_ADDRESS.test(e)||T.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),O=s.z.string().refine(e=>T.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),L=s.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),U=s.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),R=s.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),B=s.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),K=s.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),M=s.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 G(e=100){return s.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=G(100),V=G(20),q=G(20),j=s.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"),W=s.z.string().max(255,"Filename must be at most 255 characters"),H=s.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Q=s.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),X=s.z.string().datetime("Must be a valid ISO 8601 date string"),Y=s.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),J=s.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Z=s.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"),ee=s.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),te=s.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"),ae=s.z.string().min(1,"Token category must not be empty").default("Unit"),ne=s.z.string().min(1,"Token collection must not be empty").default("Token"),re=s.z.object({minFeePortion:L,maxFeePortion:L}),se=s.z.object({tokenName:S,tokenSymbol:I,tokenDescription:D,tokenImage:s.z.union([s.z.instanceof(File),s.z.instanceof(Buffer),s.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:U.default("0"),websiteUrl:K,telegramUrl:K,twitterUrl:K,tokenCategory:ae,tokenCollection:ne,reverseBondingCurveConfiguration:re.optional(),privateKey:J.optional()}),oe=s.z.object({file:s.z.union([s.z.instanceof(File),s.z.instanceof(Buffer)]),tokenName:S}),ie=s.z.enum(["recent","popular"]),ce=s.z.object({tokenName:S.optional(),symbol:I.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),le=s.z.enum(["NATIVE","MEME"]),de=s.z.enum(["IN","OUT"]),ue=s.z.object({from:s.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:s.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:s.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:S}),he=s.z.object({tokenName:S,slippageToleranceFactor:s.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:s.z.number().min(0).max(1).optional(),privateKey:J.optional()}),pe=[".png",".jpg",".jpeg",".gif",".webp",".svg"],ge=s.z.object({file:s.z.union([s.z.instanceof(File),s.z.instanceof(Buffer)]),name:W,size:j,type:H}),me=s.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"),fe=s.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),ye=s.z.union([me,fe]),Ae=s.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),we=W.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return pe.includes(t)},`Filename must end with one of: ${pe.join(", ")}`),ve=s.z.object({page:M,limit:z}),ke=s.z.object({page:M,limit:V}),Te=s.z.object({page:M,limit:q}),be=s.z.object({page:M,limit:G(50)}),Ee=ve.extend({type:s.z.enum(["recent","popular"]).optional(),tokenName:s.z.string().min(1).max(50).optional(),search:s.z.string().min(1).max(100).optional()}),Ne=ke.extend({tokenName:s.z.string().min(1).max(50).optional(),search:s.z.string().min(1).max(100).optional()}),Se=Te.extend({tradeType:s.z.enum(["BUY","SELL"]).optional(),tokenName:s.z.string().min(1).max(50).optional(),userAddress:s.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:s.z.string().datetime().optional(),endDate:s.z.string().datetime().optional(),sortOrder:s.z.enum(["ASC","DESC"]).default("DESC")}),Ie=s.z.object({page:s.z.number().int().min(1),limit:s.z.number().int().min(1),total:s.z.number().int().min(0),totalPages:s.z.number().int().min(0),hasNext:s.z.boolean(),hasPrevious:s.z.boolean()});const De=s.z.enum(["all","DEFI","ASSET"]),xe=ke.extend({type:De.optional(),address:P.optional(),search:F.optional(),tokenName:x.optional()}),Fe=s.z.object({walletAddress:P,amount:R}),Ce=s.z.object({address:P.optional(),refresh:s.z.boolean().optional()}),$e=s.z.object({profileImage:s.z.string(),fullName:C,address:P,privateKey:J.optional()}),_e=s.z.object({file:s.z.union([s.z.instanceof(File),s.z.instanceof(Buffer)]),address:P.optional(),privateKey:J.optional()}),Pe=s.z.object({address:P,tokenId:s.z.union([s.z.string(),s.z.object({collection:s.z.string(),category:s.z.string(),type:s.z.string(),additionalKey:s.z.string()}),s.z.object({collection:s.z.string(),category:s.z.string(),type:s.z.string(),additionalKey:s.z.string(),instance:s.z.string()})]).optional(),tokenClassKey:s.z.object({collection:s.z.string(),category:s.z.string(),type:s.z.string(),additionalKey:s.z.string()}).optional(),tokenName:x.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),Oe=s.z.enum(["buy","sell"]),Le=s.z.enum(["BUY","SELL"]),Ue=s.z.object({tradeType:Oe,tokenAmount:L,vaultAddress:O,userAddress:P,slippageTolerance:L.optional(),deadline:s.z.number().int().positive().optional()}),Re=s.z.object({tokenSymbol:I,nativeTokenQuantity:L,expectedToken:L,maxAcceptableReverseBondingCurveFee:U.default("0").optional()}),Be=s.z.object({tokenSymbol:I,tokenQuantity:L,expectedNativeToken:L,maxAcceptableReverseBondingCurveFee:U.default("0").optional()}),Ke=Te.extend({tokenName:x.optional()}),Me=s.z.object({page:s.z.number().int().min(1).max(1e3).default(1).optional(),limit:s.z.number().int().min(1).max(20).default(10).optional()}),Ge=s.z.enum(["NATIVE","MEME"]),ze=s.z.enum(["IN","OUT"]),Ve=s.z.object({type:Ge,method:ze,vaultAddress:O,amount:L}),qe=s.z.object({nativeTokenQuantity:L}),je=s.z.object({vaultAddress:O}),We=s.z.object({minFeePortion:L,maxFeePortion:L});function He(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 Qe=He(S),Xe=He(I),Ye=He(D),Je=He(P),Ze=He(O),et=He(L),tt=He(R),at=He(C),nt=He(F),rt=He(x),st=He(se),ot=He(te),it=He(oe),ct=He(ce),lt=He(xe),dt=He(Fe),ut=He(Ce),ht=He($e),pt=He(_e),gt=He(Pe),mt=He(Ue),ft=He(Re),yt=He(Be),At=He(Ke),wt=He(Me),vt=He(Ve),kt=He(qe),Tt=He(je);function bt(e,t){throw new y(e.join("; "),t,"VALIDATION_ERROR")}function Et(e){const t=Qe(e);!t.success&&t.errors&&bt(t.errors,"tokenName")}function Nt(e){const t=Ee.safeParse(e);t.success||bt(t.error.errors.map(e=>e.message),"pagination")}function St(e){const t=ct(e);!t.success&&t.errors&&bt(t.errors,"options")}function It(e){const t=vt(e);!t.success&&t.errors&&bt(t.errors,"options")}function Dt(e){const t=ue.safeParse(e);t.success||bt(t.error.errors.map(e=>e.message),"options")}function xt(e){const t=P.safeParse(e);if(!t.success)throw new y("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}var Ft=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=P.safeParse(e);if(!t.success)throw new y(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:xt,validateCheckPoolOptions:St,validateGetAmountOptions:It,validateGetGraphOptions:Dt,validatePagination:Nt,validateTokenName:Et});function Ct(e){if(!e)return[];return(Array.isArray(e)?e:e.token??[]).map(e=>({...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}))}function $t(e,t){const a=Number(e.page)||t.page,n=Number(e.limit)||t.limit,r=Number(e.total)||Number(e.data?.count)||0;return{page:a,limit:n,total:r,totalPages:Math.ceil(r/n)}}function _t(e,t){return{hasNext:e<t,hasPrevious:e>1}}function Pt(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 Ot="/launchpad/upload-image",Lt="/launchpad/fetch-pool",Ut="/launchpad/check-pool",Rt="/launchpad/get-graph-data",Bt="/holders",Kt="/launchpad/get-badge/",Mt="/trade/",Gt="/token/commment",zt="/token/commment",Vt="/user/profile",qt="/user/profile",jt="/user/token-list",Wt="/user/token-hold",Ht="/user/transfer-faucets";function Qt(e,t){return new y(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Xt(e,t){const a=t||e.charAt(0).toUpperCase()+e.slice(1);return new y(`${a} is required`,e,"REQUIRED_FIELD")}function Yt(e,t,a){const n=a||e.charAt(0).toUpperCase()+e.slice(1);return new y(`${n} must be ${t}`,e,"INVALID_FORMAT")}function Jt(e,t,a){return new A(e,t,a)}function Zt(e,t){return new w(e,t)}function ea(e,t,a){return new v(e,t,a)}function ta(e){return e&&"object"==typeof e&&"string"==typeof e.tokenName&&(void 0===e.from||"number"==typeof e.from)&&(void 0===e.to||"number"==typeof e.to)&&(void 0===e.resolution||"number"==typeof e.resolution)}class aa{constructor(e){this.http=e}async fetchPools(e={}){let t;Nt({page:e.page??1,limit:e.limit??10}),e.tokenName&&Et(e.tokenName),"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const a={page:e.page||1,limit:e.limit||10};e.search&&(a.search=e.search),e.tokenName&&(a.tokenName=e.tokenName),t&&(a.type=t);const n={page:a.page.toString(),limit:a.limit.toString()};void 0!==a.type&&(n.type=a.type),void 0!==a.tokenName&&(n.tokenName=a.tokenName),void 0!==a.search&&(n.search=a.search);const r=p(n),s=await this.http.get(Lt,r);Pt(s,"Failed to fetch pools",!0);return{pools:function(e){if(!e)return[];let t=[];return e.tokens?t=Array.isArray(e.tokens)?e.tokens.map(e=>({...e,createdAt:new Date(e.created_at??e.createdAt)})):[{...e.tokens,createdAt:new Date(e.tokens.created_at??e.tokens.createdAt)}]:e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:new Date(e.created_at??e.createdAt)}))),t}(s.data),page:s.data.page,limit:s.data.limit,total:s.data.total,totalPages:s.data.totalPages,hasNext:s.data.page<s.data.totalPages,hasPrevious:s.data.page>1}}async checkPool(e){St(e),e.tokenName&&Et(e.tokenName);const t=p(e),a=await this.http.get(Ut,t);Pt(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(!ta(e))throw new y("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(Et(t),!a||!n||!r)throw new y("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const s={tokenName:t,from:a,to:n,resolution:r};Dt(s);const o=p(s),i=await this.http.get(Rt,o);return Pt(i,"Failed to fetch graph data",!0),{dataPoints:i.data}}async fetchTokenDistribution(e){if(!e)throw Xt("tokenName","Token name");Et(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw new y(f(e),"tokenName","VAULT_NOT_FOUND");const a=encodeURIComponent(t),n=await this.http.get(`${Bt}/${a}`);return Pt(n,"Failed to fetch token distribution",!0),{holders:n.data.holders||[],totalSupply:n.data.totalSupply||"0",totalHolders:n.data.totalHolders||0,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Xt("tokenName","Token name");Et(e);const t=await this.http.get(Kt,{tokenName:e});return Pt(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});return t.pools&&Array.isArray(t.pools)&&t.pools.length>0?t.pools[0].vaultAddress||null:t.pools&&t.pools.tokens&&t.pools.tokens.vaultAddress||null}catch{return null}}}function na(e,t={}){const{stringifyFields:a=[],optionalFields:n=[],fieldMappings:r={}}=t,s={};for(const[t,o]of Object.entries(e)){const e=t;if(n.includes(e)&&void 0===o)continue;if(n.includes(e)&&"string"==typeof o&&0===o.trim().length)continue;const i=r[e],c=i?String(i):t;a.includes(e)?s[c]=String(o):s[c]=o}return p(s)}const ra={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class sa{constructor(e){this.http=e}async fetchTrades(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.tokenName||void 0!==t.tradeType&&"buy"!==t.tradeType&&"sell"!==t.tradeType||void 0!==t.userAddress&&"string"!=typeof t.userAddress||void 0!==t.page&&"number"!=typeof t.page||void 0!==t.limit&&"number"!=typeof t.limit)throw new y("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, page?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");var t;const{tokenName:a,tradeType:n,userAddress:r,page:s=1,limit:o=10,startDate:i,endDate:c,sortOrder:l}=e;if(!b(a))throw new y("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");k(s,o,ra);const d=function(e,t,a){return na({tokenName:e,page:t,limit:a},{stringifyFields:["page","limit"]})}(a,s,o),u=await this.http.get(Mt,d),h=(p=u.data)?(Array.isArray(p)?p:p.trades?p.trades:[]).map(e=>({...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)})):[];var p;const g=$t(u,{page:s,limit:o}),m=_t(g.page,g.totalPages);return{trades:h,...g,...m}}}const oa=new h({debug:!1,context:"DateUtils"});function ia(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())?(oa.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):a}catch(a){return oa.warn(`Date parsing error for "${e}":`,a),t||new Date}}const ca={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class la{constructor(e,t){this.http=e,this.poolService=t}async fetchComments(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.tokenName||void 0!==t.page&&"number"!=typeof t.page||void 0!==t.limit&&"number"!=typeof t.limit)throw new y("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");var t;const{tokenName:a,page:n=1,limit:r=10}=e;if(!b(a))throw new y("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");k(n,r,ca);const s=await this.poolService.resolveTokenNameToVault(a);if(!s)throw Qt(a);const o=na({vaultAddress:s,page:n,limit:r},{stringifyFields:["page","limit"]}),i=await this.http.get(Gt,o);Pt(i,"Failed to fetch comments");return{comments:i.data.comments.map(e=>({...e,createdAt:ia(e.createdAt)})),total:i.data.count}}async postComment(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.tokenName||"string"!=typeof t.content)throw new y("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");var t;const{tokenName:a,content:n}=e;if(!b(a))throw new y("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>=ca.CONTENT.MIN_LENGTH&&t.length<=ca.CONTENT.MAX_LENGTH}(n))throw new y(`Comment content must be between ${ca.CONTENT.MIN_LENGTH} and ${ca.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const r=await this.poolService.resolveTokenNameToVault(a);if(!r)throw Qt(a);const s={userAddress:this.http.getAddress(),vaultAddress:r,content:n};Pt(await this.http.post(zt,s),"Failed to create comment")}}const da={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 ua(e){return!(!e||"string"!=typeof e)&&da.USER_ADDRESS.PATTERN.test(e)}const ha="Update profile";class pa{constructor(e){this.http=e}async fetchProfile(e){const t=e??this.http.getAddress();if(!ua(t))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const a={userAddress:t};return await this.http.get(Vt,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(ha),r={address:n.address,message:ha,publickey:n.ethereumAddress,sign:n.signature};Pt(await this.http.put(qt,a,r),"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();try{const a=new FormData;if("undefined"!=typeof File&&e.file instanceof File)a.append("image",e.file);else{if(!Buffer.isBuffer(e.file))throw new y("Invalid file type","file","INVALID_FILE_TYPE");{const n=`profile-image-${t}.png`,r=new Blob([e.file],{type:"image/png"});a.append("image",r,n)}}const n=await this.http.request({method:"POST",url:`${Ot}?tokenName=${encodeURIComponent(t)}`,data:a,headers:{}});return Pt(n,"Image upload failed"),"string"==typeof n.data?n.data:""}catch(e){if(e instanceof y)throw e;throw new y(`Profile image upload failed: ${e instanceof Error?e.message:"Unknown error"}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){this.validateGetTokenListOptions(e);const t=na({page:e.page,limit:e.limit,type:"all"!==e.type&&e.type?e.type:"DEFI",address:e.address,search:e.search,tokenName:e.tokenName},{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),a=await this.http.get(jt,t);Pt(a,"Failed to fetch token list",!0);const n=Ct(a.data),r=$t(a,{page:e.page||1,limit:e.limit||10}),s=_t(r.page,r.totalPages);return{tokens:n,...r,...s}}async fetchTokensHeld(e){this.validateGetTokenListOptions(e);const t=na({page:e.page,limit:e.limit,address:e.address,search:e.search,tokenName:e.tokenName},{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),a=await this.http.get(Wt,t);Pt(a,"Failed to fetch tokens held",!0);const n=Ct(a.data),r=$t(a,{page:e.page||1,limit:e.limit||10}),s=_t(r.page,r.totalPages);return{tokens:n,...r,...s}}async fetchTokensCreated(e={}){const{page:t=1,limit:a=10,search:n,tokenName:r}=e,s={type:"DEFI",address:this.http.getAddress(),page:t,limit:a};return void 0!==n&&(s.search=n),void 0!==r&&(s.tokenName=r),this.fetchTokenList(s)}validateGetTokenListOptions(e){if(k(e.page,e.limit,da),void 0!==e.address&&!ua(e.address))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(void 0!==e.search&&e.search.trim().length>0&&!((t=e.search)&&"string"==typeof t&&t.length>=da.SEARCH.MIN_LENGTH&&t.length<=da.SEARCH.MAX_LENGTH))throw new y(`Search query must be between ${da.SEARCH.MIN_LENGTH} and ${da.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>=da.TOKEN_NAME.MIN_LENGTH&&a.length<=da.TOKEN_NAME.MAX_LENGTH))throw new y(`Token name must be between ${da.TOKEN_NAME.MIN_LENGTH} and ${da.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!ua(e.address))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=da.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=da.PROFILE.FULL_NAME.MAX_LENGTH&&da.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new y(`Full name must be between ${da.PROFILE.FULL_NAME.MIN_LENGTH} and ${da.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!ua(e.address))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class ga extends Error{constructor(e,t,a){super(e),this.filename=t,this.mimeType=a,this.name="FileValidationError"}}function ma(e,t,a){if(!e)throw new ga("File is required",t,a);if("undefined"!=typeof File&&e instanceof File){const t=me.safeParse(e);if(!t.success){const a=t.error.errors.map(e=>e.message).join("; ");throw new ga(a,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new ga("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 ga(e,t,a)}if(t.length>255)throw new ga(`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 ga(`Invalid file type "${a}" is not allowed. Allowed types: ${r.join(", ")}`,t,a);const s=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),o=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!o.includes(s))throw new ga(`File extension "${s}" is not allowed. Allowed extensions: ${o.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"}}(s);if(i!==a&&"application/octet-stream"!==i)throw new ga(`File extension "${s}" does not match MIME type "${a}"`,t,a);return}throw new ga("File must be a File object (browser) or Buffer (Node.js)",t,a)}class fa{constructor(e){this.http=e}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Et(t);const n=`${t}.png`;ma(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 Yt("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:`${Ot}?tokenName=${encodeURIComponent(a.tokenName??t)}`,data:e,headers:{}});return Pt(n,"Image upload failed"),"string"==typeof n.data?n.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw Zt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class ya{constructor(e){this.http=e}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount};Pt(await this.http.post(Ht,t),"Faucet transfer failed")}validateTransferFaucetsData(e){if(!ua(e.walletAddress))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!da.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new y("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class Aa{constructor(e){this.http=e,this.poolService=new aa(e),this.tradeService=new sa(e),this.commentService=new la(e,this.poolService),this.userService=new pa(e),this.imageService=new fa(e),this.faucetService=new ya(e)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(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 Et(e)}}class wa extends r.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 s;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`);s={collection:e[0],category:e[1],type:e[2],additionalKey:e[3],instance:"0"}}else s={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new wa({from:e,to:t,quantity:a,tokenInstance:s,uniqueKey:r||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,a,n){return new wa({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 va{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 t=e.replace("0x","");return`eth|${a.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 ka(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new y(`Invalid tokenId string format: "${e}". Expected format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");if(!(t[0]&&t[1]&&t[2]&&t[3]))throw new y(`Invalid tokenId string format: "${e}". All components (collection, category, type, additionalKey) must be non-empty`,"tokenId","INVALID_TOKEN_ID_FORMAT");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3],instance:t[4]||"0"}}if("object"==typeof e&&null!==e){if(!(e.collection&&e.category&&e.type&&e.additionalKey))throw new y("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return"instance"in e&&void 0!==e.instance?e:{...e,instance:"0"}}throw new y(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}var Ta=Object.freeze({__proto__:null,normalizeToTokenInstanceKey:ka});const ba={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var Ea;!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"}(Ea||(Ea={}));class Na extends Error{constructor(e,t,a){super(e),this.type=t,this.details=a,this.name="TransferError"}}class Sa{constructor(e,t,a,n=!1){this.http=e,this.wallet=t,this.tokenResolver=a,this.signatureHelper=new va(t),this.logger=new h({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 Jt(`Failed to fetch pool details: Status ${t.Status}`,t.Status);return t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(1!==e.Status)throw Jt(`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 y("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new y("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new y("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e){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 Jt(`Failed to fetch token balance from GalaChain: ${e.message||"Unknown error"}`,void 0,e)}}async transferGala(e){this.validateTransferGalaData(e);try{const t=N(e.recipientAddress),a=N(this.wallet.address),n=wa.forGALA(a,t,e.amount,e.uniqueKey),r=await this.signatureHelper.signTransferToken(n.toSigningPayload()),s=new wa({...n.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(s,null,2));const o=await this.http.post("/api/asset/token-contract/TransferToken",s);if(this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(o,null,2)),o&&"object"==typeof o){if("Status"in o&&1===o.Status&&"Data"in o){const e=o;return Array.isArray(e.Data)&&e.Data.length>0?"gala-transfer-successful":"transfer-successful-no-id"}if("transactionId"in o&&o.transactionId)return o.transactionId}throw new Na("Transfer succeeded but transaction ID could not be extracted",Ea.NETWORK_ERROR)}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){this.validateTransferTokenData(e);try{const t=N(e.to),a=N(this.wallet.address);let n;if(e.tokenId)n=ka(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 Na("Must provide either tokenId or tokenName for token identification",Ea.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const r=new wa({from:a,to:t,quantity:e.amount,tokenInstance:n,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),s=await this.signatureHelper.signTransferToken(r.toSigningPayload()),o=new wa({...r.toSigningPayload(),signedPayload:s});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(o,null,2));const i=await this.http.post("/api/asset/token-contract/TransferToken",o);if(this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(i,null,2)),i&&"object"==typeof i){if("Status"in i&&1===i.Status&&"Data"in i){const e=i;return Array.isArray(e.Data)&&e.Data.length>0?"token-transfer-successful":"transfer-successful-no-id"}if("transactionId"in i&&i.transactionId)return i.transactionId}throw new Na("Transfer succeeded but transaction ID could not be extracted",Ea.NETWORK_ERROR)}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 Na)throw t;throw new Na(`Failed to resolve token class key for '${e}': ${t instanceof Error?t.message:String(t)}`,Ea.TOKEN_NOT_FOUND,{tokenName:e})}}validateTransferGalaData(e){if(!((t=e)&&"object"==typeof t&&"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)throw new y("Invalid GALA transfer data: missing required fields");var t;if(!E(e.recipientAddress))throw new Na("Invalid recipient address format",Ea.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});if(parseFloat(e.amount)<=0)throw new Na("Transfer amount must be positive",Ea.INVALID_AMOUNT,{amount:e.amount});if(e.uniqueKey){if(e.uniqueKey.length>ba.MAX_UNIQUE_KEY_LENGTH)throw new y(`Unique key too long. Maximum length: ${ba.MAX_UNIQUE_KEY_LENGTH}`);if(!ba.UNIQUE_KEY_PATTERN.test(e.uniqueKey))throw new Na('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Ea.INVALID_AMOUNT,{uniqueKey:e.uniqueKey})}}validateTransferTokenData(e){if(!((t=e)&&"object"==typeof t&&"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)throw new y("Invalid token transfer data: missing required fields");var t;if(!E(e.to))throw new Na("Invalid recipient address format",Ea.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Na("Must provide either tokenId or tokenName for token identification",Ea.TOKEN_NOT_FOUND);if(e.tokenName&&!ba.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Na("Invalid token name format",Ea.TOKEN_NOT_FOUND,{tokenName:e.tokenName});if(parseFloat(e.amount)<=0)throw new Na("Transfer amount must be positive",Ea.INVALID_AMOUNT,{amount:e.amount});if(e.uniqueKey){if(e.uniqueKey.length>ba.MAX_UNIQUE_KEY_LENGTH)throw new y(`Unique key too long. Maximum length: ${ba.MAX_UNIQUE_KEY_LENGTH}`);if(!ba.UNIQUE_KEY_PATTERN.test(e.uniqueKey))throw new Na('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Ea.INVALID_AMOUNT,{uniqueKey:e.uniqueKey})}}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Na(`Token '${e}' not found or not available for transfer`,Ea.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 Na)throw t;throw new Na(`Failed to resolve token '${e}': ${t instanceof Error?t.message:String(t)}`,Ea.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){const[t,a]=e.split("|");if(!a)throw new Na(`Invalid vault address format: missing token components. Address: ${e}`,Ea.TOKEN_NOT_FOUND);const n=a.split("$");if(n.length<4)throw new Na(`Invalid vault address format: insufficient token components. Expected 4+, got ${n.length}. Address: ${e}`,Ea.TOKEN_NOT_FOUND);return{collection:n[0],category:n[1],type:n[2],additionalKey:n[3],instance:"0"}}handleTransferError(e,t,a){if(e instanceof Na)return e;if(e instanceof y)return new Na(e.message,Ea.INVALID_AMOUNT);if(400===e.response?.status)return new Na(e.response.data?.message||"Invalid transfer request",Ea.INVALID_AMOUNT);if(403===e.response?.status)return new Na("Insufficient balance for transfer",Ea.INSUFFICIENT_BALANCE);if(404===e.response?.status){const e={};return"tokenName"in a&&(e.tokenName=a.tokenName),new Na("Token not found",Ea.TOKEN_NOT_FOUND,e)}return"ECONNABORTED"===e.code||"ETIMEDOUT"===e.code?new Na("Transfer request timed out",Ea.NETWORK_ERROR):new Na(e.message||t,Ea.NETWORK_ERROR)}}class Ia{constructor(e){this.http=e}async fetchTokenSpotPrice(e){if(!e||Array.isArray(e)&&0===e.length)throw Xt("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 Jt(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`)}}async fetchLaunchpadTokenSpotPrice(e,t){if(!e||"string"!=typeof e)throw new Error(m);try{const a=await t({tokenName:e,amount:"1",type:"native"}),n=(await this.fetchTokenSpotPrice("GALA"))[0];if(!n)throw Jt("GALA price not available");const r=Number(a.amount)/1e18;if(r<=0)throw new y(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const s=n.price/r;return{symbol:e.toUpperCase(),price:s}}catch(t){if(t instanceof Error)throw Jt(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw Jt(`Failed to calculate launchpad token spot price for ${e}: ${String(t)}`)}}}function Da(e,t=18){const a=parseFloat(e);if(0===a)return"0";return a.toFixed(t).replace(/\.?0+$/,"")}function xa(e){return Da(e,8)}function Fa(e){return Da(e,18)}new h({debug:!1,context:"NumberUtils"});class Ca extends r.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=xa(t),this.expectedToken=Fa(a),this.extraFees={maxAcceptableReverseBondingCurveFee:xa(n.maxAcceptableReverseBondingCurveFee)}}}class $a extends r.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Fa(t),this.expectedNativeToken=xa(a),this.extraFees={maxAcceptableReverseBondingCurveFee:xa(n.maxAcceptableReverseBondingCurveFee)}}}class _a extends r.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Fa(t),this.expectedNativeToken=xa(a),this.extraFees={maxAcceptableReverseBondingCurveFee:xa(n.maxAcceptableReverseBondingCurveFee)}}}class Pa extends r.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=xa(t),this.expectedToken=Fa(a),this.extraFees={maxAcceptableReverseBondingCurveFee:xa(n.maxAcceptableReverseBondingCurveFee)}}}const Oa={BuyNativeDto:Ca,BuyExactDto:$a,SellExactDto:_a,SellNativeDto:Pa};var La,Ua,Ra;!function(e){e[e.METAMASK=0]="METAMASK",e[e.TRUST_WALLET=1]="TRUST_WALLET",e[e.GALA_WALLET=2]="GALA_WALLET"}(La||(La={}));class Ba{constructor(e,t=!1){this.walletProvider=e,this.debug=t,this.logger=new h({debug:t,context:"SignatureService"})}async signDTO(e,t,a,n=La.METAMASK){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,walletPreference:n,dtoKeys:Object.keys(e)});const s=this.generateEIP712Types(t,e),o=r.calculatePersonalSignPrefix(e),i={...e,prefix:o};let c,l,d;switch(n){case La.GALA_WALLET:({signature:c,domain:l}=await this.signWithGalaWallet(s,i,t,a));break;case La.TRUST_WALLET:c=await this.signWithTrustWallet(i),l={name:"ethereum",chainId:1};break;case La.METAMASK:default:({signature:c,domain:l}=await this.signWithMetaMask(s,i))}return d=n===La.TRUST_WALLET?{...i,signature:c}:{...e,signature:c,types:s,domain:l},this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(d),signatureLength:c.length}),d}catch(e){throw this.logger.error("❌ Signature generation failed:",e),ea(`Failed to sign DTO: ${e.message}`)}}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 Zt("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 ea(`MetaMask/ethers signing failed: ${e.message}`)}}async signWithTrustWallet(e){try{const a=(t=e,JSON.stringify(t));let n;if(!this.walletProvider.signMessage)throw Zt("Wallet provider does not support signMessage","walletProvider");return n=await this.walletProvider.signMessage(a),n}catch(e){throw ea(`TrustWallet signing failed: ${e.message}`)}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 s={domain:r,types:e,message:t,Primary_type:a},o=window;if(!o?.gala)throw Zt("GalaWallet not found in window object","galaWallet");await o.gala.setAddress(n);return{signature:await o.gala.request({method:"eth_signTypedData",params:[JSON.stringify(s),n]}),domain:r}}catch(e){throw ea(`GalaWallet signing failed: ${e.message}`)}}generateEIP712Types(e,t){const a={};a[e]=[];const n=(e,t,r,s=!1)=>{if(void 0!==t){if(Array.isArray(t)){const o=n(e,t[0],r,!0);return s||a[r].push({name:e,type:(o??e)+"[]"}),o?o+"[]":void 0}if("object"==typeof t&&null!==t){if(a[e])throw new y(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return a[e]=[],Object.entries(t).forEach(([t,a])=>{n(t,a,e)}),s||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 y(`Unsupported type for fieldName ${e}: ${typeof t}, value: ${t}`,"fieldValue","UNSUPPORTED_TYPE")}return s||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 La.METAMASK;const e=window;return e?.gala?La.GALA_WALLET:e?.trustWallet?.isTrust?La.TRUST_WALLET:La.METAMASK}}class Ka{constructor(e=!1){this.debug=e,this.logger=new h({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`,s=`$tokenBalance$${a.toStringKey()}$${e}`,o=`$tokenBalance$${a.toStringKey()}$${e}`,i=`$tokenBalance$${n.toStringKey()}$${e}`,c=[r,s,o,i,`$tokenBalance$${n.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){throw this.logger.error("❌ Failed to generate stringsInstructions:",e),new y(`Failed to generate stringsInstructions: ${e.message}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new o.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 o.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 Xt("vaultAddress","Vault address");const t=e.split("$");if(t.length<3)throw Yt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");const a=t[2];if(!a||0===a.trim().length)throw new y(`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 Xt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Yt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Yt("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw Yt("vaultAddress",'having at least 5 parts separated by "$"');const a=t[2];if(!a||!/^[A-Za-z]{1,10}$/.test(a))throw Yt("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 Yt("stringKey","format: collection$category$type$additionalKey (4 parts)");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}}function Ma(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 i(e);if(n.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const r=n.multipliedBy(t);let 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 i(0)),s.toFixed()}class Ga{constructor(e,t,a=!1,n,r,s=.05,o=.01){this.httpClient=e,this.tokenResolver=t,this.walletProvider=n,this.userAddress=r,this.defaultSlippageToleranceFactor=s,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=o,this.bundleEndpoint="/bundle",this.logger=new h({debug:a,context:"BundleService"}),n&&r&&(this.signatureService=new Ba(n,a),this.tokenKeyService=new Ka(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 Xt("bundleData","Bundle data");if(!e.signedDto)throw Xt("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw Xt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Yt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new y("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Yt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new y(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new y(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT")}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){if(e.data&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",e.data),{success:!0,data:e.data};const t=e.error||e.message||"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",t),{success:!1,error:t}}formatErrorMessage(e){return"string"==typeof e?e:e?.response?.data?.error?e.response.data.error:e?.response?.data?.message?e.response.data.message:e?.message?e.message:"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw Xt("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 Xt("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,maxAcceptableReverseBondingCurveFee:s,maxAcceptableReverseBondingCurveFeeSlippageFactor:o,slippageToleranceFactor:i}=e,c=i??this.defaultSlippageToleranceFactor,l=o??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let d=s||"0";s&&(d=Ma(s,l,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:s,slippageFactor:l,adjustedMaxFee:d}));const u=await this.resolveTokenNameToVault(t);if(!u)throw Qt(t);if("native"===n){if(!r)throw new y("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ma(r,c,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:r,slippageFactor:c,adjustedMinTokens:e});const t=new Oa.BuyNativeDto(u,a,e,{maxAcceptableReverseBondingCurveFee:d});return await this.executeBundleTransaction(t,"BuyWithNative",u)}{if(!r)throw new y("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ma(r,c,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:r,slippageFactor:c,adjustedMaxGalaCost:e});const t=new Oa.BuyExactDto(u,a,e,{maxAcceptableReverseBondingCurveFee:d});return await this.executeBundleTransaction(t,"BuyExactToken",u)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:a,type:n,expectedAmount:r,maxAcceptableReverseBondingCurveFee:s,maxAcceptableReverseBondingCurveFeeSlippageFactor:o,slippageToleranceFactor:i}=e,c=i??this.defaultSlippageToleranceFactor,l=o??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let d=s||"0";s&&(d=Ma(s,l,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:s,slippageFactor:l,adjustedMaxFee:d}));const u=await this.resolveTokenNameToVault(t);if(!u)throw Qt(t);if("exact"===n){if(!r)throw new y("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ma(r,c,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:r,slippageFactor:c,adjustedMinGala:e});const t=new Oa.SellExactDto(u,a,e,{maxAcceptableReverseBondingCurveFee:s||"0"});return await this.executeBundleTransaction(t,"SellExactToken",u)}{if(!r)throw new y("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ma(r,c,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:r,slippageFactor:c,adjustedMaxTokensToSell:e});const t=new Oa.SellNativeDto(u,a,e,{maxAcceptableReverseBondingCurveFee:s||"0"});return await this.executeBundleTransaction(t,"SellWithNative",u)}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw Zt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw Xt("userAddress","User address")}async executeBundleTransaction(e,t,a){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${c.v4()}-${Date.now()}-${this.userAddress}`;const n=await this.signatureService.signDTO(e,t,this.userAddress),r=this.tokenKeyService.generateStringsInstructions(a),s={stringsInstructions:r,method:t,signedDto:n};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:r,dtoKeys:Object.keys(n)});const o=await this.submitTransaction(s);if(o.success&&o.data)return this.logger.debug("✅ Bundle transaction submitted:",o.data),{success:!0,data:{transactionId:o.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(o.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"}(Ua||(Ua={})),exports.SDKTransactionStatus=void 0,(Ra=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",Ra.PROCESSING="processing",Ra.COMPLETED="completed",Ra.FAILED="failed",Ra.TIMEOUT="timeout";const za={[Ua.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[Ua.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[Ua.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[Ua.FAILED]:exports.SDKTransactionStatus.FAILED,[Ua.ERROR]:exports.SDKTransactionStatus.FAILED,[Ua.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[Ua.PENDING]:exports.SDKTransactionStatus.PENDING};class Va{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 h({debug:t,context:"WebSocketService"}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof l.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=l.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(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const a=setTimeout(()=>{if(this.listeners.has(e)){const a={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:"Transaction monitoring timeout - no response after 60 seconds",timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e}`),t(a),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},6e4);if(this.timeouts.set(e,a),this.socket&&this.socket.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,a=>{this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(a,null,2));const n=a?.status||a?.Status||a?.data?.status||a?.data?.Status;let r=a?.message||a?.Message||a?.data?.message||a?.data?.Message||a?.error||a?.data?.error;r&&"string"==typeof r||(r=n===Ua.FAILED||n===Ua.ERROR?"Transaction failed - check transaction details":n===Ua.COMPLETED||n===Ua.PROCESSED||n===Ua.SUCCESS?"Transaction completed successfully":n?`Transaction status: ${n}`:"Unknown transaction status");const s={transactionId:e,status:this.mapSocketStatus(n),message:r,timestamp:Date.now(),blockHash:a?.blockHash||a?.data?.blockHash,gasUsed:a?.gasUsed||a?.data?.gasUsed};if(this.logger.debug(`📡 Mapped status for ${e}: ${n} -> ${s.status}`),this.logger.debug(`📡 Final message: "${r}"`),t(s),s.status===exports.SDKTransactionStatus.COMPLETED||s.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${s.status})`)}});else{const a={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(a),this.listeners.delete(e),this.timeouts.delete(e)}}async waitForTransaction(e){return new Promise((t,a)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||a(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return za[t]||exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectCount<this.config.reconnectAttempts?(this.reconnectCount++,this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectCount}/${this.config.reconnectAttempts}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.config.reconnectDelay)):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.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 qa{constructor(e){this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!b(e))throw new y("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 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:a}of e)this.set(t,a)}parseVaultAddressToTokenClassKey(e){const t=e.split("|");if(2!==t.length)throw Yt("vaultAddress","format: service|Token$Unit$...$launchpad","Vault address");const a=t[1].split("$");if(a.length<4)throw Yt("vaultAddress","at least 4 parts after service|","Vault address");return{collection:a[0],category:a[1],type:a[2],additionalKey:a[3]}}}function ja(e){const t=function(e){const t=st(e);return t.success?[]:t.errors||["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}const Wa="/api/asset/launchpad-contract/CallNativeTokenIn",Ha="/api/asset/launchpad-contract/CallNativeTokenOut",Qa="/api/asset/launchpad-contract/CallMemeTokenIn",Xa="/api/asset/launchpad-contract/CallMemeTokenOut";class Ya extends r.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 Ja(e){return e&&"object"==typeof e&&"number"==typeof e.Status&&e.Data&&"object"==typeof e.Data&&"string"==typeof e.Data.calculatedQuantity&&e.Data.extraFees&&"object"==typeof e.Data.extraFees&&"string"==typeof e.Data.extraFees.reverseBondingCurve&&"string"==typeof e.Data.extraFees.transactionFees}const Za={NATIVE:"native",EXACT:"exact"};class en{constructor(e,t,a,n,r,s){this.http=e,this.tokenResolver=t,this.logger=a,this.bundleHttp=n,this.galaChainHttp=r,this.dexApiHttp=s}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Et(t);const n=`${t}.png`;ma(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 Yt("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 Jt(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 Zt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){Nt(e),e.tokenName&&Et(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=p(t),n=await this.http.get("/launchpad/fetch-pool",a);if(!0===n.error||200!==n.status||!n.data)throw Jt(n.message||"Failed to fetch pools",n.status);let r=[];return n.data.tokens?r=Array.isArray(n.data.tokens)?n.data.tokens.map(e=>({...e,createdAt:new Date(e.created_at||e.createdAt)})):[{...n.data.tokens,createdAt:new Date(n.data.tokens.created_at||n.data.tokens.createdAt)}]:n.data.pools&&Array.isArray(n.data.pools)&&(r=n.data.pools.map(e=>({...e,createdAt:new Date(e.created_at||e.createdAt)}))),{pools:r,page:n.data.page,limit:n.data.limit,total:n.data.total,totalPages:n.data.totalPages,hasNext:n.data.page<n.data.totalPages,hasPrevious:n.data.page>1}}async _getAmount(e){if(It(e),!this.galaChainHttp)throw Zt("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:Wa,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:Ha,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:Qa,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:Xa,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};throw Yt("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(!Ja(e))throw Jt("Malformed response data from GalaChain gateway");if(1!==e.Status)throw Jt(`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){St(e),e.tokenName&&Et(e.tokenName);const t=p(e),a=await this.http.get("/launchpad/check-pool",t);if(!0===a.error||200!==a.status)throw Jt(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(!ta(e))throw new y("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(Et(t),!a||!n||!r)throw new y("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const s={tokenName:t,from:a,to:n,resolution:r};Dt(s);const o=p(s),i=await this.http.get("/launchpad/get-graph-data",o);if(!0===i.error||200!==i.status||!i.data)throw Jt(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 y("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:a,type:n}=e;if(!t||"string"!=typeof t)throw new y("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!a||"string"!=typeof a)throw new y("Amount is required and must be a string","amount","INVALID_AMOUNT");const r=await this.tokenResolver.resolveTokenToVault(t);if(!r)throw new y(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");if(n!==Za.NATIVE&&n!==Za.EXACT)throw new y('Type must be either "native" or "exact"',"type","INVALID_TYPE");return n===Za.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}=e,r=await this.tokenResolver.resolveTokenToVault(t);if(!r)throw new y(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Za.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:r,amount:a}):this._getAmount({type:"MEME",method:"IN",vaultAddress:r,amount:a})}async calculateBuyAmountForGraduation(e){Et(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new y(f(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw Zt("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==a.Status)throw Jt(`Failed to fetch pool details: Status ${a.Status}`,a.Status);const n=a.Data.sellingTokenQuantity;if("0"===n)throw new y(`Token ${e} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");return await this.calculateBuyAmount({tokenName:e,amount:n,type:"exact"})}async launchToken(e){if(!this.bundleHttp)throw Zt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");ja(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new y("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:a}=e.reverseBondingCurveConfiguration,n=Number(t),r=Number(a);if(isNaN(n)||isNaN(r)||n<=0||r<=0||n>=r)throw new y("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 Jt("Image upload failed: No URL returned");a=t}else"string"==typeof e.tokenImage&&(a=e.tokenImage);const n=`galaswap - operation - ${c.v4()}-${Date.now()}-${this.http.getAddress()}`,s={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:n};e.reverseBondingCurveConfiguration&&(s.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const o=new Ya(s),i=await this.http.signWithGalaChain("CreateSale",o,r.SigningType.SIGN_TYPED_DATA),{signature:l,types:d,domain:u,prefix:h}=i,p={tokenName:o.tokenName,tokenSymbol:o.tokenSymbol,tokenDescription:o.tokenDescription,tokenImage:o.tokenImage,preBuyQuantity:o.preBuyQuantity,websiteUrl:o.websiteUrl,telegramUrl:o.telegramUrl,twitterUrl:o.twitterUrl,tokenCategory:o.tokenCategory,tokenCollection:o.tokenCollection,uniqueKey:o.uniqueKey,signature:l,types:d,domain:u,...h&&{prefix:h},...o.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:o.reverseBondingCurveConfiguration}},g=`${e.tokenName.trim()}$Unit$none$none`,m="GALA$Unit$none$none";let f;if(parseFloat(t)>0){const e=`$service$${g}$launchpad`;f=[e,`$token$${g}$${e}`,`$tokenBalance$${g}$${e}`,`$tokenBalance$${g}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`]}else{const e=`$service$${g}$launchpad`;f=[e,`$token$${g}$${e}`,`$tokenBalance$${g}$${e}`]}const A={signedDto:p,stringsInstructions:f,method:"CreateSale"},w=await this.bundleHttp.post("/bundle",A);if(w.error||!w.data)throw Jt(w.message||"Token launch failed");return w.data}async fetchTokenDistribution(e){if(!e)throw Xt("tokenName","Token name");Et(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new y(f(e),"tokenName","VAULT_NOT_FOUND");const a=encodeURIComponent(t),n=await this.http.get(`/holders/${a}`);if(!0===n.error||200!==n.status||!n.data)throw Jt(n.message||"Failed to fetch token distribution",n.status);return{holders:n.data.holders||[],totalSupply:n.data.totalSupply||"0",totalHolders:n.data.totalHolders||0,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Xt("tokenName","Token name");Et(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw Jt(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(!(t=e)||"object"!=typeof t||"string"!=typeof t.nativeTokenQuantity||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)throw new y("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");var t;if(!this.galaChainHttp)throw Zt("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(!Ja(a))throw Jt("Malformed response data from GalaChain gateway");if(1!==a.Status)throw Jt(`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)}`)}}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return xt(e)}validateTokenName(e){return Et(e)}validatePagination(e){return Nt(e)}async fetchTokenSpotPrice(e){if(!this.dexApiHttp)throw Zt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw Xt("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 Jt(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(e){if(!e||"string"!=typeof e)throw Xt("tokenName","Token name (string)");try{const t=await this.calculateBuyAmount({tokenName:e,amount:"1",type:"native"}),a=(await this.fetchTokenSpotPrice("GALA"))[0];if(!a)throw Jt("GALA price not available");const n=Number(t.amount)/1e18;if(n<=0)throw new y(`Invalid token amount calculation: ${n}`,"amount","INVALID_CALCULATION");const r=a.price/n;return{symbol:e.toUpperCase(),price:r}}catch(t){if(t instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${e}: ${String(t)}`)}}}const tn={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-dev1.defi.gala.com"}};function an(e){return tn[e]}class nn extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class rn 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 sn(e,t){if(!e)throw new nn(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new nn(`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 nn(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function on(e,t,a,n){sn(e,t);const r=e?.data||{};if(!(s=r)||"object"!=typeof s||void 0!==s.inputQuantity&&"string"!=typeof s.inputQuantity||void 0!==s.outputQuantity&&"string"!=typeof s.outputQuantity||void 0!==s.totalFees&&"string"!=typeof s.totalFees||void 0!==s.vaultAddress&&"string"!=typeof s.vaultAddress)throw new nn(`Invalid trade data received for transaction ${t}`);var s;const o={transactionId:t,type:a,method:"native"===n.type?"native":"exact",inputAmount:r.inputQuantity||n.amount,outputAmount:r.outputQuantity||n.expectedAmount||"0",totalFees:r.totalFees||"0",tokenName:n.tokenName,vaultAddress:r.vaultAddress||"",blockHash:e.blockHash,gasUsed:e.gasUsed,timestamp:Date.now()};return void 0!==n.slippageToleranceFactor&&(o.slippageTolerance=n.slippageToleranceFactor),o}class cn{constructor(e){let t=null;t=e.env?an(e.env):e.baseUrl?.includes("prod")?an("PROD"):an("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 h({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?cn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?cn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.auth=new u({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new g(this.auth,this.config),this.galaChainHttp=new g(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new g(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new g(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.launchpadService=new Aa(this.http),this.tokenResolverService=new qa(this.launchpadService.poolService),this.launchpadAPI=new en(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp),this.galaChainService=new Sa(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1),this.dexService=new Ia(this.dexApiHttp),this.bundleService=new Ga(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,this.getAddress(),this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Va({url:this.config.webSocketUrl},this.config.debug)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw Zt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Zt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new a.Wallet(e),n={...this.config,wallet:t};return new cn(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}}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw Zt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){return this.launchpadService.fetchPools(e||{})}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 Jt("Failed to fetch GALA price - no price data returned");const t=e.find(e=>"GALA"===e.symbol);if(!t)throw Jt("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(f(e));return(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data}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 Ft}),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 Ft}),a=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Ta}),n=t(e.tokenId),{collection:r,category:s,type:o,additionalKey:i}=n;return this.galaChainService.fetchTokenBalance({owner:a,collection:r,category:s,additionalKey:i,type:o,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 Xt("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 calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:a,maxAcceptableReverseBondingCurveFeeSlippageFactor:n,privateKey:r}=e,s=await this.calculateBuyAmountForGraduation(t),o={tokenName:t,amount:s.amount,type:"exact",expectedAmount:s.amount,maxAcceptableReverseBondingCurveFee:s.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==a&&(o.slippageToleranceFactor=a),void 0!==n&&(o.maxAcceptableReverseBondingCurveFeeSlippageFactor=n),void 0!==r&&(o.privateKey=r),await this.buy(o)}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),a=t.data?.transactionId;if(!a)throw ea("No transaction ID returned from buy operation");return this.waitForConfirmation(a,t=>on(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),a=t.data?.transactionId;if(!a)throw ea("No transaction ID returned from sell operation");return this.waitForConfirmation(a,t=>on(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=>{sn(a,t);const n=a?.data||{};if(!function(e){return!(!e||"object"!=typeof e||void 0!==e.vaultAddress&&"string"!=typeof e.vaultAddress||void 0!==e.tokenStringKey&&"string"!=typeof e.tokenStringKey||void 0!==e.creatorAddress&&"string"!=typeof e.creatorAddress)}(n))throw new nn(`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 Ft}),a=t(e)||this.getAddress();return this.launchpadService.fetchProfile(a)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ft}),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 Ft}),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 Ft}),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 Ft}),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 Ft}),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 Ft}),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 Ft}),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)}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 Zt("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw Zt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Zt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Zt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw Zt(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Zt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Zt(`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: ${cn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),cn.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: ${cn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),cn.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 rn(e,a.status,a.message);let n;try{n=t(a)}catch(t){if(t instanceof nn)throw t;throw new nn(`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 rn||t instanceof nn)throw t;throw new nn(`WebSocket confirmation failed for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),this.websocketService&&this.websocketService.disconnect(),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new h({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:a}=require("./services/WebSocketService");a.cleanupAll(e),t.debug("Global cleanup completed")}}cn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,cn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01;class ln{static generateWallet(){try{const e=a.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 a.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 a.Wallet(t),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 t=new a.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=a.Mnemonic.fromPhrase(e),r=a.HDNodeWallet.fromMnemonic(n,`m/44'/60'/0'/0/${t}`),s=new a.Wallet(r.privateKey),o=this.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:o,mnemonic:e,wallet:s}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${t}-${e}`,r="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),s=new a.Wallet(r),o=this.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:o,mnemonic:e,wallet:s}}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 dn(e){if(void 0===e)return ln.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 ln.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 ln.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?"...":""}"`)}ln.testCounter=0;exports.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 cn(n),s={sdk:r,wallet:a,config:n};if(!1!==e.autoValidate){const e=await this.validateSetup(r,a);return{...s,validation:e}}return s}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||ln.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?ln.fromPrivateKey(e):ln.generateWallet()}return"generate"===e?ln.generateWallet():ln.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}},exports.FileValidationError=ga,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.IMAGE_EXTENSIONS=pe,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LaunchpadSDK=cn,exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.SDK_VERSION="3.7.0",exports.TRADING_TYPES=Za,exports.TransactionFailedError=rn,exports.ValidationError=y,exports.WebSocketError=nn,exports.WebSocketTimeoutError=class extends nn{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.addressFormatSchema=$,exports.amountMethodSchema=de,exports.amountTypeSchema=le,exports.browserFileSchema=me,exports.bufferFileSchema=fe,exports.buyTokensDataSchema=Re,exports.calculatePreMintDataSchema=qe,exports.checkPoolOptionsSchema=ce,exports.commentMessageSchema=Q,exports.commentPaginationSchema=be,exports.createLaunchpadSDK=function(e){const{wallet:t,env:n,config:r={}}=e||{};let s;if(t)if("string"==typeof t){s=dn(t).wallet}else{if(!(t instanceof a.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");s=t}else{s=dn().wallet}const o={wallet:s,...n&&{env:n},debug:!1,timeout:3e4,...r};return new cn(o)},exports.createLimitSchema=G,exports.createPaginatedResultSchema=function(e){return s.z.object({data:s.z.array(e),page:s.z.number().int().min(1),limit:s.z.number().int().min(1),total:s.z.number().int().min(0),totalPages:s.z.number().int().min(0),hasNext:s.z.boolean(),hasPrevious:s.z.boolean()})},exports.createTradeDataSchema=Ue,exports.createWallet=dn,exports.ethereumAddressSchema=_,exports.faucetAmountSchema=R,exports.fetchGalaBalanceOptionsSchema=Ce,exports.fetchPoolDetailsDataSchema=je,exports.fetchTokenBalanceOptionsSchema=Pe,exports.fileSizeSchema=j,exports.fileUploadSchema=ge,exports.filenameSchema=W,exports.flexibleAddressSchema=P,exports.flexibleFileSchema=ye,exports.formatGalaForDTO=xa,exports.formatLaunchpadTokenForDTO=Fa,exports.fullNameSchema=C,exports.getAmountOptionsSchema=Ve,exports.getTradeOptionsSchema=Ke,exports.graduateTokenOptionsSchema=he,exports.graphDataOptionsSchema=ue,exports.imageExtensionSchema=Ae,exports.imageFilenameSchema=we,exports.imageMimeTypeSchema=H,exports.imageUploadOptionsSchema=oe,exports.isoDateStringSchema=X,exports.launchTokenDataSchema=se,exports.nonNegativeDecimalStringSchema=U,exports.optionalUrlSchema=K,exports.pageNumberSchema=M,exports.paginationResultMetaSchema=Ie,exports.poolFetchTypeSchema=ie,exports.poolPaginationSchema=Ee,exports.positiveDecimalStringSchema=L,exports.privateKeySchema=J,exports.reverseBondingCurveConfigSchema=re,exports.reverseBondingCurveConfigurationSchema=We,exports.searchQuerySchema=F,exports.sellTokensDataSchema=Be,exports.standardLimitSchema=z,exports.standardPaginationSchema=ve,exports.timestampSchema=Y,exports.tokenCategorySchema=ae,exports.tokenCollectionSchema=ne,exports.tokenDescriptionSchema=D,exports.tokenListOptionsSchema=xe,exports.tokenNameSchema=S,exports.tokenSymbolSchema=I,exports.tokenUrlsSchema=te,exports.tradeCalculationMethodSchema=ze,exports.tradeCalculationTypeSchema=Ge,exports.tradeLimitSchema=q,exports.tradeListParamsSchema=Me,exports.tradePaginationSchema=Te,exports.tradePaginationWithFiltersSchema=Se,exports.tradeTypeBackendSchema=Le,exports.tradeTypeSchema=Oe,exports.transactionIdSchema=Z,exports.transferFaucetsDataSchema=Fe,exports.uniqueKeySchema=ee,exports.updateProfileDataSchema=$e,exports.uploadProfileImageOptionsSchema=_e,exports.urlSchema=B,exports.userLimitSchema=V,exports.userPaginationSchema=ke,exports.userTokenNameSchema=x,exports.userTokenTypeSchema=De,exports.userTokensPaginationSchema=Ne,exports.validateAddress=Je,exports.validateAmountString=et,exports.validateBuyTokensData=ft,exports.validateCalculatePreMintData=kt,exports.validateCheckPoolOptions=ct,exports.validateCreateTradeData=mt,exports.validateFaucetAmount=tt,exports.validateFetchGalaBalanceOptions=ut,exports.validateFetchPoolDetailsData=Tt,exports.validateFetchTokenBalanceOptions=gt,exports.validateFullName=at,exports.validateGetAmountOptions=vt,exports.validateGetTradeOptions=At,exports.validateImageUploadOptions=it,exports.validateLaunchTokenData=st,exports.validateSearchQuery=nt,exports.validateSellTokensData=yt,exports.validateTokenDescription=Ye,exports.validateTokenListOptions=lt,exports.validateTokenName=Qe,exports.validateTokenSymbol=Xe,exports.validateTokenUrls=ot,exports.validateTradeListParams=wt,exports.validateTransferFaucetsData=dt,exports.validateUpdateProfileData=ht,exports.validateUploadProfileImageOptions=pt,exports.validateUserTokenName=rt,exports.validateVaultAddress=Ze,exports.vaultAddressSchema=O;
1
+ "use strict";var e,t,a=require("ethers"),n=require("axios"),r=require("@gala-chain/connect"),s=require("zod"),o=require("@gala-chain/api"),i=require("bignumber.js"),c=require("uuid"),l=require("socket.io-client");!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"}(e||(e={}));class u extends Error{constructor(e,t,a){super(t),this.type=e,this.originalError=a,this.name="AuthError"}}class d{constructor(t){if(this.wallet=t.wallet,this.messagePrefix=t.messagePrefix||"Create a GalaChain Wallet",""===t.messagePrefix)throw new u(e.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(t){throw new u(e.SIGNATURE_FAILED,"Failed to generate signature for authentication",t instanceof Error?t:new Error(String(t)))}}getAddress(){return this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.wallet.address}formatAddress(t){const a=t.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(a))throw new u(e.INVALID_ADDRESS,`Invalid Ethereum address format: ${t}`);return`eth|${a}`}async signMessage(t){try{return{message:t,signature:await this.wallet.signMessage(t),address:this.wallet.address,timestamp:Date.now()}}catch(t){const a=t instanceof Error?t.message:String(t);throw new u(e.SIGNATURE_FAILED,a,t instanceof Error?t:new Error(String(t)))}}async generateAuthHeaders(t,a){try{const e=Date.now(),n=`${this.messagePrefix} ${a.toUpperCase()} ${t} ${e}`,r=await this.wallet.signMessage(n);return{"x-signature":r,"x-address":this.formatAddress(this.wallet.address),"x-message":n,"x-timestamp":e.toString()}}catch(t){throw new u(e.SIGNATURE_FAILED,"Failed to generate authentication headers",t instanceof Error?t:new Error(String(t)))}}async signTypedData(t,a,n){try{return await this.wallet.signTypedData(t,a,n)}catch(t){throw new u(e.SIGNATURE_FAILED,"Failed to sign typed data",t instanceof Error?t:new Error(String(t)))}}async generateCustomSignature(t){if(!t||"string"!=typeof t||0===t.trim().length)throw new u(e.SIGNATURE_FAILED,"Custom message must be a non-empty string");try{const e=await this.wallet.signMessage(t);return{message:t,signature:e,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(t){throw new u(e.SIGNATURE_FAILED,"Failed to generate custom message signature",t instanceof Error?t:new Error(String(t)))}}validateWallet(){if(!this.wallet)throw new u(e.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new u(e.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new u(e.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"}(t||(t={}));class h{constructor(e){this.levelPriority={[t.DEBUG]:0,[t.INFO]:1,[t.WARN]:2,[t.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?t.DEBUG:t.INFO)}debug(e,a){this.log(t.DEBUG,e,a)}info(e,a){this.log(t.INFO,e,a)}warn(e,a){this.log(t.WARN,e,a)}error(e,a){this.log(t.ERROR,e,a)}log(e,a,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===t.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?n instanceof Error?s(`${r} ${a}`,n.message,n.stack):s(`${r} ${a}`,n):s(`${r} ${a}`)}getConsoleMethod(e){switch(e){case t.DEBUG:return console.debug;case t.INFO:return console.info;case t.WARN:return console.warn;case t.ERROR:return console.error;default:return console.log}}child(e){return new h({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[t.DEBUG]>=this.levelPriority[this.minLevel]}}function p(e){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 g{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new h({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:p(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=r.SigningType.SIGN_TYPED_DATA){const n=this.auth.wallet.privateKey;if(!n)throw new Error("Wallet private key not available for @gala-chain signing");const s=new r.SigningClient(n);return await s.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 m="Token name is required and must be a string",f=e=>`Could not find vault address for token: ${e}`;class y 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 v extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class w extends Error{constructor(e,t,a){super(e),this.transactionId=t,this.code=a,this.name="TransactionError"}}function T(e,t,a){const{MIN_PAGE:n,MAX_PAGE:r,MIN_LIMIT:s,MAX_LIMIT:o}=a.PAGINATION;if("number"!=typeof e||e<n||e>r)throw new y(`Page must be a number between ${n} and ${r}`,"page","INVALID_PAGE");if("number"!=typeof t||t<s||t>o)throw new y(`Limit must be a number between ${s} and ${o}`,"limit","INVALID_LIMIT")}const k={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 N(e){return!(!e||"string"!=typeof e)&&(k.ETH_ADDRESS.test(e)||k.BACKEND_ADDRESS.test(e))}function b(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const S=s.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"),I=s.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"),F=s.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),D=s.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),C=s.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),x=s.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"),_=s.z.string().regex(k.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),P=s.z.string().regex(k.ETH_ADDRESS,"Invalid Ethereum address format"),L=s.z.string().refine(e=>k.BACKEND_ADDRESS.test(e)||k.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),$=s.z.string().refine(e=>k.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),O=s.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),U=s.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),B=s.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),R=s.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),M=s.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),K=s.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 G(e=100){return s.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=G(100),V=G(20),q=G(20),W=s.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"),j=s.z.string().max(255,"Filename must be at most 255 characters"),H=s.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Q=s.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),X=s.z.string().datetime("Must be a valid ISO 8601 date string"),Y=s.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Z=s.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),J=s.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"),ee=s.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),te=s.z.object({websiteUrl:M,telegramUrl:M,twitterUrl:M}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),ae=s.z.string().min(1,"Token category must not be empty").default("Unit"),ne=s.z.string().min(1,"Token collection must not be empty").default("Token"),re=s.z.object({minFeePortion:O,maxFeePortion:O}),se=s.z.object({tokenName:S,tokenSymbol:I,tokenDescription:F,tokenImage:s.z.union([s.z.instanceof(File),s.z.instanceof(Buffer),s.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:U.default("0"),websiteUrl:M,telegramUrl:M,twitterUrl:M,tokenCategory:ae,tokenCollection:ne,reverseBondingCurveConfiguration:re.optional(),privateKey:Z.optional()}),oe=s.z.object({file:s.z.union([s.z.instanceof(File),s.z.instanceof(Buffer)]),tokenName:S}),ie=s.z.enum(["recent","popular"]),ce=s.z.object({tokenName:S.optional(),symbol:I.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),le=s.z.enum(["NATIVE","MEME"]),ue=s.z.enum(["IN","OUT"]),de=s.z.object({from:s.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:s.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:s.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:S}),he=s.z.object({tokenName:S,slippageToleranceFactor:s.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:s.z.number().min(0).max(1).optional(),privateKey:Z.optional()}),pe=[".png",".jpg",".jpeg",".gif",".webp",".svg"],ge=s.z.object({file:s.z.union([s.z.instanceof(File),s.z.instanceof(Buffer)]),name:j,size:W,type:H}),me=s.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"),fe=s.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),ye=s.z.union([me,fe]),Ae=s.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),ve=j.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return pe.includes(t)},`Filename must end with one of: ${pe.join(", ")}`),we=s.z.object({page:K,limit:z}),Te=s.z.object({page:K,limit:V}),ke=s.z.object({page:K,limit:q}),Ee=s.z.object({page:K,limit:G(50)}),Ne=we.extend({type:s.z.enum(["recent","popular"]).optional(),tokenName:s.z.string().min(1).max(50).optional(),search:s.z.string().min(1).max(100).optional()}),be=Te.extend({tokenName:s.z.string().min(1).max(50).optional(),search:s.z.string().min(1).max(100).optional()}),Se=ke.extend({tradeType:s.z.enum(["BUY","SELL"]).optional(),tokenName:s.z.string().min(1).max(50).optional(),userAddress:s.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:s.z.string().datetime().optional(),endDate:s.z.string().datetime().optional(),sortOrder:s.z.enum(["ASC","DESC"]).default("DESC")}),Ie=s.z.object({page:s.z.number().int().min(1),limit:s.z.number().int().min(1),total:s.z.number().int().min(0),totalPages:s.z.number().int().min(0),hasNext:s.z.boolean(),hasPrevious:s.z.boolean()});const Fe=s.z.enum(["all","DEFI","ASSET"]),De=Te.extend({type:Fe.optional(),address:L.optional(),search:C.optional(),tokenName:D.optional()}),Ce=s.z.object({walletAddress:L,amount:B}),xe=s.z.object({address:L.optional(),refresh:s.z.boolean().optional()}),_e=s.z.object({profileImage:s.z.string(),fullName:x,address:L,privateKey:Z.optional()}),Pe=s.z.object({file:s.z.union([s.z.instanceof(File),s.z.instanceof(Buffer)]),address:L.optional(),privateKey:Z.optional()}),Le=s.z.object({address:L,tokenId:s.z.union([s.z.string(),s.z.object({collection:s.z.string(),category:s.z.string(),type:s.z.string(),additionalKey:s.z.string()}),s.z.object({collection:s.z.string(),category:s.z.string(),type:s.z.string(),additionalKey:s.z.string(),instance:s.z.string()})]).optional(),tokenClassKey:s.z.object({collection:s.z.string(),category:s.z.string(),type:s.z.string(),additionalKey:s.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"),$e=s.z.enum(["buy","sell"]),Oe=s.z.enum(["BUY","SELL"]),Ue=s.z.object({tradeType:$e,tokenAmount:O,vaultAddress:$,userAddress:L,slippageTolerance:O.optional(),deadline:s.z.number().int().positive().optional()}),Be=s.z.object({tokenSymbol:I,nativeTokenQuantity:O,expectedToken:O,maxAcceptableReverseBondingCurveFee:U.default("0").optional()}),Re=s.z.object({tokenSymbol:I,tokenQuantity:O,expectedNativeToken:O,maxAcceptableReverseBondingCurveFee:U.default("0").optional()}),Me=ke.extend({tokenName:D.optional()}),Ke=s.z.object({page:s.z.number().int().min(1).max(1e3).default(1).optional(),limit:s.z.number().int().min(1).max(20).default(10).optional()}),Ge=s.z.enum(["NATIVE","MEME"]),ze=s.z.enum(["IN","OUT"]),Ve=s.z.object({type:Ge,method:ze,vaultAddress:$,amount:O}),qe=s.z.object({nativeTokenQuantity:O}),We=s.z.object({vaultAddress:$}),je=s.z.object({minFeePortion:O,maxFeePortion:O});function He(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 Qe=He(S),Xe=He(I),Ye=He(F),Ze=He(L),Je=He($),et=He(O),tt=He(B),at=He(x),nt=He(C),rt=He(D),st=He(se),ot=He(te),it=He(oe),ct=He(ce),lt=He(De),ut=He(Ce),dt=He(xe),ht=He(_e),pt=He(Pe),gt=He(Le),mt=He(Ue),ft=He(Be),yt=He(Re),At=He(Me),vt=He(Ke),wt=He(Ve),Tt=He(qe),kt=He(We);function Et(e,t){throw new y(e.join("; "),t,"VALIDATION_ERROR")}function Nt(e){const t=Qe(e);!t.success&&t.errors&&Et(t.errors,"tokenName")}function bt(e){const t=Ne.safeParse(e);t.success||Et(t.error.errors.map(e=>e.message),"pagination")}function St(e){const t=ct(e);!t.success&&t.errors&&Et(t.errors,"options")}function It(e){const t=wt(e);!t.success&&t.errors&&Et(t.errors,"options")}function Ft(e){const t=de.safeParse(e);t.success||Et(t.error.errors.map(e=>e.message),"options")}function Dt(e){const t=L.safeParse(e);if(!t.success)throw new y("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Ct(e,t,a=!0){if(!e||""===e.trim())throw new y(`${t} cannot be empty or whitespace-only. Provide a valid numeric string or omit the parameter to auto-fetch.`,t,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new y(`${t} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,t,"INVALID_NUMERIC_STRING");const n=parseFloat(e);if(isNaN(n))throw new y(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(n))throw new y(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(n<0)throw new y(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!a&&0===n)throw new y(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var xt=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=L.safeParse(e);if(!t.success)throw new y(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:Dt,validateCheckPoolOptions:St,validateGetAmountOptions:It,validateGetGraphOptions:Ft,validateNumericString:Ct,validatePagination:bt,validateTokenName:Nt});function _t(e){if(!e)return[];return(Array.isArray(e)?e:e.token??[]).map(e=>({...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}))}function Pt(e,t){const a=Number(e.page)||t.page,n=Number(e.limit)||t.limit,r=Number(e.total)||Number(e.data?.count)||0;return{page:a,limit:n,total:r,totalPages:Math.ceil(r/n)}}function Lt(e,t){return{hasNext:e<t,hasPrevious:e>1}}function $t(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 Ot="/launchpad/upload-image",Ut="/launchpad/fetch-pool",Bt="/launchpad/check-pool",Rt="/launchpad/get-graph-data",Mt="/holders",Kt="/launchpad/get-badge/",Gt="/trade/",zt="/token/commment",Vt="/token/commment",qt="/user/profile",Wt="/user/profile",jt="/user/token-list",Ht="/user/token-hold",Qt="/user/transfer-faucets";function Xt(e,t){return new y(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Yt(e,t){const a=t||e.charAt(0).toUpperCase()+e.slice(1);return new y(`${a} is required`,e,"REQUIRED_FIELD")}function Zt(e,t,a){const n=a||e.charAt(0).toUpperCase()+e.slice(1);return new y(`${n} must be ${t}`,e,"INVALID_FORMAT")}function Jt(e,t,a){return new A(e,t,a)}function ea(e,t){return new v(e,t)}function ta(e,t,a){return new w(e,t,a)}function aa(e){return e&&"object"==typeof e&&"string"==typeof e.tokenName&&(void 0===e.from||"number"==typeof e.from)&&(void 0===e.to||"number"==typeof e.to)&&(void 0===e.resolution||"number"==typeof e.resolution)}class na{constructor(e){this.http=e}async fetchPools(e={}){let t;bt({page:e.page??1,limit:e.limit??10}),e.tokenName&&Nt(e.tokenName),"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const a={page:e.page||1,limit:e.limit||10};e.search&&(a.search=e.search),e.tokenName&&(a.tokenName=e.tokenName),t&&(a.type=t);const n={page:a.page.toString(),limit:a.limit.toString()};void 0!==a.type&&(n.type=a.type),void 0!==a.tokenName&&(n.tokenName=a.tokenName),void 0!==a.search&&(n.search=a.search);const r=p(n),s=await this.http.get(Ut,r);$t(s,"Failed to fetch pools",!0);return{pools:function(e){if(!e)return[];let t=[];return e.tokens?t=Array.isArray(e.tokens)?e.tokens.map(e=>({...e,createdAt:new Date(e.created_at??e.createdAt)})):[{...e.tokens,createdAt:new Date(e.tokens.created_at??e.tokens.createdAt)}]:e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:new Date(e.created_at??e.createdAt)}))),t}(s.data),page:s.data.page,limit:s.data.limit,total:s.data.total,totalPages:s.data.totalPages,hasNext:s.data.page<s.data.totalPages,hasPrevious:s.data.page>1}}async checkPool(e){St(e),e.tokenName&&Nt(e.tokenName);const t=p(e),a=await this.http.get(Bt,t);$t(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(!aa(e))throw new y("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(Nt(t),!a||!n||!r)throw new y("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const s={tokenName:t,from:a,to:n,resolution:r};Ft(s);const o=p(s),i=await this.http.get(Rt,o);return $t(i,"Failed to fetch graph data",!0),{dataPoints:i.data}}async fetchTokenDistribution(e){if(!e)throw Yt("tokenName","Token name");Nt(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw new y(f(e),"tokenName","VAULT_NOT_FOUND");const a=encodeURIComponent(t),n=await this.http.get(`${Mt}/${a}`);return $t(n,"Failed to fetch token distribution",!0),{holders:n.data.holders||[],totalSupply:n.data.totalSupply||"0",totalHolders:n.data.totalHolders||0,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Yt("tokenName","Token name");Nt(e);const t=await this.http.get(Kt,{tokenName:e});return $t(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});return t.pools&&Array.isArray(t.pools)&&t.pools.length>0?t.pools[0].vaultAddress||null:t.pools&&t.pools.tokens&&t.pools.tokens.vaultAddress||null}catch{return null}}}function ra(e,t={}){const{stringifyFields:a=[],optionalFields:n=[],fieldMappings:r={}}=t,s={};for(const[t,o]of Object.entries(e)){const e=t;if(n.includes(e)&&void 0===o)continue;if(n.includes(e)&&"string"==typeof o&&0===o.trim().length)continue;const i=r[e],c=i?String(i):t;a.includes(e)?s[c]=String(o):s[c]=o}return p(s)}const sa={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class oa{constructor(e){this.http=e}async fetchTrades(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.tokenName||void 0!==t.tradeType&&"buy"!==t.tradeType&&"sell"!==t.tradeType||void 0!==t.userAddress&&"string"!=typeof t.userAddress||void 0!==t.page&&"number"!=typeof t.page||void 0!==t.limit&&"number"!=typeof t.limit)throw new y("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, page?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");var t;const{tokenName:a,tradeType:n,userAddress:r,page:s=1,limit:o=10,startDate:i,endDate:c,sortOrder:l}=e;if(!E(a))throw new y("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");T(s,o,sa);const u=function(e,t,a){return ra({tokenName:e,page:t,limit:a},{stringifyFields:["page","limit"]})}(a,s,o),d=await this.http.get(Gt,u),h=(p=d.data)?(Array.isArray(p)?p:p.trades?p.trades:[]).map(e=>({...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)})):[];var p;const g=Pt(d,{page:s,limit:o}),m=Lt(g.page,g.totalPages);return{trades:h,...g,...m}}}const ia=new h({debug:!1,context:"DateUtils"});function ca(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())?(ia.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):a}catch(a){return ia.warn(`Date parsing error for "${e}":`,a),t||new Date}}const la={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class ua{constructor(e,t){this.http=e,this.poolService=t}async fetchComments(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.tokenName||void 0!==t.page&&"number"!=typeof t.page||void 0!==t.limit&&"number"!=typeof t.limit)throw new y("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");var t;const{tokenName:a,page:n=1,limit:r=10}=e;if(!E(a))throw new y("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");T(n,r,la);const s=await this.poolService.resolveTokenNameToVault(a);if(!s)throw Xt(a);const o=ra({vaultAddress:s,page:n,limit:r},{stringifyFields:["page","limit"]}),i=await this.http.get(zt,o);$t(i,"Failed to fetch comments");return{comments:i.data.comments.map(e=>({...e,createdAt:ca(e.createdAt)})),total:i.data.count}}async postComment(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.tokenName||"string"!=typeof t.content)throw new y("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");var t;const{tokenName:a,content:n}=e;if(!E(a))throw new y("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>=la.CONTENT.MIN_LENGTH&&t.length<=la.CONTENT.MAX_LENGTH}(n))throw new y(`Comment content must be between ${la.CONTENT.MIN_LENGTH} and ${la.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const r=await this.poolService.resolveTokenNameToVault(a);if(!r)throw Xt(a);const s={userAddress:this.http.getAddress(),vaultAddress:r,content:n};$t(await this.http.post(Vt,s),"Failed to create comment")}}const da={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 ha(e){return!(!e||"string"!=typeof e)&&da.USER_ADDRESS.PATTERN.test(e)}const pa="Update profile";class ga{constructor(e){this.http=e}async fetchProfile(e){const t=e??this.http.getAddress();if(!ha(t))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const a={userAddress:t};return await this.http.get(qt,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(pa),r={address:n.address,message:pa,publickey:n.ethereumAddress,sign:n.signature};$t(await this.http.put(Wt,a,r),"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();try{const a=new FormData;if("undefined"!=typeof File&&e.file instanceof File)a.append("image",e.file);else{if(!Buffer.isBuffer(e.file))throw new y("Invalid file type","file","INVALID_FILE_TYPE");{const n=`profile-image-${t}.png`,r=new Blob([e.file],{type:"image/png"});a.append("image",r,n)}}const n=await this.http.request({method:"POST",url:`${Ot}?tokenName=${encodeURIComponent(t)}`,data:a,headers:{}});return $t(n,"Image upload failed"),"string"==typeof n.data?n.data:""}catch(e){if(e instanceof y)throw e;throw new y(`Profile image upload failed: ${e instanceof Error?e.message:"Unknown error"}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){this.validateGetTokenListOptions(e);const t=ra({page:e.page,limit:e.limit,type:"all"!==e.type&&e.type?e.type:"DEFI",address:e.address,search:e.search,tokenName:e.tokenName},{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),a=await this.http.get(jt,t);$t(a,"Failed to fetch token list",!0);const n=_t(a.data),r=Pt(a,{page:e.page||1,limit:e.limit||10}),s=Lt(r.page,r.totalPages);return{tokens:n,...r,...s}}async fetchTokensHeld(e){this.validateGetTokenListOptions(e);const t=ra({page:e.page,limit:e.limit,address:e.address,search:e.search,tokenName:e.tokenName},{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),a=await this.http.get(Ht,t);$t(a,"Failed to fetch tokens held",!0);const n=_t(a.data),r=Pt(a,{page:e.page||1,limit:e.limit||10}),s=Lt(r.page,r.totalPages);return{tokens:n,...r,...s}}async fetchTokensCreated(e={}){const{page:t=1,limit:a=10,search:n,tokenName:r}=e,s={type:"DEFI",address:this.http.getAddress(),page:t,limit:a};return void 0!==n&&(s.search=n),void 0!==r&&(s.tokenName=r),this.fetchTokenList(s)}validateGetTokenListOptions(e){if(T(e.page,e.limit,da),void 0!==e.address&&!ha(e.address))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(void 0!==e.search&&e.search.trim().length>0&&!((t=e.search)&&"string"==typeof t&&t.length>=da.SEARCH.MIN_LENGTH&&t.length<=da.SEARCH.MAX_LENGTH))throw new y(`Search query must be between ${da.SEARCH.MIN_LENGTH} and ${da.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>=da.TOKEN_NAME.MIN_LENGTH&&a.length<=da.TOKEN_NAME.MAX_LENGTH))throw new y(`Token name must be between ${da.TOKEN_NAME.MIN_LENGTH} and ${da.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!ha(e.address))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=da.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=da.PROFILE.FULL_NAME.MAX_LENGTH&&da.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new y(`Full name must be between ${da.PROFILE.FULL_NAME.MIN_LENGTH} and ${da.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!ha(e.address))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class ma 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 ma("File is required",t,a);if("undefined"!=typeof File&&e instanceof File){const t=me.safeParse(e);if(!t.success){const a=t.error.errors.map(e=>e.message).join("; ");throw new ma(a,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new ma("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 ma(e,t,a)}if(t.length>255)throw new ma(`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 ma(`Invalid file type "${a}" is not allowed. Allowed types: ${r.join(", ")}`,t,a);const s=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),o=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!o.includes(s))throw new ma(`File extension "${s}" is not allowed. Allowed extensions: ${o.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"}}(s);if(i!==a&&"application/octet-stream"!==i)throw new ma(`File extension "${s}" does not match MIME type "${a}"`,t,a);return}throw new ma("File must be a File object (browser) or Buffer (Node.js)",t,a)}class ya{constructor(e){this.http=e}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Nt(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 Zt("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:`${Ot}?tokenName=${encodeURIComponent(a.tokenName??t)}`,data:e,headers:{}});return $t(n,"Image upload failed"),"string"==typeof n.data?n.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw ea("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class Aa{constructor(e){this.http=e}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount};$t(await this.http.post(Qt,t),"Faucet transfer failed")}validateTransferFaucetsData(e){if(!ha(e.walletAddress))throw new y("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!da.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new y("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class va{constructor(e){this.http=e,this.poolService=new na(e),this.tradeService=new oa(e),this.commentService=new ua(e,this.poolService),this.userService=new ga(e),this.imageService=new ya(e),this.faucetService=new Aa(e)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(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 Nt(e)}}class wa extends r.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 s;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`);s={collection:e[0],category:e[1],type:e[2],additionalKey:e[3],instance:"0"}}else s={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new wa({from:e,to:t,quantity:a,tokenInstance:s,uniqueKey:r||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,a,n){return new wa({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 Ta{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 t=e.replace("0x","");return`eth|${a.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 ka(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new y(`Invalid tokenId string format: "${e}". Expected format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");if(!(t[0]&&t[1]&&t[2]&&t[3]))throw new y(`Invalid tokenId string format: "${e}". All components (collection, category, type, additionalKey) must be non-empty`,"tokenId","INVALID_TOKEN_ID_FORMAT");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3],instance:t[4]||"0"}}if("object"==typeof e&&null!==e){if(!(e.collection&&e.category&&e.type&&e.additionalKey))throw new y("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return"instance"in e&&void 0!==e.instance?e:{...e,instance:"0"}}throw new y(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}var Ea=Object.freeze({__proto__:null,normalizeToTokenInstanceKey:ka});const Na={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var ba;!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"}(ba||(ba={}));class Sa extends Error{constructor(e,t,a){super(e),this.type=t,this.details=a,this.name="TransferError"}}class Ia{constructor(e,t,a,n=!1){this.http=e,this.wallet=t,this.tokenResolver=a,this.signatureHelper=new Ta(t),this.logger=new h({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 Jt(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const a=t.Data,n=a.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",s=n?.maxFeePortion??"0",o=(await import("bignumber.js")).default,i=!new o(r).isZero()||!new o(s).isZero();return a.reverseBondingCurveMinFeePortion=r,a.reverseBondingCurveMaxFeePortion=s,a.hasReverseBondingCurveFee=i,a.isGraduated="Completed"===a.saleStatus,delete a.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(1!==e.Status)throw Jt(`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 y("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new y("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new y("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e){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 Jt(`Failed to fetch token balance from GalaChain: ${e.message||"Unknown error"}`,void 0,e)}}async transferGala(e){this.validateTransferGalaData(e);try{const t=b(e.recipientAddress),a=b(this.wallet.address),n=wa.forGALA(a,t,e.amount,e.uniqueKey),r=await this.signatureHelper.signTransferToken(n.toSigningPayload()),s=new wa({...n.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(s,null,2));const o=await this.http.post("/api/asset/token-contract/TransferToken",s);if(this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(o,null,2)),o&&"object"==typeof o){if("Status"in o&&1===o.Status&&"Data"in o){const e=o;return Array.isArray(e.Data)&&e.Data.length>0?"gala-transfer-successful":"transfer-successful-no-id"}if("transactionId"in o&&o.transactionId)return o.transactionId}throw new Sa("Transfer succeeded but transaction ID could not be extracted",ba.NETWORK_ERROR)}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=ka(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 Sa("Must provide either tokenId or tokenName for token identification",ba.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const r=new wa({from:a,to:t,quantity:e.amount,tokenInstance:n,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),s=await this.signatureHelper.signTransferToken(r.toSigningPayload()),o=new wa({...r.toSigningPayload(),signedPayload:s});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(o,null,2));const i=await this.http.post("/api/asset/token-contract/TransferToken",o);if(this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(i,null,2)),i&&"object"==typeof i){if("Status"in i&&1===i.Status&&"Data"in i){const e=i;return Array.isArray(e.Data)&&e.Data.length>0?"token-transfer-successful":"transfer-successful-no-id"}if("transactionId"in i&&i.transactionId)return i.transactionId}throw new Sa("Transfer succeeded but transaction ID could not be extracted",ba.NETWORK_ERROR)}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 Sa)throw t;throw new Sa(`Failed to resolve token class key for '${e}': ${t instanceof Error?t.message:String(t)}`,ba.TOKEN_NOT_FOUND,{tokenName:e})}}validateTransferGalaData(e){if(!((t=e)&&"object"==typeof t&&"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)throw new y("Invalid GALA transfer data: missing required fields");var t;if(!N(e.recipientAddress))throw new Sa("Invalid recipient address format",ba.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});if(parseFloat(e.amount)<=0)throw new Sa("Transfer amount must be positive",ba.INVALID_AMOUNT,{amount:e.amount});if(e.uniqueKey){if(e.uniqueKey.length>Na.MAX_UNIQUE_KEY_LENGTH)throw new y(`Unique key too long. Maximum length: ${Na.MAX_UNIQUE_KEY_LENGTH}`);if(!Na.UNIQUE_KEY_PATTERN.test(e.uniqueKey))throw new Sa('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',ba.INVALID_AMOUNT,{uniqueKey:e.uniqueKey})}}validateTransferTokenData(e){if(!((t=e)&&"object"==typeof t&&"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)throw new y("Invalid token transfer data: missing required fields");var t;if(!N(e.to))throw new Sa("Invalid recipient address format",ba.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Sa("Must provide either tokenId or tokenName for token identification",ba.TOKEN_NOT_FOUND);if(e.tokenName&&!Na.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Sa("Invalid token name format",ba.TOKEN_NOT_FOUND,{tokenName:e.tokenName});if(parseFloat(e.amount)<=0)throw new Sa("Transfer amount must be positive",ba.INVALID_AMOUNT,{amount:e.amount});if(e.uniqueKey){if(e.uniqueKey.length>Na.MAX_UNIQUE_KEY_LENGTH)throw new y(`Unique key too long. Maximum length: ${Na.MAX_UNIQUE_KEY_LENGTH}`);if(!Na.UNIQUE_KEY_PATTERN.test(e.uniqueKey))throw new Sa('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',ba.INVALID_AMOUNT,{uniqueKey:e.uniqueKey})}}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Sa(`Token '${e}' not found or not available for transfer`,ba.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 Sa)throw t;throw new Sa(`Failed to resolve token '${e}': ${t instanceof Error?t.message:String(t)}`,ba.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){const[t,a]=e.split("|");if(!a)throw new Sa(`Invalid vault address format: missing token components. Address: ${e}`,ba.TOKEN_NOT_FOUND);const n=a.split("$");if(n.length<4)throw new Sa(`Invalid vault address format: insufficient token components. Expected 4+, got ${n.length}. Address: ${e}`,ba.TOKEN_NOT_FOUND);return{collection:n[0],category:n[1],type:n[2],additionalKey:n[3],instance:"0"}}handleTransferError(e,t,a){if(e instanceof Sa)return e;if(e instanceof y)return new Sa(e.message,ba.INVALID_AMOUNT);if(400===e.response?.status)return new Sa(e.response.data?.message||"Invalid transfer request",ba.INVALID_AMOUNT);if(403===e.response?.status)return new Sa("Insufficient balance for transfer",ba.INSUFFICIENT_BALANCE);if(404===e.response?.status){const e={};return"tokenName"in a&&(e.tokenName=a.tokenName),new Sa("Token not found",ba.TOKEN_NOT_FOUND,e)}return"ECONNABORTED"===e.code||"ETIMEDOUT"===e.code?new Sa("Transfer request timed out",ba.NETWORK_ERROR):new Sa(e.message||t,ba.NETWORK_ERROR)}}class Fa{constructor(e){this.http=e}async fetchTokenSpotPrice(e){if(!e||Array.isArray(e)&&0===e.length)throw Yt("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 Jt(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`)}}async fetchLaunchpadTokenSpotPrice(e,t){if(!e||"string"!=typeof e)throw new Error(m);try{const a=await t({tokenName:e,amount:"1",type:"native"}),n=(await this.fetchTokenSpotPrice("GALA"))[0];if(!n)throw Jt("GALA price not available");const r=Number(a.amount)/1e18;if(r<=0)throw new y(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const s=n.price/r;return{symbol:e.toUpperCase(),price:s}}catch(t){if(t instanceof Error)throw Jt(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw Jt(`Failed to calculate launchpad token spot price for ${e}: ${String(t)}`)}}}function Da(e,t=18){const a=parseFloat(e);if(0===a)return"0";return a.toFixed(t).replace(/\.?0+$/,"")}function Ca(e){return Da(e,8)}function xa(e){return Da(e,18)}new h({debug:!1,context:"NumberUtils"});class _a extends r.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Ca(t),this.expectedToken=xa(a),this.extraFees={maxAcceptableReverseBondingCurveFee:Ca(n.maxAcceptableReverseBondingCurveFee)}}}class Pa extends r.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=xa(t),this.expectedNativeToken=Ca(a),this.extraFees={maxAcceptableReverseBondingCurveFee:Ca(n.maxAcceptableReverseBondingCurveFee)}}}class La extends r.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=xa(t),this.expectedNativeToken=Ca(a),this.extraFees={maxAcceptableReverseBondingCurveFee:Ca(n.maxAcceptableReverseBondingCurveFee)}}}class $a extends r.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Ca(t),this.expectedToken=xa(a),this.extraFees={maxAcceptableReverseBondingCurveFee:Ca(n.maxAcceptableReverseBondingCurveFee)}}}const Oa={BuyNativeDto:_a,BuyExactDto:Pa,SellExactDto:La,SellNativeDto:$a};var Ua,Ba,Ra;!function(e){e[e.METAMASK=0]="METAMASK",e[e.TRUST_WALLET=1]="TRUST_WALLET",e[e.GALA_WALLET=2]="GALA_WALLET"}(Ua||(Ua={}));class Ma{constructor(e,t=!1){this.walletProvider=e,this.debug=t,this.logger=new h({debug:t,context:"SignatureService"})}async signDTO(e,t,a,n=Ua.METAMASK){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,walletPreference:n,dtoKeys:Object.keys(e)});const s=this.generateEIP712Types(t,e),o=r.calculatePersonalSignPrefix(e),i={...e,prefix:o};let c,l,u;switch(n){case Ua.GALA_WALLET:({signature:c,domain:l}=await this.signWithGalaWallet(s,i,t,a));break;case Ua.TRUST_WALLET:c=await this.signWithTrustWallet(i),l={name:"ethereum",chainId:1};break;case Ua.METAMASK:default:({signature:c,domain:l}=await this.signWithMetaMask(s,i))}return u=n===Ua.TRUST_WALLET?{...i,signature:c}:{...e,signature:c,types:s,domain:l},this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(u),signatureLength:c.length}),u}catch(e){throw this.logger.error("❌ Signature generation failed:",e),ta(`Failed to sign DTO: ${e.message}`)}}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 ea("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 ta(`MetaMask/ethers signing failed: ${e.message}`)}}async signWithTrustWallet(e){try{const a=(t=e,JSON.stringify(t));let n;if(!this.walletProvider.signMessage)throw ea("Wallet provider does not support signMessage","walletProvider");return n=await this.walletProvider.signMessage(a),n}catch(e){throw ta(`TrustWallet signing failed: ${e.message}`)}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 s={domain:r,types:e,message:t,Primary_type:a},o=window;if(!o?.gala)throw ea("GalaWallet not found in window object","galaWallet");await o.gala.setAddress(n);return{signature:await o.gala.request({method:"eth_signTypedData",params:[JSON.stringify(s),n]}),domain:r}}catch(e){throw ta(`GalaWallet signing failed: ${e.message}`)}}generateEIP712Types(e,t){const a={};a[e]=[];const n=(e,t,r,s=!1)=>{if(void 0!==t){if(Array.isArray(t)){const o=n(e,t[0],r,!0);return s||a[r].push({name:e,type:(o??e)+"[]"}),o?o+"[]":void 0}if("object"==typeof t&&null!==t){if(a[e])throw new y(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return a[e]=[],Object.entries(t).forEach(([t,a])=>{n(t,a,e)}),s||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 y(`Unsupported type for fieldName ${e}: ${typeof t}, value: ${t}`,"fieldValue","UNSUPPORTED_TYPE")}return s||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 Ua.METAMASK;const e=window;return e?.gala?Ua.GALA_WALLET:e?.trustWallet?.isTrust?Ua.TRUST_WALLET:Ua.METAMASK}}class Ka{constructor(e=!1){this.debug=e,this.logger=new h({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`,s=`$tokenBalance$${a.toStringKey()}$${e}`,o=`$tokenBalance$${a.toStringKey()}$${e}`,i=`$tokenBalance$${n.toStringKey()}$${e}`,c=[r,s,o,i,`$tokenBalance$${n.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){throw this.logger.error("❌ Failed to generate stringsInstructions:",e),new y(`Failed to generate stringsInstructions: ${e.message}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new o.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 o.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 Yt("vaultAddress","Vault address");const t=e.split("$");if(t.length<3)throw Zt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");const a=t[2];if(!a||0===a.trim().length)throw new y(`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 Yt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Zt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Zt("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw Zt("vaultAddress",'having at least 5 parts separated by "$"');const a=t[2];if(!a||!/^[A-Za-z]{1,10}$/.test(a))throw Zt("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 Zt("stringKey","format: collection$category$type$additionalKey (4 parts)");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}}function Ga(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 i(e);if(n.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const r=n.multipliedBy(t);let 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 i(0)),s.toFixed()}class za{constructor(e,t,a=!1,n,r,s=.05,o=.01){this.httpClient=e,this.tokenResolver=t,this.walletProvider=n,this.userAddress=r,this.defaultSlippageToleranceFactor=s,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=o,this.bundleEndpoint="/bundle",this.logger=new h({debug:a,context:"BundleService"}),n&&r&&(this.signatureService=new Ma(n,a),this.tokenKeyService=new Ka(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 Yt("bundleData","Bundle data");if(!e.signedDto)throw Yt("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw Yt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Zt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new y("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Zt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new y(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new y(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT")}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){if(e.data&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",e.data),{success:!0,data:e.data};const t=e.error||e.message||"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",t),{success:!1,error:t}}formatErrorMessage(e){return"string"==typeof e?e:e?.response?.data?.error?e.response.data.error:e?.response?.data?.message?e.response.data.message:e?.message?e.message:"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw Yt("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 Yt("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,maxAcceptableReverseBondingCurveFee:s,maxAcceptableReverseBondingCurveFeeSlippageFactor:o,slippageToleranceFactor:i}=e,c=i??this.defaultSlippageToleranceFactor,l=o??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let u=s||"0";s&&(u=Ga(s,l,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:s,slippageFactor:l,adjustedMaxFee:u}));const d=await this.resolveTokenNameToVault(t);if(!d)throw Xt(t);if("native"===n){if(!r)throw new y("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ga(r,c,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:r,slippageFactor:c,adjustedMinTokens:e});const t=new Oa.BuyNativeDto(d,a,e,{maxAcceptableReverseBondingCurveFee:u});return await this.executeBundleTransaction(t,"BuyWithNative",d)}{if(!r)throw new y("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ga(r,c,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:r,slippageFactor:c,adjustedMaxGalaCost:e});const t=new Oa.BuyExactDto(d,a,e,{maxAcceptableReverseBondingCurveFee:u});return await this.executeBundleTransaction(t,"BuyExactToken",d)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:a,type:n,expectedAmount:r,maxAcceptableReverseBondingCurveFee:s,maxAcceptableReverseBondingCurveFeeSlippageFactor:o,slippageToleranceFactor:i}=e,c=i??this.defaultSlippageToleranceFactor,l=o??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let u=s||"0";s&&(u=Ga(s,l,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:s,slippageFactor:l,adjustedMaxFee:u}));const d=await this.resolveTokenNameToVault(t);if(!d)throw Xt(t);if("exact"===n){if(!r)throw new y("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ga(r,c,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:r,slippageFactor:c,adjustedMinGala:e});const t=new Oa.SellExactDto(d,a,e,{maxAcceptableReverseBondingCurveFee:s||"0"});return await this.executeBundleTransaction(t,"SellExactToken",d)}{if(!r)throw new y("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ga(r,c,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:r,slippageFactor:c,adjustedMaxTokensToSell:e});const t=new Oa.SellNativeDto(d,a,e,{maxAcceptableReverseBondingCurveFee:s||"0"});return await this.executeBundleTransaction(t,"SellWithNative",d)}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw ea("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw Yt("userAddress","User address")}async executeBundleTransaction(e,t,a){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${c.v4()}-${Date.now()}-${this.userAddress}`;const n=await this.signatureService.signDTO(e,t,this.userAddress),r=this.tokenKeyService.generateStringsInstructions(a),s={stringsInstructions:r,method:t,signedDto:n};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:r,dtoKeys:Object.keys(n)});const o=await this.submitTransaction(s);if(o.success&&o.data)return this.logger.debug("✅ Bundle transaction submitted:",o.data),{success:!0,data:{transactionId:o.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(o.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"}(Ba||(Ba={})),exports.SDKTransactionStatus=void 0,(Ra=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",Ra.PROCESSING="processing",Ra.COMPLETED="completed",Ra.FAILED="failed",Ra.TIMEOUT="timeout";const Va={[Ba.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[Ba.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[Ba.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[Ba.FAILED]:exports.SDKTransactionStatus.FAILED,[Ba.ERROR]:exports.SDKTransactionStatus.FAILED,[Ba.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[Ba.PENDING]:exports.SDKTransactionStatus.PENDING};class qa{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 h({debug:t,context:"WebSocketService"}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof l.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=l.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(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const a=setTimeout(()=>{if(this.listeners.has(e)){const a={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:"Transaction monitoring timeout - no response after 60 seconds",timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e}`),t(a),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},6e4);if(this.timeouts.set(e,a),this.socket&&this.socket.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,a=>{this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(a,null,2));const n=a?.status||a?.Status||a?.data?.status||a?.data?.Status;let r=a?.message||a?.Message||a?.data?.message||a?.data?.Message||a?.error||a?.data?.error;r&&"string"==typeof r||(r=n===Ba.FAILED||n===Ba.ERROR?"Transaction failed - check transaction details":n===Ba.COMPLETED||n===Ba.PROCESSED||n===Ba.SUCCESS?"Transaction completed successfully":n?`Transaction status: ${n}`:"Unknown transaction status");const s={transactionId:e,status:this.mapSocketStatus(n),message:r,timestamp:Date.now(),blockHash:a?.blockHash||a?.data?.blockHash,gasUsed:a?.gasUsed||a?.data?.gasUsed};if(this.logger.debug(`📡 Mapped status for ${e}: ${n} -> ${s.status}`),this.logger.debug(`📡 Final message: "${r}"`),t(s),s.status===exports.SDKTransactionStatus.COMPLETED||s.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${s.status})`)}});else{const a={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(a),this.listeners.delete(e),this.timeouts.delete(e)}}async waitForTransaction(e){return new Promise((t,a)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||a(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Va[t]||exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectCount<this.config.reconnectAttempts?(this.reconnectCount++,this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectCount}/${this.config.reconnectAttempts}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.config.reconnectDelay)):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.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 Wa{constructor(e){this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!E(e))throw new y("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 Xt(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 Zt("vaultAddress","format: service|Token$Unit$...$launchpad","Vault address");const a=t[1].split("$");if(a.length<4)throw Zt("vaultAddress","at least 4 parts after service|","Vault address");return{collection:a[0],category:a[1],type:a[2],additionalKey:a[3]}}}function ja(e){const t=function(e){const t=st(e);return t.success?[]:t.errors||["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}const Ha="/api/asset/launchpad-contract/CallNativeTokenIn",Qa="/api/asset/launchpad-contract/CallNativeTokenOut",Xa="/api/asset/launchpad-contract/CallMemeTokenIn",Ya="/api/asset/launchpad-contract/CallMemeTokenOut";class Za extends r.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 Ja(e){return e&&"object"==typeof e&&"number"==typeof e.Status&&e.Data&&"object"==typeof e.Data&&"string"==typeof e.Data.calculatedQuantity&&e.Data.extraFees&&"object"==typeof e.Data.extraFees&&"string"==typeof e.Data.extraFees.reverseBondingCurve&&"string"==typeof e.Data.extraFees.transactionFees}const en={NATIVE:"native",EXACT:"exact"};class tn{}tn.BASE_PRICE=1650667151e-14,tn.PRICE_SCALING_FACTOR=1166069e-12,tn.TRADING_FEE_FACTOR=.001,tn.GAS_FEE="1",tn.MIN_UNBONDING_FEE_FACTOR=0,tn.MAX_UNBONDING_FEE_FACTOR=.5,tn.NET_UNBONDING_FEE_FACTOR=.5,tn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class an{static calculateBuyWithExact(e,t){const a=parseFloat(e),n=parseFloat(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:s,TRADING_FEE_FACTOR:o,GAS_FEE:c}=tn,l=this.roundUp(r*(Math.exp((n+a)*s)-Math.exp(n*s))/s,8),u=new i(l).multipliedBy(o).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:o,GAS_FEE:c}=tn,l=Math.log(a*s/r+Math.exp(n*s))/s-n,u=new i(l).multipliedBy(o).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateSellWithExact(e,t,a,n,r){const s=parseFloat(e),o=parseFloat(t),c=parseFloat(a),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=tn,p=l*(Math.exp(o*u)-Math.exp((o-s)*u))/u,g=new i(p),m=n+o/c*(r-n),f=g.multipliedBy(m).toFixed(8,i.ROUND_UP),y=g.multipliedBy(d).toFixed();return{amount:p.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,a,n,r){const s=parseFloat(e),o=parseFloat(t),c=parseFloat(a),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=tn,p=o-Math.log(Math.exp(o*u)-s*u/l)/u,g=new i(s),m=n+o/c*(r-n),f=g.multipliedBy(m).toFixed(8,i.ROUND_UP),y=g.multipliedBy(d).toFixed();return{amount:p.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static roundUp(e,t){const a=Math.pow(10,t);return Math.ceil(e*a)/a}}class nn{constructor(e,t,a,n,r,s,o="local"){this.http=e,this.tokenResolver=t,this.logger=a,this.bundleHttp=n,this.galaChainHttp=r,this.dexApiHttp=s,this.defaultCalculateAmountMode=o}addIfDefined(e,t,a){return void 0!==a&&(e[t]=a),e}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Nt(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 Zt("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 Jt(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 ea("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){bt(e),e.tokenName&&Nt(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=p(t),n=await this.http.get("/launchpad/fetch-pool",a);if(!0===n.error||200!==n.status||!n.data)throw Jt(n.message||"Failed to fetch pools",n.status);let r=[];const s=(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 s(t).isZero()||!new s(a).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:a,hasReverseBondingCurveFee:n,createdAt:new Date(e.created_at||e.createdAt)}});else{const e=n.data.tokens.reverseBondingCurveMinFeePortion??"0",t=n.data.tokens.reverseBondingCurveMaxFeePortion??"0",a=!new s(e).isZero()||!new s(t).isZero();r=[{...n.data.tokens,reverseBondingCurveMinFeePortion:e,reverseBondingCurveMaxFeePortion:t,hasReverseBondingCurveFee:a,createdAt:new Date(n.data.tokens.created_at||n.data.tokens.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 s(t).isZero()||!new s(a).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:a,hasReverseBondingCurveFee:n,createdAt:new Date(e.created_at||e.createdAt)}}));return{pools:r,page:n.data.page,limit:n.data.limit,total:n.data.total,totalPages:n.data.totalPages,hasNext:n.data.page<n.data.totalPages,hasPrevious:n.data.page>1}}async _getAmount(e){if(It(e),!this.galaChainHttp)throw ea("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:Ha,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:Qa,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:Xa,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:Ya,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};throw Zt("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(!Ja(e))throw Jt("Malformed response data from GalaChain gateway");if(1!==e.Status)throw Jt(`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){St(e),e.tokenName&&Nt(e.tokenName);const t=p(e),a=await this.http.get("/launchpad/check-pool",t);if(!0===a.error||200!==a.status)throw Jt(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(!aa(e))throw new y("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(Nt(t),!a||!n||!r)throw new y("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const s={tokenName:t,from:a,to:n,resolution:r};Ft(s);const o=p(s),i=await this.http.get("/launchpad/get-graph-data",o);if(!0===i.error||200!==i.status||!i.data)throw Jt(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 y("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:a,type:n,currentSupply:r}=e,s=e.mode??this.defaultCalculateAmountMode;if("local"!==s&&"external"!==s)throw new y(`Invalid calculation mode "${s}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new y("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!a||"string"!=typeof a)throw new y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==en.NATIVE&&n!==en.EXACT)throw new y('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===s?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 y(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===en.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:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new y(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new y("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!a||"string"!=typeof a)throw new y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==en.EXACT&&n!==en.NATIVE)throw new y('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:a,type:n});{let e={tokenName:t,amount:a,type:n};return e=this.addIfDefined(e,"currentSupply",r),e=this.addIfDefined(e,"maxSupply",s),e=this.addIfDefined(e,"reverseBondingCurveMaxFeeFactor",o),e=this.addIfDefined(e,"reverseBondingCurveMinFeeFactor",i),this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:a,type:n}=e,r=await this.tokenResolver.resolveTokenToVault(t);if(!r)throw new y(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===en.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 y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==en.NATIVE&&n!==en.EXACT)throw new y('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==r&&Ct(r,"currentSupply");const s=!r;if(s&&!t)throw new y("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&Nt(t);let o=r;if(s){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return n===en.EXACT?an.calculateBuyWithExact(a,o):an.calculateBuyWithNative(a,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:a,type:n,currentSupply:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i}=e;if(!a||"string"!=typeof a)throw new y("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==en.EXACT&&n!==en.NATIVE)throw new y('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==r&&Ct(r,"currentSupply");const c=!r||!s||void 0===o||void 0===i;if(c&&!t)throw new y("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&Nt(t);let l=r,u=s,d=o,h=i;if(c){const e=await this.fetchPoolDetailsForCalculation(t);l=l??e.currentSupply,u=u??e.maxSupply,d=d??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}return n===en.EXACT?an.calculateSellWithExact(a,l,u,h,d):an.calculateSellWithNative(a,l,u,h,d)}async calculateBuyAmountForGraduation(e){Nt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new y(f(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw ea("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==a.Status)throw Jt(`Failed to fetch pool details: Status ${a.Status}`,a.Status);const n=a.Data,r=(await import("bignumber.js")).default;n.currentSupply=new r(n.maxSupply).minus(n.sellingTokenQuantity).toFixed();const s=n.sellingTokenQuantity;if("0"===s)throw new y(`Token ${e} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");return await this.calculateBuyAmount({tokenName:e,amount:s,type:"exact"})}async launchToken(e){if(!this.bundleHttp)throw ea("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");ja(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new y("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:a}=e.reverseBondingCurveConfiguration,n=Number(t),r=Number(a);if(isNaN(n)||isNaN(r)||n<=0||r<=0||n>=r)throw new y("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 Jt("Image upload failed: No URL returned");a=t}else"string"==typeof e.tokenImage&&(a=e.tokenImage);const n=`galaswap - operation - ${c.v4()}-${Date.now()}-${this.http.getAddress()}`,s={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:n};e.reverseBondingCurveConfiguration&&(s.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const o=new Za(s),i=await this.http.signWithGalaChain("CreateSale",o,r.SigningType.SIGN_TYPED_DATA),{signature:l,types:u,domain:d,prefix:h}=i,p={tokenName:o.tokenName,tokenSymbol:o.tokenSymbol,tokenDescription:o.tokenDescription,tokenImage:o.tokenImage,preBuyQuantity:o.preBuyQuantity,websiteUrl:o.websiteUrl,telegramUrl:o.telegramUrl,twitterUrl:o.twitterUrl,tokenCategory:o.tokenCategory,tokenCollection:o.tokenCollection,uniqueKey:o.uniqueKey,signature:l,types:u,domain:d,...h&&{prefix:h},...o.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:o.reverseBondingCurveConfiguration}},g=`${e.tokenName.trim()}$Unit$none$none`,m="GALA$Unit$none$none";let f;if(parseFloat(t)>0){const e=`$service$${g}$launchpad`;f=[e,`$token$${g}$${e}`,`$tokenBalance$${g}$${e}`,`$tokenBalance$${g}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`]}else{const e=`$service$${g}$launchpad`;f=[e,`$token$${g}$${e}`,`$tokenBalance$${g}$${e}`]}const A={signedDto:p,stringsInstructions:f,method:"CreateSale"},v=await this.bundleHttp.post("/bundle",A);if(v.error||!v.data)throw Jt(v.message||"Token launch failed");return v.data}async fetchTokenDistribution(e){if(!e)throw Yt("tokenName","Token name");Nt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new y(f(e),"tokenName","VAULT_NOT_FOUND");const a=encodeURIComponent(t),n=await this.http.get(`/holders/${a}`);if(!0===n.error||200!==n.status||!n.data)throw Jt(n.message||"Failed to fetch token distribution",n.status);return{holders:n.data.holders||[],totalSupply:n.data.totalSupply||"0",totalHolders:n.data.totalHolders||0,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Yt("tokenName","Token name");Nt(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw Jt(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(!(t=e)||"object"!=typeof t||"string"!=typeof t.nativeTokenQuantity||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)throw new y("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");var t;if(!this.galaChainHttp)throw ea("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(!Ja(a))throw Jt("Malformed response data from GalaChain gateway");if(1!==a.Status)throw Jt(`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 y(f(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw ea("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==a.Status)throw Jt(`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(),s=n.sellingTokenQuantity,o=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)`);return{currentSupply:r,remainingTokens:s,maxSupply:o,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:i-c}}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Dt(e)}validateTokenName(e){return Nt(e)}validatePagination(e){return bt(e)}async fetchTokenSpotPrice(e){if(!this.dexApiHttp)throw ea("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw Yt("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 Jt(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(e){if(!e||"string"!=typeof e)throw Yt("tokenName","Token name (string)");try{const t=await this.calculateBuyAmount({tokenName:e,amount:"1",type:"native"}),a=(await this.fetchTokenSpotPrice("GALA"))[0];if(!a)throw Jt("GALA price not available");const n=Number(t.amount)/1e18;if(n<=0)throw new y(`Invalid token amount calculation: ${n}`,"amount","INVALID_CALCULATION");const r=a.price/n;return{symbol:e.toUpperCase(),price:r}}catch(t){if(t instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${e}: ${String(t)}`)}}}const rn={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-dev1.defi.gala.com"}};function sn(e){return rn[e]}class on extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class cn 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 ln(e,t){if(!e)throw new on(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new on(`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 on(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function un(e,t,a,n){ln(e,t);const r=e?.data||{};if(!(s=r)||"object"!=typeof s||void 0!==s.inputQuantity&&"string"!=typeof s.inputQuantity||void 0!==s.outputQuantity&&"string"!=typeof s.outputQuantity||void 0!==s.totalFees&&"string"!=typeof s.totalFees||void 0!==s.vaultAddress&&"string"!=typeof s.vaultAddress)throw new on(`Invalid trade data received for transaction ${t}`);var s;const o={transactionId:t,type:a,method:"native"===n.type?"native":"exact",inputAmount:r.inputQuantity||n.amount,outputAmount:r.outputQuantity||n.expectedAmount||"0",totalFees:r.totalFees||"0",tokenName:n.tokenName,vaultAddress:r.vaultAddress||"",blockHash:e.blockHash,gasUsed:e.gasUsed,timestamp:Date.now()};return void 0!==n.slippageToleranceFactor&&(o.slippageTolerance=n.slippageToleranceFactor),o}class dn{constructor(e){let t=null;t=e.env?sn(e.env):e.baseUrl?.includes("prod")?sn("PROD"):sn("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 h({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?dn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?dn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||dn.DEFAULT_CALCULATE_AMOUNT_MODE,this.auth=new d({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new g(this.auth,this.config),this.galaChainHttp=new g(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new g(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new g(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.launchpadService=new va(this.http),this.tokenResolverService=new Wa(this.launchpadService.poolService),this.launchpadAPI=new nn(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new Ia(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1),this.dexService=new Fa(this.dexApiHttp),this.bundleService=new za(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,this.getAddress(),this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new qa({url:this.config.webSocketUrl},this.config.debug)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw ea("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw ea('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new a.Wallet(e),n={...this.config,wallet:t};return new dn(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}}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw ea("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){return this.launchpadService.fetchPools(e||{})}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 Jt("Failed to fetch GALA price - no price data returned");const t=e.find(e=>"GALA"===e.symbol);if(!t)throw Jt("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(f(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}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 xt}),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 xt}),a=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Ea}),n=t(e.tokenId),{collection:r,category:s,type:o,additionalKey:i}=n;return this.galaChainService.fetchTokenBalance({owner:a,collection:r,category:s,additionalKey:i,type:o,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 Yt("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}=e,s=await this.calculateBuyAmountForGraduation(t),o={tokenName:t,amount:s.amount,type:"exact",expectedAmount:s.amount,maxAcceptableReverseBondingCurveFee:s.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==a&&(o.slippageToleranceFactor=a),void 0!==n&&(o.maxAcceptableReverseBondingCurveFeeSlippageFactor=n),void 0!==r&&(o.privateKey=r),await this.buy(o)}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),a=t.data?.transactionId;if(!a)throw ta("No transaction ID returned from buy operation");return this.waitForConfirmation(a,t=>un(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),a=t.data?.transactionId;if(!a)throw ta("No transaction ID returned from sell operation");return this.waitForConfirmation(a,t=>un(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=>{ln(a,t);const n=a?.data||{};if(!function(e){return!(!e||"object"!=typeof e||void 0!==e.vaultAddress&&"string"!=typeof e.vaultAddress||void 0!==e.tokenStringKey&&"string"!=typeof e.tokenStringKey||void 0!==e.creatorAddress&&"string"!=typeof e.creatorAddress)}(n))throw new on(`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 xt}),a=t(e)||this.getAddress();return this.launchpadService.fetchProfile(a)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return xt}),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 xt}),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 xt}),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 xt}),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 xt}),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 xt}),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 xt}),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)}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 ea("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw ea("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw ea(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw ea(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw ea(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw ea(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw ea(`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: ${dn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),dn.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: ${dn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),dn.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 cn(e,a.status,a.message);let n;try{n=t(a)}catch(t){if(t instanceof on)throw t;throw new on(`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 cn||t instanceof on)throw t;throw new on(`WebSocket confirmation failed for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),this.websocketService&&this.websocketService.disconnect(),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new h({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:a}=require("./services/WebSocketService");a.cleanupAll(e),t.debug("Global cleanup completed")}}dn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,dn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,dn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=tn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,dn.DEFAULT_CALCULATE_AMOUNT_MODE="local";class hn{static generateWallet(){try{const e=a.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 a.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 a.Wallet(t),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 t=new a.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=a.Mnemonic.fromPhrase(e),r=a.HDNodeWallet.fromMnemonic(n,`m/44'/60'/0'/0/${t}`),s=new a.Wallet(r.privateKey),o=this.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:o,mnemonic:e,wallet:s}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${t}-${e}`,r="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),s=new a.Wallet(r),o=this.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:o,mnemonic:e,wallet:s}}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 pn(e){if(void 0===e)return hn.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 hn.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 hn.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?"...":""}"`)}hn.testCounter=0;exports.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 dn(n),s={sdk:r,wallet:a,config:n};if(!1!==e.autoValidate){const e=await this.validateSetup(r,a);return{...s,validation:e}}return s}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||hn.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?hn.fromPrivateKey(e):hn.generateWallet()}return"generate"===e?hn.generateWallet():hn.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}},exports.FileValidationError=ma,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.IMAGE_EXTENSIONS=pe,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LaunchpadSDK=dn,exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.SDK_VERSION="3.7.0",exports.TRADING_TYPES=en,exports.TransactionFailedError=cn,exports.ValidationError=y,exports.WebSocketError=on,exports.WebSocketTimeoutError=class extends on{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.addressFormatSchema=_,exports.amountMethodSchema=ue,exports.amountTypeSchema=le,exports.browserFileSchema=me,exports.bufferFileSchema=fe,exports.buyTokensDataSchema=Be,exports.calculatePreMintDataSchema=qe,exports.checkPoolOptionsSchema=ce,exports.commentMessageSchema=Q,exports.commentPaginationSchema=Ee,exports.createLaunchpadSDK=function(e){const{wallet:t,env:n,config:r={}}=e||{};let s;if(t)if("string"==typeof t){s=pn(t).wallet}else{if(!(t instanceof a.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");s=t}else{s=pn().wallet}const o={wallet:s,...n&&{env:n},debug:!1,timeout:3e4,...r};return new dn(o)},exports.createLimitSchema=G,exports.createPaginatedResultSchema=function(e){return s.z.object({data:s.z.array(e),page:s.z.number().int().min(1),limit:s.z.number().int().min(1),total:s.z.number().int().min(0),totalPages:s.z.number().int().min(0),hasNext:s.z.boolean(),hasPrevious:s.z.boolean()})},exports.createTradeDataSchema=Ue,exports.createWallet=pn,exports.ethereumAddressSchema=P,exports.faucetAmountSchema=B,exports.fetchGalaBalanceOptionsSchema=xe,exports.fetchPoolDetailsDataSchema=We,exports.fetchTokenBalanceOptionsSchema=Le,exports.fileSizeSchema=W,exports.fileUploadSchema=ge,exports.filenameSchema=j,exports.flexibleAddressSchema=L,exports.flexibleFileSchema=ye,exports.formatGalaForDTO=Ca,exports.formatLaunchpadTokenForDTO=xa,exports.fullNameSchema=x,exports.getAmountOptionsSchema=Ve,exports.getTradeOptionsSchema=Me,exports.graduateTokenOptionsSchema=he,exports.graphDataOptionsSchema=de,exports.imageExtensionSchema=Ae,exports.imageFilenameSchema=ve,exports.imageMimeTypeSchema=H,exports.imageUploadOptionsSchema=oe,exports.isoDateStringSchema=X,exports.launchTokenDataSchema=se,exports.nonNegativeDecimalStringSchema=U,exports.optionalUrlSchema=M,exports.pageNumberSchema=K,exports.paginationResultMetaSchema=Ie,exports.poolFetchTypeSchema=ie,exports.poolPaginationSchema=Ne,exports.positiveDecimalStringSchema=O,exports.privateKeySchema=Z,exports.reverseBondingCurveConfigSchema=re,exports.reverseBondingCurveConfigurationSchema=je,exports.searchQuerySchema=C,exports.sellTokensDataSchema=Re,exports.standardLimitSchema=z,exports.standardPaginationSchema=we,exports.timestampSchema=Y,exports.tokenCategorySchema=ae,exports.tokenCollectionSchema=ne,exports.tokenDescriptionSchema=F,exports.tokenListOptionsSchema=De,exports.tokenNameSchema=S,exports.tokenSymbolSchema=I,exports.tokenUrlsSchema=te,exports.tradeCalculationMethodSchema=ze,exports.tradeCalculationTypeSchema=Ge,exports.tradeLimitSchema=q,exports.tradeListParamsSchema=Ke,exports.tradePaginationSchema=ke,exports.tradePaginationWithFiltersSchema=Se,exports.tradeTypeBackendSchema=Oe,exports.tradeTypeSchema=$e,exports.transactionIdSchema=J,exports.transferFaucetsDataSchema=Ce,exports.uniqueKeySchema=ee,exports.updateProfileDataSchema=_e,exports.uploadProfileImageOptionsSchema=Pe,exports.urlSchema=R,exports.userLimitSchema=V,exports.userPaginationSchema=Te,exports.userTokenNameSchema=D,exports.userTokenTypeSchema=Fe,exports.userTokensPaginationSchema=be,exports.validateAddress=Ze,exports.validateAmountString=et,exports.validateBuyTokensData=ft,exports.validateCalculatePreMintData=Tt,exports.validateCheckPoolOptions=ct,exports.validateCreateTradeData=mt,exports.validateFaucetAmount=tt,exports.validateFetchGalaBalanceOptions=dt,exports.validateFetchPoolDetailsData=kt,exports.validateFetchTokenBalanceOptions=gt,exports.validateFullName=at,exports.validateGetAmountOptions=wt,exports.validateGetTradeOptions=At,exports.validateImageUploadOptions=it,exports.validateLaunchTokenData=st,exports.validateSearchQuery=nt,exports.validateSellTokensData=yt,exports.validateTokenDescription=Ye,exports.validateTokenListOptions=lt,exports.validateTokenName=Qe,exports.validateTokenSymbol=Xe,exports.validateTokenUrls=ot,exports.validateTradeListParams=vt,exports.validateTransferFaucetsData=ut,exports.validateUpdateProfileData=ht,exports.validateUploadProfileImageOptions=pt,exports.validateUserTokenName=rt,exports.validateVaultAddress=Je,exports.vaultAddressSchema=$;