@gala-chain/launchpad-sdk 3.31.0 → 4.0.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/API.md +524 -4
- package/CHANGELOG.md +92 -0
- package/EXAMPLES.md +845 -0
- package/README.md +421 -14
- package/dist/LaunchpadSDK.d.ts +435 -18
- package/dist/LaunchpadSDK.d.ts.map +1 -1
- package/dist/api/LaunchpadAPI.d.ts.map +1 -1
- package/dist/api/dto/TransferTokenDto.d.ts.map +1 -1
- package/dist/constants/version.generated.d.ts +1 -1
- package/dist/constants/version.generated.d.ts.map +1 -1
- package/dist/helpers/sdk.d.ts +1 -0
- package/dist/helpers/sdk.d.ts.map +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +10 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/services/BaseService.d.ts +32 -3
- package/dist/services/BaseService.d.ts.map +1 -1
- package/dist/services/BundleService.d.ts.map +1 -1
- package/dist/services/CommentService.d.ts.map +1 -1
- package/dist/services/DexBackendClient.d.ts +46 -0
- package/dist/services/DexBackendClient.d.ts.map +1 -0
- package/dist/services/DexPoolService.d.ts +54 -12
- package/dist/services/DexPoolService.d.ts.map +1 -1
- package/dist/services/DexQuoteService.d.ts +288 -0
- package/dist/services/DexQuoteService.d.ts.map +1 -0
- package/dist/services/DexService.d.ts.map +1 -1
- package/dist/services/FaucetService.d.ts.map +1 -1
- package/dist/services/GSwapService.d.ts +519 -44
- package/dist/services/GSwapService.d.ts.map +1 -1
- package/dist/services/GalaChainGatewayClient.d.ts +89 -0
- package/dist/services/GalaChainGatewayClient.d.ts.map +1 -0
- package/dist/services/GalaChainService.d.ts +26 -0
- package/dist/services/GalaChainService.d.ts.map +1 -1
- package/dist/services/ImageService.d.ts.map +1 -1
- package/dist/services/PoolService.d.ts.map +1 -1
- package/dist/services/PoolStateManager.d.ts +176 -0
- package/dist/services/PoolStateManager.d.ts.map +1 -0
- package/dist/services/PriceHistoryService.d.ts +4 -5
- package/dist/services/PriceHistoryService.d.ts.map +1 -1
- package/dist/services/SignatureService.d.ts +15 -38
- package/dist/services/SignatureService.d.ts.map +1 -1
- package/dist/services/TokenClassKeyService.d.ts +3 -4
- package/dist/services/TokenClassKeyService.d.ts.map +1 -1
- package/dist/services/TokenMetadataCache.d.ts +2 -2
- package/dist/services/TokenMetadataCache.d.ts.map +1 -1
- package/dist/services/TokenMetadataService.d.ts +3 -3
- package/dist/services/TokenMetadataService.d.ts.map +1 -1
- package/dist/services/TokenResolverService.d.ts +2 -2
- package/dist/services/TokenResolverService.d.ts.map +1 -1
- package/dist/services/TradeService.d.ts.map +1 -1
- package/dist/services/UserService.d.ts.map +1 -1
- package/dist/services/WebSocketService.d.ts +100 -2
- package/dist/services/WebSocketService.d.ts.map +1 -1
- package/dist/services/__mocks__/logger.mock.d.ts +17 -0
- package/dist/services/__mocks__/logger.mock.d.ts.map +1 -0
- package/dist/types/common.d.ts +2 -0
- package/dist/types/common.d.ts.map +1 -1
- package/dist/types/composite-pool.dto.d.ts +103 -0
- package/dist/types/composite-pool.dto.d.ts.map +1 -0
- package/dist/types/dex-pool.dto.d.ts +56 -5
- package/dist/types/dex-pool.dto.d.ts.map +1 -1
- package/dist/types/dto.d.ts +6 -6
- package/dist/types/dto.d.ts.map +1 -1
- package/dist/types/eip712-types.d.ts +140 -0
- package/dist/types/eip712-types.d.ts.map +1 -0
- package/dist/types/galachain-api.types.d.ts +206 -0
- package/dist/types/galachain-api.types.d.ts.map +1 -0
- package/dist/types/gswap-responses.types.d.ts +366 -0
- package/dist/types/gswap-responses.types.d.ts.map +1 -0
- package/dist/types/gswap.dto.d.ts +58 -3
- package/dist/types/gswap.dto.d.ts.map +1 -1
- package/dist/types/launchpad.dto.d.ts +57 -0
- package/dist/types/launchpad.dto.d.ts.map +1 -1
- package/dist/types/pool-state-delta.dto.d.ts +246 -0
- package/dist/types/pool-state-delta.dto.d.ts.map +1 -0
- package/dist/types/pool-state-manager-config.dto.d.ts +103 -0
- package/dist/types/pool-state-manager-config.dto.d.ts.map +1 -0
- package/dist/utils/SignatureHelper.d.ts.map +1 -1
- package/dist/utils/auto-pagination.d.ts +206 -0
- package/dist/utils/auto-pagination.d.ts.map +1 -0
- package/dist/utils/bignumber-helpers.d.ts +336 -0
- package/dist/utils/bignumber-helpers.d.ts.map +1 -0
- package/dist/utils/bignumber-pool-cache.d.ts +169 -0
- package/dist/utils/bignumber-pool-cache.d.ts.map +1 -0
- package/dist/utils/composite-pool-converter.d.ts +121 -0
- package/dist/utils/composite-pool-converter.d.ts.map +1 -0
- package/dist/utils/errors.d.ts +86 -0
- package/dist/utils/errors.d.ts.map +1 -1
- package/dist/utils/http.d.ts.map +1 -1
- package/dist/utils/load-env.d.ts +31 -0
- package/dist/utils/load-env.d.ts.map +1 -0
- package/dist/utils/pool-pair-parser.d.ts +55 -0
- package/dist/utils/pool-pair-parser.d.ts.map +1 -0
- package/dist/utils/pool-state-validator.d.ts +207 -0
- package/dist/utils/pool-state-validator.d.ts.map +1 -0
- package/dist/utils/position-filters.d.ts +253 -0
- package/dist/utils/position-filters.d.ts.map +1 -0
- package/dist/utils/swap-delta-calculator.d.ts +231 -0
- package/dist/utils/swap-delta-calculator.d.ts.map +1 -0
- package/dist/utils/tick-crossing-handler.d.ts +250 -0
- package/dist/utils/tick-crossing-handler.d.ts.map +1 -0
- package/dist/utils/token-format-converter.d.ts +85 -6
- package/dist/utils/token-format-converter.d.ts.map +1 -1
- package/dist/utils/token-parser.d.ts +235 -0
- package/dist/utils/token-parser.d.ts.map +1 -0
- package/dist/utils/tokenNormalizer.d.ts +66 -0
- package/dist/utils/tokenNormalizer.d.ts.map +1 -1
- package/dist/utils/transfer-validation.d.ts.map +1 -1
- package/dist/utils/validation-helpers.d.ts +75 -0
- package/dist/utils/validation-helpers.d.ts.map +1 -1
- package/package.json +36 -15
- package/dist/utils/tokenFormatConverter.d.ts +0 -53
- package/dist/utils/tokenFormatConverter.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("axios"),require("ethers"),require("@gala-chain/connect"),require("zod"),require("bignumber.js"),require("@gala-chain/api"),require("uuid"),require("socket.io-client"),require("@gala-chain/gswap-sdk")):"function"==typeof define&&define.amd?define(["exports","axios","ethers","@gala-chain/connect","zod","bignumber.js","@gala-chain/api","uuid","socket.io-client","@gala-chain/gswap-sdk"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GalaLaunchpadSDK={},e.axios,e.ethers,e.GalaChainConnect,e.z,e.BigNumber,e.GalaChainAPI,e.uuid,e.io,e.GalaSwapSDK)}(this,function(e,t,a,n,o,r,i,s,c,l){"use strict";if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}var u,d;!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"}(u||(u={}));class h extends Error{constructor(e,t,a){super(t),this.type=e,this.originalError=a,this.name="AuthError"}}class g{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new h(u.SIGNATURE_FAILED,"Message prefix cannot be empty")}hasWallet(){return void 0!==this.wallet}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new h(u.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new h(u.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,a=await this.wallet.signMessage(t);return{message:t,signature:a,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof h)throw e;throw new h(u.SIGNATURE_FAILED,"Failed to generate signature for authentication",e instanceof Error?e:new Error(String(e)))}}getAddress(){return this.validateWallet(),this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.validateWallet(),this.wallet.address}getPrivateKey(){if(this.validateWallet(),!this.wallet.privateKey)throw new h(u.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new h(u.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`);return`eth|${t}`}async signMessage(e){this.validateWallet();try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){if(e instanceof h)throw e;const t=e instanceof Error?e.message:String(e);throw new h(u.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const a=Date.now(),n=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${a}`,o=await this.wallet.signMessage(n);return{"x-signature":o,"x-address":this.formatAddress(this.wallet.address),"x-message":n,"x-timestamp":a.toString()}}catch(e){if(e instanceof h)throw e;throw new h(u.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(e)))}}async signTypedData(e,t,a){this.validateWallet();try{return await this.wallet.signTypedData(e,t,a)}catch(e){if(e instanceof h)throw e;throw new h(u.SIGNATURE_FAILED,"Failed to sign typed data",e instanceof Error?e:new Error(String(e)))}}async generateCustomSignature(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new h(u.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){if(e instanceof h)throw e;throw new h(u.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new h(u.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new h(u.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new h(u.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"}(d||(d={}));class p{constructor(e){this.levelPriority={[d.DEBUG]:0,[d.INFO]:1,[d.WARN]:2,[d.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?d.DEBUG:d.INFO)}debug(e,t){this.log(d.DEBUG,e,t)}info(e,t){this.log(d.INFO,e,t)}warn(e,t){this.log(d.WARN,e,t)}error(e,t){this.log(d.ERROR,e,t)}log(e,t,a){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===d.DEBUG&&!this.debugEnabled)return;const n=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,o=this.getConsoleMethod(e);void 0!==a?a instanceof Error?o(`${n} ${t}`,a.message,a.stack):o(`${n} ${t}`,a):o(`${n} ${t}`)}getConsoleMethod(e){switch(e){case d.DEBUG:return console.debug;case d.INFO:return console.info;case d.WARN:return console.warn;case d.ERROR:return console.error;default:return console.log}}child(e){return new p({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[d.DEBUG]>=this.levelPriority[this.minLevel]}}function m(e){if(!e||"object"!=typeof e)return{};const t={};for(const[a,n]of Object.entries(e))null!=n&&("string"==typeof n?t[a]=n:"number"==typeof n||"boolean"==typeof n?t[a]=n.toString():Array.isArray(n)?t[a]=n.join(","):t[a]="object"==typeof n?JSON.stringify(n):String(n));return t}class f{constructor(e,a={}){this.auth=e,this.debug=a.debug??!1,this.logger=new p({debug:this.debug,context:"HttpClient"}),this.axios=t.create({baseURL:a.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:a.timeout||3e4,headers:{Accept:"application/json",...a.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:m(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};e.data instanceof FormData&&(t.headers&&t.headers["Content-Type"]&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload"));const a=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:a,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const n=await this.axios.request(t);return this.logger.debug("Response:",{status:n.status,data:n.data}),n.data}catch(e){throw this.logger.error("Error:",e),e}}async get(e,t,a){return this.request({method:"GET",url:e,...t&&{params:t},...a&&{headers:a}})}async post(e,t,a){return this.request({method:"POST",url:e,data:t,...a&&{headers:a}})}async put(e,t,a){return this.request({method:"PUT",url:e,data:t,...a&&{headers:a}})}async delete(e,t,a){return this.request({method:"DELETE",url:e,...t&&{params:t},...a&&{headers:a}})}async patch(e,t,a){return this.request({method:"PATCH",url:e,data:t,...a&&{headers:a}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,a){return await this.auth.signTypedData(e,t,a)}async signCustomMessage(e){try{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}}catch(e){throw this.logger.error("Custom signature generation failed:",e),new Error(`Failed to generate custom signature for message: ${e instanceof Error?e.message:"Unknown error"}`)}}async signWithGalaChain(e,t,a=n.SigningType.SIGN_TYPED_DATA){const o=this.auth.getPrivateKey(),r=new n.SigningClient(o);return await r.sign(e,t,a)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{try{if(e.headers||(e.headers={}),this.auth.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),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 y="Token name is required and must be a string",w=e=>`Could not find vault address for token: ${e}`;class k extends Error{constructor(e,t,a){super(e),this.field=t,this.code=a,this.name="ValidationError"}}class v extends Error{constructor(e,t,a){super(e),this.statusCode=t,this.originalError=a,this.name="NetworkError"}}class A extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class T extends Error{constructor(e,t,a){super(e),this.transactionId=t,this.code=a,this.name="TransactionError"}}class S extends Error{constructor(e,t,a){super(e),this.originalError=t,this.code=a,this.name="GSwapQuoteError"}}class E extends Error{constructor(e,t,a,n){super(e),this.originalError=t,this.transactionHash=a,this.code=n,this.name="GSwapSwapError"}}class b extends Error{constructor(e,t,a,n,o){super(e),this.originalError=t,this.tokenA=a,this.tokenB=n,this.code=o,this.name="GSwapPoolError"}}class N extends Error{constructor(e,t,a,n){super(e),this.originalError=t,this.walletAddress=a,this.code=n,this.name="GSwapAssetError"}}class I extends Error{constructor(e,t,a){super(e),this.originalError=t,this.code=a,this.name="GSwapPositionError"}}function F(e,t,a){const{MIN_PAGE:n,MAX_PAGE:o,MIN_LIMIT:r,MAX_LIMIT:i}=a.PAGINATION;if("number"!=typeof e||e<n||e>o)throw new k(`Page must be a number between ${n} and ${o}`,"page","INVALID_PAGE");if("number"!=typeof t||t<r||t>i)throw new k(`Limit must be a number between ${r} and ${i}`,"limit","INVALID_LIMIT")}const C={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function D(e){return"string"==typeof e&&e.trim().length>0}function P(e){return!(!e||"string"!=typeof e)&&(C.ETH_ADDRESS.test(e)||C.BACKEND_ADDRESS.test(e))}function x(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const $=o.z.string().min(3,"Token name must be at least 3 characters").max(20,"Token name must be at most 20 characters").regex(/^[a-zA-Z0-9]{3,20}$/,"Token name can only contain letters and numbers"),L=o.z.string().min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),_=o.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),U=o.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),B=o.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),M=o.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),O=o.z.string().regex(C.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),R=o.z.string().regex(C.ETH_ADDRESS,"Invalid Ethereum address format"),G=o.z.string().refine(e=>C.BACKEND_ADDRESS.test(e)||C.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),K=o.z.string().refine(e=>C.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),q=o.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),z=o.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),V=o.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),W=o.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),j=o.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),H=o.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function X(e=100){return o.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const Q=X(100),Y=X(20),Z=X(20),J=o.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),ee=o.z.string().max(255,"Filename must be at most 255 characters"),te=o.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),ae=o.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),ne=o.z.string().datetime("Must be a valid ISO 8601 date string"),oe=o.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),re=o.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),ie=o.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),se=o.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),ce=o.z.object({websiteUrl:j,telegramUrl:j,twitterUrl:j}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),le=o.z.string().min(1,"Token category must not be empty").default("Unit"),ue=o.z.string().min(1,"Token collection must not be empty").default("Token"),de=o.z.object({minFeePortion:q,maxFeePortion:q}),he=o.z.object({tokenName:$,tokenSymbol:L,tokenDescription:_,tokenImage:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer),o.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:z.default("0"),websiteUrl:j,telegramUrl:j,twitterUrl:j,tokenCategory:le,tokenCollection:ue,reverseBondingCurveConfiguration:de.optional(),privateKey:re.optional()}),ge=o.z.object({file:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer)]),tokenName:$}),pe=o.z.enum(["recent","popular"]),me=o.z.object({tokenName:$.optional(),symbol:L.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),fe=o.z.enum(["NATIVE","MEME"]),ye=o.z.enum(["IN","OUT"]),we=o.z.object({from:o.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:o.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:o.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:$}),ke=o.z.object({tokenName:$,slippageToleranceFactor:o.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:o.z.number().min(0).max(1).optional(),privateKey:re.optional()}),ve=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Ae=o.z.object({file:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer)]),name:ee,size:J,type:te}),Te=o.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),Se=o.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Ee=o.z.union([Te,Se]),be=o.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Ne=ee.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return ve.includes(t)},`Filename must end with one of: ${ve.join(", ")}`),Ie=o.z.object({page:H,limit:Q}),Fe=o.z.object({page:H,limit:Y}),Ce=o.z.object({page:H,limit:Z}),De=o.z.object({page:H,limit:X(50)}),Pe=Ie.extend({type:o.z.enum(["recent","popular"]).optional(),tokenName:o.z.string().min(1).max(50).optional(),search:o.z.string().min(1).max(100).optional()}),xe=Fe.extend({tokenName:o.z.string().min(1).max(50).optional(),search:o.z.string().min(1).max(100).optional()}),$e=Ce.extend({tradeType:o.z.enum(["BUY","SELL"]).optional(),tokenName:o.z.string().min(1).max(50).optional(),userAddress:o.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:o.z.string().datetime().optional(),endDate:o.z.string().datetime().optional(),sortOrder:o.z.enum(["ASC","DESC"]).default("DESC")}),Le=o.z.object({page:o.z.number().int().min(1),limit:o.z.number().int().min(1),total:o.z.number().int().min(0),totalPages:o.z.number().int().min(0),hasNext:o.z.boolean(),hasPrevious:o.z.boolean()});const _e=o.z.enum(["all","DEFI","ASSET"]),Ue=Fe.extend({type:_e.optional(),address:G.optional(),search:B.optional(),tokenName:U.optional()}),Be=o.z.object({walletAddress:G,amount:V}),Me=o.z.object({address:G.optional(),refresh:o.z.boolean().optional()}),Oe=o.z.object({profileImage:o.z.string(),fullName:M,address:G,privateKey:re.optional()}),Re=o.z.object({file:o.z.union([o.z.instanceof(File),o.z.instanceof(Buffer)]),address:G.optional(),privateKey:re.optional()}),Ge=o.z.object({address:G,tokenId:o.z.union([o.z.string(),o.z.object({collection:o.z.string(),category:o.z.string(),type:o.z.string(),additionalKey:o.z.string()}),o.z.object({collection:o.z.string(),category:o.z.string(),type:o.z.string(),additionalKey:o.z.string(),instance:o.z.string()})]).optional(),tokenName:U.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),Ke=o.z.enum(["buy","sell"]),qe=o.z.enum(["BUY","SELL"]),ze=o.z.object({tradeType:Ke,tokenAmount:q,vaultAddress:K,userAddress:G,slippageTolerance:q.optional(),deadline:o.z.number().int().positive().optional()}),Ve=o.z.object({tokenSymbol:L,nativeTokenQuantity:q,expectedToken:q,maxAcceptableReverseBondingCurveFee:z.default("0").optional()}),We=o.z.object({tokenSymbol:L,tokenQuantity:q,expectedNativeToken:q,maxAcceptableReverseBondingCurveFee:z.default("0").optional()}),je=Ce.extend({tokenName:U.optional()}),He=o.z.object({page:o.z.number().int().min(1).max(1e3).default(1).optional(),limit:o.z.number().int().min(1).max(20).default(10).optional()}),Xe=o.z.enum(["NATIVE","MEME"]),Qe=o.z.enum(["IN","OUT"]),Ye=o.z.object({type:Xe,method:Qe,vaultAddress:K,amount:q}),Ze=o.z.object({nativeTokenQuantity:q}),Je=o.z.object({vaultAddress:K}),et=o.z.object({minFeePortion:q,maxFeePortion:q});function tt(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 at=tt($),nt=tt(L),ot=tt(_),rt=tt(G),it=tt(K),st=tt(q),ct=tt(V),lt=tt(M),ut=tt(B),dt=tt(U),ht=tt(he),gt=tt(ce),pt=tt(ge),mt=tt(me),ft=tt(Ue),yt=tt(Be),wt=tt(Me),kt=tt(Oe),vt=tt(Re),At=tt(Ge),Tt=tt(ze),St=tt(Ve),Et=tt(We),bt=tt(je),Nt=tt(He),It=tt(Ye),Ft=tt(Ze),Ct=tt(Je);function Dt(e,t){throw new k(e.join("; "),t,"VALIDATION_ERROR")}function Pt(e){const t=at(e);!t.success&&t.errors&&Dt(t.errors,"tokenName")}function xt(e){const t=Pe.safeParse(e);t.success||Dt(t.error.errors.map(e=>e.message),"pagination")}function $t(e){const t=mt(e);!t.success&&t.errors&&Dt(t.errors,"options")}function Lt(e){const t=It(e);!t.success&&t.errors&&Dt(t.errors,"options")}function _t(e){const t=we.safeParse(e);t.success||Dt(t.error.errors.map(e=>e.message),"options")}function Ut(e){const t=G.safeParse(e);if(!t.success)throw new k("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Bt(e,t,a=!0){if(!e||""===e.trim())throw new k(`${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 k(`${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 k(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(n))throw new k(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(n<0)throw new k(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!a&&0===n)throw new k(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var Mt=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=G.safeParse(e);if(!t.success)throw new k(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:Ut,validateCheckPoolOptions:$t,validateGetAmountOptions:Lt,validateGetGraphOptions:_t,validateNumericString:Bt,validatePagination:xt,validateTokenName:Pt});function Ot(e,t){return new k(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Rt(e,t){const a=t||e.charAt(0).toUpperCase()+e.slice(1);return new k(`${a} is required`,e,"REQUIRED_FIELD")}function Gt(e,t,a){const n=a||e.charAt(0).toUpperCase()+e.slice(1);return new k(`${n} must be ${t}`,e,"INVALID_FORMAT")}function Kt(e,t,a){return new v(e,t,a)}function qt(e,t){return new A(e,t)}function zt(e,t,a){return new T(e,t,a)}function Vt(e,t){const a=e,n=Number(a.page)||t.page,o=Number(a.limit)||t.limit,r=a.data,i=Number(a.total)||Number(r?.count)||0;return{page:n,limit:o,total:i,totalPages:Math.ceil(i/o)}}function Wt(e,t){return{hasNext:e<t,hasPrevious:e>1}}function jt(e,t,a=!1){const n=!0===e.error||200!==e.status,o=a&&!e.data;if(n||o)throw new Error(e.message||t)}const Ht="/launchpad/upload-image",Xt="/launchpad/fetch-pool",Qt="/launchpad/check-pool",Yt="/launchpad/get-graph-data",Zt="/holders",Jt="/launchpad/get-badge/",ea="/trade/",ta="/token/commment",aa="/token/commment",na="/user/profile",oa="/user/profile",ra="/user/token-list",ia="/user/token-hold",sa="/user/transfer-faucets",ca={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};class la{constructor(e,t=!1){this.http=e,this.logger=new p({debug:t,context:this.constructor.name})}}function ua(e,t){return"string"==typeof e[t]}function da(e,t){return void 0===e[t]||"string"==typeof e[t]}function ha(e,t){return void 0===e[t]||"number"==typeof e[t]}function ga(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function pa(e){if(!e||"object"!=typeof e)return!1;const t=e;return ua(t,"tokenName")&&ha(t,"from")&&ha(t,"to")&&ha(t,"resolution")}class ma extends la{constructor(e,t=!1){super(e,t)}async fetchSinglePage(e){const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const a=m(t),n=await this.http.get(Xt,a);jt(n,"Failed to fetch pools",!0);const o=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at||e.createdAt||""}));else{const a=e.tokens;t=[{...a,createdAt:a.created_at||a.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(n.data),r=n.data.count??n.data.total??0;return{pools:o,total:r,totalPages:e.limit>0?Math.ceil(r/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:a,pageSize:n,...o}=e,r=[];if(a&&a>=t){const e=[];for(let n=t;n<=a;n++)e.push(n);for(let t=0;t<e.length;t+=5){const a=e.slice(t,t+5).map(e=>this.fetchSinglePage({...o,page:e,limit:n}));(await Promise.all(a)).forEach(e=>{r.push(...e.pools)})}return r}let i=t,s=!0;for(;s;){const e=[];for(let t=0;t<5&&s;t++)e.push(i+t);const t=e.map(e=>this.fetchSinglePage({...o,page:e,limit:n})),a=await Promise.all(t);for(const e of a){if(0===e.pools.length){s=!1;break}r.push(...e.pools)}i+=e.length,i>ca.SAFETY_MAX_PAGES&&(s=!1)}return r}async fetchPools(e={}){const t=e.page||ca.DEFAULT_PAGE,a=e.limit??ca.DEFAULT_LIMIT;let n;if(0!==a&&xt({page:t,limit:a}),e.tokenName&&Pt(e.tokenName),"recent"===e.type?n="RECENT":"popular"===e.type&&(n="POPULAR"),a>0&&a<=20){const o=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:a});return{pools:o.pools,page:t,limit:a,total:o.total,totalPages:o.totalPages,hasNext:t<o.totalPages,hasPrevious:t>1}}if(0===a){const t=ca.BACKEND_MAX_PAGE_SIZE,a=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:1,limit:t}),o=[...a.pools];if(a.pools.length>0){const r=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:2,totalPages:a.totalPages>1?a.totalPages:null,pageSize:t});o.push(...r)}return{pools:o,page:1,limit:o.length,total:a.total||o.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const o=ca.BACKEND_MAX_PAGE_SIZE,r=Math.ceil(a/o),i=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:o}),s=[...i.pools],c=Math.min(r,i.totalPages-t+1);if(c>1){const a=t+c-1,r=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:t+1,totalPages:a,pageSize:o});s.push(...r)}const l=s.slice(0,a);return{pools:l,page:t,limit:a,total:i.total,totalPages:i.totalPages,hasNext:t<i.totalPages&&l.length<i.total,hasPrevious:t>1}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){$t(e),e.tokenName&&Pt(e.tokenName);const t=m(e),a=await this.http.get(Qt,t);jt(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(!pa(e))throw new k("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:a,to:n,resolution:o}=e;if(Pt(t),!a||!n||!o)throw new k("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:a,to:n,resolution:o};_t(r);const i=m(r),s=await this.http.get(Yt,i);return jt(s,"Failed to fetch graph data",!0),{dataPoints:s.data}}async fetchTokenDistribution(e){if(!e)throw Rt("tokenName","Token name");Pt(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw Ot(e);const a=encodeURIComponent(t),n=await this.http.get(`${Zt}/${a}`);jt(n,"Failed to fetch token distribution",!0);const o=n.data;if(!Array.isArray(o))throw Kt("Invalid API response: expected array of holders",n.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw Kt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw Kt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw Kt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const i=o.reduce((e,t)=>e.plus(t.quantity),new r(0));return{holders:o.map(e=>{const t=new r(e.quantity),a=i.isZero()?0:t.dividedBy(i).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:a}}),totalSupply:i.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Rt("tokenName","Token name");Pt(e);const t=await this.http.get(Jt,{tokenName:e});return jt(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 o=("volume"===a?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return o?.isActive||!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(t.pools&&Array.isArray(t.pools)&&t.pools.length>0)return t.pools[0].vaultAddress||null;if(t.pools&&"object"==typeof t.pools){const e=t.pools.tokens;return e?.vaultAddress||null}return null}catch{return null}}}function fa(e,t={}){const{stringifyFields:a=[],optionalFields:n=[],fieldMappings:o={}}=t,r={};for(const[t,i]of Object.entries(e)){const e=t;if(n.includes(e)&&void 0===i)continue;if(n.includes(e)&&"string"==typeof i&&0===i.trim().length)continue;const s=o[e],c=s?String(s):t;a.includes(e)?r[c]=String(i):r[c]=i}return m(r)}const ya={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class wa extends la{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ua(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&da(t,"userAddress")&&ha(t,"page")&&ha(t,"limit")}(e))throw new k("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, page?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:a,userAddress:n,page:o=ca.DEFAULT_PAGE,limit:r=ca.DEFAULT_LIMIT,startDate:i,endDate:s,sortOrder:c}=e;if(!D(t))throw new k("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");F(o,r,ya);const l=function(e,t,a){return fa({tokenName:e,page:t,limit:a},{stringifyFields:["page","limit"]})}(t,o,r),u=await this.http.get(ea,l),d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const g=Vt(u,{page:o,limit:r}),p=Wt(g.page,g.totalPages);return{trades:d,...g,...p}}}const ka=new p({debug:!1,context:"DateUtils"});function va(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())?(ka.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):a}catch(a){return ka.warn(`Date parsing error for "${e}":`,a),t||new Date}}const Aa={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class Ta extends la{constructor(e,t,a=!1){super(e,a),this.poolService=t}async fetchComments(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ua(t,"tokenName")&&ha(t,"page")&&ha(t,"limit")}(e))throw new k("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:a=ca.DEFAULT_PAGE,limit:n=ca.DEFAULT_LIMIT}=e;if(!D(t))throw new k("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");F(a,n,Aa);const o=await this.poolService.resolveTokenNameToVault(t);if(!o)throw Ot(t);const r=fa({vaultAddress:o,page:a,limit:n},{stringifyFields:["page","limit"]}),i=await this.http.get(ta,r);jt(i,"Failed to fetch comments");return{comments:i.data.comments.map(e=>({...e,createdAt:va(e.createdAt)})),total:i.data.count}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ua(t,"tokenName")&&ua(t,"content")}(e))throw new k("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:a}=e;if(!D(t))throw new k("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>=Aa.CONTENT.MIN_LENGTH&&t.length<=Aa.CONTENT.MAX_LENGTH}(a))throw new k(`Comment content must be between ${Aa.CONTENT.MIN_LENGTH} and ${Aa.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const n=await this.poolService.resolveTokenNameToVault(t);if(!n)throw Ot(t);const o={userAddress:this.http.getAddress(),vaultAddress:n,content:a};jt(await this.http.post(aa,o),"Failed to create comment")}}function Sa(e){return e instanceof Error}function Ea(e){return Sa(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function ba(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Na(e,t="image",a){const n=new FormData;if("undefined"!=typeof File&&e instanceof File)n.append(t,e);else{if(!Buffer.isBuffer(e))throw Gt("file","a File object (browser) or Buffer (Node.js)");{const o=new Blob([e],{type:"image/png"});n.append(t,o,a)}}return n}const Ia={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 Fa(e){return!(!e||"string"!=typeof e)&&Ia.USER_ADDRESS.PATTERN.test(e)}const Ca="Update profile";class Da extends la{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!Fa(t))throw new k("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const a={userAddress:t};return await this.http.get(na,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(Ca),o={address:n.address,message:Ca,publickey:n.ethereumAddress,sign:n.signature};jt(await this.http.put(oa,a,o),"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();try{const a=`profile-image-${t}.png`,n=Na(e.file,"image",a),o=await this.http.request({method:"POST",url:`${Ht}?tokenName=${encodeURIComponent(t)}`,data:n,headers:{}});return jt(o,"Image upload failed"),"string"==typeof o.data?o.data:""}catch(e){if(e instanceof k)throw e;throw new k(`Profile image upload failed: ${Ea(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(ra,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(ia,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=ca.DEFAULT_PAGE,limit:a=ca.DEFAULT_LIMIT,search:n,tokenName:o}=e,r={type:"DEFI",address:this.http.getAddress(),page:t,limit:a};return void 0!==n&&(r.search=n),void 0!==o&&(r.tokenName=o),this.fetchTokenList(r)}async buildFetchRequest(e,t,a){this.validateGetTokenListOptions(t);const n={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},o=fa(a.includeType?{...n,type:"all"!==t.type&&t.type?t.type:"DEFI"}:n,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),r=await this.http.get(e,o);jt(r,a.errorMessage,!0);const i=(s=r.data)?Array.isArray(s)?s:s.token:[];var s;const c=Vt(r,{page:t.page||ca.DEFAULT_PAGE,limit:t.limit||ca.DEFAULT_LIMIT}),l=Wt(c.page,c.totalPages);return{tokens:i,...c,...l}}validateGetTokenListOptions(e){if(F(e.page,e.limit,Ia),void 0!==e.address&&!Fa(e.address))throw new k("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>=Ia.SEARCH.MIN_LENGTH&&t.length<=Ia.SEARCH.MAX_LENGTH))throw new k(`Search query must be between ${Ia.SEARCH.MIN_LENGTH} and ${Ia.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>=Ia.TOKEN_NAME.MIN_LENGTH&&a.length<=Ia.TOKEN_NAME.MAX_LENGTH))throw new k(`Token name must be between ${Ia.TOKEN_NAME.MIN_LENGTH} and ${Ia.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!Fa(e.address))throw new k("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=Ia.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=Ia.PROFILE.FULL_NAME.MAX_LENGTH&&Ia.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new k(`Full name must be between ${Ia.PROFILE.FULL_NAME.MIN_LENGTH} and ${Ia.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!Fa(e.address))throw new k("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Pa extends Error{constructor(e,t,a){super(e),this.filename=t,this.mimeType=a,this.name="FileValidationError"}}function xa(e,t,a){if(!e)throw new Pa("File is required",t,a);if("undefined"!=typeof File&&e instanceof File){const t=Te.safeParse(e);if(!t.success){const a=t.error.errors.map(e=>e.message).join("; ");throw new Pa(a,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Pa("Filename is required when uploading Buffer objects",t,a);const n=Se.safeParse(e);if(!n.success){const e=n.error.errors.map(e=>e.message).join("; ");throw new Pa(e,t,a)}if(t.length>255)throw new Pa(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,a);const o=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!o.includes(a))throw new Pa(`Invalid file type "${a}" is not allowed. Allowed types: ${o.join(", ")}`,t,a);const r=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),i=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!i.includes(r))throw new Pa(`File extension "${r}" is not allowed. Allowed extensions: ${i.join(", ")}`,t,a);const s=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(r);if(s!==a&&"application/octet-stream"!==s)throw new Pa(`File extension "${r}" does not match MIME type "${a}"`,t,a);return}throw new Pa("File must be a File object (browser) or Buffer (Node.js)",t,a)}class $a extends la{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Pt(t);const n=`${t}.png`;xa(a.file,n,"image/png");try{const e=`${a.tokenName??t}.png`,n=Na(a.file,"image",e),o=await this.http.request({method:"POST",url:`${Ht}?tokenName=${encodeURIComponent(a.tokenName??t)}`,data:n,headers:{}});return jt(o,"Image upload failed"),"string"==typeof o.data?o.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw qt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class La extends la{constructor(e,t=!1){super(e,t)}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount};jt(await this.http.post(sa,t),"Faucet transfer failed")}validateTransferFaucetsData(e){if(!Fa(e.walletAddress))throw new k("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!Ia.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new k("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class _a{constructor(e,t=!1){this.http=e,this.poolService=new ma(e,t),this.tradeService=new wa(e,t),this.commentService=new Ta(e,this.poolService,t),this.userService=new Da(e,t),this.imageService=new $a(e,t),this.faucetService=new La(e,t)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async fetchComments(e){return this.commentService.fetchComments(e)}async postComment(e){return this.commentService.postComment(e)}async fetchProfile(e){return this.userService.fetchProfile(e)}async updateProfile(e){return this.userService.updateProfile(e)}async uploadProfileImage(e){return this.userService.uploadProfileImage(e)}async fetchTokenList(e){return this.userService.fetchTokenList(e)}async fetchTokensHeld(e){return this.userService.fetchTokensHeld(e)}async fetchTokensCreated(e={}){return this.userService.fetchTokensCreated(e)}async transferFaucets(e){return this.faucetService.transferFaucets(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return Pt(e)}}const Ua={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",e.WALLET_REQUIRED="WALLET_REQUIRED"}(Ba||(Ba={}));class Ma extends Error{constructor(e,t,a){super(e),this.type=t,this.details=a,this.name="TransferError"}}class Oa{static validateAmount(e){if(parseFloat(e)<=0)throw new Ma("Transfer amount must be positive",Ba.INVALID_AMOUNT,{amount:e})}static validateUniqueKey(e){if(e){if(e.length>Ua.MAX_UNIQUE_KEY_LENGTH)throw new k(`Unique key too long. Maximum length: ${Ua.MAX_UNIQUE_KEY_LENGTH}`);if(!Ua.UNIQUE_KEY_PATTERN.test(e))throw new Ma('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Ba.INVALID_AMOUNT,{uniqueKey:e})}}}class Ra extends n.ChainCallDTO{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,a,n,o){let r;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`);r={collection:e[0],category:e[1],type:e[2],additionalKey:e[3],instance:"0"}}else r={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new Ra({from:e,to:t,quantity:a,tokenInstance:r,uniqueKey:o||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,a,n){return new Ra({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 Ga{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 k(`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 k(`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 k("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 k(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}var qa=Object.freeze({__proto__:null,normalizeToTokenInstanceKey:Ka});const za="gala-transfer-successful",Va="token-transfer-successful",Wa="transfer-successful-no-id";class ja extends la{constructor(e,t,a,n=!1,o){super(e,n),this.wallet=t,this.tokenResolver=a,this.publicAxios=o,this.signatureHelper=t?new Ga(t):void 0}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(1!==t.Status)throw Kt(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const a=t.Data.reverseBondingCurveConfiguration,n=a?.minFeePortion??"0",o=a?.maxFeePortion??"0",r=(await import("bignumber.js")).default,i=!new r(n).isZero()||!new r(o).isZero(),s=t.Data;return s.reverseBondingCurveMinFeePortion=n,s.reverseBondingCurveMaxFeePortion=o,s.hasReverseBondingCurveFee=i,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(1!==e.Status)throw Kt(`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 k("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new k("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new k("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 Kt(`Failed to fetch token balance from GalaChain: ${Ea(e)}`,void 0,Sa(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Ka(e):e,a={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]},n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",a)).data;if(1!==n.Status)throw Kt(`Failed to fetch token class from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw Kt(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return n.Data[0]}catch(e){if(ba(e)&&404===e.response?.status)throw Kt("Token not found on GalaChain",404,Sa(e)?e:void 0);const t=Ea(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw Kt(`Failed to fetch token class from GalaChain: ${t}`,void 0,Sa(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new Ma("Wallet required for GALA transfer operations",Ba.WALLET_REQUIRED);try{const t=x(e.recipientAddress),a=x(this.wallet.address),n=Ra.forGALA(a,t,e.amount,e.uniqueKey),o=await this.signatureHelper.signTransferToken(n.toSigningPayload()),r=new Ra({...n.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(r,null,2));const i=await this.http.post("/api/asset/token-contract/TransferToken",r);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(i,null,2)),this.extractTransactionIdFromResponse(i,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new Ma("Wallet required for token transfer operations",Ba.WALLET_REQUIRED);try{const t=x(e.to),a=x(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 Ma("Must provide either tokenId or tokenName for token identification",Ba.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const o=new Ra({from:a,to:t,quantity:e.amount,tokenInstance:n,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),r=await this.signatureHelper.signTransferToken(o.toSigningPayload()),i=new Ra({...o.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(i,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",i);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"token")}catch(t){throw this.handleTransferError(t,"Token transfer failed",e)}}async resolveTokenClassKey(e){try{const t=await this.tokenResolver.resolveTokenClassKey(e);return this.logger.debug(`[DEBUG] Token class key resolution for '${e}':`,JSON.stringify(t,null,2)),t}catch(t){if(t instanceof Ma)throw t;throw new Ma(`Failed to resolve token class key for '${e}': ${Ea(t)}`,Ba.TOKEN_NOT_FOUND,{tokenName:e})}}validateTransferGalaData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.recipientAddress&&t.recipientAddress.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new k("Invalid GALA transfer data: missing required fields");if(!P(e.recipientAddress))throw new Ma("Invalid recipient address format",Ba.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Oa.validateAmount(e.amount),Oa.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.to&&t.to.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new k("Invalid token transfer data: missing required fields");if(!P(e.to))throw new Ma("Invalid recipient address format",Ba.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Ma("Must provide either tokenId or tokenName for token identification",Ba.TOKEN_NOT_FOUND);if(e.tokenName&&!Ua.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Ma("Invalid token name format",Ba.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Oa.validateAmount(e.amount),Oa.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Ma(`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 Ma)throw t;throw new Ma(`Failed to resolve token '${e}': ${Ea(t)}`,Ba.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){const[t,a]=e.split("|");if(!a)throw new Ma(`Invalid vault address format: missing token components. Address: ${e}`,Ba.TOKEN_NOT_FOUND);const n=a.split("$");if(n.length<4)throw new Ma(`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"}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const a=e;return Array.isArray(a.Data)&&a.Data.length>0?"gala"===t?za:Va:Wa}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Ma("Transfer succeeded but transaction ID could not be extracted",Ba.NETWORK_ERROR)}handleTransferError(e,t,a){if(e instanceof Ma)return e;if(e instanceof k)return new Ma(e.message,Ba.INVALID_AMOUNT);if(ba(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t)return new Ma(("string"==typeof n?.message?n.message:void 0)||"Invalid transfer request",Ba.INVALID_AMOUNT);if(403===t)return new Ma("Insufficient balance for transfer",Ba.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in a&&(e.tokenName=a.tokenName),new Ma("Token not found",Ba.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new Ma("Transfer request timed out",Ba.NETWORK_ERROR);const n=Ea(e);return new Ma(n||t,Ba.NETWORK_ERROR)}}function Ha(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}class Xa{constructor(e,t,a,n=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=a,this.logger=new p({debug:n,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:a}=e;if(!t&&!a)throw Rt("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&a)throw new k("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS");if(a)return this.logger.debug(`Fetching spot price by tokenId: ${a}`),this._fetchDexTokenSpotPrice(a);throw new k("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw Rt("tokenId","Token ID");try{const t=Ka(e),a=Ha(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${a}`),!this.dexBackendHttp)throw Kt("DEX Backend API client not configured");const n=await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:a}});if(!n.data||"string"!=typeof n.data)throw new k("Invalid price response: data must be a string, got "+typeof n.data,"data","INVALID_RESPONSE");const o=parseFloat(n.data);if(isNaN(o))throw new k(`Invalid price value: could not parse "${n.data}" as number`,"data","INVALID_CALCULATION");const r=`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`;let i;try{if(this.cache){const e=this.cache.getByTokenId(r);if(e?.symbol)return i=e.symbol,this.logger.debug(`DEX spot price for ${i} (cached): $${o}`),{symbol:i,price:o}}this.logger.debug(`Symbol cache miss for ${r}, fetching from API`);i=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(r,{symbol:i}),this.logger.debug(`Cached symbol for ${r}: ${i}`)),this.logger.debug(`DEX spot price for ${i}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to type field: ${e instanceof Error?e.message:String(e)}`),i=t.type.toUpperCase(),this.logger.debug(`DEX spot price for ${i} (fallback): $${o}`)}return{symbol:i,price:o}}catch(e){if(e instanceof k)throw e;throw Kt(`Failed to fetch DEX spot price: ${Ea(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,a){if(!e||"string"!=typeof e)throw new Error(y);try{if(a)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await a(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const a=`${t.sellingToken.collection}|${t.sellingToken.category}|${t.sellingToken.type}|${t.sellingToken.additionalKey}`;return this._fetchDexTokenSpotPrice(a)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Ea(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),o=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(!o)throw Kt("GALA price not available");const r=Number(n.amount)/1e18;if(r<=0)throw new k(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const i=o.price/r;return{symbol:e.toUpperCase(),price:i}}catch(t){if(t instanceof Error)throw Kt(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw Kt(`Failed to calculate launchpad token spot price for ${e}: ${Ea(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw Kt("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),a={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey,symbol:t.symbol,decimals:t.decimals,name:t.name,image:t.image,description:t.description,network:t.network,...void 0!==t.contractAddress&&{contractAddress:t.contractAddress}};return this.logger.debug(`Fetched token details for ${t.symbol} from GalaChain`),a}catch(t){if((t instanceof k||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw Kt(`Failed to fetch token details from GalaChain for ${e}: ${Ea(t)}`,500)}}}function Qa(e,t=18){const a=parseFloat(e);if(0===a)return"0";return a.toFixed(t).replace(/\.?0+$/,"")}function Ya(e){return Qa(e,8)}function Za(e){return Qa(e,18)}function Ja(e){return{maxAcceptableReverseBondingCurveFee:Ya(e.maxAcceptableReverseBondingCurveFee)}}new p({debug:!1,context:"NumberUtils"});class en extends n.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Ya(t),this.expectedToken=Za(a),this.extraFees=Ja(n)}}class tn extends n.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Za(t),this.expectedNativeToken=Ya(a),this.extraFees=Ja(n)}}class an extends n.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Za(t),this.expectedNativeToken=Ya(a),this.extraFees=Ja(n)}}class nn extends n.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Ya(t),this.expectedToken=Za(a),this.extraFees=Ja(n)}}const on={BuyNativeDto:en,BuyExactDto:tn,SellExactDto:an,SellNativeDto:nn};var rn,sn,cn;!function(e){e[e.METAMASK=0]="METAMASK",e[e.TRUST_WALLET=1]="TRUST_WALLET",e[e.GALA_WALLET=2]="GALA_WALLET"}(rn||(rn={}));class ln{constructor(e,t=!1){this.walletProvider=e,this.debug=t,this.logger=new p({debug:t,context:"SignatureService"})}async signDTO(e,t,a,o=rn.METAMASK){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,walletPreference:o,dtoKeys:Object.keys(e)});const r=this.generateEIP712Types(t,e),i=n.calculatePersonalSignPrefix(e),s={...e,prefix:i};let c,l,u;switch(o){case rn.GALA_WALLET:({signature:c,domain:l}=await this.signWithGalaWallet(r,s,t,a));break;case rn.TRUST_WALLET:c=await this.signWithTrustWallet(s),l={name:"ethereum",chainId:1};break;case rn.METAMASK:default:({signature:c,domain:l}=await this.signWithMetaMask(r,s))}return u=o===rn.TRUST_WALLET?{...s,signature:c}:{...e,signature:c,types:r,domain:l},this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(u),signatureLength:c.length}),u}catch(e){this.logger.error("❌ Signature generation failed:",e);throw zt(`Failed to sign DTO: ${Ea(e)}`)}}async signWithMetaMask(e,t){try{let a,n;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)a={name:"ethereum",chainId:1},n=await this.walletProvider.signTypedData(a,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw qt("Wallet provider does not support typed data signing","walletProvider");{const o=await this.walletProvider.getNetwork();a={name:o.name,chainId:Number(o.chainId)},n=await this.walletProvider.signTypedData(a,e,t)}}return{signature:n,domain:a}}catch(e){throw zt(`MetaMask/ethers signing failed: ${Ea(e)}`)}}async signWithTrustWallet(e){try{const a=(t=e,JSON.stringify(t));let n;if(!this.walletProvider.signMessage)throw qt("Wallet provider does not support signMessage","walletProvider");return n=await this.walletProvider.signMessage(a),n}catch(e){throw zt(`TrustWallet signing failed: ${Ea(e)}`)}var t}async signWithGalaWallet(e,t,a,n){try{const o={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 r={domain:o,types:e,message:t,Primary_type:a},i=window;if(!i.gala)throw qt("GalaWallet not found in window object","galaWallet");await i.gala.setAddress(n);return{signature:await i.gala.request({method:"eth_signTypedData",params:[JSON.stringify(r),n]}),domain:o}}catch(e){throw zt(`GalaWallet signing failed: ${Ea(e)}`)}}generateEIP712Types(e,t){const a={};a[e]=[];const n=(e,t,o,r=!1)=>{if(void 0!==t){if(Array.isArray(t)){const i=n(e,t[0],o,!0);return r||a[o].push({name:e,type:(i??e)+"[]"}),i?i+"[]":void 0}if("object"==typeof t&&null!==t){if(a[e])throw new k(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return a[e]=[],Object.entries(t).forEach(([t,a])=>{n(t,a,e)}),r||a[o].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 k(`Unsupported type for fieldName ${e}: ${typeof t}, value: ${t}`,"fieldValue","UNSUPPORTED_TYPE")}return r||a[o].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 rn.METAMASK;const e=window;return e.gala?rn.GALA_WALLET:e.trustWallet?.isTrust?rn.TRUST_WALLET:(e.ethereum,rn.METAMASK)}}class un{constructor(e=!1){this.debug=e,this.logger=new p({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(),o=`$service$${a.toStringKey()}$launchpad`,r=`$tokenBalance$${a.toStringKey()}$${e}`,i=`$tokenBalance$${a.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,c=[o,r,i,s,`$tokenBalance$${n.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Ea(e);throw new k(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new i.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 i.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 Rt("vaultAddress","Vault address");const t=e.split("$");if(t.length<3)throw Gt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");const a=t[2];if(!a||0===a.trim().length)throw new k(`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 Rt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Gt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Gt("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw Gt("vaultAddress",'having at least 5 parts separated by "$"');const a=t[2];if(!a||!/^[A-Za-z]{1,10}$/.test(a))throw Gt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,a,n){return`${e}$${t}$${a}$${n}`}parseTokenClassKeyString(e){const t=e.split("$");if(4!==t.length)throw Gt("stringKey","format: collection$category$type$additionalKey (4 parts)");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}}function dn(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 r(e);if(n.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const o=n.multipliedBy(t);let i;switch(a){case"buy-native":case"sell-exact":i=n.minus(o);break;case"buy-exact":case"sell-native":i=n.plus(o);break;default:throw new Error(`Unknown operation type: ${a}`)}return i.isLessThan(0)&&(i=new r(0)),i.toFixed()}class hn extends la{constructor(e,t,a=!1,n,o,r=.05,i=.01){super(e,a),this.tokenResolver=t,this.walletProvider=n,this.userAddress=o,this.defaultSlippageToleranceFactor=r,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=i,this.bundleEndpoint="/bundle",n&&o&&(this.signatureService=new ln(n,a),this.tokenKeyService=new un(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.http.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 Rt("bundleData","Bundle data");if(!e.signedDto)throw Rt("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw Rt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Gt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new k("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Gt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new k(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new k(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT")}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){if(e.data&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",e.data),{success:!0,data:e.data};const t=e.error||e.message||"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",t),{success:!1,error:t}}formatErrorMessage(e){if("string"==typeof e)return e;if(ba(e)&&e.response){const t=e.response.data;if(t&&"object"==typeof t){const e=t;if(e.error)return String(e.error);if(e.message)return String(e.message)}}return Ea(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw Rt("transactionId","Transaction ID");this.logger.debug("🔍 Checking bundler transaction result:",e);const t=await this.http.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 Rt("transactionId","Transaction ID");this.logger.debug("🚫 Cancelling transaction:",e);const t=await this.http.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.http.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:o}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===n){if(!o)throw new k("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=dn(o,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:o,slippageFactor:r,adjustedMinTokens:e});const t=new on.BuyNativeDto(s,a,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",s)}{if(!o)throw new k("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=dn(o,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:o,slippageFactor:r,adjustedMaxGalaCost:e});const t=new on.BuyExactDto(s,a,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyExactToken",s)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:a,type:n,expectedAmount:o}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===n){if(!o)throw new k("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=dn(o,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:o,slippageFactor:r,adjustedMinGala:e});const t=new on.SellExactDto(s,a,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellExactToken",s)}{if(!o)throw new k("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=dn(o,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:o,slippageFactor:r,adjustedMaxTokensToSell:e});const t=new on.SellNativeDto(s,a,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellWithNative",s)}}async prepareTradingOperation(e,t,a,n){const{effectiveSlippageFactor:o,effectiveMaxFee:r}=this.calculateEffectiveSlippage(t,a,n),i=await this.resolveTokenNameToVault(e);if(!i)throw Ot(e);return{effectiveSlippageFactor:o,effectiveMaxFee:r,vaultAddress:i}}calculateEffectiveSlippage(e,t,a){const n=a??this.defaultSlippageToleranceFactor,o=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let r=e||"0";return e&&(r=dn(e,o,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:o,adjustedMaxFee:r})),{effectiveSlippageFactor:n,effectiveFeeSlippageFactor:o,effectiveMaxFee:r}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw qt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw Rt("userAddress","User address")}async executeBundleTransaction(e,t,a){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${s.v4()}-${Date.now()}-${this.userAddress}`;const n=await this.signatureService.signDTO(e,t,this.userAddress),o=this.tokenKeyService.generateStringsInstructions(a),r={stringsInstructions:o,method:t,signedDto:n};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:o,dtoKeys:Object.keys(n)});const i=await this.submitTransaction(r);if(i.success&&i.data)return this.logger.debug("✅ Bundle transaction submitted:",i.data),{success:!0,data:{transactionId:i.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(i.error||"Bundle transaction failed"))}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(sn||(sn={})),e.SDKTransactionStatus=void 0,(cn=e.SDKTransactionStatus||(e.SDKTransactionStatus={})).PENDING="pending",cn.PROCESSING="processing",cn.COMPLETED="completed",cn.FAILED="failed",cn.TIMEOUT="timeout";const gn={[sn.PROCESSED]:e.SDKTransactionStatus.COMPLETED,[sn.COMPLETED]:e.SDKTransactionStatus.COMPLETED,[sn.SUCCESS]:e.SDKTransactionStatus.COMPLETED,[sn.FAILED]:e.SDKTransactionStatus.FAILED,[sn.ERROR]:e.SDKTransactionStatus.FAILED,[sn.PROCESSING]:e.SDKTransactionStatus.PROCESSING,[sn.PENDING]:e.SDKTransactionStatus.PENDING};class pn{constructor(e,t=!1){this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.reconnectCount=0,this.hasOnAnyListener=!1,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.logger=new p({debug:t,context:"WebSocketService"}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof c.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{try{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');return this.logger.error("❌ Socket.IO connection failed:",e.message),void t(e)}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=c.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts||5,reconnectionDelay:this.config.reconnectDelay||2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectCount=0,e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.debug&&(this.socket.onAny((e,...t)=>{this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0)}catch(e){t(e)}})}async monitorTransaction(t,a){this.listeners.set(t,a),this.logger.debug(`📡 Starting to monitor transaction: ${t}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=setTimeout(()=>{if(this.listeners.has(t)){const n={transactionId:t,status:e.SDKTransactionStatus.TIMEOUT,message:"Transaction monitoring timeout - no response after 60 seconds",timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${t}`),a(n),this.listeners.delete(t),this.timeouts.delete(t),this.socket?.off(t)}},6e4);if(this.timeouts.set(t,n),this.socket&&this.socket.connected)this.socket.off(t),this.logger.debug(`📡 Listening for transaction updates: ${t}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(t,n=>{this.logger.debug(`📡 Socket.IO transaction update for ${t}:`,JSON.stringify(n,null,2));const o=n,r=o?.data,i=o?.status||o?.Status||r?.status||r?.Status;let s=o?.message||o?.Message||r?.message||r?.Message||o?.error||r?.error;s&&"string"==typeof s||(s=i===sn.FAILED||i===sn.ERROR?"Transaction failed - check transaction details":i===sn.COMPLETED||i===sn.PROCESSED||i===sn.SUCCESS?"Transaction completed successfully":i?`Transaction status: ${i}`:"Unknown transaction status");const c=o?.blockHash||r?.blockHash,l=o?.gasUsed||r?.gasUsed,u={transactionId:t,status:this.mapSocketStatus(i),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...c&&{blockHash:c},...l&&{gasUsed:l}};if(this.logger.debug(`📡 Mapped status for ${t}: ${i} -> ${u.status}`),this.logger.debug(`📡 Final message: "${s}"`),a(u),u.status===e.SDKTransactionStatus.COMPLETED||u.status===e.SDKTransactionStatus.FAILED){this.listeners.delete(t);const e=this.timeouts.get(t);e&&(clearTimeout(e),this.timeouts.delete(t)),this.socket?.off(t),this.logger.debug(`📡 Cleaned up listener for ${t} (${u.status})`)}});else{const n={transactionId:t,status:e.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};a(n),this.listeners.delete(t),this.timeouts.delete(t)}}async waitForTransaction(t){return new Promise((a,n)=>{this.monitorTransaction(t,t=>{t.status===e.SDKTransactionStatus.COMPLETED?a(t):t.status!==e.SDKTransactionStatus.FAILED&&t.status!==e.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${t.status}: ${t.message}`))})})}mapSocketStatus(t){const a=t?.toUpperCase();return gn[a]||e.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectCount<this.config.reconnectAttempts?(this.reconnectCount++,this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectCount}/${this.config.reconnectAttempts}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.config.reconnectDelay)):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected"))}isConnected(){return this.socket?.connected||!1}getSocket(){return this.socket}}class mn{constructor(e,t=!1){this.poolService=e,this.cache=new Map,this.logger=new p({debug:t,context:"TokenResolverService"})}async resolveTokenToVault(e){if(!D(e))throw new k("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 Ot(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(e.toLowerCase())||null}set(e,t){this.cache.set(e.toLowerCase(),t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}preWarm(e){for(const{tokenName:t,vaultAddress:a}of e)this.set(t,a)}parseVaultAddressToTokenClassKey(e){const t=e.split("|");if(2!==t.length)throw Gt("vaultAddress","format: service|Token$Unit$...$launchpad","Vault address");const a=t[1].split("$");if(a.length<4)throw Gt("vaultAddress","at least 4 parts after service|","Vault address");return{collection:a[0],category:a[1],type:a[2],additionalKey:a[3]}}}class fn{constructor(e,t=!1,a){this.httpClient=e,this.tokenResolverService=a,this.logger=new p({debug:t,context:"PriceHistoryService"})}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw qt("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");if(!e||"string"!=typeof e||e.length<3||e.length>20)throw qt("Token name must be a string between 3 and 20 characters","tokenName");this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(!t)throw qt(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const a=t.split("|");if(2!==a.length||"service"!==a[0])throw qt(`Invalid vault address format: ${t}. Expected service|Token$Unit$...`,"vaultAddress");const n=a[1].split("$");if(n.length<4)throw qt(`Invalid token parts in vault address: ${t}. Expected at least 4 parts separated by $`,"vaultAddress");const o=n[0],r=n[1],i=n[2],s=n.slice(3,-1),c=`${o}|${r}|${i}|${s.join("$")}`;return this.logger.debug(`Extracted token class key: ${c}`),c}catch(t){if(t instanceof Error&&t.message.includes("ConfigurationError"))throw t;throw Kt(`Failed to resolve token name '${e}': ${Ea(t)}`,500)}}async fetchPriceHistory(e){if(this.logger.debug("Fetching price history from DEX Backend API with options:",e),!this.httpClient)throw qt("HttpClient is required for fetchPriceHistory","httpClient");this.validateOptions(e);try{let t=e.tokenId;if(e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const a=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=a,this.logger.debug(`Resolved to token ID: ${a}`)}if(!t)throw qt("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:a}=await Promise.resolve().then(function(){return qa}),n=a(t),o=Ha(`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`),{from:r,to:i,sortOrder:s="DESC",page:c=1,limit:l=10}=e,u={token:o,page:String(c),limit:String(l)};r&&(u.from=r.toISOString()),i&&(u.to=i.toISOString());const d=function(e){if(e)return e.toLowerCase()}(s);d&&(u.order=d),this.logger.debug(`Querying price snapshots for token ${o}, page ${c}, limit ${l}`);const h=await this.httpClient.get("/price-oracle/fetch-price",u),g=this.transformApiResponseToPriceHistory(h);return this.logger.debug(`Found ${g.snapshots.length} price snapshots, total ${g.total}`),g}catch(e){if(e instanceof Error&&(e.message.includes("ConfigurationError")||e.message.includes("NetworkError")))throw e;throw Kt(`Failed to fetch price history: ${Ea(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw Kt("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw Kt("Invalid API response: missing data.meta pagination info",500);const t=e.data.data.map(e=>({price:e.price,timestamp:new Date(e.createdAt),tokenId:`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`})),a=e.data.meta,n=a.currentPage??1,o=a.totalPages??1;return{snapshots:t,page:n,limit:a.pageSize??50,total:a.totalItems??0,totalPages:o,hasNext:n<o,hasPrevious:n>1}}async fetchAllPriceHistory(e){this.logger.debug("Fetching all price history with options:",e);const t=[];let a=1,n=!0;const o=1e4;for(;n&&a<=o;){const o=await this.fetchPriceHistory({...e,page:a,limit:50});if(this.logger.debug(`Fetched page ${a}: ${o.snapshots.length} snapshots, hasNext: ${o.hasNext}`),t.push(...o.snapshots),0===o.snapshots.length){this.logger.debug("No snapshots returned on page ${page}, exiting pagination loop");break}n=o.hasNext,a++}return a>o&&this.logger.warn("Auto-pagination exceeded MAX_PAGES limit of 10000, stopping iteration"),{snapshots:t,page:1,limit:t.length||0,total:t.length,totalPages:1,hasNext:!1,hasPrevious:!1}}validateOptions(e){const{tokenName:t,tokenId:a}=e,n=null!=t&&""!==t,o=null!=a;if(!n&&!o)throw qt("Either tokenName or tokenId must be provided","tokenId");if(n&&o)throw qt("Cannot provide both tokenName and tokenId. Provide exactly one.","tokenId");const{from:r,to:i,sortOrder:s,page:c=1,limit:l=10}=e;if(r&&!(r instanceof Date)&&isNaN(new Date(r).getTime()))throw qt("from must be a valid Date","from");if(i&&!(i instanceof Date)&&isNaN(new Date(i).getTime()))throw qt("to must be a valid Date","to");if(s&&"ASC"!==s&&"DESC"!==s)throw qt('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(c)||c<1)throw qt("page must be a positive integer","page");if(!Number.isInteger(l)||l<1||l>50)throw qt("limit must be between 1 and 50","limit")}}class yn{toLaunchpadFormat(e){if(!e)return"unknown|Unit|none|none";if("string"==typeof e)return e.includes("|")?e:`${e}|Unit|none|none`;return`${e.type||e.symbol||"unknown"}|${e.category||"Unit"}|none|${e.additionalKey||"none"}`}toTokenClass(e){if("object"==typeof e&&null!==e)return{collection:e.collection||"Token",category:e.category||"Unit",type:e.type||e.symbol||"unknown",additionalKey:e.additionalKey||"none"};if("string"!=typeof e)throw new Error("Invalid token format: expected string or object, got "+typeof e);const t=e.split("|");if(t.length<3)throw new Error(`Invalid token format: ${e}`);const a=("Token"===t[0]||"Collection"===t[0])&&t[2]?t[2]:t[0];return{collection:t[0]||"Token",category:t[1]||"Unit",type:a,additionalKey:t[3]||"none"}}isGSwapFormat(e){return"string"==typeof e&&e.includes("|")}normalize(e){return"string"==typeof e&&this.isGSwapFormat(e)?e:this.toLaunchpadFormat(e)}}class wn{constructor(e,t){if(this.tokenConverter=new yn,this.logger=new p({debug:!1,context:"GSwapService"}),this.webSocketService=t,!e.gatewayBaseUrl||!e.bundlerBaseUrl||!e.dexBackendBaseUrl)throw new Error("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, and dexBackendBaseUrl configuration. These must be provided by LaunchpadSDK to ensure environment alignment.");if(e.privateKey&&e.walletAddress)try{const t=new l.PrivateKeySigner(e.privateKey);this.gswap=new l.GSwap({signer:t,walletAddress:e.walletAddress,gatewayBaseUrl:e.gatewayBaseUrl,bundlerBaseUrl:e.bundlerBaseUrl,dexBackendBaseUrl:e.dexBackendBaseUrl}),this.logger.debug("GSwap initialized in full-access mode")}catch(e){throw this.logger.error("Failed to initialize GSwap with signer",e),new Error("Failed to initialize GSwap SDK with signer")}else this.gswap=new l.GSwap({gatewayBaseUrl:e.gatewayBaseUrl,bundlerBaseUrl:e.bundlerBaseUrl,dexBackendBaseUrl:e.dexBackendBaseUrl}),this.logger.debug("GSwap initialized in read-only mode")}async getSwapQuoteExactInput(e){try{this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),a=this.tokenConverter.toLaunchpadFormat(e.toToken),n=await this.gswap.quoting.quoteExactInput(t,a,e.amount);return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:n.outTokenAmount.toFixed(),feeTier:n.feeTier,priceImpact:n.priceImpact.toString(),executionPrice:this.calculateExecutionPrice(e.amount,n.outTokenAmount)}}catch(e){this.logger.error("Failed to get swap quote",e);const t=e;throw new S(`Failed to get swap quote for exact input: ${t?.message||String(e)}`,e,this.extractGSwapErrorCode(e))}}async getSwapQuoteExactOutput(e){try{this.logger.debug("Getting swap quote for exact output",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),a=this.tokenConverter.toLaunchpadFormat(e.toToken),n=await this.gswap.quoting.quoteExactOutput(t,a,e.amount);return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:n.inTokenAmount.toFixed(),estimatedOutput:e.amount,feeTier:n.feeTier,priceImpact:n.priceImpact.toString(),executionPrice:this.calculateExecutionPrice(n.inTokenAmount,e.amount)}}catch(e){this.logger.error("Failed to get swap quote for exact output",e);const t=e;throw new S(`Failed to get swap quote for exact output: ${t?.message||String(e)}`,e,this.extractGSwapErrorCode(e))}}async executeSwap(e){try{if(!this.gswap)throw new Error("GSwap SDK not initialized");this.logger.debug("Executing swap",{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),a=this.tokenConverter.toLaunchpadFormat(e.toToken),n=new r(e.estimatedOutput),o=new r(1).minus(e.slippageTolerance||.01),i=n.multipliedBy(o),s=(await this.gswap.swaps.swap(t,a,e.feeTier,{exactIn:e.inputAmount,amountOutMinimum:i.toFixed()})).transactionId;if(!s)throw new Error("Failed to get transaction ID from swap result");this.logger.debug("Swap submitted, monitoring transaction",{transactionId:s,fromToken:e.fromToken,toToken:e.toToken}),this.webSocketService.isConnected()||await this.webSocketService.connect();const c=await this.webSocketService.waitForTransaction(s);return{transactionId:c.transactionId,status:c.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(c.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(s)}}}catch(e){this.logger.error("Failed to execute swap",e);const t=e;throw new E(`Failed to execute swap: ${t?.message||String(e)}`,e,t?.txHash,this.extractGSwapErrorCode(e))}}async getUserAssets(e){try{this.logger.debug("Fetching user assets",{walletAddress:e});const t=await this.gswap.assets.getUserAssets(e);return(Array.isArray(t)?t:[t]).map(t=>{const a=t.tokenInstance,n=t.tokenClassKey,o=t.type,i=a||n||o||"";if(!i||""===i.trim()){const r=[];throw a||r.push("tokenInstance"),n||r.push("tokenClassKey"),o||r.push("type"),new N(`Asset "${t.symbol||"UNKNOWN"}" (balance: ${t.balance}) missing required token identifier. Missing fields: ${r.join(", ")}. This indicates a data quality issue in the upstream GSwap API response.`,new Error("Missing token identifier"),e,"INVALID_ASSET_FORMAT")}try{this.tokenConverter.toTokenClass(i)}catch(a){throw new N(`Cannot convert token identifier for asset "${t.symbol||"UNKNOWN"}". Invalid token format: "${i}". Error: ${a instanceof Error?a.message:String(a)}. This indicates malformed data in the upstream GSwap API response.`,a,e,"INVALID_TOKEN_FORMAT")}return{tokenId:this.tokenConverter.toTokenClass(i),symbol:t.symbol||t.type||"UNKNOWN",balance:new r(t.balance||0).toFixed(),decimals:t.decimals||18}})}catch(t){this.logger.error("Failed to fetch user assets",t);const a=t;throw new N(`Failed to fetch user assets: ${a?.message||String(t)}`,t,e,this.extractGSwapErrorCode(t))}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const a=this.tokenConverter.toLaunchpadFormat(e),n=this.tokenConverter.toLaunchpadFormat(t),o=[500,3e3,1e4];let i=new r(0),s=0;for(const c of o)try{const e=await this.gswap.pools.getPoolData(a,n,c);e&&(i=i.plus(new r(e.liquidity||0)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:c})}return{tokenA:e,tokenB:t,liquidity:i.toFixed(),feeTiers:o,swapCount:s}}catch(a){this.logger.warn("Failed to fetch pool info",a);const n=a;return this.logger.debug("Pool error details",{error:new b(`Failed to fetch pool info: ${n?.message||String(a)}`,a,e,t,this.extractGSwapErrorCode(a))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}async getUserLiquidityPositions(e,t=100,a){try{this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:t});const n=await this.gswap.positions.getUserPositions(e,t,a);let o;Array.isArray(n)?o=n:n?.positions&&Array.isArray(n.positions)?o=n.positions:n?o=[n]:(o=[],this.logger.warn("No positions returned from API for wallet",{ownerAddress:e}));const r=o.filter(e=>null!=e&&"object"==typeof e&&"positionId"in e);return r.length!==o.length&&this.logger.warn("Filtered out invalid position objects",{total:o.length,valid:r.length}),this.logger.debug("Retrieved liquidity positions",{count:r.length}),r}catch(e){throw this.logger.error("Failed to fetch user liquidity positions",e),new I(`Failed to fetch user liquidity positions: ${e?.message||String(e)}`,e)}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t});const a=this.tokenConverter.toLaunchpadFormat(t.token0),n=this.tokenConverter.toLaunchpadFormat(t.token1),o=await this.gswap.positions.getPosition(e,{token0:a,token1:n,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper});if(!o||"object"!=typeof o||!("positionId"in o))throw new Error("Invalid position data returned from API");return this.logger.debug("Retrieved liquidity position",{positionId:o.positionId}),o}catch(e){throw this.logger.error("Failed to fetch liquidity position",e),new I(`Failed to fetch liquidity position: ${e?.message||String(e)}`,e)}}async getLiquidityPositionById(e,t){try{this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t});const a=await this.gswap.positions.getPositionById(e,t);if(!a||"object"!=typeof a||!("positionId"in a))throw new Error("Invalid position data returned from API");return this.logger.debug("Retrieved liquidity position by ID",{positionId:a.positionId}),a}catch(e){throw this.logger.error("Failed to fetch liquidity position by ID",e),new I(`Failed to fetch liquidity position: ${e?.message||String(e)}`,e)}}async estimateRemoveLiquidity(e){try{this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1});const t=this.tokenConverter.toLaunchpadFormat(e.token0),a=this.tokenConverter.toLaunchpadFormat(e.token1),n=await this.gswap.positions.estimateRemoveLiquidity({token0:t,token1:a,fee:e.fee,liquidity:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper});return this.logger.debug("Estimated removal",{result:n}),n}catch(e){throw this.logger.error("Failed to estimate liquidity removal",e),new I(`Failed to estimate liquidity removal: ${e?.message||String(e)}`,e)}}async addLiquidityByPrice(e){try{if(!this.gswap)throw new Error("GSwap SDK not initialized");this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const t=this.tokenConverter.toLaunchpadFormat(e.token0),a=this.tokenConverter.toLaunchpadFormat(e.token1),n=await this.gswap.positions.addLiquidityByPrice({token0:t,token1:a,fee:e.fee,minPrice:e.minPrice,maxPrice:e.maxPrice,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0"}),o=n.transactionId;return this.logger.debug("Liquidity added",{transactionId:o}),o&&!this.webSocketService.isConnected()&&await this.webSocketService.connect(),n}catch(e){throw this.logger.error("Failed to add liquidity by price",e),new I(`Failed to add liquidity: ${e?.message||String(e)}`,e)}}async addLiquidityByTicks(e){try{if(!this.gswap)throw new Error("GSwap SDK not initialized");this.logger.debug("Adding liquidity by ticks",{token0:e.token0,token1:e.token1,tickRange:`${e.tickLower}-${e.tickUpper}`});const t=this.tokenConverter.toLaunchpadFormat(e.token0),a=this.tokenConverter.toLaunchpadFormat(e.token1),n=await this.gswap.positions.addLiquidityByTicks({token0:t,token1:a,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0"}),o=n.transactionId;return this.logger.debug("Liquidity added",{transactionId:o}),o&&!this.webSocketService.isConnected()&&await this.webSocketService.connect(),n}catch(e){throw this.logger.error("Failed to add liquidity by ticks",e),new I(`Failed to add liquidity: ${e?.message||String(e)}`,e)}}async removeLiquidity(e){try{if(!this.gswap)throw new Error("GSwap SDK not initialized");this.logger.debug("Removing liquidity",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});const t=this.tokenConverter.toLaunchpadFormat(e.token0),a=this.tokenConverter.toLaunchpadFormat(e.token1),n=await this.gswap.positions.removeLiquidity({token0:t,token1:a,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,liquidity:e.liquidity,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0"}),o=n.transactionId;return this.logger.debug("Liquidity removed",{transactionId:o}),o&&!this.webSocketService.isConnected()&&await this.webSocketService.connect(),n}catch(e){throw this.logger.error("Failed to remove liquidity",e),new I(`Failed to remove liquidity: ${e?.message||String(e)}`,e)}}async collectPositionFees(e){try{if(!this.gswap)throw new Error("GSwap SDK not initialized");this.logger.debug("Collecting position fees",{token0:e.token0,token1:e.token1});const t=this.tokenConverter.toLaunchpadFormat(e.token0),a=this.tokenConverter.toLaunchpadFormat(e.token1),n=await this.gswap.positions.collectPositionFees({token0:t,token1:a,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper}),o=n.transactionId;return this.logger.debug("Fees collected",{transactionId:o}),o&&!this.webSocketService.isConnected()&&await this.webSocketService.connect(),n}catch(e){throw this.logger.error("Failed to collect position fees",e),new I(`Failed to collect fees: ${e?.message||String(e)}`,e)}}async getPoolData(e,t,a){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:a});const n=this.tokenConverter.toLaunchpadFormat(e),o=this.tokenConverter.toLaunchpadFormat(t),i=await this.gswap.pools.getPoolData(n,o,a),s=this.calculatePriceFromSqrtPriceX96(new r(i.sqrtPriceX96));return{tokenA:e,tokenB:t,feeTier:a,liquidity:i.liquidity.toString(),sqrtPriceX96:i.sqrtPriceX96.toString(),tick:i.tick,feeGrowthGlobal0X128:i.feeGrowthGlobal0X128.toString(),feeGrowthGlobal1X128:i.feeGrowthGlobal1X128.toString(),currentPrice:s.toFixed()}}catch(e){throw this.logger.error("Failed to get pool data",e),new b(`Failed to get pool data: ${e?.message||String(e)}`,e)}}async calculateDexPoolSpotPrice(e,t,a){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:a});const n=await this.getPoolData(e,t,a),o=new r(n.currentPrice);return{tokenA:e,tokenB:t,feeTier:a,price:o.toFixed(),invertedPrice:new r(1).dividedBy(o).toFixed(),tick:n.tick,liquidity:n.liquidity}}catch(e){throw this.logger.error("Failed to calculate spot price",e),new b(`Failed to calculate spot price: ${e?.message||String(e)}`,e)}}async calculateOptimalPositionSize(e,t,a,n,o,i,s){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:n,desiredAmount1:o});const c=(await this.getPoolData(e,t,a)).tick,l=this.calculateLiquidityFromAmount0(new r(n),i,Math.min(s,c)),u=this.calculateLiquidityFromAmount1(new r(o),Math.max(i,c),s),d=r.min(l,u),h=this.calculateAmount0FromLiquidity(d,i,c),g=this.calculateAmount1FromLiquidity(d,c,s),p=new r(n),m=new r(o);return{amount0:h.toFixed(),amount1:g.toFixed(),liquidity:d.toFixed(),ratio:h.dividedBy(g).toFixed(),utilizationPercent:{amount0:h.dividedBy(p).multipliedBy(100).toFixed(2),amount1:g.dividedBy(m).multipliedBy(100).toFixed(2)}}}catch(e){throw this.logger.error("Failed to calculate optimal position size",e),new I(`Failed to calculate optimal position: ${e?.message||String(e)}`,e)}}async validatePositionParameters(e,t,a,n,o,i,s){const c=[],l=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:n,tickUpper:o});const u=[500,3e3,1e4];u.includes(a)||c.push(`Invalid fee tier: ${a}. Must be one of: ${u.join(", ")}`);const d=this.getTickSpacing(a);let h;n%d!==0&&c.push(`tickLower must be multiple of ${d}`),o%d!==0&&c.push(`tickUpper must be multiple of ${d}`),n>=o&&c.push(`tickLower (${n}) must be less than tickUpper (${o})`);try{h=await this.getPoolData(e,t,a)}catch{return c.push(`Pool not found for ${e}/${t} at fee tier ${a}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}const g=new r(i),p=new r(s);(g.isNaN()||g.isNegative())&&c.push("amount0 must be a valid positive number"),(p.isNaN()||p.isNegative())&&c.push("amount1 must be a valid positive number");const m=h.tick;(m<n||m>o)&&l.push("Position is out of current price range - will not earn fees until price moves into range");new r(h.liquidity).lt("1000000")&&l.push("Low pool liquidity - consider higher slippage tolerance");const f=0===c.length?35e4:0;return{valid:0===c.length,errors:c,warnings:l,gasEstimate:f,tickSpacing:d,currentTick:m,poolLiquidity:h.liquidity}}catch(e){return c.includes(e.message)||c.push(`Validation failed: ${e?.message||String(e)}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}}async calculateTicksForPrice(e,t,a,n,o){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:a,maxPrice:n});const i=this.getTickSpacing(o),s=new r(a),c=new r(n);if(s.gte(c))throw new Error("minPrice must be less than maxPrice");const l=Math.floor(Math.log(s.toNumber())/Math.log(1.0001)),u=Math.ceil(Math.log(c.toNumber())/Math.log(1.0001)),d=Math.floor(l/i)*i,h=Math.ceil(u/i)*i,g=Math.pow(1.0001,d),p=Math.pow(1.0001,h),m=new r(g),f=new r(p);return{tokenA:e,tokenB:t,feeTier:o,tickLower:d,tickUpper:h,tickSpacing:i,requestedMinPrice:a,requestedMaxPrice:n,actualMinPrice:m.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:m.minus(s).dividedBy(s).multipliedBy(100).toFixed(4),maxPriceDeviation:f.minus(c).dividedBy(c).multipliedBy(100).toFixed(4)}}}catch(e){throw this.logger.error("Failed to calculate ticks for price",e),new I(`Failed to calculate ticks: ${e?.message||String(e)}`,e)}}async calculatePriceForTicks(e,t,a,n){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:a,tickUpper:n});const o=Math.pow(1.0001,a),i=Math.pow(1.0001,n);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const c=new r(o),l=new r(i);return{tokenA:e,tokenB:t,tickLower:a,tickUpper:n,minPrice:c.toFixed(8),maxPrice:l.toFixed(8),currentPrice:s,priceRange:`${c.toFixed(4)} - ${l.toFixed(4)}`,tickSpread:n-a}}catch(e){throw this.logger.error("Failed to calculate price for ticks",e),new I(`Failed to calculate prices: ${e?.message||String(e)}`,e)}}calculateExecutionPrice(e,t){try{const a=new r(e),n=new r(t);return a.isZero()?"0":n.dividedBy(a).toFixed()}catch{return"0"}}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw new Error(`Invalid fee tier: ${e}`)}}calculatePriceFromSqrtPriceX96(e){try{const t=new r(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new r(0)}}calculateLiquidityFromAmount0(e,t,a){try{const n=new r(Math.pow(1.0001,t/2)),o=new r(Math.pow(1.0001,a/2));return e.multipliedBy(n).multipliedBy(o).dividedBy(o.minus(n))}catch{return new r(0)}}calculateLiquidityFromAmount1(e,t,a){try{const n=new r(Math.pow(1.0001,t/2)),o=new r(Math.pow(1.0001,a/2));return e.dividedBy(o.minus(n))}catch{return new r(0)}}calculateAmount0FromLiquidity(e,t,a){try{const n=new r(Math.pow(1.0001,t/2)),o=new r(Math.pow(1.0001,a/2));return e.multipliedBy(o.minus(n)).dividedBy(n.multipliedBy(o))}catch{return new r(0)}}calculateAmount1FromLiquidity(e,t,a){try{const n=new r(Math.pow(1.0001,t/2)),o=new r(Math.pow(1.0001,a/2));return e.multipliedBy(o.minus(n))}catch{return new r(0)}}extractGSwapErrorCode(e){if(e&&"object"==typeof e){const t=e;if(t.constructor&&"GSwapSDKError"===t.constructor.name)return t.code;if("code"in t&&"string"==typeof t.code)return t.code}}}class kn{}kn.BASE_PRICE=1650667151e-14,kn.PRICE_SCALING_FACTOR=1166069e-12,kn.TRADING_FEE_FACTOR=.001,kn.GAS_FEE="1",kn.MIN_UNBONDING_FEE_FACTOR=0,kn.MAX_UNBONDING_FEE_FACTOR=.5,kn.NET_UNBONDING_FEE_FACTOR=.5,kn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class vn{constructor(e=!1){this.cache=new Map,this.logger=new p({debug:e,context:"TokenMetadataCache"})}getLRUKey(){const e=this.cache.keys().next().value;return void 0!==e?e:null}normalizeTokenName(e){return e.trim().toLowerCase().replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}updateCacheEntry(e,t){const a=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=vn.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...a||{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const a=this.normalizeTokenName(e);this.updateCacheEntry(a,t)}set(e,t){const a=this.normalizeTokenName(e);this.updateCacheEntry(a,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),a=this.cache.get(t);return a?.maxSupply||kn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeTokenName(e);return this.cache.has(t)}clear(e){if(e){const t=this.normalizeTokenName(e);this.cache.delete(t)}else this.cache.clear()}dump(){const e={};return this.cache.forEach((t,a)=>{e[a]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((a,n)=>{a.lastUpdated<e&&(e=a.lastUpdated);let o=0;o+=2*n.length,void 0!==a.reverseBondingCurveMinFeeFactor&&(o+=8),void 0!==a.reverseBondingCurveMaxFeeFactor&&(o+=8),void 0!==a.reverseBondingCurveNetFeeFactor&&(o+=8),o+=8,a.vaultAddress&&(o+=2*a.vaultAddress.length),a.maxSupply&&(o+=2*a.maxSupply.length),a.symbol&&(o+=2*a.symbol.length),o+=32,t+=o}),{totalTokens:this.cache.size,cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.get(t)||null}setByTokenId(e,t){const a=`token:${e.toLowerCase().trim()}`;this.updateCacheEntry(a,t)}hasByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.has(t)}}vn.MAX_CACHE_SIZE=1e4;class An extends la{constructor(e,t,a=!1){super(e,a),this.dexBackendBaseUrl=t}async fetchDexPools(e={}){const{search:t,sortBy:a="tvl",sortOrder:n="desc",page:o=ca.DEFAULT_PAGE,limit:r=ca.DEFAULT_LIMIT}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:a,sortOrder:n,page:o,limit:r});const i=new URLSearchParams({page:o.toString(),limit:Math.min(r,20).toString(),sortBy:a,sortOrder:n});t&&i.append("search",t);const s=`${this.dexBackendBaseUrl}/explore/pools?${i}`;try{const e=await this.http.get(s),t=e.data.pools,a=e.data.count,n=Math.min(r,20),i=Math.ceil(a/n);return this.logger.debug("DEX pools fetched successfully",{poolCount:t.length,total:a,totalPages:i}),{pools:t,page:o,limit:n,total:a,totalPages:i,hasNext:o<i,hasPrevious:o>1}}catch(e){throw this.logger.error("Failed to fetch DEX pools",{error:e,url:s}),e}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=[];let a=1,n=!0,o=0;for(;n;){const r=await this.fetchDexPools({...e,page:a,limit:20});t.push(...r.pools),o=r.total,n=r.hasNext,a++,this.logger.debug("Auto-pagination progress",{currentPage:a-1,poolsFetched:t.length,totalPools:o})}return this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.length}),{pools:t,page:1,limit:t.length,total:o,totalPages:1,hasNext:!1,hasPrevious:!1}}}function Tn(e){const t=function(e){const t=ht(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 Sn="/api/asset/launchpad-contract/CallNativeTokenIn",En="/api/asset/launchpad-contract/CallNativeTokenOut",bn="/api/asset/launchpad-contract/CallMemeTokenIn",Nn="/api/asset/launchpad-contract/CallMemeTokenOut";class In extends n.ChainCallDTO{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,this.websiteUrl=e.websiteUrl,this.telegramUrl=e.telegramUrl,this.twitterUrl=e.twitterUrl,this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function Fn(e){if(!e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.Status&&void 0!==t.Data&&"object"==typeof t.Data&&null!==t.Data&&"string"==typeof t.Data.calculatedQuantity&&void 0!==t.Data.extraFees&&"object"==typeof t.Data.extraFees&&null!==t.Data.extraFees&&"string"==typeof t.Data.extraFees.reverseBondingCurve&&"string"==typeof t.Data.extraFees.transactionFees}const Cn={NATIVE:"native",EXACT:"exact"},Dn={LOCAL:"local",EXTERNAL:"external"};class Pn{static calculateBuyWithExact(e,t){const a=parseFloat(e),n=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:s,GAS_FEE:c}=kn,l=this.roundUp(o*(Math.exp((n+a)*i)-Math.exp(n*i))/i,8),u=new r(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateBuyWithNative(e,t){const a=parseFloat(e),n=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:s,GAS_FEE:c}=kn,l=Math.log(a*i/o+Math.exp(n*i))/i-n,u=new r(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateSellWithExact(e,t,a,n,o){const i=parseFloat(e),s=parseFloat(t),c=parseFloat(a),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=kn,g=l*(Math.exp(s*u)-Math.exp((s-i)*u))/u,p=new r(g),m=n+s/c*(o-n),f=p.multipliedBy(m).toFixed(8,r.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,a,n,o){const i=parseFloat(e),s=parseFloat(t),c=parseFloat(a),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=kn,g=s-Math.log(Math.exp(s*u)-i*u/l)/u,p=new r(i),m=n+s/c*(o-n),f=p.multipliedBy(m).toFixed(8,r.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static roundUp(e,t){const a=Math.pow(10,t);return Math.ceil(e*a)/a}}class xn{constructor(e,t,a,n,o,r,i="local"){this.http=e,this.tokenResolver=t,this.logger=a,this.bundleHttp=n,this.galaChainHttp=o,this.dexApiHttp=r,this.defaultCalculateAmountMode=i,this.metadataCache=new vn}addIfDefined(e,t,a){return void 0!==a&&(e[t]=a),e}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Pt(t);const n=`${t}.png`;xa(a.file,n,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&a.file instanceof File)e.append("image",a.file);else{if(!Buffer.isBuffer(a.file))throw Gt("file","a File object (browser) or Buffer (Node.js)");{const n=`${a.tokenName||t}.png`,o=new Blob([a.file],{type:"image/png"});e.append("image",o,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 Kt(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 qt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){xt(e),e.tokenName&&Pt(e.tokenName);const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const a=m(t),n=await this.http.get("/launchpad/fetch-pool",a);if(!0===n.error||200!==n.status||!n.data)throw Kt(n.message||"Failed to fetch pools",n.status);let o=[];const r=(await import("bignumber.js")).default;if(n.data.tokens)if(Array.isArray(n.data.tokens))o=n.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",a=e.reverseBondingCurveMaxFeePortion??"0",n=!new r(t).isZero()||!new r(a).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:a,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}});else{const e=n.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",a=e.reverseBondingCurveMaxFeePortion??"0",i=!new r(t).isZero()||!new r(a).isZero();o=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:a,hasReverseBondingCurveFee:i,createdAt:e.created_at||e.createdAt||""}]}else n.data.pools&&Array.isArray(n.data.pools)&&(o=n.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",a=e.reverseBondingCurveMaxFeePortion??"0",n=!new r(t).isZero()||!new r(a).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:a,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:i,isValidPoolForCaching:s}=await Promise.resolve().then(function(){return qn});o.forEach(e=>{if(!s(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=i(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=n.data.count??n.data.total??0,l=n.data.page??e.page??1,u=n.data.limit??e.limit??10,d=u>0?Math.ceil(c/u):1;return{pools:o,page:l,limit:u,total:c,totalPages:d,hasNext:l<d,hasPrevious:l>1}}async _getAmount(e){if(Lt(e),!this.galaChainHttp)throw qt("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:Sn,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:En,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:bn,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:Nn,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};throw Gt("type-method","one of: NATIVE-IN, NATIVE-OUT, MEME-IN, MEME-OUT")})(e.type,e.method,e.vaultAddress,e.amount);try{const e=await this.galaChainHttp.post(t,a);if(!Fn(e))throw Kt("Malformed response data from GalaChain gateway");if(1!==e.Status)throw Kt(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:n,extraFees:o}=e.Data;return{amount:n,reverseBondingCurveFee:o.reverseBondingCurve,transactionFee:o.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){$t(e),e.tokenName&&Pt(e.tokenName);const t=m(e),a=await this.http.get("/launchpad/check-pool",t);if(!0===a.error||200!==a.status)throw Kt(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(!pa(e))throw new k("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:a,to:n,resolution:o}=e;if(Pt(t),!a||!n||!o)throw new k("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:a,to:n,resolution:o};_t(r);const i=m(r),s=await this.http.get("/launchpad/get-graph-data",i);if(!0===s.error||200!==s.status||!s.data)throw Kt(s.message||"Failed to fetch graph data",s.status);return{dataPoints:s.data}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const 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 k("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:a,type:n,currentSupply:o}=e,r=e.mode??this.defaultCalculateAmountMode;if("local"!==r&&"external"!==r)throw new k(`Invalid calculation mode "${r}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new k("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!a||"string"!=typeof a)throw new k("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Cn.NATIVE&&n!==Cn.EXACT)throw new k('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===r?this.calculateBuyAmountExternal({tokenName:t,amount:a,type:n}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:a,type:n},"currentSupply",o))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:a,type:n}=e,o=await this.tokenResolver.resolveTokenToVault(t);if(!o)throw new k(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Cn.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:o,amount:a}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:o,amount:a})}async calculateSellAmount(e){const{tokenName:t,amount:a,type:n,currentSupply:o,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:s}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new k(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new k("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!a||"string"!=typeof a)throw new k("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Cn.EXACT&&n!==Cn.NATIVE)throw new k('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:a,type:n});{const e={tokenName:t,amount:a,type:n,...void 0!==o&&{currentSupply:o},...void 0!==r&&{maxSupply:r},...void 0!==i&&{reverseBondingCurveMaxFeeFactor:i},...void 0!==s&&{reverseBondingCurveMinFeeFactor:s}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:a,type:n}=e,o=await this.tokenResolver.resolveTokenToVault(t);if(!o)throw new k(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Cn.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:o,amount:a}):this._getAmount({type:"MEME",method:"IN",vaultAddress:o,amount:a})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:a,type:n,currentSupply:o}=e;if(!a||"string"!=typeof a)throw new k("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Cn.NATIVE&&n!==Cn.EXACT)throw new k('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==o&&Bt(o,"currentSupply");const r=!o;if(r&&!t)throw new k("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&Pt(t);let i=o;if(r){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return n===Cn.EXACT?Pn.calculateBuyWithExact(a,i):Pn.calculateBuyWithNative(a,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:a,type:n,currentSupply:o,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:s}=e;if(!a||"string"!=typeof a)throw new k("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Cn.EXACT&&n!==Cn.NATIVE)throw new k('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==o&&Bt(o,"currentSupply");const c=!o||!r||void 0===i||void 0===s;if(c&&!t)throw new k("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&Pt(t);let l=o,u=r,d=i,h=s;if(c&&t){const e=this.metadataCache.get(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,l||(l=await this.fetchCurrentSupply(t));if(void 0===d||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);d=d??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return n===Cn.EXACT?Pn.calculateSellWithExact(a,l,u,h,d):Pn.calculateSellWithNative(a,l,u,h,d)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ua(t,"tokenName")&&ga(t)&&da(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:a,calculateAmountMode:n,currentSupply:o}=t;Pt(a);const r=await this.tokenResolver.resolveTokenToVault(a);if(!r)throw new k(w(a),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw qt("GalaChain HTTP client not configured");const i=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:r});if(1!==i.Status)throw Kt(`Failed to fetch pool details: Status ${i.Status}`,i.Status);const s=i.Data,c=(await import("bignumber.js")).default,l=o??new c(s.maxSupply).minus(s.sellingTokenQuantity).toFixed(),u=s.sellingTokenQuantity;if("0"===u)throw new k(`Token ${a} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const d={tokenName:a,amount:u,type:"exact",currentSupply:l,...void 0!==n&&{mode:n}};return await this.calculateBuyAmount(d)}async launchToken(e){if(!this.bundleHttp)throw qt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Tn(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new k("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),o=Number(a);if(isNaN(n)||isNaN(o)||n<=0||o<=0||n>=o)throw new k("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 Kt("Image upload failed: No URL returned");a=t}else"string"==typeof e.tokenImage&&(a=e.tokenImage);const o=`galaswap - operation - ${s.v4()}-${Date.now()}-${this.http.getAddress()}`,r={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:o};e.reverseBondingCurveConfiguration&&(r.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const i=new In(r),c=await this.http.signWithGalaChain("CreateSale",i,n.SigningType.SIGN_TYPED_DATA),{signature:l,types:u,domain:d,prefix:h}=c,g={tokenName:i.tokenName,tokenSymbol:i.tokenSymbol,tokenDescription:i.tokenDescription,tokenImage:i.tokenImage,preBuyQuantity:i.preBuyQuantity,websiteUrl:i.websiteUrl,telegramUrl:i.telegramUrl,twitterUrl:i.twitterUrl,tokenCategory:i.tokenCategory,tokenCollection:i.tokenCollection,uniqueKey:i.uniqueKey,signature:l,types:u,domain:d,...h&&{prefix:h},...i.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:i.reverseBondingCurveConfiguration}},p=`${e.tokenName.trim()}$Unit$none$none`,m="GALA$Unit$none$none";let f;if(parseFloat(t)>0){const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`]}else{const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`]}const y={signedDto:g,stringsInstructions:f,method:"CreateSale"},w=await this.bundleHttp.post("/bundle",y);if(w.error||!w.data)throw Kt(w.message||"Token launch failed");return w.data}async fetchTokenDistribution(e){if(!e)throw Rt("tokenName","Token name");Pt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new k(w(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const a=encodeURIComponent(t),n=await this.http.get(`/holders/${a}`);if(!0===n.error||200!==n.status||!n.data)throw Kt(n.message||"Failed to fetch token distribution",n.status);const o=n.data;if(!Array.isArray(o))throw Kt("Invalid API response: expected array of holders",n.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw Kt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw Kt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw Kt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const i=o.reduce((e,t)=>e.plus(t.quantity),new r(0));return{holders:o.map(e=>{const t=new r(e.quantity),a=i.isZero()?0:t.dividedBy(i).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:a}}),totalSupply:i.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Rt("tokenName","Token name");Pt(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw Kt(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 o=("volume"===a?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return o?.isActive||!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.nativeTokenQuantity&&(void 0===t.vaultAddress||"string"==typeof t.vaultAddress)}(e))throw new k("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw qt("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(!Fn(a))throw Kt("Malformed response data from GalaChain gateway");if(1!==a.Status)throw Kt(`GalaChain calculation failed with status ${a.Status}`,a.Status);const{calculatedQuantity:n,extraFees:o}=a.Data;return{amount:n,reverseBondingCurveFee:o.reverseBondingCurve,transactionFee:o.transactionFees,gasFee:"1"}}catch(e){if(e instanceof Error){const t=new Error(`Pre-mint calculation failed: ${e.message}`);throw e.stack&&(t.stack=e.stack),t}throw new Error(`Pre-mint calculation failed: ${String(e)}`)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new k(w(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw qt("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==a.Status)throw Kt(`Failed to fetch pool details: Status ${a.Status}`,a.Status);const n=a.Data,o=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),r=n.sellingTokenQuantity,i=n.maxSupply;let s=.5,c=0;n.reverseBondingCurveConfiguration?(s=parseFloat(n.reverseBondingCurveConfiguration.maxFeePortion),c=parseFloat(n.reverseBondingCurveConfiguration.minFeePortion)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const l=s-c;return this.metadataCache.set(e,{maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}),{currentSupply:o,remainingTokens:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}}async fetchCurrentSupply(e){Pt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new k(w(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw qt("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==a.Status)throw Kt(`Failed to fetch pool details: Status ${a.Status}`,a.Status);const n=a.Data,o=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),r=n.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),o}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Ut(e)}validateTokenName(e){return Pt(e)}validatePagination(e){return xt(e)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw qt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw Rt("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 Kt(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ua(t,"tokenName")&&ga(t)&&da(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:a,calculateAmountMode:n,currentSupply:o}=t;if(!a||"string"!=typeof a)throw Rt("tokenName","Token name (string)");try{const e={tokenName:a,amount:"1",type:"native",...void 0!==n&&{mode:n},...void 0!==o&&{currentSupply:o}},t=await this.calculateBuyAmount(e),r=(await this.fetchTokenPrice("GALA"))[0];if(!r)throw Kt("GALA price not available");const i=Number(t.amount);if(i<=0)throw new k(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const s=r.price/i;return{symbol:a.toUpperCase(),price:s}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${a}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${a}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}const $n={PROD:{launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",galaChainBaseUrl:"https://gateway-mainnet.galachain.com",bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},STAGE:{launchpadBaseUrl:"https://lpad-backend-dev1.defi.gala.com",galaChainBaseUrl:"https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com",bundleBaseUrl:"https://bundle-backend-dev1.defi.gala.com",webSocketUrl:"https://bundle-backend-dev1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-dev1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function Ln(e){return $n[e]}class _n extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Un 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 Bn(e,t){if(!e)throw new _n(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new _n(`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 _n(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Mn(e,t,a,n){Bn(e,t);const o=e,r=o.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(r))throw new _n(`Invalid trade data received for transaction ${t}`);const i={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||"",timestamp:Date.now()};return void 0!==o.blockHash&&(i.blockHash=o.blockHash),void 0!==o.gasUsed&&(i.gasUsed=o.gasUsed),void 0!==n.slippageToleranceFactor&&(i.slippageTolerance=n.slippageToleranceFactor),i}const On="3.31.0";class Rn{constructor(e){this.wallet=e.wallet;let a=null;a=e.env?Ln(e.env):e.baseUrl?.includes("prod")?Ln("PROD"):Ln("STAGE"),this.config={baseUrl:a.launchpadBaseUrl,galaChainBaseUrl:a.galaChainBaseUrl,bundleBaseUrl:a.bundleBaseUrl,webSocketUrl:a.webSocketUrl,dexApiBaseUrl:a.dexApiBaseUrl,dexBackendBaseUrl:a.dexBackendBaseUrl,launchpadFrontendUrl:a.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new p({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Rn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Rn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||Rn.DEFAULT_CALCULATE_AMOUNT_MODE,this.auth=new g({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new f(this.auth,this.config),this.galaChainHttp=new f(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new f(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new f(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new f(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=t.create({baseURL:this.config.galaChainBaseUrl,timeout:this.config.timeout||3e4,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.cache=new vn(e.debug||!1),this.launchpadService=new _a(this.http),this.tokenResolverService=new mn(this.launchpadService.poolService),this.launchpadAPI=new xn(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new ja(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1,this.galaChainPublicAxios),this.dexService=new Xa(this.dexBackendHttp,this.cache,this.galaChainService,e.debug||!1),this.bundleService=new hn(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,e.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new pn({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new fn(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.gswapService=new wn({privateKey:e.wallet?.privateKey,walletAddress:e.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl},this.websocketService),this.dexPoolService=new An(this.dexBackendHttp,this.config.dexBackendBaseUrl,e.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw qt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw qt('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 Rn(n)}getAddress(){return this.validateWallet(),this.auth.getAddress()}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw new k("Wallet is required for this operation",void 0,"WALLET_REQUIRED");return this.wallet}setWallet(e){if(!e||"object"!=typeof e||!("address"in e))throw new k("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}getWallet(){return this.wallet}hasWallet(){return void 0!==this.wallet}getConfig(){const{wallet:e,...t}=this.config;return{...t,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode}}getVersion(){return On}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw qt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e||{});return await this.warmCacheFromPools(t.pools),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.pools),t}async fetchDexPools(e={}){return this.dexPoolService.fetchDexPools(e)}async fetchAllDexPools(e={}){return this.dexPoolService.fetchAllDexPools(e)}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:a,currentSupply:n,calculateAmountMode:o}=e;if(t&&!a){const e={tokenName:t};return n&&(e.currentSupply=n),o&&(e.calculateAmountMode=o),this.fetchLaunchpadTokenSpotPrice(e)}if(a&&!t)try{return await this.dexService.fetchTokenPrice({tokenId:a})}catch(e){const t=function(e){if(ba(e)&&e.response)return e.response.status}(e);if(400===t||404===t){this.logger.debug(`DEX spot price not available (HTTP ${t}) for tokenId, attempting launchpad fallback`);try{const t=(await this.fetchTokenDetails(a)).name.trim().toLowerCase();if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`);const r={tokenName:t};return n&&(r.currentSupply=n),o&&(r.calculateAmountMode=o),this.fetchLaunchpadTokenSpotPrice(r)}catch(t){throw this.logger.error(`Launchpad fallback failed: ${Ea(t)}`),e}}throw e}if(!t&&!a)throw Rt("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");throw new k("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS")}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;return this.dexService.fetchLaunchpadTokenSpotPrice(t.tokenName,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(!t)throw new Error(w(e));const a=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return a.currentSupply=n.currentSupply,a.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,a.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,a.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,a.tokenName=e,a}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a=t(e)||this.getAddress();return this.galaChainService.fetchGalaBalance({owner:a,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return qa}),n=t(e.tokenId),{collection:o,category:r,type:i,additionalKey:s}=n;return this.galaChainService.fetchTokenBalance({owner:a,collection:o,category:r,additionalKey:s,type:i,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 Rt("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:o,calculateAmountMode:r,currentSupply:i}=e;let s=t;void 0===r&&void 0===i||(s={tokenName:t,...void 0!==r&&{calculateAmountMode:r},...void 0!==i&&{currentSupply:i}});const c=await this.calculateBuyAmountForGraduation(s),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==a&&(l.slippageToleranceFactor=a),void 0!==n&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=n),void 0!==o&&(l.privateKey=o),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:a,...n}=e;return t.buy(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,a=t?.transactionId;if(!a)throw zt("No transaction ID returned from buy operation");return this.waitForConfirmation(a,t=>Mn(t,a,"buy",e))}async sell(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:a,...n}=e;return t.sell(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,a=t?.transactionId;if(!a)throw zt("No transaction ID returned from sell operation");return this.waitForConfirmation(a,t=>Mn(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.validateWallet(),this.launchpadService.postComment(e)}async launchToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:a,...n}=e;return t.launchToken(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,a=>{Bn(a,t);const n=a?.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(n))throw new _n(`Invalid launch data received for transaction ${t}`);const o={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&&(o.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(o.preBuyQuantity=e.preBuyQuantity),o.vaultAddress&&this.tokenResolverService.set(e.tokenName,o.vaultAddress),o})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:a,...n}=e;return t.uploadTokenImage(n)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a=t(e)||this.getAddress();return this.launchpadService.fetchProfile(a)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={...e,address:t(e.address)};if(a.privateKey){const e=this.createOverrideSdk(a.privateKey),{privateKey:t,...n}=a;return e.updateProfile(n)}return this.validateWallet(),this.launchpadService.updateProfile(a)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={...e,address:t(e.address)||this.getAddress()};if(a.privateKey){const e=this.createOverrideSdk(a.privateKey),{privateKey:t,...n}=a;return e.uploadProfileImage(n)}return this.validateWallet(),this.launchpadService.uploadProfileImage(a)}async retrieveGalaFromFaucet(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={walletAddress:t(e)||this.getAddress(),amount:"5"};return this.launchpadService.transferFaucets(a)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a=t(e?.address)||this.getAddress(),n={page:e?.page||1,limit:e?.limit||10,address:a};return e?.tokenName&&(n.tokenName=e.tokenName),e?.search&&(n.search=e.search),this.launchpadService.fetchTokensHeld(n)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(a.tokenName=e.tokenName),e?.search&&(a.search=e.search),this.launchpadService.fetchTokenList(a)}async fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={...e,recipientAddress:t(e.recipientAddress)};if(a.privateKey){const e=this.createOverrideSdk(a.privateKey),{privateKey:t,...n}=a;return e.transferGala(n)}return this.validateWallet(),this.galaChainService.transferGala(a)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Mt}),a={...e,to:t(e.to)};if(a.privateKey){const e=this.createOverrideSdk(a.privateKey),{privateKey:t,...n}=a;return e.transferToken(n)}return this.validateWallet(),this.galaChainService.transferToken(a)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}getCacheInfo(){return this.launchpadAPI.getCacheStats()}clearCache(e){this.launchpadAPI.clearCache(e)}validateConfiguration(){if(("number"!=typeof this.config.timeout||this.config.timeout<=0||this.config.timeout>3e5)&&(this.logger.warn(`Invalid timeout value: ${this.config.timeout}. Using default 30000ms.`),this.config.timeout=3e4),!this.config.baseUrl)throw qt("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw qt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw qt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw qt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw qt(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw qt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw qt(`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: ${Rn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Rn.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: ${Rn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Rn.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 Un(e,a.status,a.message);let n;try{n=t(a)}catch(t){if(t instanceof _n)throw t;throw new _n(`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 Un||t instanceof _n)throw t;throw new _n(`WebSocket confirmation failed for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}}async warmCacheFromPools(e){if(!e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return qn});e.forEach(e=>{if(!a(e))return;const n=t(e,this.logger);n&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,n)})}async getSwapQuoteExactInput(e,t,a){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:a})}async getSwapQuoteExactOutput(e,t,a){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:a})}async executeSwap(e,t,a,n,o,r=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:a,estimatedOutput:n,feeTier:o,slippageTolerance:r})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapUserLiquidityPositions(e,t,a){return this.gswapService.getUserLiquidityPositions(e,t,a)}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t){return this.gswapService.getLiquidityPositionById(e,t)}async getSwapEstimateRemoveLiquidity(e){return this.gswapService.estimateRemoveLiquidity(e)}async addSwapLiquidityByPrice(e){return this.gswapService.addLiquidityByPrice(e)}async addSwapLiquidityByTicks(e){return this.gswapService.addLiquidityByTicks(e)}async removeSwapLiquidity(e){return this.gswapService.removeLiquidity(e)}async collectSwapPositionFees(e){return this.gswapService.collectPositionFees(e)}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const a=this.websocketService.getSocket();return a?(a.on(e,t),()=>{a.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onDexPoolCreation(e,t){const a=1e3,n=Math.max(t?.intervalMs??3e4,a);t?.intervalMs&&t.intervalMs<a&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const o=t?.minTVL,r=t?.tokens,i=new Map;let s=!0,c=null;let l=0;const u=async()=>{if(s){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.pools.forEach(t=>{const a=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!i.has(a)){if((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(a),o){if((t.token0Tvl+t.token1Tvl)/2<o)return}if(r&&r.length>0){if(!(r.includes(t.token0)||r.includes(t.token1)))return}e(t)}})}catch(e){l++;const t=e instanceof Error?e.message:String(e);l>=5?this.logger.error(`Polling for new DEX pools failed ${l} consecutive times. Last error: ${t}. Continuing to retry...`):l>1?this.logger.warn(`Error polling for new DEX pools (attempt ${l}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(s){const e=Math.min(Math.max(l-1,0),2),t=n*Math.pow(2,e);c=setTimeout(u,t)}}};return u(),()=>{s=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const a=1e3,n=Math.max(t?.intervalMs??3e4,a);t?.intervalMs&&t.intervalMs<a&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const o=t?.creatorAddress,r=new Map;let i=!0,s=null;let c=0;const l=async()=>{if(i){try{const t=await this.fetchPools({type:"recent",limit:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.pools.forEach(t=>{r.has(t.tokenName)||((e=>{if(r.set(e,!0),r.size>1e3){const e=r.keys().next().value;void 0!==e&&r.delete(e)}})(t.tokenName),o&&t.creatorAddress!==o||e(t))})}catch(e){c++;const t=e instanceof Error?e.message:String(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(i){const e=Math.min(Math.max(c-1,0),2),t=n*Math.pow(2,e);s=setTimeout(l,t)}}};return l(),()=>{i=!1,s&&clearTimeout(s),this.logger.debug("Stopped watching for launchpad token creation")}}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 p({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:a}=require("./services/WebSocketService");a.cleanupAll(e),t.debug("Global cleanup completed")}}Rn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Rn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Rn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=kn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Rn.DEFAULT_CALCULATE_AMOUNT_MODE=Dn.LOCAL;class Gn{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),o=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:o,mnemonic:"test test test test test test test test test test test junk",wallet:n}}throw e}}static fromPrivateKey(e){const t=new 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),o=a.HDNodeWallet.fromMnemonic(n,`m/44'/60'/0'/0/${t}`),r=new a.Wallet(o.privateKey),i=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${t}-${e}`,o="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),r=new a.Wallet(o),i=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}throw n}}static toGalaAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid Ethereum address format: ${e}`);return`eth|${t}`}static toEthereumAddress(e){if(!e.startsWith("eth|"))throw new Error(`Invalid Gala address format: ${e}. Must start with 'eth|'`);const t=e.slice(4);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid address in Gala format: ${e}`);return`0x${t}`}static isValidEthereumAddress(e){try{const t=e.replace(/^0x/i,"");return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){try{if(!e.startsWith("eth|"))return!1;const t=e.slice(4);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static generateMultipleWallets(e=1){if(e<1||e>100)throw new Error("Count must be between 1 and 100");const t=[];if("undefined"!=typeof process&&"test"===process.env.NODE_ENV)for(let 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 Kn(e){if(void 0===e)return Gn.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 Gn.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 Gn.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?"...":""}"`)}Gn.testCounter=0;var qn=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const a={};if(e.vaultAddress&&(a.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const n=parseFloat(e.reverseBondingCurveMinFeePortion);isNaN(n)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):a.reverseBondingCurveMinFeeFactor=n}if(void 0!==e.reverseBondingCurveMaxFeePortion){const n=parseFloat(e.reverseBondingCurveMaxFeePortion);isNaN(n)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):a.reverseBondingCurveMaxFeeFactor=n}return void 0!==a.reverseBondingCurveMaxFeeFactor&&void 0!==a.reverseBondingCurveMinFeeFactor&&(a.reverseBondingCurveNetFeeFactor=a.reverseBondingCurveMaxFeeFactor-a.reverseBondingCurveMinFeeFactor),Object.keys(a).length>0?a:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});e.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),a=this.setupWallet(e.privateKey),n={wallet:a.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{}},o=new Rn(n),r={sdk:o,wallet:a,config:n};if(!1!==e.autoValidate){const e=await this.validateSetup(o,a);return{...r,validation:e}}return r}static async readOnlySetup(e={}){const t=e.environment||this.detectEnvironment(),a={wallet:void 0,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{}};return{sdk:new Rn(a),config:a}}static async validateSetup(e,t){const a=[],n=[],o={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(o.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);o.hasBalance=e>0,o.canTrade=e>=.1,o.canCreateTokens=e>=100,0===e?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&&o.connectionHealthy,sdk:e,wallet:t||Gn.generateWallet(),issues:a,warnings:n,capabilities:o}}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,o]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:o,agentId:`multi-wallet-${n}`,autoValidate:!1});a[n]=e}return a}static detectEnvironment(){const e=process.env.NODE_ENV?.toLowerCase();return"development"===e?"development":"test"===e||"testing"===e?"testing":"production"}static setupWallet(e){if(!e){const e=process.env.PRIVATE_KEY;return e?Gn.fromPrivateKey(e):Gn.generateWallet()}return"generate"===e?Gn.generateWallet():Gn.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}},e.CALCULATION_MODES=Dn,e.ConfigurationError=A,e.FileValidationError=Pa,e.GALA_DECIMALS=8,e.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},e.GSwapAssetError=N,e.GSwapPoolError=b,e.GSwapQuoteError=S,e.GSwapSwapError=E,e.IMAGE_EXTENSIONS=ve,e.LAUNCHPAD_TOKEN_DECIMALS=18,e.LaunchpadSDK=Rn,e.MAX_CONCURRENT_POOL_FETCHES=5,e.NetworkError=v,e.PAGINATION_DEFAULTS=ca,e.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},e.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},e.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},e.SDK_VERSION=On,e.TRADING_TYPES=Cn,e.TokenMetadataService=class{constructor(){this.cache={},this.cacheExpiry=36e5,this.logger=new p({debug:!1,context:"TokenMetadataService"})}async resolveTokenMetadata(e){const t=this.getCacheKey(e),a=this.cache[t];if(a&&!this.isCacheExpired(a.timestamp))return this.logger.debug(`Using cached metadata for token: ${t}`),a.data;const n=this.extractMetadata(e);return this.cache[t]={data:n,timestamp:Date.now()},n}async getTokenSymbol(e){return(await this.resolveTokenMetadata(e)).symbol}async getTokenDecimals(e){return(await this.resolveTokenMetadata(e)).decimals}clearCache(e){e?(delete this.cache[e],this.logger.debug(`Cleared cache for token: ${e}`)):(this.cache={},this.logger.debug("Cleared all token metadata cache"))}getCacheStats(){const e=Object.keys(this.cache);return{size:e.length,entries:e}}getCacheKey(e){if("string"==typeof e)return e.toLowerCase();return`${e.type||e.symbol||"unknown"}|${e.additionalKey||"none"}`.toLowerCase()}extractMetadata(e){let t,a,n="Token",o="Unit",r="none";if("string"==typeof e)if(e.includes("|")){const i=e.split("|");"Token"===i[0]&&i[2]?(n=i[0],o=i[1]||"Unit",t=i[2],r=i[3]||"none",a=t):(t=i[0],a=t,o=i[1]||"Unit",r=i[3]||"none")}else t=e,a=e;else t=e.type||"unknown",a=e.symbol||e.type||"unknown",n=e.collection||"Token",o=e.category||"Unit",r=e.additionalKey||"none";const i=this.getDecimalsForToken(a);return{symbol:a.toUpperCase(),decimals:i,collection:n,category:o,type:t.toUpperCase(),additionalKey:r,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return Date.now()-e>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}},e.TransactionError=T,e.TransactionFailedError=Un,e.ValidationError=k,e.WebSocketError=_n,e.WebSocketTimeoutError=class extends _n{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},e.addressFormatSchema=O,e.amountMethodSchema=ye,e.amountTypeSchema=fe,e.browserFileSchema=Te,e.bufferFileSchema=Se,e.buyTokensDataSchema=Ve,e.calculatePreMintDataSchema=Ze,e.checkPoolOptionsSchema=me,e.commentMessageSchema=ae,e.commentPaginationSchema=De,e.createLaunchpadSDK=function(e){const{wallet:t,env:n,config:o={}}=e||{};let r;if(t)if("string"==typeof t){r=Kn(t).wallet}else{if(!(t instanceof a.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");r=t}else{r=Kn().wallet}const i={wallet:r,...n&&{env:n},debug:!1,timeout:3e4,...o};return new Rn(i)},e.createLimitSchema=X,e.createPaginatedResultSchema=function(e){return o.z.object({data:o.z.array(e),page:o.z.number().int().min(1),limit:o.z.number().int().min(1),total:o.z.number().int().min(0),totalPages:o.z.number().int().min(0),hasNext:o.z.boolean(),hasPrevious:o.z.boolean()})},e.createTradeDataSchema=ze,e.createWallet=Kn,e.ethereumAddressSchema=R,e.faucetAmountSchema=V,e.fetchGalaBalanceOptionsSchema=Me,e.fetchPoolDetailsDataSchema=Je,e.fetchTokenBalanceOptionsSchema=Ge,e.fileSizeSchema=J,e.fileUploadSchema=Ae,e.filenameSchema=ee,e.flexibleAddressSchema=G,e.flexibleFileSchema=Ee,e.formatGalaForDTO=Ya,e.formatLaunchpadTokenForDTO=Za,e.fullNameSchema=M,e.getAmountOptionsSchema=Ye,e.getTradeOptionsSchema=je,e.graduateTokenOptionsSchema=ke,e.graphDataOptionsSchema=we,e.imageExtensionSchema=be,e.imageFilenameSchema=Ne,e.imageMimeTypeSchema=te,e.imageUploadOptionsSchema=ge,e.isoDateStringSchema=ne,e.launchTokenDataSchema=he,e.nonNegativeDecimalStringSchema=z,e.optionalUrlSchema=j,e.pageNumberSchema=H,e.paginationResultMetaSchema=Le,e.poolFetchTypeSchema=pe,e.poolPaginationSchema=Pe,e.positiveDecimalStringSchema=q,e.privateKeySchema=re,e.reverseBondingCurveConfigSchema=de,e.reverseBondingCurveConfigurationSchema=et,e.searchQuerySchema=B,e.sellTokensDataSchema=We,e.standardLimitSchema=Q,e.standardPaginationSchema=Ie,e.timestampSchema=oe,e.tokenCategorySchema=le,e.tokenCollectionSchema=ue,e.tokenDescriptionSchema=_,e.tokenListOptionsSchema=Ue,e.tokenNameSchema=$,e.tokenSymbolSchema=L,e.tokenUrlsSchema=ce,e.tradeCalculationMethodSchema=Qe,e.tradeCalculationTypeSchema=Xe,e.tradeLimitSchema=Z,e.tradeListParamsSchema=He,e.tradePaginationSchema=Ce,e.tradePaginationWithFiltersSchema=$e,e.tradeTypeBackendSchema=qe,e.tradeTypeSchema=Ke,e.transactionIdSchema=ie,e.transferFaucetsDataSchema=Be,e.uniqueKeySchema=se,e.updateProfileDataSchema=Oe,e.uploadProfileImageOptionsSchema=Re,e.urlSchema=W,e.userLimitSchema=Y,e.userPaginationSchema=Fe,e.userTokenNameSchema=U,e.userTokenTypeSchema=_e,e.userTokensPaginationSchema=xe,e.validateAddress=rt,e.validateAmountString=st,e.validateBuyTokensData=St,e.validateCalculatePreMintData=Ft,e.validateCheckPoolOptions=mt,e.validateCreateTradeData=Tt,e.validateFaucetAmount=ct,e.validateFetchGalaBalanceOptions=wt,e.validateFetchPoolDetailsData=Ct,e.validateFetchTokenBalanceOptions=At,e.validateFullName=lt,e.validateGetAmountOptions=It,e.validateGetTradeOptions=bt,e.validateImageUploadOptions=pt,e.validateLaunchTokenData=ht,e.validateSearchQuery=ut,e.validateSellTokensData=Et,e.validateTokenDescription=ot,e.validateTokenListOptions=ft,e.validateTokenName=at,e.validateTokenSymbol=nt,e.validateTokenUrls=gt,e.validateTradeListParams=Nt,e.validateTransferFaucetsData=yt,e.validateUpdateProfileData=kt,e.validateUploadProfileImageOptions=vt,e.validateUserTokenName=dt,e.validateVaultAddress=it,e.vaultAddressSchema=K});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("axios"),require("ethers"),require("@gala-chain/connect"),require("zod"),require("bignumber.js"),require("@gala-chain/dex"),require("@gala-chain/api"),require("uuid"),require("socket.io-client"),require("path"),require("fs"),require("dotenv"),require("crypto")):"function"==typeof define&&define.amd?define(["exports","axios","ethers","@gala-chain/connect","zod","bignumber.js","@gala-chain/dex","@gala-chain/api","uuid","socket.io-client","path","fs","dotenv","crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GalaLaunchpadSDK={},e.axios,e.ethers,e.GalaChainConnect,e.z,e.BigNumber,e.GalaChainDex,e.GalaChainAPI,e.uuid,e.io,e.path,e.fs,e.dotenv,e.crypto)}(this,function(e,t,n,o,a,i,r,s,c,l,u,d,h,g){"use strict";function p(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var m,f,y=p(u),w=p(d),k=p(h);if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(m||(m={}));class v extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class T{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new v(m.SIGNATURE_FAILED,"Message prefix cannot be empty")}hasWallet(){return void 0!==this.wallet}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new v(m.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new v(m.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.wallet.signMessage(t);return{message:t,signature:n,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof v)throw e;throw new v(m.SIGNATURE_FAILED,"Failed to generate signature for authentication",e instanceof Error?e:new Error(String(e)))}}getAddress(){return this.validateWallet(),this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.validateWallet(),this.wallet.address}getPrivateKey(){if(this.validateWallet(),!this.wallet.privateKey)throw new v(m.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new v(m.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`);return`eth|${t}`}async signMessage(e){this.validateWallet();try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){if(e instanceof v)throw e;const t=e instanceof Error?e.message:String(e);throw new v(m.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const n=Date.now(),o=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,a=await this.wallet.signMessage(o);return{"x-signature":a,"x-address":this.formatAddress(this.wallet.address),"x-message":o,"x-timestamp":n.toString()}}catch(e){if(e instanceof v)throw e;throw new v(m.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(e)))}}async signTypedData(e,t,n){this.validateWallet();try{return await this.wallet.signTypedData(e,t,n)}catch(e){if(e instanceof v)throw e;throw new v(m.SIGNATURE_FAILED,"Failed to sign typed data",e instanceof Error?e:new Error(String(e)))}}async generateCustomSignature(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new v(m.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){if(e instanceof v)throw e;throw new v(m.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new v(m.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new v(m.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new v(m.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"}(f||(f={}));class S{constructor(e){this.levelPriority={[f.DEBUG]:0,[f.INFO]:1,[f.WARN]:2,[f.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?f.DEBUG:f.INFO)}debug(e,t){this.log(f.DEBUG,e,t)}info(e,t){this.log(f.INFO,e,t)}warn(e,t){this.log(f.WARN,e,t)}error(e,t){this.log(f.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===f.DEBUG&&!this.debugEnabled)return;const o=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,a=this.getConsoleMethod(e);void 0!==n?n instanceof Error?a(`${o} ${t}`,n.message,n.stack):a(`${o} ${t}`,n):a(`${o} ${t}`)}getConsoleMethod(e){switch(e){case f.DEBUG:return console.debug;case f.INFO:return console.info;case f.WARN:return console.warn;case f.ERROR:return console.error;default:return console.log}}child(e){return new S({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[f.DEBUG]>=this.levelPriority[this.minLevel]}}function A(e){if(!e||"object"!=typeof e)return{};const t={};for(const[n,o]of Object.entries(e))null!=o&&("string"==typeof o?t[n]=o:"number"==typeof o||"boolean"==typeof o?t[n]=o.toString():Array.isArray(o)?t[n]=o.join(","):t[n]="object"==typeof o?JSON.stringify(o):String(o));return t}class b{constructor(e,n={}){this.auth=e,this.debug=n.debug??!1,this.logger=new S({debug:this.debug,context:"HttpClient"}),this.axios=t.create({baseURL:n.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:n.timeout||3e4,headers:{Accept:"application/json",...n.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:A(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};e.headers&&this.logger.debug("Custom headers provided:",e.headers),e.data instanceof FormData&&(t.headers&&t.headers["Content-Type"]&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload"));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const o=await this.axios.request(t);return this.logger.debug("Response:",{status:o.status,data:o.data}),o.data}catch(e){throw this.logger.error("Error:",e),e}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){try{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}}catch(e){throw this.logger.error("Custom signature generation failed:",e),new Error(`Failed to generate custom signature for message: ${e instanceof Error?e.message:"Unknown error"}`)}}async signWithGalaChain(e,t,n=o.SigningType.SIGN_TYPED_DATA){const a=this.auth.getPrivateKey(),i=new o.SigningClient(a);return await i.sign(e,t,n)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{try{if(e.headers||(e.headers={}),this.auth.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request headers being sent:",e.headers),e}catch(e){throw this.logger.error("Failed to add signature:",e),e}},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{if(e.response){const t={message:e.response.data?.message||e.message,error:e.response.data?.error,statusCode:e.response.status,details:e.response.data?.details,timestamp:e.response.data?.timestamp,path:e.response.data?.path};e.launchpadError=t,this.logger.error("Backend error:",t)}else e.request?this.logger.error("Network error:",e.message):this.logger.error("Request setup error:",e.message);return Promise.reject(e)})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}const E="Token name is required and must be a string",I=e=>`Could not find vault address for token: ${e}`;class N extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class P extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class F extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class D extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class C extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class x extends Error{constructor(e,t,n,o){super(e),this.originalError=t,this.transactionHash=n,this.code=o,this.name="GSwapSwapError"}}class $ extends Error{constructor(e,t,n,o,a){super(e),this.originalError=t,this.tokenA=n,this.tokenB=o,this.code=a,this.name="GSwapPoolError"}}class L extends Error{constructor(e,t,n,o){super(e),this.originalError=t,this.walletAddress=n,this.code=o,this.name="GSwapAssetError"}}class B extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class U extends N{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class O extends N{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function _(e,t){return new N(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function R(e,t){const n=t||e.charAt(0).toUpperCase()+e.slice(1);return new N(`${n} is required`,e,"REQUIRED_FIELD")}function q(e,t,n){const o=n||e.charAt(0).toUpperCase()+e.slice(1);return new N(`${o} must be ${t}`,e,"INVALID_FORMAT")}function M(e,t,n){return new P(e,t,n)}function G(e,t){return new F(e,t)}function K(e,t,n){return new D(e,t,n)}function z(e,t,n){const{MIN_PAGE:o,MAX_PAGE:a,MIN_LIMIT:i,MAX_LIMIT:r}=n.PAGINATION;if("number"!=typeof e||e<o||e>a)throw new N(`Page must be a number between ${o} and ${a}`,"page","INVALID_PAGE");if("number"!=typeof t||t<i||t>r)throw new N(`Limit must be a number between ${i} and ${r}`,"limit","INVALID_LIMIT")}const V={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function j(e){return"string"==typeof e&&e.trim().length>0}function W(e){return!(!e||"string"!=typeof e)&&(V.ETH_ADDRESS.test(e)||V.BACKEND_ADDRESS.test(e))}function H(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const Q=a.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"),X=a.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"),Z=a.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Y=a.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),J=a.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),ee=a.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"),te=a.z.string().regex(V.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),ne=a.z.string().regex(V.ETH_ADDRESS,"Invalid Ethereum address format"),oe=a.z.string().refine(e=>V.BACKEND_ADDRESS.test(e)||V.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),ae=a.z.string().refine(e=>V.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),ie=a.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),re=a.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),se=a.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),ce=a.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),le=a.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),ue=a.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 de(e=100){return a.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 he=de(100),ge=de(20),pe=de(20),me=a.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"),fe=a.z.string().max(255,"Filename must be at most 255 characters"),ye=a.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),we=a.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),ke=a.z.string().datetime("Must be a valid ISO 8601 date string"),ve=a.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Te=a.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Se=a.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"),Ae=a.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),be=a.z.object({websiteUrl:le,telegramUrl:le,twitterUrl:le}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),Ee=a.z.string().min(1,"Token category must not be empty").default("Unit"),Ie=a.z.string().min(1,"Token collection must not be empty").default("Token"),Ne=a.z.object({minFeePortion:ie,maxFeePortion:ie}),Pe=a.z.object({tokenName:Q,tokenSymbol:X,tokenDescription:Z,tokenImage:a.z.union([a.z.instanceof(File),a.z.instanceof(Buffer),a.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:re.default("0"),websiteUrl:le,telegramUrl:le,twitterUrl:le,tokenCategory:Ee,tokenCollection:Ie,reverseBondingCurveConfiguration:Ne.optional(),privateKey:Te.optional()}),Fe=a.z.object({file:a.z.union([a.z.instanceof(File),a.z.instanceof(Buffer)]),tokenName:Q}),De=a.z.enum(["recent","popular"]),Ce=a.z.object({tokenName:Q.optional(),symbol:X.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),xe=a.z.enum(["NATIVE","MEME"]),$e=a.z.enum(["IN","OUT"]),Le=a.z.object({from:a.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:a.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:a.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Q}),Be=a.z.object({tokenName:Q,slippageToleranceFactor:a.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:a.z.number().min(0).max(1).optional(),privateKey:Te.optional()}),Ue=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Oe=a.z.object({file:a.z.union([a.z.instanceof(File),a.z.instanceof(Buffer)]),name:fe,size:me,type:ye}),_e=a.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"),Re=a.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),qe=a.z.union([_e,Re]),Me=a.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Ge=fe.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Ue.includes(t)},`Filename must end with one of: ${Ue.join(", ")}`),Ke=a.z.object({page:ue,limit:he}),ze=a.z.object({page:ue,limit:ge}),Ve=a.z.object({page:ue,limit:pe}),je=a.z.object({page:ue,limit:de(50)}),We=Ke.extend({type:a.z.enum(["recent","popular"]).optional(),tokenName:a.z.string().min(1).max(50).optional(),search:a.z.string().min(1).max(100).optional()}),He=ze.extend({tokenName:a.z.string().min(1).max(50).optional(),search:a.z.string().min(1).max(100).optional()}),Qe=Ve.extend({tradeType:a.z.enum(["BUY","SELL"]).optional(),tokenName:a.z.string().min(1).max(50).optional(),userAddress:a.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:a.z.string().datetime().optional(),endDate:a.z.string().datetime().optional(),sortOrder:a.z.enum(["ASC","DESC"]).default("DESC")}),Xe=a.z.object({page:a.z.number().int().min(1),limit:a.z.number().int().min(1),total:a.z.number().int().min(0),totalPages:a.z.number().int().min(0),hasNext:a.z.boolean(),hasPrevious:a.z.boolean()});const Ze=a.z.enum(["all","DEFI","ASSET"]),Ye=ze.extend({type:Ze.optional(),address:oe.optional(),search:J.optional(),tokenName:Y.optional()}),Je=a.z.object({walletAddress:oe,amount:se}),et=a.z.object({address:oe.optional(),refresh:a.z.boolean().optional()}),tt=a.z.object({profileImage:a.z.string(),fullName:ee,address:oe,privateKey:Te.optional()}),nt=a.z.object({file:a.z.union([a.z.instanceof(File),a.z.instanceof(Buffer)]),address:oe.optional(),privateKey:Te.optional()}),ot=a.z.object({address:oe,tokenId:a.z.union([a.z.string(),a.z.object({collection:a.z.string(),category:a.z.string(),type:a.z.string(),additionalKey:a.z.string()}),a.z.object({collection:a.z.string(),category:a.z.string(),type:a.z.string(),additionalKey:a.z.string(),instance:a.z.string()})]).optional(),tokenName:Y.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),at=a.z.enum(["buy","sell"]),it=a.z.enum(["BUY","SELL"]),rt=a.z.object({tradeType:at,tokenAmount:ie,vaultAddress:ae,userAddress:oe,slippageTolerance:ie.optional(),deadline:a.z.number().int().positive().optional()}),st=a.z.object({tokenSymbol:X,nativeTokenQuantity:ie,expectedToken:ie,maxAcceptableReverseBondingCurveFee:re.default("0").optional()}),ct=a.z.object({tokenSymbol:X,tokenQuantity:ie,expectedNativeToken:ie,maxAcceptableReverseBondingCurveFee:re.default("0").optional()}),lt=Ve.extend({tokenName:Y.optional()}),ut=a.z.object({page:a.z.number().int().min(1).max(1e3).default(1).optional(),limit:a.z.number().int().min(1).max(20).default(10).optional()}),dt=a.z.enum(["NATIVE","MEME"]),ht=a.z.enum(["IN","OUT"]),gt=a.z.object({type:dt,method:ht,vaultAddress:ae,amount:ie}),pt=a.z.object({nativeTokenQuantity:ie}),mt=a.z.object({vaultAddress:ae}),ft=a.z.object({minFeePortion:ie,maxFeePortion:ie});function yt(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.errors.map(e=>e.message)}}}const wt=yt(Q),kt=yt(X),vt=yt(Z),Tt=yt(oe),St=yt(ae),At=yt(ie),bt=yt(se),Et=yt(ee),It=yt(J),Nt=yt(Y),Pt=yt(Pe),Ft=yt(be),Dt=yt(Fe),Ct=yt(Ce),xt=yt(Ye),$t=yt(Je),Lt=yt(et),Bt=yt(tt),Ut=yt(nt),Ot=yt(ot),_t=yt(rt),Rt=yt(st),qt=yt(ct),Mt=yt(lt),Gt=yt(ut),Kt=yt(gt),zt=yt(pt),Vt=yt(mt);function jt(e,t){throw new N(e.join("; "),t,"VALIDATION_ERROR")}function Wt(e){const t=wt(e);!t.success&&t.errors&&jt(t.errors,"tokenName")}function Ht(e){const t=We.safeParse(e);t.success||jt(t.error.errors.map(e=>e.message),"pagination")}function Qt(e){const t=Ct(e);!t.success&&t.errors&&jt(t.errors,"options")}function Xt(e){const t=Kt(e);!t.success&&t.errors&&jt(t.errors,"options")}function Zt(e){const t=Le.safeParse(e);t.success||jt(t.error.errors.map(e=>e.message),"options")}function Yt(e){const t=oe.safeParse(e);if(!t.success)throw new N("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Jt(e,t,n=!0){if(!e||""===e.trim())throw new N(`${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 N(`${t} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,t,"INVALID_NUMERIC_STRING");const o=parseFloat(e);if(isNaN(o))throw new N(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new N(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(o<0)throw new N(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new N(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var en=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=oe.safeParse(e);if(!t.success)throw new N(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:Yt,validateCheckPoolOptions:Qt,validateGetAmountOptions:Xt,validateGetGraphOptions:Zt,validateNumericString:Jt,validatePagination:Ht,validateTokenName:Wt});function tn(e,t){const n=e,o=Number(n.page)||t.page,a=Number(n.limit)||t.limit,i=n.data,r=Number(n.total)||Number(i?.count)||0;return{page:o,limit:a,total:r,totalPages:Math.ceil(r/a)}}function nn(e,t){return{hasNext:e<t,hasPrevious:e>1}}function on(e,t,n=!1){const o=!0===e.error||200!==e.status,a=n&&!e.data;if(o||a)throw new Error(e.message||t)}const an="/launchpad/upload-image",rn="/launchpad/fetch-pool",sn="/launchpad/check-pool",cn="/launchpad/get-graph-data",ln="/holders",un="/launchpad/get-badge/",dn="/trade/",hn="/token/commment",gn="/token/commment",pn="/user/profile",mn="/user/profile",fn="/user/token-list",yn="/user/token-hold",wn="/user/transfer-faucets",kn={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};class vn{constructor(e,t=!1){this.http=e,this.logger=new S({debug:t,context:this.constructor.name})}}class Tn{constructor(e=!1){this.logger=new S({debug:e,context:this.constructor.name})}}function Sn(e,t){return"string"==typeof e[t]}function An(e,t){return void 0===e[t]||"string"==typeof e[t]}function bn(e,t){return void 0===e[t]||"number"==typeof e[t]}function En(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function In(e){if(!e||"object"!=typeof e)return!1;const t=e;return Sn(t,"tokenName")&&bn(t,"from")&&bn(t,"to")&&bn(t,"resolution")}class Nn extends vn{constructor(e,t=!1){super(e,t)}async fetchSinglePage(e){const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const n=A(t),o=await this.http.get(rn,n);if(!o)throw M("No response from pool service",500);on(o,"Failed to fetch pools",!0);const a=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at||e.createdAt||""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at||n.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(o.data),i=o.data.count??o.data.total??0;return{pools:a,total:i,totalPages:e.limit>0?Math.ceil(i/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:n,pageSize:o,...a}=e,i=[];if(n&&n>=t){const e=[];for(let o=t;o<=n;o++)e.push(o);for(let t=0;t<e.length;t+=5){const n=e.slice(t,t+5).map(e=>this.fetchSinglePage({...a,page:e,limit:o}));(await Promise.all(n)).forEach(e=>{i.push(...e.pools)})}return i}let r=t,s=!0;for(;s;){const e=[];for(let t=0;t<5&&s;t++)e.push(r+t);const t=e.map(e=>this.fetchSinglePage({...a,page:e,limit:o})),n=await Promise.all(t);for(const e of n){if(0===e.pools.length){s=!1;break}i.push(...e.pools)}r+=e.length,r>kn.SAFETY_MAX_PAGES&&(s=!1)}return i}async fetchPools(e={}){const t=e.page||kn.DEFAULT_PAGE,n=e.limit??kn.DEFAULT_LIMIT;let o;if(0!==n&&Ht({page:t,limit:n}),e.tokenName&&Wt(e.tokenName),"recent"===e.type?o="RECENT":"popular"===e.type&&(o="POPULAR"),n>0&&n<=20){const a=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...o&&{type:o},page:t,limit:n});return{pools:a.pools,page:t,limit:n,total:a.total,totalPages:a.totalPages,hasNext:t<a.totalPages,hasPrevious:t>1}}if(0===n){const t=kn.BACKEND_MAX_PAGE_SIZE,n=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...o&&{type:o},page:1,limit:t}),a=[...n.pools];if(n.pools.length>0){const i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...o&&{type:o},startPage:2,totalPages:n.totalPages>1?n.totalPages:null,pageSize:t});a.push(...i)}return{pools:a,page:1,limit:a.length,total:n.total||a.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const a=kn.BACKEND_MAX_PAGE_SIZE,i=Math.ceil(n/a),r=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...o&&{type:o},page:t,limit:a}),s=[...r.pools],c=Math.min(i,r.totalPages-t+1);if(c>1){const n=t+c-1,i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...o&&{type:o},startPage:t+1,totalPages:n,pageSize:a});s.push(...i)}const l=s.slice(0,n);return{pools:l,page:t,limit:n,total:r.total,totalPages:r.totalPages,hasNext:t<r.totalPages&&l.length<r.total,hasPrevious:t>1}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){Qt(e),e.tokenName&&Wt(e.tokenName);const t=A(e),n=await this.http.get(sn,t);if(!n)throw M("No response from pool service",500);on(n,"Failed to check pool");const o=n.data;return e.symbol?o?.isSymbolExist??!1:e.tokenName?o?.isNameExist??!1:o?.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(!In(e))throw new N("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:o,resolution:a}=e;if(Wt(t),!n||!o||!a)throw new N("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:o,resolution:a};Zt(i);const r=A(i),s=await this.http.get(cn,r);if(!s)throw M("No response from pool service",500);return on(s,"Failed to fetch graph data",!0),{dataPoints:s.data}}async fetchTokenDistribution(e){if(!e)throw R("tokenName","Token name");Wt(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw _(e);const n=encodeURIComponent(t),o=await this.http.get(`${ln}/${n}`);if(!o)throw M("No response from pool service",500);on(o,"Failed to fetch token distribution",!0);const a=o.data;if(!Array.isArray(a))throw M("Invalid API response: expected array of holders",o.status);for(const e of a){if(!e.owner||"string"!=typeof e.owner)throw M("Invalid holder data: missing or invalid owner field",o.status);if(!e.quantity||"string"!=typeof e.quantity)throw M("Invalid holder data: missing or invalid quantity field",o.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw M(`Invalid holder quantity: "${e.quantity}"`,o.status)}const r=a.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:a.map(e=>{const t=new i(e.quantity),n=r.isZero()?0:t.dividedBy(r).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:r.toFixed(),totalHolders:a.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw R("tokenName","Token name");Wt(e);const t=await this.http.get(un,{tokenName:e});if(!t)throw M("No response from pool service",500);return on(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:o}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const a=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===o);return a?.isActive||!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(t.pools&&Array.isArray(t.pools)&&t.pools.length>0)return t.pools[0].vaultAddress||null;if(t.pools&&"object"==typeof t.pools){const e=t.pools.tokens;return e?.vaultAddress||null}return null}catch{return null}}}function Pn(e,t={}){const{stringifyFields:n=[],optionalFields:o=[],fieldMappings:a={}}=t,i={};for(const[t,r]of Object.entries(e)){const e=t;if(o.includes(e)&&void 0===r)continue;if(o.includes(e)&&"string"==typeof r&&0===r.trim().length)continue;const s=a[e],c=s?String(s):t;n.includes(e)?i[c]=String(r):i[c]=r}return A(i)}const Fn={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class Dn extends vn{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Sn(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&An(t,"userAddress")&&bn(t,"page")&&bn(t,"limit")}(e))throw new N("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, page?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:n,userAddress:o,page:a=kn.DEFAULT_PAGE,limit:i=kn.DEFAULT_LIMIT,startDate:r,endDate:s,sortOrder:c}=e;if(!j(t))throw new N("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");z(a,i,Fn);const l=function(e,t,n){return Pn({tokenName:e,page:t,limit:n},{stringifyFields:["page","limit"]})}(t,a,i),u=await this.http.get(dn,l);if(!u)throw new N("No response from trade service","response","NO_RESPONSE");const d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const g=tn(u,{page:a,limit:i}),p=nn(g.page,g.totalPages);return{trades:d,...g,...p}}}const Cn=new S({debug:!1,context:"DateUtils"});function xn(e,t){if(!e)return t||new Date;if(e instanceof Date)return isNaN(e.getTime())?t||new Date:e;try{const n=new Date(e);return isNaN(n.getTime())?(Cn.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):n}catch(n){return Cn.warn(`Date parsing error for "${e}":`,n),t||new Date}}const $n={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class Ln extends vn{constructor(e,t,n=!1){super(e,n),this.poolService=t}async fetchComments(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Sn(t,"tokenName")&&bn(t,"page")&&bn(t,"limit")}(e))throw new N("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:n=kn.DEFAULT_PAGE,limit:o=kn.DEFAULT_LIMIT}=e;if(!j(t))throw new N("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");z(n,o,$n);const a=await this.poolService.resolveTokenNameToVault(t);if(!a)throw _(t);const i=Pn({vaultAddress:a,page:n,limit:o},{stringifyFields:["page","limit"]}),r=await this.http.get(hn,i);if(!r)throw new N("No response from comment service","response","NO_RESPONSE");if(on(r,"Failed to fetch comments"),!r.data)throw new N("Invalid response structure from comment service: no data field","response.data","INVALID_RESPONSE");if(0===Object.keys(r.data).length)return{comments:[],total:0};if(!Array.isArray(r.data.comments))throw new N("Invalid response structure from comment service: comments must be an array, got "+typeof r.data.comments,"response.data.comments","INVALID_RESPONSE");return{comments:r.data.comments.map(e=>({...e,createdAt:xn(e.createdAt)})),total:r.data.count||0}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Sn(t,"tokenName")&&Sn(t,"content")}(e))throw new N("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:n}=e;if(!j(t))throw new N("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>=$n.CONTENT.MIN_LENGTH&&t.length<=$n.CONTENT.MAX_LENGTH}(n))throw new N(`Comment content must be between ${$n.CONTENT.MIN_LENGTH} and ${$n.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const o=await this.poolService.resolveTokenNameToVault(t);if(!o)throw _(t);const a=this.http.getAddress();if(!a)throw new N("User address not available - wallet not configured","userAddress","NO_WALLET");const i={userAddress:a,vaultAddress:o,content:n},r=await this.http.post(gn,i);if(!r)throw new N("No response from comment service","response","NO_RESPONSE");on(r,"Failed to create comment")}}function Bn(e){return e instanceof Error}function Un(e){return Bn(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function On(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function _n(e,t="image",n){const o=new FormData;if("undefined"!=typeof File&&e instanceof File)o.append(t,e);else{if(!Buffer.isBuffer(e))throw q("file","a File object (browser) or Buffer (Node.js)");{const a=new Blob([e],{type:"image/png"});o.append(t,a,n)}}return o}const Rn={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 qn(e){return!(!e||"string"!=typeof e)&&Rn.USER_ADDRESS.PATTERN.test(e)}const Mn="Update profile";class Gn extends vn{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!qn(t))throw new N("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const n={userAddress:t},o=await this.http.get(pn,n);if(!o)throw new N("No response from user service","response","NO_RESPONSE");return o}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!t||""===t.trim())try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage||""}catch{t=""}const n={profileImage:t,fullName:e.fullName,userAddress:e.address},o=await this.http.signCustomMessage(Mn);if(!o)throw new N("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const a={address:o.address,message:Mn,publickey:o.ethereumAddress,sign:o.signature},i=await this.http.put(mn,n,a);if(!i)throw new N("No response from user service","response","NO_RESPONSE");on(i,"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new N("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,o=_n(e.file,"image",n),a=await this.http.request({method:"POST",url:`${an}?tokenName=${encodeURIComponent(t)}`,data:o,headers:{}});if(!a)throw new N("No response from user service","response","NO_RESPONSE");return on(a,"Image upload failed"),"string"==typeof a.data?a.data:""}catch(e){if(e instanceof N)throw e;throw new N(`Profile image upload failed: ${Un(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(fn,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(yn,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=kn.DEFAULT_PAGE,limit:n=kn.DEFAULT_LIMIT,search:o,tokenName:a}=e,i=this.http.getAddress();if(!i)throw new N("Wallet address not available - wallet not configured","address","NO_WALLET");const r={type:"DEFI",address:i,page:t,limit:n};return void 0!==o&&(r.search=o),void 0!==a&&(r.tokenName=a),this.fetchTokenList(r)}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const o={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},a=Pn(n.includeType?{...o,type:"all"!==t.type&&t.type?t.type:"DEFI"}:o,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),i=await this.http.get(e,a);if(!i)throw new N("No response from user service","response","NO_RESPONSE");on(i,n.errorMessage,!0);const r=(s=i.data)?Array.isArray(s)?s:s.token:[];var s;const c=tn(i,{page:t.page||kn.DEFAULT_PAGE,limit:t.limit||kn.DEFAULT_LIMIT}),l=nn(c.page,c.totalPages);return{tokens:r,...c,...l}}validateGetTokenListOptions(e){if(z(e.page,e.limit,Rn),void 0!==e.address&&!qn(e.address))throw new N("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>=Rn.SEARCH.MIN_LENGTH&&t.length<=Rn.SEARCH.MAX_LENGTH))throw new N(`Search query must be between ${Rn.SEARCH.MIN_LENGTH} and ${Rn.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,n;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((n=e.tokenName)&&"string"==typeof n&&n.length>=Rn.TOKEN_NAME.MIN_LENGTH&&n.length<=Rn.TOKEN_NAME.MAX_LENGTH))throw new N(`Token name must be between ${Rn.TOKEN_NAME.MIN_LENGTH} and ${Rn.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!qn(e.address))throw new N("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=Rn.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=Rn.PROFILE.FULL_NAME.MAX_LENGTH&&Rn.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new N(`Full name must be between ${Rn.PROFILE.FULL_NAME.MIN_LENGTH} and ${Rn.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!qn(e.address))throw new N("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Kn extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function zn(e,t,n){if(!e)throw new Kn("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=_e.safeParse(e);if(!t.success){const n=t.error.errors.map(e=>e.message).join("; ");throw new Kn(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Kn("Filename is required when uploading Buffer objects",t,n);const o=Re.safeParse(e);if(!o.success){const e=o.error.errors.map(e=>e.message).join("; ");throw new Kn(e,t,n)}if(t.length>255)throw new Kn(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,n);const a=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!a.includes(n))throw new Kn(`Invalid file type "${n}" is not allowed. Allowed types: ${a.join(", ")}`,t,n);const i=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),r=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!r.includes(i))throw new Kn(`File extension "${i}" is not allowed. Allowed extensions: ${r.join(", ")}`,t,n);const s=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(s!==n&&"application/octet-stream"!==s)throw new Kn(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new Kn("File must be a File object (browser) or Buffer (Node.js)",t,n)}class Vn extends vn{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Wt(t);const o=`${t}.png`;zn(n.file,o,"image/png");try{const e=`${n.tokenName??t}.png`,o=_n(n.file,"image",e),a=await this.http.request({method:"POST",url:`${an}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:o,headers:{}});if(!a)throw G("No response from image upload service","response");return on(a,"Image upload failed"),"string"==typeof a.data?a.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw G("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class jn extends vn{constructor(e,t=!1){super(e,t)}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount},n=await this.http.post(wn,t);if(!n)throw new N("No response from faucet service","response","NO_RESPONSE");on(n,"Faucet transfer failed")}validateTransferFaucetsData(e){if(!qn(e.walletAddress))throw new N("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!Rn.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new N("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class Wn{constructor(e,t=!1){this.http=e,this.poolService=new Nn(e,t),this.tradeService=new Dn(e,t),this.commentService=new Ln(e,this.poolService,t),this.userService=new Gn(e,t),this.imageService=new Vn(e,t),this.faucetService=new jn(e,t)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async fetchComments(e){return this.commentService.fetchComments(e)}async postComment(e){return this.commentService.postComment(e)}async fetchProfile(e){return this.userService.fetchProfile(e)}async updateProfile(e){return this.userService.updateProfile(e)}async uploadProfileImage(e){return this.userService.uploadProfileImage(e)}async fetchTokenList(e){return this.userService.fetchTokenList(e)}async fetchTokensHeld(e){return this.userService.fetchTokensHeld(e)}async fetchTokensCreated(e={}){return this.userService.fetchTokensCreated(e)}async transferFaucets(e){return this.faucetService.transferFaucets(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return Wt(e)}}const Hn={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var Qn;!function(e){e.INVALID_RECIPIENT="INVALID_RECIPIENT",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.DUPLICATE_TRANSFER="DUPLICATE_TRANSFER",e.TRANSFER_LIMIT_EXCEEDED="TRANSFER_LIMIT_EXCEEDED",e.WALLET_REQUIRED="WALLET_REQUIRED"}(Qn||(Qn={}));class Xn extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function Zn(e,t="0"){return new i(null==e||""===e?t:e)}function Yn(e){return r.tickToSqrtPrice(e)}function Jn(e){const t=Zn(e),n=new i(2).pow(96),o=t.sqrt().times(n);return r.sqrtPriceToTick(o)}function eo(e,t=!1){const n=Zn(e),o=new i(1).dividedBy(n);return t?o.toFixed():o}function to(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThan(0))throw new Error(`Value at index ${t} must be non-negative, got: ${e.toString()}`)})}function no(e,t,n){if(e.isNaN())throw new Error(`${t} must be a valid number, got: NaN`);if(!e.isFinite()){const o=n?`${t} must be finite ${n}, got: ${e.toString()}`:`${t} must be finite, got: ${e.toString()}`;throw new Error(o)}if(e.isLessThanOrEqualTo(0)){const o=n?`${t} must be positive ${n}, got: ${e.toString()}`:`${t} must be positive, got: ${e.toString()}`;throw new Error(o)}}class oo{static validateAmount(e){const t=new i(e);try{no(t,"amount","for transfer")}catch(t){throw new Xn(t.message,Qn.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(e){if(e.length>Hn.MAX_UNIQUE_KEY_LENGTH)throw new N(`Unique key too long. Maximum length: ${Hn.MAX_UNIQUE_KEY_LENGTH}`);if(!Hn.UNIQUE_KEY_PATTERN.test(e))throw new Xn('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Qn.INVALID_AMOUNT,{uniqueKey:e})}}}class ao{toLaunchpadFormat(e){if(!e)return"unknown|Unit|none|none";if("string"==typeof e)return e.includes("|")?e:`${e}|Unit|none|none`;return`${e.type||e.symbol||"unknown"}|${e.category||"Unit"}|none|${e.additionalKey||"none"}`}toTokenClass(e){if("object"==typeof e&&null!==e)return{collection:e.collection||"Token",category:e.category||"Unit",type:e.type||e.symbol||"unknown",additionalKey:e.additionalKey||"none"};if("string"!=typeof e)throw new Error("Invalid token format: expected string or object, got "+typeof e);const t=e.split("|");if(t.length<3)throw new Error(`Invalid token format: ${e}`);const n=("Token"===t[0]||"Collection"===t[0])&&t[2]?t[2]:t[0];return{collection:t[0]||"Token",category:t[1]||"Unit",type:n,additionalKey:t[3]||"none"}}isGSwapFormat(e){return"string"==typeof e&&e.includes("|")}normalize(e){return"string"==typeof e&&this.isGSwapFormat(e)?e:this.toLaunchpadFormat(e)}}function io(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function ro(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected at least 4 parts separated by $, got ${t.length}`);const[n,o,a,...i]=t;if(!n||!o||!a)throw new Error("Collection, category, and type must be non-empty");const r=i.join("$");if(!r)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:o,type:a,additionalKey:r}}catch(t){throw new N(`Invalid dollar-delimited token: "${e}". Expected format: "Token$Unit$SYMBOL$additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"dollarToken","INVALID_DOLLAR_DELIMITED_TOKEN_FORMAT")}}class so extends o.ChainCallDTO{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,o,a){let i;if("string"==typeof o){i={...ro(o),instance:"0"}}else i={collection:o.collection,category:o.category,type:o.type,additionalKey:o.additionalKey,instance:"0"};return new so({from:e,to:t,quantity:n,tokenInstance:i,uniqueKey:a||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n,o){return new so({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:o||`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 co{constructor(e){this.wallet=e}static generateUniqueKey(){return`${Date.now()}_${Math.random().toString(36).substring(2,8)}`}async signTransferToken(e){const t={name:"GalaChain",chainId:1},n={TransferToken:[{name:"from",type:"string"},{name:"to",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstance",type:"TokenInstance"},{name:"uniqueKey",type:"string"}],TokenInstance:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]};return{signature:await this.wallet.signTypedData(t,n,e),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const t=e.replace("0x","");return`eth|${n.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){return{...ro(e),instance:"0"}}}function lo(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new N(`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 N(`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 N("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 N(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function uo(e){try{const[t,n]=e.split("|");if(!n)throw new Error("Missing token part after service");const o=n.split("$");if(o.length<4)throw new Error(`Invalid vault address format. Expected at least 4 parts separated by $, got ${o.length}`);if(!(o[0]&&o[1]&&o[2]&&o[3]))throw new Error("All vault address components (collection, category, type, additionalKey) must be non-empty");const a=o.slice(3,-1),i=a.length>0?a.join("$"):o[3];return{collection:o[0],category:o[1],type:o[2],additionalKey:i}}catch(t){throw new N(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${t instanceof Error?t.message:String(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}function ho(e){return{...uo(e),instance:"0"}}function go(e){return uo(e).type}var po=Object.freeze({__proto__:null,extractTokenSymbolFromVault:go,normalizeToTokenInstanceKey:lo,parseVaultAddressToTokenClassKey:uo,parseVaultAddressToTokenInstance:ho});const mo="gala-transfer-successful",fo="token-transfer-successful",yo="transfer-successful-no-id";class wo extends vn{constructor(e,t,n,o=!1,a){super(e,o),this.wallet=t,this.tokenResolver=n,this.publicAxios=a,this.signatureHelper=t?new co(t):void 0}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw M("No response from GalaChain service",500);if(1!==t.Status)throw M(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const n=t.Data.reverseBondingCurveConfiguration,o=n?.minFeePortion??"0",a=n?.maxFeePortion??"0",i=(await import("bignumber.js")).default,r=!new i(o).isZero()||!new i(a).isZero(),s=t.Data;return s.reverseBondingCurveMinFeePortion=o,s.reverseBondingCurveMaxFeePortion=a,s.hasReverseBondingCurveFee=r,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(!e)throw M("No response from GalaChain service",500);if(1!==e.Status)throw M(`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 N("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new N("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new N("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e){try{const t=await this.http.post("/api/asset/token-contract/FetchBalances",e);if(!t)return null;if(1!==t.Status||!t.Data||0===t.Data.length)return null;const n=t.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!n||"0"===n.quantity)return null;const o=`${n.collection}|${n.category}|${n.additionalKey}|${n.type}`;return{quantity:n.quantity,collection:n.collection,category:n.category,tokenId:o}}catch(e){throw M(`Failed to fetch token balance from GalaChain: ${Un(e)}`,void 0,Bn(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?lo(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]},o=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(1!==o.Status)throw M(`Failed to fetch token class from GalaChain: Status ${o.Status}${o.Message?` - ${o.Message}`:""}`,o.Status);if(!o.Data||0===o.Data.length)throw M(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return o.Data[0]}catch(e){if(On(e)&&404===e.response?.status)throw M("Token not found on GalaChain",404,Bn(e)?e:void 0);const t=Un(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw M(`Failed to fetch token class from GalaChain: ${t}`,void 0,Bn(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw new N("tokenClasses array must not be empty");const t={tokenClasses:e},n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(1!==n.Status)throw M(`Failed to fetch token classes with supply from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw M("No token supply data found for requested token classes",404);return n.Data}catch(e){if(On(e)&&404===e.response?.status)throw M("Token supply data not found on GalaChain",404,Bn(e)?e:void 0);const t=Un(e);if(t.includes("Token")||t.includes("Status")||t.includes("tokenClasses"))throw e;throw M(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,Bn(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new Xn("Wallet required for GALA transfer operations",Qn.WALLET_REQUIRED);try{const t=H(e.recipientAddress),n=H(this.wallet.address),o=so.forGALA(n,t,e.amount,e.uniqueKey),a=await this.signatureHelper.signTransferToken(o.toSigningPayload()),i=new so({...o.toSigningPayload(),signedPayload:a});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(i,null,2));const r=await this.http.post("/api/asset/token-contract/TransferToken",i);if(!r)throw new Xn("No response from GalaChain transfer service",Qn.NETWORK_ERROR);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(r,null,2)),this.extractTransactionIdFromResponse(r,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new Xn("Wallet required for token transfer operations",Qn.WALLET_REQUIRED);try{const t=H(e.to),n=H(this.wallet.address);let o;if(e.tokenId)o=lo(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",JSON.stringify(o,null,2));else{if(!e.tokenName)throw new Xn("Must provide either tokenId or tokenName for token identification",Qn.TOKEN_NOT_FOUND);o=await this.resolveTokenInstance(e.tokenName)}const a=new so({from:n,to:t,quantity:e.amount,tokenInstance:o,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),i=await this.signatureHelper.signTransferToken(a.toSigningPayload()),r=new so({...a.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(r,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",r);if(!s)throw new Xn("No response from GalaChain transfer service",Qn.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"token")}catch(t){throw this.handleTransferError(t,"Token transfer failed",e)}}async resolveTokenClassKey(e){try{const t=await this.tokenResolver.resolveTokenClassKey(e);return this.logger.debug(`[DEBUG] Token class key resolution for '${e}':`,JSON.stringify(t,null,2)),t}catch(t){if(t instanceof Xn)throw t;throw new Xn(`Failed to resolve token class key for '${e}': ${Un(t)}`,Qn.TOKEN_NOT_FOUND,{tokenName:e})}}validateTransferGalaData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.recipientAddress&&t.recipientAddress.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new N("Invalid GALA transfer data: missing required fields");if(!W(e.recipientAddress))throw new Xn("Invalid recipient address format",Qn.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});oo.validateAmount(e.amount),oo.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.to&&t.to.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new N("Invalid token transfer data: missing required fields");if(!W(e.to))throw new Xn("Invalid recipient address format",Qn.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Xn("Must provide either tokenId or tokenName for token identification",Qn.TOKEN_NOT_FOUND);if(e.tokenName&&!Hn.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Xn("Invalid token name format",Qn.TOKEN_NOT_FOUND,{tokenName:e.tokenName});oo.validateAmount(e.amount),oo.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Xn(`Token '${e}' not found or not available for transfer`,Qn.TOKEN_NOT_FOUND,{tokenName:e});const n=this.resolveTokenInstanceFromVaultAddress(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}':\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}catch(t){if(t instanceof Xn)throw t;throw new Xn(`Failed to resolve token '${e}': ${Un(t)}`,Qn.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){try{return ho(e)}catch(e){if(e instanceof N)throw new Xn(`Invalid vault address format: ${e.message}`,Qn.TOKEN_NOT_FOUND);throw new Xn(`Failed to parse vault address: ${e instanceof Error?e.message:String(e)}`,Qn.TOKEN_NOT_FOUND)}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const n=e;return Array.isArray(n.Data)&&n.Data.length>0?"gala"===t?mo:fo:yo}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Xn("Transfer succeeded but transaction ID could not be extracted",Qn.NETWORK_ERROR)}handleTransferError(e,t,n){if(e instanceof Xn)return e;if(e instanceof N)return new Xn(e.message,Qn.INVALID_AMOUNT);if(On(e)&&e.response){const t=e.response.status,o=e.response.data;if(400===t)return new Xn(("string"==typeof o?.message?o.message:void 0)||"Invalid transfer request",Qn.INVALID_AMOUNT);if(403===t)return new Xn("Insufficient balance for transfer",Qn.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Xn("Token not found",Qn.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new Xn("Transfer request timed out",Qn.NETWORK_ERROR);const o=Un(e);return new Xn(o||t,Qn.NETWORK_ERROR)}}class ko{constructor(e,t,n,o=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=n,this.logger=new S({debug:o,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e;if(!t&&!n)throw R("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&n)throw new N("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS");if(n)return this.logger.debug(`Fetching spot price by tokenId: ${n}`),this._fetchDexTokenSpotPrice(n);throw new N("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw R("tokenId","Token ID");try{const t=lo(e),n=io(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${n}`),!this.dexBackendHttp)throw M("DEX Backend API client not configured");const o=await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:n}});if(!o.data||"string"!=typeof o.data)throw new N("Invalid price response: data must be a string, got "+typeof o.data,"data","INVALID_RESPONSE");const a=parseFloat(o.data);if(isNaN(a))throw new N(`Invalid price value: could not parse "${o.data}" as number`,"data","INVALID_CALCULATION");const i=`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`;let r;try{if(this.cache){const e=this.cache.getByTokenId(i);if(e?.symbol)return r=e.symbol,this.logger.debug(`DEX spot price for ${r} (cached): $${a}`),{symbol:r,price:a}}this.logger.debug(`Symbol cache miss for ${i}, fetching from API`);r=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(i,{symbol:r}),this.logger.debug(`Cached symbol for ${i}: ${r}`)),this.logger.debug(`DEX spot price for ${r}: $${a}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to type field: ${e instanceof Error?e.message:String(e)}`),r=t.type.toUpperCase(),this.logger.debug(`DEX spot price for ${r} (fallback): $${a}`)}return{symbol:r,price:a}}catch(e){if(e instanceof N)throw e;throw M(`Failed to fetch DEX spot price: ${Un(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!e||"string"!=typeof e)throw new Error(E);try{if(n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const n=`${t.sellingToken.collection}|${t.sellingToken.category}|${t.sellingToken.type}|${t.sellingToken.additionalKey}`;return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Un(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const o=await t({tokenName:e,amount:"1",type:"native"}),a=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(!a)throw M("GALA price not available");const i=Number(o.amount)/1e18;if(i<=0)throw new N(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const r=a.price/i;return{symbol:e.toUpperCase(),price:r}}catch(t){if(t instanceof Error)throw M(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw M(`Failed to calculate launchpad token spot price for ${e}: ${Un(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw M("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),n={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey,symbol:t.symbol,decimals:t.decimals,name:t.name,image:t.image,description:t.description,network:t.network,...void 0!==t.contractAddress&&{contractAddress:t.contractAddress}};return this.logger.debug(`Fetched token details for ${t.symbol} from GalaChain`),n}catch(t){if((t instanceof N||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw M(`Failed to fetch token details from GalaChain for ${e}: ${Un(t)}`,500)}}}function vo(e,t=18){const n=parseFloat(e);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function To(e){return vo(e,8)}function So(e){return vo(e,18)}function Ao(e){return{maxAcceptableReverseBondingCurveFee:To(e.maxAcceptableReverseBondingCurveFee)}}new S({debug:!1,context:"NumberUtils"});class bo extends o.ChainCallDTO{constructor(e,t,n="0",o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=To(t),this.expectedToken=So(n),this.extraFees=Ao(o)}}class Eo extends o.ChainCallDTO{constructor(e,t,n,o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=So(t),this.expectedNativeToken=To(n),this.extraFees=Ao(o)}}class Io extends o.ChainCallDTO{constructor(e,t,n="0",o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=So(t),this.expectedNativeToken=To(n),this.extraFees=Ao(o)}}class No extends o.ChainCallDTO{constructor(e,t,n,o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=To(t),this.expectedToken=So(n),this.extraFees=Ao(o)}}const Po={BuyNativeDto:bo,BuyExactDto:Eo,SellExactDto:Io,SellNativeDto:No};class Fo extends Tn{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,n){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const n=this.generateEIP712Types(t,e),a=o.calculatePersonalSignPrefix(e),i={...e,prefix:a},{signature:r,domain:s}=await this.signWithEthersWallet(n,i),c={...e,signature:r,types:n,domain:s};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(c),signatureLength:r.length}),c}catch(e){this.logger.error("❌ Signature generation failed:",e);throw K(`Failed to sign DTO: ${Un(e)}`)}}async signWithEthersWallet(e,t){try{let n,o;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)n={name:"ethereum",chainId:1},o=await this.walletProvider.signTypedData(n,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw G("Wallet provider does not support typed data signing","walletProvider");{const a=await this.walletProvider.getNetwork();n={name:a.name,chainId:Number(a.chainId)},o=await this.walletProvider.signTypedData(n,e,t)}}return{signature:o,domain:n}}catch(e){throw K(`Ethers.js signing failed: ${Un(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const o=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),a=(e,t,o,i=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const r=a(e,t[0],o,!0);return i||n[o].push({name:e,type:(r??e)+"[]"}),r?r+"[]":void 0}if("object"==typeof t&&null!==t){if(n[e])throw new N(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).forEach(([t,n])=>{a(t,n,e)}),i||n[o].push({name:e,type:e}),e}{let a;switch(typeof t){case"string":a="string";break;case"number":a="uint256";break;case"boolean":a="bool";break;default:throw new N(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return i||n[o].push({name:e,type:a}),a}}};return Object.entries(o).forEach(([t,n])=>{a(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class Do extends Tn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),o=this.createGalaInstance(),a=`$service$${n.toStringKey()}$launchpad`,i=`$tokenBalance$${n.toStringKey()}$${e}`,r=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${o.toStringKey()}$${e}`,c=[a,i,r,s,`$tokenBalance$${o.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Un(e);throw new N(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new s.TokenClassKey;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new s.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!e||"string"!=typeof e)throw R("vaultAddress","Vault address");try{const t=go(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof N)throw q("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!e||"string"!=typeof e)throw R("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw q("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw q("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw q("vaultAddress",'having at least 5 parts separated by "$"');const n=t[2];if(!n||!/^[A-Za-z]{1,10}$/.test(n))throw q("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,o){return`${e}$${t}$${n}$${o}`}parseTokenClassKeyString(e){try{return ro(e)}catch(e){if(e instanceof N)throw q("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Co(e,t,n){if(t<0||t>1)throw new Error(`Invalid slippage tolerance factor: ${t}. Must be between 0 and 1 (e.g., 0.05 for 5%)`);const o=new i(e);if(o.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const a=o.multipliedBy(t);let r;switch(n){case"buy-native":case"sell-exact":r=o.minus(a);break;case"buy-exact":case"sell-native":r=o.plus(a);break;default:throw new Error(`Unknown operation type: ${n}`)}return r.isLessThan(0)&&(r=new i(0)),r.toFixed()}class xo extends vn{constructor(e,t,n=!1,o,a,i=.05,r=.01){super(e,n),this.tokenResolver=t,this.walletProvider=o,this.userAddress=a,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=r,this.bundleEndpoint="/bundle",o&&a&&(this.signatureService=new Fo(o,n),this.tokenKeyService=new Do(n))}async submitTransaction(e){try{this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)}),this.validateBundleData(e);const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});const n=await this.http.post(this.bundleEndpoint,t);return n?(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:!!n.data,error:n.error}),this.handleBundleResponse(n)):{success:!1,error:"No response from bundle API"}}catch(e){return this.logger.error("❌ Bundle transaction submission failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}validateBundleData(e){if(!e)throw R("bundleData","Bundle data");if(!e.signedDto)throw R("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw R("method","Method name");if(!Array.isArray(e.stringsInstructions))throw q("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new N("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw q("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new N(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new N(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT")}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){if(e.data&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",e.data),{success:!0,data:e.data};const t=e.error||e.message||"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",t),{success:!1,error:t}}formatErrorMessage(e){if("string"==typeof e)return e;if(On(e)&&e.response){const t=e.response.data;if(t&&"object"==typeof t){const e=t;if(e.error)return String(e.error);if(e.message)return String(e.message)}}return Un(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw R("transactionId","Transaction ID");this.logger.debug("🔍 Checking bundler transaction result:",e);const t=await this.http.get(`${this.bundleEndpoint}?id=${e}`);return t?(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t}):{success:!1,error:"No response from bundler transaction query"}}catch(e){return this.logger.error("❌ Failed to get bundler transaction result:",e),{success:!1,error:this.formatErrorMessage(e)}}}async cancelTransaction(e){try{if(!e||"string"!=typeof e)throw R("transactionId","Transaction ID");this.logger.debug("🚫 Cancelling transaction:",e);const t=await this.http.delete(`${this.bundleEndpoint}/${e}`);return t?(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t}):{success:!1,error:"No response from transaction cancellation"}}catch(e){return this.logger.error("❌ Failed to cancel transaction:",e),{success:!1,error:this.formatErrorMessage(e)}}}async getHealthStatus(){try{this.logger.debug("🏥 Checking bundle service health");const e=await this.http.get(`${this.bundleEndpoint}/health`);return e?(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e}):{success:!1,error:"No response from bundle service health check"}}catch(e){return this.logger.error("❌ Bundle service health check failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:o,expectedAmount:a}=e,{effectiveSlippageFactor:i,effectiveMaxFee:r,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===o){if(!a)throw new N("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Co(a,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:a,slippageFactor:i,adjustedMinTokens:e});const t=new Po.BuyNativeDto(s,n,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"BuyWithNative",s)}{if(!a)throw new N("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Co(a,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:a,slippageFactor:i,adjustedMaxGalaCost:e});const t=new Po.BuyExactDto(s,n,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"BuyExactToken",s)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:o,expectedAmount:a}=e,{effectiveSlippageFactor:i,effectiveMaxFee:r,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===o){if(!a)throw new N("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Co(a,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:a,slippageFactor:i,adjustedMinGala:e});const t=new Po.SellExactDto(s,n,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"SellExactToken",s)}{if(!a)throw new N("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Co(a,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:a,slippageFactor:i,adjustedMaxTokensToSell:e});const t=new Po.SellNativeDto(s,n,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"SellWithNative",s)}}async prepareTradingOperation(e,t,n,o){const{effectiveSlippageFactor:a,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,o),r=await this.resolveTokenNameToVault(e);if(!r)throw _(e);return{effectiveSlippageFactor:a,effectiveMaxFee:i,vaultAddress:r}}calculateEffectiveSlippage(e,t,n){const o=n??this.defaultSlippageToleranceFactor,a=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e||"0";return e&&(i=Co(e,a,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:a,adjustedMaxFee:i})),{effectiveSlippageFactor:o,effectiveFeeSlippageFactor:a,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw G("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw R("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${c.v4()}-${Date.now()}-${this.userAddress}`;const o=await this.signatureService.signDTO(e,t,this.userAddress),a=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:a,method:t,signedDto:o};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:a,dtoKeys:Object.keys(o)});const r=await this.submitTransaction(i);if(r.success&&r.data)return this.logger.debug("✅ Bundle transaction submitted:",r.data),{success:!0,data:{transactionId:r.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(r.error||"Bundle transaction failed"))}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}var $o,Lo;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}($o||($o={})),e.SDKTransactionStatus=void 0,(Lo=e.SDKTransactionStatus||(e.SDKTransactionStatus={})).PENDING="pending",Lo.PROCESSING="processing",Lo.COMPLETED="completed",Lo.FAILED="failed",Lo.TIMEOUT="timeout";const Bo={[$o.PROCESSED]:e.SDKTransactionStatus.COMPLETED,[$o.COMPLETED]:e.SDKTransactionStatus.COMPLETED,[$o.SUCCESS]:e.SDKTransactionStatus.COMPLETED,[$o.FAILED]:e.SDKTransactionStatus.FAILED,[$o.ERROR]:e.SDKTransactionStatus.FAILED,[$o.PROCESSING]:e.SDKTransactionStatus.PROCESSING,[$o.PENDING]:e.SDKTransactionStatus.PENDING};class Uo extends Tn{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.reconnectCount=0,this.hasOnAnyListener=!1,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof l.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.socket.onAny((e,...t)=>{if(e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],o=n.status||n.Status;if(o&&"string"==typeof o){if(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${o}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE){const e=this.eventBuffer.keys().next().value;if(e){const t=this.eventBufferTimeouts.get(e);t&&(clearTimeout(t),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e),this.logger.warn(`📡 [Event Buffer] Buffer full (${this.MAX_BUFFER_SIZE}), dropped oldest: ${e}`)}}this.eventBuffer.set(e,n);const t=this.eventBufferTimeouts.get(e);t&&clearTimeout(t);const a=setTimeout(()=>{this.eventBuffer.has(e)&&(this.logger.debug(`📡 [Event Buffer] Cleaning up orphaned event for ${e}`),this.eventBuffer.delete(e),this.eventBufferTimeouts.delete(e))},3e4);this.eventBufferTimeouts.set(e,a)}}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0}catch(e){t(e)}})}async monitorTransaction(t,n){this.listeners.set(t,n),this.logger.debug(`📡 Starting to monitor transaction: ${t}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const o=this.eventBuffer.get(t);if(o){this.logger.debug(`📡 [Event Buffer] Found buffered event for ${t}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(t,o,n)});const e=this.eventBufferTimeouts.get(t);e&&(clearTimeout(e),this.eventBufferTimeouts.delete(t)),this.eventBuffer.delete(t)}const a=this.config.timeout||3e5,i=setTimeout(()=>{if(this.listeners.has(t)){const o=Math.round(a/1e3),i={transactionId:t,status:e.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${o} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${t} (${o}s)`),n(i),this.listeners.delete(t),this.timeouts.delete(t),this.socket?.off(t)}},a);if(this.timeouts.set(t,i),this.socket&&this.socket.connected)this.socket.off(t),this.logger.debug(`📡 Listening for transaction updates: ${t}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(t,e=>{this.processTransactionEvent(t,e,n)});else{const o={transactionId:t,status:e.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};n(o),this.listeners.delete(t),this.timeouts.delete(t)}}processTransactionEvent(t,n,o){this.logger.debug(`📡 Socket.IO transaction update for ${t}:`,JSON.stringify(n,null,2));const a=n,i=a?.data,r=a?.status||a?.Status||i?.status||i?.Status;let s=a?.message||a?.Message||i?.message||i?.Message||a?.error||i?.error;s&&"string"==typeof s||(s=r===$o.FAILED||r===$o.ERROR?"Transaction failed - check transaction details":r===$o.COMPLETED||r===$o.PROCESSED||r===$o.SUCCESS?"Transaction completed successfully":r?`Transaction status: ${r}`:"Unknown transaction status");const c=a?.blockHash||i?.blockHash,l=a?.gasUsed||i?.gasUsed,u=a?.Data||i?.Data,d={transactionId:t,status:this.mapSocketStatus(r),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...c&&{blockHash:c},...l&&{gasUsed:l},...u&&{data:u}};if(this.logger.debug(`📡 Mapped status for ${t}: ${r} -> ${d.status}`),this.logger.debug(`📡 Final message: "${s}"`),o(d),d.status===e.SDKTransactionStatus.COMPLETED||d.status===e.SDKTransactionStatus.FAILED){this.listeners.delete(t);const e=this.timeouts.get(t);e&&(clearTimeout(e),this.timeouts.delete(t)),this.socket?.off(t),this.logger.debug(`📡 Cleaned up listener for ${t} (${d.status})`)}}async waitForTransaction(t){return new Promise((n,o)=>{this.monitorTransaction(t,t=>{t.status===e.SDKTransactionStatus.COMPLETED?n(t):t.status!==e.SDKTransactionStatus.FAILED&&t.status!==e.SDKTransactionStatus.TIMEOUT||o(new Error(`Transaction ${t.status}: ${t.message}`))})})}mapSocketStatus(t){const n=t?.toUpperCase();return Bo[n]||e.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectCount<this.config.reconnectAttempts?(this.reconnectCount++,this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectCount}/${this.config.reconnectAttempts}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.config.reconnectDelay)):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.eventBufferTimeouts.forEach(e=>{clearTimeout(e)}),this.eventBufferTimeouts.clear(),this.logger.debug("🧹 Cleared event buffer and timeouts"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected"))}isConnected(){return this.socket?.connected||!1}getSocket(){return this.socket}}class Oo extends Tn{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!j(e))throw new N("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");const t=e.trim().toLowerCase(),n=this.get(t);if(n)return n;try{const n=await this.poolService.resolveTokenNameToVault(e);return n&&this.set(t,n),n}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw _(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(e.toLowerCase())||null}set(e,t){this.cache.set(e.toLowerCase(),t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}parseVaultAddressToTokenClassKey(e){try{return uo(e)}catch(e){if(e instanceof N)throw q("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}async function _o(e,t={}){const{maxPages:n=1e4,logger:o,pageSize:a=20}=t,i=[];let r=1,s=!0,c=0;for(;s&&r<=n;){o&&o.debug(`Auto-pagination: fetching page ${r} with limit ${a}`);const t=await e(r,a);if(!t||!Array.isArray(t.items)){o&&o.warn("Auto-pagination: received invalid result structure, stopping");break}if(i.push(...t.items),c=t.total,o&&o.debug(`Auto-pagination: page ${r} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){o&&o.debug(`Auto-pagination: no items returned on page ${r}, exiting loop`);break}s=t.hasNext,r++}return r>n&&o&&o.warn(`Auto-pagination: exceeded maxPages limit of ${n}, stopping iteration`),o&&o.debug(`Auto-pagination: completed with total items: ${i.length}, total count: ${c}`),{items:i,total:c}}function Ro(e,t=e.length,n="items"){return{...{page:1,limit:e.length||0,total:t,totalPages:Math.ceil(t/(e.length||1))||1,hasNext:!1,hasPrevious:!1},[n]:e}}class qo extends vn{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw G("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");if(!e||"string"!=typeof e||e.length<3||e.length>20)throw G("Token name must be a string between 3 and 20 characters","tokenName");this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(!t)throw G(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=uo(t),o=`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`;return this.logger.debug(`Extracted token class key: ${o}`),o}catch(t){if(t instanceof Error&&t.message.includes("ConfigurationError"))throw t;throw M(`Failed to resolve token name '${e}': ${Un(t)}`,500)}}async fetchPriceHistory(e){this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e);try{let t=e.tokenId;if(e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const n=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=n,this.logger.debug(`Resolved to token ID: ${n}`)}if(!t)throw G("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return po}),o=n(t),a=io(`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`),{from:i,to:r,sortOrder:s="DESC",page:c=1,limit:l=10}=e,u={token:a,page:String(c),limit:String(l)};i&&(u.from=i.toISOString()),r&&(u.to=r.toISOString());const d=function(e){if(e)return e.toLowerCase()}(s);d&&(u.order=d),this.logger.debug(`Querying price snapshots for token ${a}, page ${c}, limit ${l}`);const h=await this.http.get("/price-oracle/fetch-price",u);if(!h)throw M("No response from price history service",500);const g=this.transformApiResponseToPriceHistory(h);return this.logger.debug(`Found ${g.snapshots.length} price snapshots, total ${g.total}`),g}catch(e){if(e instanceof Error&&(e.message.includes("ConfigurationError")||e.message.includes("NetworkError")))throw e;throw M(`Failed to fetch price history: ${Un(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw M("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw M("Invalid API response: missing data.meta pagination info",500);const t=e.data.data.map(e=>({price:e.price,timestamp:new Date(e.createdAt),tokenId:`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`})),n=e.data.meta,o=n.currentPage??1,a=n.totalPages??1;return{snapshots:t,page:o,limit:n.pageSize??50,total:n.totalItems??0,totalPages:a,hasNext:o<a,hasPrevious:o>1}}async fetchAllPriceHistory(e){this.logger.debug("Fetching all price history with options:",e);const t=await _o((t,n)=>this.fetchPriceHistory({...e,page:t,limit:n}).then(e=>({items:e.snapshots,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:50});return Ro(t.items,t.total,"snapshots")}validateOptions(e){const{from:t,to:n,sortOrder:o,page:a=1,limit:i=10}=e;if(function(e,t,n,o={}){const{description:a="parameter",treatEmptyAsNull:i=!0}=o,r=e[t],s=e[n],c=null!=r&&(!i||""!==r),l=null!=s&&(!i||""!==s);if(!c&&!l)throw G(`Either ${t} or ${n} must be provided (${a})`,n);if(c&&l)throw G(`Cannot provide both ${t} and ${n}. Provide exactly one (${a}).`,n)}(e,"tokenName","tokenId",{description:"token identifier"}),t&&!(t instanceof Date)&&isNaN(new Date(t).getTime()))throw G("from must be a valid Date","from");if(n&&!(n instanceof Date)&&isNaN(new Date(n).getTime()))throw G("to must be a valid Date","to");if(o&&"ASC"!==o&&"DESC"!==o)throw G('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(a)||a<1)throw G("page must be a positive integer","page");if(!Number.isInteger(i)||i<1||i>50)throw G("limit must be between 1 and 50","limit")}}function Mo(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new N("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:o,additionalKey:a}=e;if(!t||"string"!=typeof t)throw new N("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!n||"string"!=typeof n)throw new N("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!o||"string"!=typeof o)throw new N("Token.type must be a non-empty string, got "+typeof o,"token.type","MISSING_OR_INVALID_TYPE");if(!a||"string"!=typeof a)throw new N("Token.additionalKey must be a non-empty string, got "+typeof a,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:o,additionalKey:a}}(e);if(!e)throw new N(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new N("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(e.includes("|"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected 4+ parts separated by |, got ${t.length}`);const[n,o,a,...i]=t;if(!n||!o||!a)throw new Error("Collection, category, and type must be non-empty");const r=i.join("|");if(!r)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:o,type:a,additionalKey:r}}catch(t){const n=e.split("|");throw new N(`Invalid pipe-delimited token: "${e}" (${n.length} parts). Expected format: "collection|category|type|additionalKey" (4 parts minimum). Received: [${n.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_PIPE_DELIMITED_TOKEN")}}(e);if(e.includes("$"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected 4+ parts separated by $, got ${t.length}`);const n=t[t.length-1],o=t[t.length-2],a=t[t.length-3],i=t.slice(0,t.length-3).join("$");if(!(i&&a&&o&&n))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:a,type:o,additionalKey:n}}catch(t){const n=e.split("$");throw new N(`Invalid dollar-delimited token: "${e}" (${n.length} parts). Expected format: "collection$category$type$additionalKey" (4 parts minimum). Received: [${n.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e);throw new N(`Plain token string "${e}" (length: ${e.length}) is not allowed - tokens must be delimited with | or $. Expected format: "GALA|Unit|none|none" or "GALA$Unit$none$none". Input: "${e}"`,"token","PLAIN_STRING_NOT_ALLOWED")}class Go extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function Ko(e){return"object"==typeof e&&null!==e&&"positionId"in e&&"owner"in e&&"token0"in e&&"token1"in e&&"fee"in e&&"liquidity"in e&&"string"==typeof e.positionId&&"string"==typeof e.owner&&"number"==typeof e.fee}class zo{constructor(e){this.client=t.create({baseURL:e.baseUrl,timeout:e.timeout??3e4})}async getPoolData(e){try{const n=await this.client.post("/api/asset/dexv3-contract/GetPoolData",e);this.validateResponse(n.data);const o=n.data.Data;if(!("object"==typeof(t=o)&&null!==t&&"token0"in t&&"token1"in t&&"fee"in t&&"liquidity"in t&&"sqrtPriceX96"in t&&"tick"in t&&"tickSpacing"in t&&"number"==typeof t.fee&&"number"==typeof t.tick&&"number"==typeof t.tickSpacing))throw new Go(n.status,"Invalid pool data response format",o);return o}catch(e){throw this.handleError(e,"getPoolData")}var t}async getPositions(e){try{const t=await this.client.post("/api/asset/dexv3-contract/GetPositions",e);this.validateResponse(t.data);const n=t.data.Data;if(!Array.isArray(n.positions))throw new Go(t.status,"Invalid positions response format: positions must be an array",n);for(const e of n.positions)if(!Ko(e))throw new Go(t.status,"Invalid position in response",e);return n}catch(e){throw this.handleError(e,"getPositions")}}async getPositionById(e){try{const t=await this.client.post("/api/asset/dexv3-contract/GetPositions",{positionId:e});this.validateResponse(t.data);const n=t.data.Data;if(!Array.isArray(n.positions)||0===n.positions.length)throw new Go(404,`Position not found: ${e}`);const o={Data:n.positions[0],Status:t.status};return void 0!==t.data.Message&&(o.Message=t.data.Message),o}catch(t){throw this.handleError(t,`getPositionById(${e})`)}}async getRemoveLiquidityEstimation(e){try{const t=await this.client.post("/api/asset/dexv3-contract/GetRemoveLiquidityEstimation",e);this.validateResponse(t.data);const n=t.data.Data;if("string"!=typeof n.amount0||"string"!=typeof n.amount1||"string"!=typeof n.fee0||"string"!=typeof n.fee1)throw new Go(t.status,"Invalid removal estimation response format",n);return n}catch(e){throw this.handleError(e,"getRemoveLiquidityEstimation")}}validateResponse(e){if(!e||"object"!=typeof e)throw new Go(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new Go(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new Go(e.Status,e.Message??"Gateway error",e.Data)}handleError(e,n){if(e instanceof Go)return e;if(t.isAxiosError(e)){const t=e.response?.status??500,o=e.response?.data?.Message??e.message,a=e.response?.data?.Data??void 0;return new Go(t,`${n}: ${o}`,a)}return new Go(500,`${n}: ${e instanceof Error?e.message:String(e)}`)}}class Vo{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){try{if(!e||"string"!=typeof e)throw new Go(400,"Invalid wallet address");const o=Math.max(1,Math.floor(n/t)+1),a={};a.address=e,a.page=o,a.limit=t;const i=await this.http.get("/user/assets",a);if(!i||"object"!=typeof i)throw new Go(500,"Invalid response format: not an object");const r=i.data;if(!r||"object"!=typeof r)throw new Go(500,"Invalid response format: missing data wrapper");const s=r.token;if(!Array.isArray(s))throw new Go(500,"Invalid response format: token array must be an array");const c=[];for(const e of s){if("object"!=typeof e||null===e)throw new Go(500,"Invalid asset in response: asset must be an object");const t=e;if("string"!=typeof t.symbol||"string"!=typeof t.name)throw new Go(500,"Invalid asset in response: missing symbol or name",t);const n="number"==typeof t.decimals?t.decimals:"string"==typeof t.decimals?parseInt(t.decimals,10):void 0;if("number"!=typeof n||isNaN(n))throw new Go(500,"Invalid asset in response: decimals must be a number",t);const o={tokenId:t.compositeKey||`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:n,balance:t.quantity||"0"};t.image&&(o.imageUrl=t.image),t.verify&&(o.verified=t.verify),c.push(o)}const l={tokens:c,count:r.count??c.length};return void 0!==r.totalValue&&(l.totalValue=r.totalValue),l}catch(t){throw this.handleError(t,`getUserAssets(${e})`)}}handleError(e,t){if(e instanceof Go)return e;if(e instanceof Error&&e instanceof Error&&"response"in e){const n=e,o=n.response?.status??500,a=n.response?.data?.message??n.response?.data?.Message??n.message,i=n.response?.data?.Data??n.response?.data?.data??void 0;return n.response,new Go(o,`${t}: ${a}`,i)}return new Go(500,`${t}: ${e instanceof Error?e.message:String(e)}`)}}const jo=10;class Wo extends Tn{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new ao,this.webSocketService=t,this.dexQuoteService=n,this.getWalletAddress=e.getWalletAddress,this.galaChainBaseUrl=e.galaChainBaseUrl,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.privateKey=e.privateKey,!(e.gatewayBaseUrl&&e.bundlerBaseUrl&&e.dexBackendBaseUrl&&e.dexBackendHttp))throw new Error("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.");try{this.gatewayClient=new zo({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new Vo(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{gatewayUrl:e.gatewayBaseUrl,dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new Error("Failed to initialize GSwapService HTTP clients")}}setPricingConcurrency(e){if(e<1)throw new Error("Pricing concurrency must be at least 1");e>100&&this.logger.warn("Pricing concurrency > 100 may cause performance issues",{concurrency:e}),this.pricingConcurrency=e,this.logger.debug("Updated pricing concurrency",{concurrency:this.pricingConcurrency})}async getSwapQuoteExactInput(e){try{if(new i(e.amount).isLessThanOrEqualTo(0))throw new C("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new C("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),o=[3e3,500,1e4];let a;for(const r of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:n,fee:r,gatewayBaseUrl:this.gatewayBaseUrl}),a=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),s=new i(a.currentSqrtPrice),c=new i(a.newSqrtPrice),l=s.gt(c)?s.minus(c).dividedBy(s):new i(0),u=new i(a.amount0),d=new i(a.amount1),h=String(a.amount0),g=String(a.amount1),p=u.isNegative(),m=d.isNegative();this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":h,"quoteResult.amount1":g,"amount0BN.isNegative()":p,"amount1BN.isNegative()":m,"amount0BN.toFixed()":u.toFixed(),"amount1BN.toFixed()":d.toFixed(),"amount0BN.s (sign flag)":u.s,"amount1BN.s (sign flag)":d.s});const f=p?m?u:d:u;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:!p,selectedAmount:f.toFixed(),selectedAmountAbs:f.absoluteValue().toFixed()});const y=f.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:y,feeTier:r,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,y),currentSqrtPrice:a.currentSqrtPrice,newSqrtPrice:a.newSqrtPrice}}catch(e){a=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:r,error:e?.message})}throw a||new C("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",C,e)}}async getSwapQuoteExactOutput(e){try{if(new i(e.amount).isLessThanOrEqualTo(0))throw new C("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new C("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact output",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),o=[3e3,500,1e4];let a;for(const r of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:n,fee:r,gatewayBaseUrl:this.gatewayBaseUrl}),a=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),s=new i(a.currentSqrtPrice),c=new i(a.newSqrtPrice),l=s.gt(c)?s.minus(c).dividedBy(s):new i(0),u=o.pool.token0,d="string"==typeof u?u.split("|")[0]:u?.tokenName||u,h=n.split("|")[0]===d?a.amount1:a.amount0,g=h.toFixed?.()||String(h);return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:g,estimatedOutput:e.amount,feeTier:r,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(g,e.amount),currentSqrtPrice:a.currentSqrtPrice,newSqrtPrice:a.newSqrtPrice}}catch(e){a=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:r,error:e?.message})}throw a||new C("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",C,e)}}async executeSwap(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");this.logger.debug("Executing swap",{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),o=function(e,t=.01){const n=Zn(e),o=new i(1).minus(t);return n.multipliedBy(o)}(e.estimatedOutput,e.slippageTolerance||.01),a=this.getWalletAddress();if(!a)throw new Error("Wallet address required for swap execution");let r;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});r=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:r,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:t?.message})}const s={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:o.toFixed(),feeTier:e.feeTier,walletAddress:a,slippageTolerance:e.slippageTolerance||.01};void 0!==r&&(s.currentSqrtPrice=r);const c=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:c,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const l=await this.webSocketService.waitForTransaction(c);return{transactionId:l.transactionId,status:l.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(l.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(c)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",x,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){try{this.logger.debug("Fetching user assets",{walletAddress:e,page:t,limit:n});const o=await this.dexBackendClient.getUserAssets(e,n,(t-1)*n);return(Array.isArray(o)?o:o?.tokens||[]).map(e=>{const t=e.symbol||"UNKNOWN";try{return{tokenId:Mo(`${t}|Unit|none|none`),symbol:t,balance:(n=e.quantity||e.balance||0,void 0!==o?Zn(n).toFixed(o):Zn(n).toFixed()),decimals:e.decimals||18}}catch(n){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:n instanceof Error?n.message:String(n),assetData:{symbol:t,quantity:e.quantity,balance:e.balance,decimals:e.decimals}}),null}var n,o}).filter(e=>null!==e)}catch(o){this.handleGSwapError("Failed to fetch user assets",L,o,{walletAddress:e,page:t,limit:n})}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets (auto-paginated)",{walletAddress:e});const t=await _o((t,n)=>this.getUserAssets(e,t,n).then(e=>({items:e,page:t,limit:n,total:e.length,totalPages:1,hasNext:e.length===n,hasPrevious:t>1})),{maxPages:1e4,logger:this.logger,pageSize:20});return this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:t.items.length}),t.items}catch(t){this.handleGSwapError("Failed to fetch all user assets",L,t,{walletAddress:e})}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:o}=this.convertTokenPair(e,t),a=[500,3e3,1e4];let r=new i(0),s=0;for(const c of a)try{const e=await this.gatewayClient.getPoolData({tokenA:n,tokenB:o,feeTier:c});e&&(r=r.plus(new i(e.liquidity||0)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:c})}return{tokenA:e,tokenB:t,liquidity:r.toFixed(),feeTiers:a,swapCount:s}}catch(n){this.logger.warn("Failed to fetch pool info",n);const o=n;return this.logger.debug("Pool error details",{error:new $(`Failed to fetch pool info: ${o?.message||String(n)}`,n,e,t,this.extractGSwapErrorCode(n))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const n=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;n.has(e)||n.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const o=Array.from(n.values()),a=this.chunkArray(o,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:a.length,concurrency:t});const i=new Map;for(let e=0;e<a.length;e++){const t=a[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?i.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return i}normalizePositionResponse(e,t){const n=e=>{if(!e)return"";if("string"==typeof e)return e;if("object"==typeof e){if(e.type&&"none"!==e.type)return e.type;if(e.collection)return e.collection;if(e.symbol)return e.symbol;if(e.tokenSymbol)return e.tokenSymbol;if(e.name)return e.name}return""};return{positionId:e.positionId||e.id||"",ownerAddress:t||e.ownerAddress||e.owner||"",token0:e.token0Symbol||n(e.token0)||n(e.tokenA)||e.tokenSymbol0||"",token1:e.token1Symbol||n(e.token1)||n(e.tokenB)||e.tokenSymbol1||"",feeTier:e.feeTier||e.fee||e.feeAmount||0,tickLower:e.tickLower||e.lowerTick||0,tickUpper:e.tickUpper||e.upperTick||0,liquidity:String(e.liquidity||e.liquidityAmount||"0"),amount0:String(e.amount0||e.amountA||"0"),amount1:String(e.amount1||e.amountB||"0"),feeAmount0:String(e.feeAmount0||e.feesA||"0"),feeAmount1:String(e.feeAmount1||e.feesB||"0"),...e.createdAt&&{createdAt:new Date(e.createdAt)},...e.updatedAt&&{updatedAt:new Date(e.updatedAt)}}}parseTokenFlexible(e){try{return Mo(e)}catch(t){if(t instanceof Error&&t.message?.includes("Plain token string"))return this.logger.debug("Using default TokenClassKey for simple token symbol",{token:e}),{collection:"Token",category:"Unit",type:e,additionalKey:"none"};throw t}}async getUserLiquidityPositions(e,n=10,o,a){try{this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:n,bookmark:o});const i=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,r={user:e,limit:n,bookmark:o||""};this.logger.debug("Sending position query request",{endpoint:i,payload:r});const s=await t.post(i,r,{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==s.status||1!==s.data?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:s.status,apiStatus:s.data?.Status}),{items:[]};const c=s.data.Data||{},l=c.positions||[],u=c.nextBookMark,d=l.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(t=>this.normalizePositionResponse(t,e));let h;this.logger.debug("Retrieved liquidity positions",{count:d.length,hasNextBookmark:!!u,nextBookmark:u}),a?.withPrices&&d.length>0&&(h=await this.fetchPositionPrices(d));const g={items:d};return void 0!==u&&(g.nextBookmark=u),void 0!==h&&(g.prices=h),g}catch(t){if(t&&"object"==typeof t&&"response"in t){const n=t;this.logger.error("Position query failed with HTTP error",{status:n.response?.status,statusText:n.response?.statusText,data:n.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:e})}this.handleGSwapError("Failed to fetch user liquidity positions",B,t)}}async getAllSwapUserLiquidityPositions(e,t){try{this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const n=async t=>{const n=await this.getUserLiquidityPositions(e,jo,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},o=await async function(e,t={}){const{maxPages:n=1e4,logger:o,pageSize:a=20}=t,i=[];let r,s=0;for(;s<n;){o&&o.debug(`Auto-pagination (bookmark): fetching page ${s+1} with pageSize ${a}`,{bookmark:r});const t=await e(r,a);let n,c,l;if(Array.isArray(t))n=t,c=void 0,l=!1;else{if(!t||"object"!=typeof t||!("items"in t)){o&&o.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}n=t.items,c=t.nextBookmark,l=!0}if(!Array.isArray(n)){o&&o.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===n.length){o&&o.debug(`Auto-pagination (bookmark): no items returned on page ${s+1}, exiting loop`);break}i.push(...n),s++,o&&o.debug(`Auto-pagination (bookmark): page ${s} returned ${n.length} items`,{hasNextBookmark:!!c,format:l?"BookmarkPaginationResult":"legacy-array"});const u=n.length<a;if(l&&(""===c||void 0===c)){o&&o.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(u){o&&o.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:n.length,pageSize:a,format:l?"BookmarkPaginationResult":"legacy-array"});break}r=c}return s>=n&&o&&o.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${n}, stopping iteration`),o&&o.debug(`Auto-pagination (bookmark): completed with total items: ${i.length}`,{pageCount:s}),{items:i,total:i.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:jo}),a=o.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:a.length}),t?.withPrices&&a.length>0){return{items:a,prices:await this.fetchPositionPrices(a)}}return a}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",B,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t});const{gswapToken0:n,gswapToken1:o}=this.convertTokenPair(t.token0,t.token1),a=(await this.gatewayClient.getPositions({owner:e,tokenA:n,tokenB:o,feeTier:t.fee})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!a||"object"!=typeof a||!("positionId"in a)&&!("id"in a))throw new Error("Invalid position data returned from API");const i=this.normalizePositionResponse(a,e);return this.logger.debug("Retrieved liquidity position",{positionId:i.positionId}),i}catch(e){this.handleGSwapError("Failed to fetch liquidity position",B,e)}}async getLiquidityPositionById(e,t){try{let n;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t});let o=null;const a=5,i=2e3;for(let e=1;e<=a;e++)try{if(n=(await this.gatewayClient.getPositionById(t)).Data,n&&"object"==typeof n&&("positionId"in n||"id"in n)){this.logger.debug("Successfully fetched position on attempt",{attempt:e,positionId:t});break}if(e<a){this.logger.warn("Position not yet indexed, retrying",{attempt:e,positionId:t,resultType:typeof n}),await new Promise(e=>setTimeout(e,i));continue}o=new Error("Position not found after retries")}catch(n){if(e<a){this.logger.warn("Error fetching position, retrying",{attempt:e,positionId:t,error:n instanceof Error?n.message:n}),await new Promise(e=>setTimeout(e,i));continue}o=n instanceof Error?n:new Error(String(n))}if(!n||"object"!=typeof n||!("positionId"in n)&&!("id"in n))throw this.logger.error("Invalid position data returned from API after retries",{positionId:t,resultType:typeof n,resultKeys:n?Object.keys(n):"null",resultValue:JSON.stringify(n),lastError:o?.message}),o||new Error("Invalid position data returned from API");const r=this.normalizePositionResponse(n,e);return this.logger.debug("Retrieved liquidity position by ID",{positionId:r.positionId}),r}catch(e){this.handleGSwapError("Failed to fetch liquidity position by ID",B,e)}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t="string"==typeof e.token0?this.parseTokenFlexible(e.token0):e.token0,n={token0:t,token1:"string"==typeof e.token1?this.parseTokenFlexible(e.token1):e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner},o=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetPositions`;this.logger.debug("Calling position endpoint via compound key",{url:o});const a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!a.ok){if(404===a.status)throw new Error("Position not found (HTTP 404): No position exists for this compound key");if(400===a.status)throw new Error("Invalid parameters (HTTP 400): Check token format, fee (500|3000|10000), and tick ranges");throw new Error(`HTTP ${a.status}: ${a.statusText}`)}const i=await a.json();if(1!==i.Status||!i.Data)throw new Error(`Position not found: ${i.Message||"API returned no position data"}`);const r=this.normalizePositionResponse(i.Data,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:r.positionId,token0:r.token0,token1:r.token1}),r}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",B,e)}}async estimateRemoveLiquidity(e){try{this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1),o=await this.gatewayClient.getRemoveLiquidityEstimation({tokenA:t,tokenB:n,fee:e.fee,liquidity:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper});return this.logger.debug("Estimated removal",{result:o}),o}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",B,e)}}async addLiquidityByPrice(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected(),this.logger.debug("Converting price range to ticks",{token0:e.token0,token1:e.token1,minPrice:e.minPrice,maxPrice:e.maxPrice,fee:e.fee});const o=(await this.gatewayClient.getPoolData({tokenA:t,tokenB:n,feeTier:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:o,fee:e.fee});const a=new i(e.minPrice),r=new i(e.maxPrice),s=Math.floor(Jn(a)),c=Math.ceil(Jn(r)),l=Math.floor(s/o)*o,u=Math.ceil(c/o)*o;this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:l,tickUpper:u,tickSpacing:o});const d=this.getWalletAddress();if(!d)throw new Error("GSwapService: No wallet address available - cannot create position");const h="string"==typeof e.token0?Mo(e.token0):e.token0,g="string"==typeof e.token1?Mo(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${l}-${u}`,walletAddress:d});const p=await this.sendAddLiquidityToBundler({token0:h,token1:g,fee:e.fee,tickLower:l,tickUpper:u,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:d}),m={transactionId:p};if(m.positionId&&p){this.logger.debug("Position ID returned directly from backend",{transactionId:p,positionId:m.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(p);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:e.status});const t=this.getWalletAddress();if(t&&m.positionId)try{const n=await this.getLiquidityPositionById(t,m.positionId);return{...m,...n,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}catch(t){return{...m,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}}if(p){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:p}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(p);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:t.status});let o=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");const a=(await this.getUserLiquidityPositions(t,10)).items;if(a&&a.length>0){const t=e.token0.split("|")[0].toUpperCase(),i=e.token1.split("|")[0].toUpperCase(),r=[];for(const n of a){if(!n||!n.positionId)continue;const o=n.token0?.toUpperCase(),a=n.token1?.toUpperCase();if(!o||!a)continue;const s=o===t&&a===i||o===i&&a===t,c=n.feeTier===e.fee;s&&c&&r.push(n)}r.length>0&&(o=r[r.length-1],n=o.positionId,this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:a.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}let a=o;if(n)try{a=await this.getLiquidityPositionById(d,n)}catch(e){}return{...m,...a,positionId:n,status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),{...m,positionId:void 0}}catch(e){Error,this.handleGSwapError("Failed to add liquidity by price",B,e)}}async addSwapLiquidityByTicks(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");const t=this.getWalletAddress();if(!t)throw new Error("GSwapService: No wallet address available - cannot create position");this.logger.debug("Adding liquidity by ticks with direct bundler",{token0:e.token0,token1:e.token1,fee:e.fee,walletAddress:t,tickRange:`${e.tickLower}-${e.tickUpper}`});const n="string"==typeof e.token0?Mo(e.token0):e.token0,o="string"==typeof e.token1?Mo(e.token1):e.token1;await this.ensureWebSocketConnected();const a=await this.sendAddLiquidityToBundler({token0:n,token1:o,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:t});this.logger.info("Liquidity transaction submitted to bundler",{transactionId:a});const i=this.webSocketService.waitForTransaction(a),r={transactionId:a};if(r.positionId&&a){this.logger.info("Position ID returned directly from backend",{transactionId:a,positionId:r.positionId});const e=await i;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:a,status:e.status});const t=this.getWalletAddress();if(t&&r.positionId)try{this.logger.debug("Fetching full position details",{positionId:r.positionId});const n=await this.getLiquidityPositionById(t,r.positionId);return this.logger.debug("Fetched full position data",{positionId:n.positionId,liquidity:n.liquidity,amount0:n.amount0,amount1:n.amount1}),{...r,...n,positionId:r.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:r.positionId,error:t instanceof Error?t.message:String(t)}),{...r,positionId:r.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}}if(a){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:a});const n=await i;let o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:a,status:n.status});let s=null;const c="string"==typeof e.token0?e.token0:e.token0.type,l="string"==typeof e.token1?e.token1:e.token1.type;this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:l,fee:e.fee});try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:jo});const n=3,a=5e3,i=3e3;let r=[];for(let c=1;c<=n;c++){const l=1===c?a:i;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:n,delayMs:l}),await new Promise(e=>setTimeout(e,l)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:jo});if(r=(await this.getUserLiquidityPositions(t,jo)).items,this.logger.debug("Got positions from API",{count:r?.length||0}),r&&r.length>0){const t=("string"==typeof e.token0?e.token0.split("|")[0]:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?e.token1.split("|")[0]:e.token1.collection).toUpperCase(),a=[];for(const o of r){if(!o||!o.positionId)continue;const i=o.token0?.toUpperCase(),r=o.token1?.toUpperCase();if(!i||!r){this.logger.debug("Skipping position with empty tokens",{positionId:o.positionId});continue}const s=i===t&&r===n||i===n&&r===t,c=o.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:o.positionId,tokens:`${i}/${r}`,tokensMatch:s,fee:o.feeTier,feeMatches:c}),s&&c&&a.push(o)}if(a.length>0){s=a[a.length-1],o=s.positionId,this.logger.info("Found newly created position",{positionId:o,liquidity:s.liquidity,amount0:s.amount0,amount1:s.amount1,fee:s.feeTier}),this.logger.debug("Found newly created position",{positionId:o,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:r.length});break}this.logger.debug("No matching position found in this attempt")}else this.logger.debug("No positions returned from API in this attempt")}}catch(e){this.logger.error("Error fetching positions during discovery",{error:e instanceof Error?e.message:String(e)}),this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}this.logger.debug("Position discovery complete",{positionId:o||"not found",found:!!o}),this.logger.debug("Matched position data",{positionId:s?.positionId,liquidity:s?.liquidity,amount0:s?.amount0,amount1:s?.amount1,feeAmount0:s?.feeAmount0,feeAmount1:s?.feeAmount1,token0:s?.token0,token1:s?.token1,feeTier:s?.feeTier});let u=s;if(o)try{this.logger.debug("Fetching full position details",{positionId:o}),u=await this.getLiquidityPositionById(t,o),this.logger.debug("Fetched full position data",{positionId:u.positionId,liquidity:u.liquidity,amount0:u.amount0,amount1:u.amount1,feeAmount0:u.feeAmount0,feeAmount1:u.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:o,error:e instanceof Error?e.message:String(e)})}return{...r,...u,positionId:o,status:n.status,transactionId:n.transactionId,timestamp:new Date(n.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),{...r,positionId:void 0}}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",B,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let o;try{o=await t,this.logger.debug(`${n} transaction confirmed on-chain`,{transactionId:e,status:o.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${n} transaction, returning result with transaction ID`,{transactionId:e,error:t instanceof Error?t.message:String(t)}),{transactionId:e,status:"SUBMITTED",timestamp:new Date,wait:async t=>{try{await this.webSocketService.waitForTransaction(e)}catch{this.logger.debug("Explicit wait also timed out",{transactionId:e})}}}}return{transactionId:o.transactionId,status:o.status,timestamp:new Date(o.timestamp),wait:async t=>{await this.webSocketService.waitForTransaction(e)}}}async removeLiquidity(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});try{const t=parseFloat(e.liquidity);if(isNaN(t))throw new Error(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${e.positionId||"unknown"}`);if(0===t)throw new Error(`Cannot remove zero liquidity from position. This would waste gas fees without any effect. Position ID: ${e.positionId||"unknown"}`)}catch(e){if(e instanceof Error&&e.message.includes("Cannot remove zero liquidity"))throw e;if(e instanceof Error&&e.message.includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?Mo(e.token0):e.token0,n="string"==typeof e.token1?Mo(e.token1):e.token1;await this.ensureWebSocketConnected();const o=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,n,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||"");this.logger.debug("Liquidity removal submitted to bundler",{transactionId:o});const a=this.webSocketService.waitForTransaction(o);return this.monitorBundlerTransaction(o,a,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",B,e)}}async collectPositionFees(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0.type,token1:"string"==typeof e.token1?e.token1:e.token1.type,tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?Mo(e.token0):e.token0,n="string"==typeof e.token1?Mo(e.token1):e.token1;await this.ensureWebSocketConnected();const o=await this.sendCollectPositionFeesToBundler(t,n,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||"");this.logger.debug("Fee collection submitted to bundler",{transactionId:o});const a=this.webSocketService.waitForTransaction(o);return this.monitorBundlerTransaction(o,a,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",B,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:o,gswapToken1:a}=this.convertTokenPair(e,t),r=await this.gatewayClient.getPoolData({tokenA:o,tokenB:a,feeTier:n}),s=this.calculatePriceFromSqrtPriceX96(new i(r.sqrtPriceX96));return{tokenA:e,tokenB:t,feeTier:n,liquidity:r.liquidity.toString(),sqrtPriceX96:r.sqrtPriceX96.toString(),tick:r.tick,feeGrowthGlobal0X128:r.feeGrowthGlobal0X128.toString(),feeGrowthGlobal1X128:r.feeGrowthGlobal1X128.toString(),currentPrice:s.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",$,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const o=await this.getPoolData(e,t,n),a=Zn(o.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:a.toFixed(),invertedPrice:eo(a,!0),tick:o.tick,liquidity:o.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",$,e)}}async calculateOptimalPositionSize(e,t,n,o,a,s,c){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:o,desiredAmount1:a});const l=(await this.getPoolData(e,t,n)).tick,u=r.tickToSqrtPrice(s),d=r.tickToSqrtPrice(l),h=r.tickToSqrtPrice(c),g=r.getLiquidityForAmounts(new i(o),new i(a),u,d,h),p=r.getAmountsForLiquidity(g,d,u,h),m=p[0],f=p[1],y=new i(o),w=new i(a);return{amount0:m.toFixed(),amount1:f.toFixed(),liquidity:g.toFixed(),ratio:m.dividedBy(f).toFixed(),utilizationPercent:{amount0:m.dividedBy(y).multipliedBy(100).toFixed(2),amount1:f.dividedBy(w).multipliedBy(100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",B,e)}}async validatePositionParameters(e,t,n,o,a,r,s){const c=[],l=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:o,tickUpper:a});const u=[500,3e3,1e4];u.includes(n)||c.push(`Invalid fee tier: ${n}. Must be one of: ${u.join(", ")}`);const d=this.getTickSpacing(n);let h;o%d!==0&&c.push(`tickLower must be multiple of ${d}`),a%d!==0&&c.push(`tickUpper must be multiple of ${d}`),o>=a&&c.push(`tickLower (${o}) must be less than tickUpper (${a})`);try{h=await this.getPoolData(e,t,n)}catch{return c.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}const g=new i(r),p=new i(s);if(g.isNaN()||p.isNaN())c.push("Amounts must be valid numbers");else try{to(g,p)}catch(e){c.push(`Liquidity amounts must be non-negative: ${e.message}`)}const m=h.tick;(m<o||m>a)&&l.push("Position is out of current price range - will not earn fees until price moves into range");new i(h.liquidity).lt("1000000")&&l.push("Low pool liquidity - consider higher slippage tolerance");const f=0===c.length?35e4:0;return{valid:0===c.length,errors:c,warnings:l,gasEstimate:f,tickSpacing:d,currentTick:m,poolLiquidity:h.liquidity}}catch(e){const t=e;return c.includes(t?.message||"")||c.push(`Validation failed: ${t?.message||String(e)}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}}async calculateTicksForPrice(e,t,n,o,a){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:o});const r=this.getTickSpacing(a),s=new i(n),c=new i(o);if(s.gte(c))throw new Error("minPrice must be less than maxPrice");const l=Math.floor(Jn(s)),u=Math.ceil(Jn(c)),d=Math.floor(l/r)*r,h=Math.ceil(u/r)*r,g=Math.pow(1.0001,d),p=Math.pow(1.0001,h),m=new i(g),f=new i(p);return{tokenA:e,tokenB:t,feeTier:a,tickLower:d,tickUpper:h,tickSpacing:r,requestedMinPrice:n,requestedMaxPrice:o,actualMinPrice:m.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:m.minus(s).dividedBy(s).multipliedBy(100).toFixed(4),maxPriceDeviation:f.minus(c).dividedBy(c).multipliedBy(100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",B,e)}}async calculatePriceForTicks(e,t,n,o){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:o});const a=Math.pow(1.0001,n),r=Math.pow(1.0001,o);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const c=new i(a),l=new i(r);return{tokenA:e,tokenB:t,tickLower:n,tickUpper:o,minPrice:c.toFixed(8),maxPrice:l.toFixed(8),currentPrice:s,priceRange:`${c.toFixed(4)} - ${l.toFixed(4)}`,tickSpread:o-n}}catch(e){this.handleGSwapError("Failed to calculate price for ticks",B,e)}}calculateExecutionPrice(e,t){try{const n=new i(e),o=new i(t);return n.isZero()?"0":o.dividedBy(n).toFixed()}catch{return"0"}}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw new Error(`Invalid fee tier: ${e}`)}}calculatePriceFromSqrtPriceX96(e){try{const t=new i(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new i(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return new i(0)}}async getPoolSlot0(e,n,o){try{this.logger.debug("Fetching pool slot0 data",{token0:e,token1:n,fee:o});const a="string"==typeof e?Mo(e):e,i="string"==typeof n?Mo(n):n,r=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetSlot0`,s=await t.post(r,{token0:a,token1:i,fee:o},{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==s.status||1!==s.data?.Status)throw this.logger.warn("Unexpected GetSlot0 API response",{httpStatus:s.status,apiStatus:s.data?.Status}),new $("GetSlot0 API returned unexpected status",{httpStatus:s.status,apiStatus:s.data?.Status});const c=s.data.Data||{},l={sqrtPrice:c.sqrtPrice||"0",tick:c.tick||0,liquidity:c.liquidity||"0",grossPoolLiquidity:c.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:l.sqrtPrice,tick:l.tick,liquidity:l.liquidity}),l}catch(t){this.handleGSwapError("Failed to fetch pool slot0 data",$,t,{token0:e,token1:n,fee:o})}}async getPositionCurrentPrice(e){try{this.logger.debug("Fetching position current price",{token0:e.token0,token1:e.token1,feeTier:e.feeTier});const t=await this.getPoolSlot0(e.token0,e.token1,e.feeTier),n=new i(t.sqrtPrice),o={price:this.calculatePriceFromSqrtPriceDecimal(n).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:o.price,tick:o.tick}),o}catch(t){this.handleGSwapError("Failed to fetch position current price",$,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,n){try{const o=Yn(t),a=Yn(n);return r.liquidity0(e,o,a)}catch{return new i(0)}}calculateLiquidityFromAmount1(e,t,n){try{const o=Yn(t),a=Yn(n);return r.liquidity1(e,o,a)}catch{return new i(0)}}calculateAmount0FromLiquidity(e,t,n){try{const o=Yn(t),a=Yn(n);return r.getAmount0Delta(o,a,e)}catch{return new i(0)}}calculateAmount1FromLiquidity(e,t,n){try{const o=Yn(t),a=Yn(n);return r.getAmount1Delta(o,a,e)}catch{return new i(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(e){if(!this.privateKey)throw new Error("GSwapService: AddLiquidity requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:e.token0.type,token1:e.token1.type,fee:e.fee,tickRange:`${e.tickLower}-${e.tickUpper}`});const o=`galaswap - operation - ${c.v4()}-${Date.now()}-${e.owner}`,a={token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min,amount1Min:e.amount1Min,positionId:"",uniqueKey:o},i=new n.ethers.Wallet(this.privateKey),r={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},s={name:"ethereum",chainId:1},l=this.calculatePersonalSignPrefix(a),u={...a,prefix:l},d=await i.signTypedData(s,r,u),h={...u,signature:d,types:r,domain:s};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:h.signature?.substring(0,20)+"...",prefix:h.prefix,tickLower:a.tickLower,tickUpper:a.tickUpper});const g=this.buildLiquidityStringsInstructions(e.token0,e.token1,e.fee,e.owner),p=t.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),m=await p.post("/bundle",{method:"AddLiquidity",signedDto:h,stringsInstructions:g}),f=m.data?.data||m.data?.transactionId||m.data?.id;if(!f)throw this.logger.error("Bundler response structure",{status:m.status,data:m.data,dataType:typeof m.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(m.data)}`);return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:f}),f}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(e,o,a,i,r,s,l,u,d){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const h=new n.ethers.Wallet(this.privateKey),g=await h.getAddress(),p=`galaswap - operation - ${c.v4()}-${Date.now()}-${g}`,m={tickLower:e,tickUpper:o,amount:a,token0:i,token1:r,fee:s,amount0Min:l,amount1Min:u,positionId:d,uniqueKey:p},f={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},y={name:"ethereum",chainId:1},w=this.calculatePersonalSignPrefix(m),k={...m,prefix:w},v=await h.signTypedData(y,f,k),T={...k,signature:v,types:f,domain:y},S=this.buildLiquidityStringsInstructions(i,r,s,g);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:e,tickUpper:o,amount:a,fee:s,positionId:d,transactionId:p});const A=t.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),b=await A.post("/bundle",{method:"RemoveLiquidity",signedDto:T,stringsInstructions:S}),E=b.data?.data||b.data?.transactionId||b.data?.id;if(!E)throw this.logger.error("Bundler response structure",{status:b.status,data:b.data,dataType:typeof b.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(b.data)}`);return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:E}),E}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(e,o,a,i,r,s,l,u){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const d=new n.ethers.Wallet(this.privateKey),h=await d.getAddress(),g=`galaswap - operation - ${c.v4()}-${Date.now()}-${h}`,p={token0:e,token1:o,fee:a,amount0Requested:i,amount1Requested:r,tickLower:s,tickUpper:l,positionId:u,uniqueKey:g},m={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},k=await d.signTypedData(f,m,w),v={...w,signature:k,types:m,domain:f},T=this.buildLiquidityStringsInstructions(e,o,a,h);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:a,amount0Requested:i,amount1Requested:r,tickLower:s,tickUpper:l,positionId:u,transactionId:g});const S=t.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),A=await S.post("/bundle",{method:"CollectPositionFees",signedDto:v,stringsInstructions:T}),b=A.data?.data||A.data?.transactionId||A.data?.id;if(!b)throw this.logger.error("Bundler response structure",{status:A.status,data:A.data,dataType:typeof A.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(A.data)}`);return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:b}),b}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(e){if(!this.privateKey)throw new Error("GSwapService: Swap requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const o=[500,3e3,1e4];if(!o.includes(e.feeTier))throw new Error(`GSwapService: Invalid fee tier ${e.feeTier}. Must be one of: ${o.join(", ")} (basis points)`);try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof e.fromToken?e.fromToken:e.fromToken.type,toToken:"string"==typeof e.toToken?e.toToken:e.toToken.type,inputAmount:e.inputAmount,minOutput:e.minOutput,feeTier:e.feeTier});let o=e.fromToken,a=e.toToken;"string"==typeof o&&(o=Mo(o)),"string"==typeof a&&(a=Mo(a));const r=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`,s=`${a.collection}|${a.category}|${a.type}|${a.additionalKey}`,l=r<s?[o,a,r,s]:[a,o,s,r],[u,d,h,g]=l,p="string"==typeof e.fromToken?Mo(e.fromToken):e.fromToken,m=`${p.collection}|${p.category}|${p.type}|${p.additionalKey}`,f=m===h,y=`galaswap - operation - ${c.v4()}-${Date.now()}-${e.walletAddress}`;let w;if(!e.currentSqrtPrice)throw new Error("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation");const k=new i(e.currentSqrtPrice);w=f?k.multipliedBy(.01).toString():k.multipliedBy(100).toString(),this.logger.debug("Using relative price bounds for sqrtPriceLimit",{currentSqrtPrice:e.currentSqrtPrice,zeroForOne:f,sqrtPriceLimit:w,direction:f?"token0→token1 (downward)":"token1→token0 (upward)",reason:"amountOutMinimum provides slippage protection, sqrtPriceLimit sets wide boundaries"});const v={token0:u,token1:d,fee:e.feeTier,amount:new i(e.inputAmount).toFixed(),zeroForOne:f,sqrtPriceLimit:w,recipient:e.walletAddress,amountOutMinimum:new i(e.minOutput).multipliedBy(-1).toFixed(),uniqueKey:y};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:h,orderedToken1String:g,fromTokenStr:m,zeroForOne:f?`TRUE (${h} → ${g})`:`FALSE (${g} → ${h})`,inputAmount:e.inputAmount,expectedOutput:e.minOutput,slippageTolerance:100*(e.slippageTolerance||.01)+"%",currentSqrtPrice:e.currentSqrtPrice,swapDto:{amount:v.amount,zeroForOne:v.zeroForOne,sqrtPriceLimit:v.sqrtPriceLimit,amountOutMinimum:v.amountOutMinimum}});const T=new n.ethers.Wallet(this.privateKey),S={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},A={name:"ethereum",chainId:1},b=this.calculatePersonalSignPrefix(v),E={...v,prefix:b},I=await T.signTypedData(A,S,E),N={...E,signature:I,types:S,domain:A};this.logger.debug("Swap DTO signed",{signature:N.signature?.substring(0,20)+"...",prefix:N.prefix,zeroForOne:v.zeroForOne});const P=this.buildLiquidityStringsInstructions(u,d,e.feeTier,e.walletAddress),F=t.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),D=await F.post("/bundle",{method:"Swap",signedDto:N,stringsInstructions:P}),C=D.data?.data||D.data?.transactionId||D.data?.id;if(!C)throw this.logger.error("Bundler response structure",{status:D.status,data:D.data,dataType:typeof D.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(D.data)}`);return this.logger.debug("Swap transaction sent to bundler",{transactionId:C,inputAmount:e.inputAmount,minOutput:e.minOutput}),C}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,o){const a=`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`,i=`$${t.collection}$${t.category}$${t.type}$${t.additionalKey}`,r=`$pool${a}${i}$${n}`;return[r,`$userPosition${o}`,`$tokenBalance${a}${o}`,`$tokenBalance${i}${o}`,`$tokenBalance${a}${r}`,`$tokenBalance${i}${r}`]}handleGSwapError(e,t,n,o){this.logger.error(e,n);const a=this.extractGSwapErrorCode(n),i=n,r=[`${e}: ${i?.message||String(n)}`,n];throw o&&("GSwapSwapError"===t.name&&o.transactionHash&&r.push(o.transactionHash),"GSwapPoolError"===t.name&&(o.tokenA&&r.push(o.tokenA),o.tokenB&&r.push(o.tokenB)),"GSwapAssetError"===t.name&&o.walletAddress&&r.push(o.walletAddress)),a&&r.push(a),new t(...r)}extractGSwapErrorCode(e){if(e&&"object"==typeof e){const t=e;if(t.constructor&&"GSwapSDKError"===t.constructor.name)return t.code;if("code"in t&&"string"==typeof t.code)return t.code}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}}class Ho{}Ho.BASE_PRICE=1650667151e-14,Ho.PRICE_SCALING_FACTOR=1166069e-12,Ho.TRADING_FEE_FACTOR=.001,Ho.GAS_FEE="1",Ho.MIN_UNBONDING_FEE_FACTOR=0,Ho.MAX_UNBONDING_FEE_FACTOR=.5,Ho.NET_UNBONDING_FEE_FACTOR=.5,Ho.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class Qo extends Tn{constructor(e=!1){super(e),this.cache=new Map}getLRUKey(){const e=this.cache.keys().next().value;return void 0!==e?e:null}normalizeTokenName(e){return e.trim().toLowerCase().replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=Qo.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n||{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeTokenName(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeTokenName(e);this.updateCacheEntry(n,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),n=this.cache.get(t);return n?.maxSupply||Ho.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeTokenName(e);return this.cache.has(t)}clear(e){if(e){const t=this.normalizeTokenName(e);this.cache.delete(t)}else this.cache.clear()}dump(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((n,o)=>{n.lastUpdated<e&&(e=n.lastUpdated);let a=0;a+=2*o.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(a+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(a+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(a+=8),a+=8,n.vaultAddress&&(a+=2*n.vaultAddress.length),n.maxSupply&&(a+=2*n.maxSupply.length),n.symbol&&(a+=2*n.symbol.length),a+=32,t+=a}),{totalTokens:this.cache.size,cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.get(t)||null}setByTokenId(e,t){const n=`token:${e.toLowerCase().trim()}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.has(t)}}Qo.MAX_CACHE_SIZE=1e4;class Xo extends vn{constructor(e,t,n=void 0,o=5,a=!1){super(e,a),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=n,this.pricingConcurrency=o}setGSwapService(e){this.gswapService=e}setPricingConcurrency(e){this.pricingConcurrency=Math.max(1,Math.min(e,20))}async enrichPoolsWithPricing(e){if(!this.gswapService)return this.logger.warn("GSwap service not available, skipping pricing enrichment"),e;if(0===e.length)return e;this.logger.debug("Starting pricing enrichment",{poolCount:e.length,concurrency:this.pricingConcurrency});const t=[];for(let n=0;n<e.length;n++){const o=e[n];t.push({poolIndex:n,token:o.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:o.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${o.token0}`,{error:e.message})})}),t.push({poolIndex:n,token:o.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:o.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${o.token1}`,{error:e.message})})})}const n=new Map;for(let t=0;t<e.length;t++)n.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const o=t.slice(e,e+this.pricingConcurrency),a=await Promise.allSettled(o.map(e=>e.task));for(let e=0;e<o.length;e++){const t=o[e],i=a[e],r=n.get(t.poolIndex)||{};"fulfilled"===i.status&&i.value&&(t.isToken0?r.token0Price=i.value:r.token1Price=i.value),n.set(t.poolIndex,r)}}const o=e.map((e,t)=>{const o=n.get(t)||{},a={...e};return void 0!==o.token0Price&&(a.token0Price=o.token0Price),void 0!==o.token1Price&&(a.token1Price=o.token1Price),a}),a=o.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:a,failed:e.length-a}),o}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:o="desc",page:a=kn.DEFAULT_PAGE,limit:i=kn.DEFAULT_LIMIT,withPrices:r=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:o,page:a,limit:i,withPrices:r});const s=new URLSearchParams({page:a.toString(),limit:Math.min(i,20).toString(),sortBy:n,sortOrder:o});t&&s.append("search",t);const c=`${this.dexBackendBaseUrl}/explore/pools?${s}`;try{const e=await this.http.get(c);if(!e||!e.data)throw new Error("No response from DEX pool service");let t=e.data.pools;const n=e.data.count,o=Math.min(i,20),s=Math.ceil(n/o);return r&&(t=await this.enrichPoolsWithPricing(t)),this.logger.debug("DEX pools fetched successfully",{poolCount:t.length,total:n,totalPages:s,withPrices:r}),{pools:t,page:a,limit:o,total:n,totalPages:s,hasNext:a<s,hasPrevious:a>1}}catch(e){throw this.logger.error("Failed to fetch DEX pools",{error:e,url:c}),e}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=await _o((t,n)=>this.fetchDexPools({...e,page:t,limit:n}).then(e=>({items:e.pools,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:20});return this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.items.length,totalCount:t.total,withPrices:e.withPrices}),Ro(t.items,t.total,"pools")}}function Zo(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected at least 4 parts separated by |, got ${t.length}`);const[n,o,a,...i]=t;if(!n||!o||!a)throw new Error("Collection, category, and type must be non-empty");const r=i.join("|");if(!r)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:o,type:a,additionalKey:r}}catch(t){throw new N(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}class Yo extends vn{constructor(e,t,n=!1,o=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=o}validateFetchCompositePoolDataInput(e,t,n){if(!e||"string"!=typeof e)throw new U("token0 must be a non-empty string",{token0:e});if(!t||"string"!=typeof t)throw new U("token1 must be a non-empty string",{token1:t});const o=e.split("|"),a=t.split("|");if(4!==o.length)throw new U("token0 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token0:e});if(4!==a.length)throw new U("token1 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token1:t});const i=[500,3e3,1e4];if(!Number.isInteger(n)||!i.includes(n))throw new U(`fee must be one of: ${i.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!e||"string"!=typeof e)throw new U("amount must be a non-empty string",{amount:e});const t=new i(e);try{no(t,"amount","for quote calculation")}catch(t){throw new U(t.message,{amount:e})}}convertTokenClassKey(e){const t=new s.TokenClassKey;return t.collection=e.collection,t.category=e.category,t.type=e.type,t.additionalKey=e.additionalKey,t}setCompositePoolFetchConcurrency(e){this.compositePoolFetchConcurrency=Math.max(1,Math.min(e,20)),this.logger.debug(`Composite pool fetch concurrency set to ${this.compositePoolFetchConcurrency}`)}async fetchCompositePoolData(e){const{token0:t,token1:n,fee:o,gatewayBaseUrl:a}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:o}),this.validateFetchCompositePoolDataInput(t,n,o);try{const e=Zo(t),c=Zo(n),l=this.convertTokenClassKey(e),u=this.convertTokenClassKey(c),d=new r.GetCompositePoolDto(l,u,o),h=`${a||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,g=await this.http.post(h,d);if(!g||1!==g.Status)throw new O(`Pool not found: ${t}/${n} with fee ${o}`);const p=function(e){return{pool:e.pool,tickDataMap:e.tickDataMap,token0Balance:e.token0Balance,token1Balance:e.token1Balance,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals,compositePoolDto:e}}(function(e){const t=new r.Pool(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,new i(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=new i(e.pool.grossPoolLiquidity),t.liquidity=new i(e.pool.liquidity),t.feeGrowthGlobal0=new i(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=new i(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=new i(e.pool.protocolFeesToken0),t.protocolFeesToken1=new i(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=new i(e.pool.maxLiquidityPerTick);const n={};Object.keys(e.tickDataMap).forEach(t=>{const o=e.tickDataMap[t],a=new r.TickData(o.poolHash,o.tick);a.initialised=o.initialised,a.liquidityNet=new i(o.liquidityNet),a.liquidityGross=new i(o.liquidityGross),a.feeGrowthOutside0=new i(o.feeGrowthOutside0),a.feeGrowthOutside1=new i(o.feeGrowthOutside1),n[t]=a});const o={...e.token0Balance},a=new s.TokenBalance(o);a.quantity=new i(e.token0Balance.quantity);const c={...e.token1Balance},l=new s.TokenBalance(c);return l.quantity=new i(e.token1Balance.quantity),new r.CompositePoolDto(t,n,a,l,e.token0Decimals,e.token1Decimals)}(g.Data),g.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:o,liquidity:p.pool.liquidity.toString()}),p}catch(e){if(e instanceof O)throw e;throw this.logger.error("Failed to fetch composite pool data",e),new U(`Failed to fetch composite pool data: ${e.message}`,{token0:t,token1:n,fee:o})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:n,toToken:o,amount:a}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:o,amount:a}),this.validateQuoteAmount(a),!t)throw new U("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0,s=Zo(n),c=Zo(o),l=this.convertTokenClassKey(s),u=this.convertTokenClassKey(c),d=new r.QuoteExactAmountDto(l,u,t.pool.fee,new i(a),e,t.compositePoolDto),h=await r.quoteExactAmount(void 0,d);return this.logger.debug("Local quote calculated",{amount0:h.amount0,amount1:h.amount1}),{amount0:h.amount0.toString(),amount1:h.amount1.toString(),currentSqrtPrice:h.currentSqrtPrice.toString(),newSqrtPrice:h.newSqrtPrice.toString()}}catch(e){throw this.logger.error("Local quote calculation failed",e),new U(`Local quote calculation failed: ${e.message}`,{fromToken:n,toToken:o,amount:a})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:o,amount:a}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:o,amount:a}),this.validateQuoteAmount(a),!t)throw new U("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0,s=Zo(n),c=Zo(o),l=this.convertTokenClassKey(s),u=this.convertTokenClassKey(c),d=new r.QuoteExactAmountDto(l,u,t.pool.fee,new i(a),e,void 0),h=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,g=await this.http.post(h,d);if(!g||1!==g.Status)throw new U("External quote failed: "+(g?.Message||"Unknown error"));const p=g.Data;return this.logger.debug("External quote calculated",{amount0:p.amount0,amount1:p.amount1}),{amount0:p.amount0.toString(),amount1:p.amount1.toString(),currentSqrtPrice:p.currentSqrtPrice.toString(),newSqrtPrice:p.newSqrtPrice.toString()}}catch(e){throw this.logger.error("External quote calculation failed",e),new U(`External quote calculation failed: ${e.message}`,{fromToken:n,toToken:o,amount:a})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}function Jo(e){const t=function(e){const t=Pt(e);return t.success?[]:t.errors||["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}const ea="/api/asset/launchpad-contract/CallNativeTokenIn",ta="/api/asset/launchpad-contract/CallNativeTokenOut",na="/api/asset/launchpad-contract/CallMemeTokenIn",oa="/api/asset/launchpad-contract/CallMemeTokenOut";class aa extends o.ChainCallDTO{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,e.websiteUrl&&(this.websiteUrl=e.websiteUrl),e.telegramUrl&&(this.telegramUrl=e.telegramUrl),e.twitterUrl&&(this.twitterUrl=e.twitterUrl),this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function ia(e){if(!e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.Status&&void 0!==t.Data&&"object"==typeof t.Data&&null!==t.Data&&"string"==typeof t.Data.calculatedQuantity&&void 0!==t.Data.extraFees&&"object"==typeof t.Data.extraFees&&null!==t.Data.extraFees&&"string"==typeof t.Data.extraFees.reverseBondingCurve&&"string"==typeof t.Data.extraFees.transactionFees}const ra={NATIVE:"native",EXACT:"exact"},sa={LOCAL:"local",EXTERNAL:"external"};class ca{static calculateBuyWithExact(e,t){const n=parseFloat(e),o=parseFloat(t),{BASE_PRICE:a,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:s,GAS_FEE:c}=Ho,l=this.roundUp(a*(Math.exp((o+n)*r)-Math.exp(o*r))/r,8),u=new i(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateBuyWithNative(e,t){const n=parseFloat(e),o=parseFloat(t),{BASE_PRICE:a,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:s,GAS_FEE:c}=Ho,l=Math.log(n*r/a+Math.exp(o*r))/r-o,u=new i(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateSellWithExact(e,t,n,o,a){const r=parseFloat(e),s=parseFloat(t),c=parseFloat(n),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=Ho,g=l*(Math.exp(s*u)-Math.exp((s-r)*u))/u,p=new i(g),m=o+s/c*(a-o),f=p.multipliedBy(m).toFixed(8,i.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,n,o,a){const r=parseFloat(e),s=parseFloat(t),c=parseFloat(n),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=Ho,g=s-Math.log(Math.exp(s*u)-r*u/l)/u,p=new i(r),m=o+s/c*(a-o),f=p.multipliedBy(m).toFixed(8,i.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class la{constructor(e,t,n,o,a,i,r="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=o,this.galaChainHttp=a,this.dexApiHttp=i,this.defaultCalculateAmountMode=r,this.metadataCache=new Qo}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Wt(t);const o=`${t}.png`;zn(n.file,o,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&n.file instanceof File)e.append("image",n.file);else{if(!Buffer.isBuffer(n.file))throw q("file","a File object (browser) or Buffer (Node.js)");{const o=`${n.tokenName||t}.png`,a=new Blob([n.file],{type:"image/png"});e.append("image",a,o)}}const o=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(n.tokenName||t)}`,data:e,headers:{}});if(!0===o.error||200!==o.status||!o.data?.imageUrl)throw M(o.message||"Image upload failed - no URL returned",o.status);return o.data.imageUrl}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw G("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){Ht(e),e.tokenName&&Wt(e.tokenName);const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const n=A(t),o=await this.http.get("/launchpad/fetch-pool",n);if(!0===o.error||200!==o.status||!o.data)throw M(o.message||"Failed to fetch pools",o.status);let a=[];const i=(await import("bignumber.js")).default;if(o.data.tokens)if(Array.isArray(o.data.tokens))a=o.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",o=!new i(t).isZero()||!new i(n).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:o,createdAt:e.created_at||e.createdAt||""}});else{const e=o.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!new i(t).isZero()||!new i(n).isZero();a=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}]}else o.data.pools&&Array.isArray(o.data.pools)&&(a=o.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",o=!new i(t).isZero()||!new i(n).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:o,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:r,isValidPoolForCaching:s}=await Promise.resolve().then(function(){return Ea});a.forEach(e=>{if(!s(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=r(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=o.data.count??o.data.total??0,l=o.data.page??e.page??1,u=o.data.limit??e.limit??10,d=u>0?Math.ceil(c/u):1;return{pools:a,page:l,limit:u,total:c,totalPages:d,hasNext:l<d,hasPrevious:l>1}}async _getAmount(e){if(Xt(e),!this.galaChainHttp)throw G("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:n}=((e,t,n,o)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:ea,body:{vaultAddress:n,tokenQuantity:o,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:ta,body:{vaultAddress:n,tokenQuantity:o,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:na,body:{vaultAddress:n,nativeTokenQuantity:o,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:oa,body:{vaultAddress:n,nativeTokenQuantity:o,IsPreMint:!1}};throw q("type-method","one of: NATIVE-IN, NATIVE-OUT, MEME-IN, MEME-OUT")})(e.type,e.method,e.vaultAddress,e.amount);try{const e=await this.galaChainHttp.post(t,n);if(!ia(e))throw M("Malformed response data from GalaChain gateway");if(1!==e.Status)throw M(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:o,extraFees:a}=e.Data;return{amount:o,reverseBondingCurveFee:a.reverseBondingCurve,transactionFee:a.transactionFees,gasFee:"1"}}catch(o){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:n,error:o instanceof Error?o.message:o}),o}}async checkPool(e){Qt(e),e.tokenName&&Wt(e.tokenName);const t=A(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw M(n.message||"Failed to check pool",n.status);const o=n.data;return e.symbol?o?.isSymbolExist??!1:e.tokenName?o?.isNameExist??!1:o?.exists??!1}async fetchVolumeData(e){if(!In(e))throw new N("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:o,resolution:a}=e;if(Wt(t),!n||!o||!a)throw new N("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:o,resolution:a};Zt(i);const r=A(i),s=await this.http.get("/launchpad/get-graph-data",r);if(!0===s.error||200!==s.status||!s.data)throw M(s.message||"Failed to fetch graph data",s.status);return{dataPoints:s.data}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={page:e.page||1,limit:e.limit||10};return e.search&&(n.search=e.search),e.tokenName&&(n.tokenName=e.tokenName),t&&(n.type=t),this.fetchPoolsFromAPI(n)}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async calculateBuyAmount(e){if(!e||"object"!=typeof e)throw new N("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:n,type:o,currentSupply:a}=e,i=e.mode??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw new N(`Invalid calculation mode "${i}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new N("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!n||"string"!=typeof n)throw new N("Amount is required and must be a string","amount","INVALID_AMOUNT");if(o!==ra.NATIVE&&o!==ra.EXACT)throw new N('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===i?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:o}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:o},"currentSupply",a))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:o}=e,a=await this.tokenResolver.resolveTokenToVault(t);if(!a)throw new N(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return o===ra.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:a,amount:n}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:a,amount:n})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:o,currentSupply:a,maxSupply:i,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:s}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new N(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new N("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!n||"string"!=typeof n)throw new N("Amount is required and must be a string","amount","INVALID_AMOUNT");if(o!==ra.EXACT&&o!==ra.NATIVE)throw new N('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:n,type:o});{const e={tokenName:t,amount:n,type:o,...void 0!==a&&{currentSupply:a},...void 0!==i&&{maxSupply:i},...void 0!==r&&{reverseBondingCurveMaxFeeFactor:r},...void 0!==s&&{reverseBondingCurveMinFeeFactor:s}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:o}=e,a=await this.tokenResolver.resolveTokenToVault(t);if(!a)throw new N(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return o===ra.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:a,amount:n}):this._getAmount({type:"MEME",method:"IN",vaultAddress:a,amount:n})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:o,currentSupply:a}=e;if(!n||"string"!=typeof n)throw new N("Amount is required and must be a string","amount","INVALID_AMOUNT");if(o!==ra.NATIVE&&o!==ra.EXACT)throw new N('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==a&&Jt(a,"currentSupply");const i=!a;if(i&&!t)throw new N("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&Wt(t);let r=a;if(i){r=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return o===ra.EXACT?ca.calculateBuyWithExact(n,r):ca.calculateBuyWithNative(n,r)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:o,currentSupply:a,maxSupply:i,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:s}=e;if(!n||"string"!=typeof n)throw new N("Amount is required and must be a string","amount","INVALID_AMOUNT");if(o!==ra.EXACT&&o!==ra.NATIVE)throw new N('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==a&&Jt(a,"currentSupply");const c=!a||!i||void 0===r||void 0===s;if(c&&!t)throw new N("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&Wt(t);let l=a,u=i,d=r,h=s;if(c&&t){const e=this.metadataCache.get(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,l||(l=await this.fetchCurrentSupply(t));if(void 0===d||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);d=d??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return o===ra.EXACT?ca.calculateSellWithExact(n,l,u,h,d):ca.calculateSellWithNative(n,l,u,h,d)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Sn(t,"tokenName")&&En(t)&&An(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:n,calculateAmountMode:o,currentSupply:a}=t;Wt(n);const i=await this.tokenResolver.resolveTokenToVault(n);if(!i)throw new N(I(n),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw G("GalaChain HTTP client not configured");const r=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:i});if(1!==r.Status)throw M(`Failed to fetch pool details: Status ${r.Status}`,r.Status);const s=r.Data,c=(await import("bignumber.js")).default,l=a??new c(s.maxSupply).minus(s.sellingTokenQuantity).toFixed(),u=s.sellingTokenQuantity;if("0"===u)throw new N(`Token ${n} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const d={tokenName:n,amount:u,type:"exact",currentSupply:l,...void 0!==o&&{mode:o}};return await this.calculateBuyAmount(d)}async launchToken(e){if(!this.bundleHttp)throw G("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Jo(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new N("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration,o=Number(t),a=Number(n);if(isNaN(o)||isNaN(a)||o<=0||a<=0||o>=a)throw new N("Reverse bonding curve configuration must have valid min/max fee portions with min < max","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG")}let n="";if(e.tokenImage)if(e.tokenImage instanceof File||Buffer.isBuffer(e.tokenImage)){const t=await this.uploadImageByTokenName({tokenName:e.tokenName,options:{file:e.tokenImage,tokenName:e.tokenName}});if(!t)throw M("Image upload failed: No URL returned");n=t}else"string"==typeof e.tokenImage&&(n=e.tokenImage);const a=`galaswap - operation - ${c.v4()}-${Date.now()}-${this.http.getAddress()}`,i={tokenName:e.tokenName.trim(),tokenSymbol:e.tokenSymbol.trim().toUpperCase(),tokenDescription:e.tokenDescription.trim(),tokenImage:n.trim(),preBuyQuantity:t.toString(),tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:a};e.websiteUrl?.trim()&&(i.websiteUrl=e.websiteUrl.trim()),e.telegramUrl?.trim()&&(i.telegramUrl=e.telegramUrl.trim()),e.twitterUrl?.trim()&&(i.twitterUrl=e.twitterUrl.trim()),e.reverseBondingCurveConfiguration&&(i.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const r=new aa(i),s=await this.http.signWithGalaChain("CreateSale",r,o.SigningType.SIGN_TYPED_DATA),{signature:l,types:u,domain:d,prefix:h}=s,g={tokenName:r.tokenName,tokenSymbol:r.tokenSymbol,tokenDescription:r.tokenDescription,tokenImage:r.tokenImage,preBuyQuantity:r.preBuyQuantity,...r.websiteUrl&&{websiteUrl:r.websiteUrl},...r.telegramUrl&&{telegramUrl:r.telegramUrl},...r.twitterUrl&&{twitterUrl:r.twitterUrl},tokenCategory:r.tokenCategory,tokenCollection:r.tokenCollection,uniqueKey:r.uniqueKey,signature:l,types:u,domain:d,...h&&{prefix:h},...r.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:r.reverseBondingCurveConfiguration}},p=`${e.tokenName.trim()}$Unit$none$none`,m="GALA$Unit$none$none";let f;if(parseFloat(t)>0){const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`]}else{const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`]}const y={signedDto:g,stringsInstructions:f,method:"CreateSale"},w=await this.bundleHttp.post("/bundle",y);if(w.error||!w.data)throw M(w.message||"Token launch failed");return w.data}async fetchTokenDistribution(e){if(!e)throw R("tokenName","Token name");Wt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new N(I(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const n=encodeURIComponent(t),o=await this.http.get(`/holders/${n}`);if(!0===o.error||200!==o.status||!o.data)throw M(o.message||"Failed to fetch token distribution",o.status);const a=o.data;if(!Array.isArray(a))throw M("Invalid API response: expected array of holders",o.status);for(const e of a){if(!e.owner||"string"!=typeof e.owner)throw M("Invalid holder data: missing or invalid owner field",o.status);if(!e.quantity||"string"!=typeof e.quantity)throw M("Invalid holder data: missing or invalid quantity field",o.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw M(`Invalid holder quantity: "${e.quantity}"`,o.status)}const r=a.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:a.map(e=>{const t=new i(e.quantity),n=r.isZero()?0:t.dividedBy(r).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:r.toFixed(),totalHolders:a.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw R("tokenName","Token name");Wt(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw M(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:n,badgeName:o}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const a=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===o);return a?.isActive||!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.nativeTokenQuantity&&(void 0===t.vaultAddress||"string"==typeof t.vaultAddress)}(e))throw new N("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw G("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},n=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!ia(n))throw M("Malformed response data from GalaChain gateway");if(1!==n.Status)throw M(`GalaChain calculation failed with status ${n.Status}`,n.Status);const{calculatedQuantity:o,extraFees:a}=n.Data;return{amount:o,reverseBondingCurveFee:a.reverseBondingCurve,transactionFee:a.transactionFees,gasFee:"1"}}catch(e){if(e instanceof Error){const t=new Error(`Pre-mint calculation failed: ${e.message}`);throw e.stack&&(t.stack=e.stack),t}throw new Error(`Pre-mint calculation failed: ${String(e)}`)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new N(I(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw G("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw M(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const o=n.Data,a=new(0,(await import("bignumber.js")).default)(o.maxSupply).minus(o.sellingTokenQuantity).toFixed(),i=o.sellingTokenQuantity,r=o.maxSupply;let s=.5,c=0;o.reverseBondingCurveConfiguration?(s=parseFloat(o.reverseBondingCurveConfiguration.maxFeePortion),c=parseFloat(o.reverseBondingCurveConfiguration.minFeePortion)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const l=s-c;return this.metadataCache.set(e,{maxSupply:r,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}),{currentSupply:a,remainingTokens:i,maxSupply:r,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}}async fetchCurrentSupply(e){Wt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new N(I(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw G("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw M(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const o=n.Data,a=new(0,(await import("bignumber.js")).default)(o.maxSupply).minus(o.sellingTokenQuantity).toFixed(),i=o.maxSupply;return this.metadataCache.set(e,{maxSupply:i}),a}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Yt(e)}validateTokenName(e){return Wt(e)}validatePagination(e){return Ht(e)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw G("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw R("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),n=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&n.push({symbol:e.symbol,price:e.currentPrices.usd})}),n}catch(e){throw M(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return Sn(t,"tokenName")&&En(t)&&An(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:n,calculateAmountMode:o,currentSupply:a}=t;if(!n||"string"!=typeof n)throw R("tokenName","Token name (string)");try{const e={tokenName:n,amount:"1",type:"native",...void 0!==o&&{mode:o},...void 0!==a&&{currentSupply:a}},t=await this.calculateBuyAmount(e),i=(await this.fetchTokenPrice("GALA"))[0];if(!i)throw M("GALA price not available");const r=Number(t.amount);if(r<=0)throw new N(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const s=i.price/r;return{symbol:n.toUpperCase(),price:s}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${n}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${n}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}const ua={PROD:{launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",galaChainBaseUrl:"https://gateway-mainnet.galachain.com",bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},STAGE:{launchpadBaseUrl:"https://lpad-backend-dev1.defi.gala.com",galaChainBaseUrl:"https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com",bundleBaseUrl:"https://bundle-backend-dev1.defi.gala.com",webSocketUrl:"https://bundle-backend-dev1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-dev1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function da(e){return ua[e]}class ha extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class ga extends Error{constructor(e,t,n){super(`Transaction ${e} failed with status: ${t}${n?` - ${n}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function pa(e,t){if(!e)throw new ha(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new ha(`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 ha(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function ma(e,t,n,o){pa(e,t);const a=e,i=a.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new ha(`Invalid trade data received for transaction ${t}`);const r={transactionId:t,type:n,method:"native"===o.type?"native":"exact",inputAmount:i.inputQuantity||o.amount,outputAmount:i.outputQuantity||o.expectedAmount||"0",totalFees:i.totalFees||"0",tokenName:o.tokenName,vaultAddress:i.vaultAddress||"",timestamp:Date.now()};return void 0!==a.blockHash&&(r.blockHash=a.blockHash),void 0!==a.gasUsed&&(r.gasUsed=a.gasUsed),void 0!==o.slippageToleranceFactor&&(r.slippageTolerance=o.slippageToleranceFactor),r}const fa="4.0.0";class ya{constructor(e){this.wallet=e.wallet;let n=null,o="STAGE";e.env?(o=e.env,n=da(e.env)):e.baseUrl?.includes("prod")?(o="PROD",n=da("PROD")):(o="STAGE",n=da("STAGE")),this.environment=o,this.config={baseUrl:n.launchpadBaseUrl,galaChainBaseUrl:n.galaChainBaseUrl,bundleBaseUrl:n.bundleBaseUrl,webSocketUrl:n.webSocketUrl,dexApiBaseUrl:n.dexApiBaseUrl,dexBackendBaseUrl:n.dexBackendBaseUrl,launchpadFrontendUrl:n.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new S({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?ya.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?ya.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||ya.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=e.pricingConcurrency||5,this.auth=new T({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new b(this.auth,this.config),this.galaChainHttp=new b(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new b(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new b(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new b(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=t.create({baseURL:this.config.galaChainBaseUrl,timeout:this.config.timeout||3e4,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.cache=new Qo(e.debug||!1),this.launchpadService=new Wn(this.http),this.tokenResolverService=new Oo(this.launchpadService.poolService),this.launchpadAPI=new la(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new wo(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1,this.galaChainPublicAxios),this.dexService=new ko(this.dexBackendHttp,this.cache,this.galaChainService,e.debug||!1),this.bundleService=new xo(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,e.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Uo({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new qo(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new Yo(this.galaChainHttp,this.config.galaChainBaseUrl,e.debug||!1,e.dexQuoteNetworkTimeout||3e4),this.gswapService=new Wo({privateKey:e.wallet?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,galaChainBaseUrl:this.config.galaChainBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new Xo(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,e.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw G("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw G('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new n.Wallet(e),o={...this.config,wallet:t};return new ya(o)}getAddress(){return this.validateWallet(),this.auth.getAddress()}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw new N("Wallet is required for this operation",void 0,"WALLET_REQUIRED");return this.wallet}setWallet(e){if(!e||"object"!=typeof e||!("address"in e))throw new N("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}getWallet(){return this.wallet}hasWallet(){return void 0!==this.wallet}getConfig(){const{wallet:e,...t}=this.config;return{...t,environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode}}getVersion(){return fa}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw G("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e||{});return await this.warmCacheFromPools(t.pools),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.pools),t}async fetchDexPools(e={}){return this.dexPoolService.fetchDexPools(e)}async fetchAllDexPools(e={}){return this.dexPoolService.fetchAllDexPools(e)}async fetchCompositePoolData(e){return this.dexQuoteService.fetchCompositePoolData(e)}async calculateDexPoolQuoteExactAmountLocal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountLocal(e)}async calculateDexPoolQuoteExactAmountExternal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountExternal(e)}async calculateDexPoolQuoteExactAmount(e,t="local"){return this.dexQuoteService.calculateDexPoolQuoteExactAmount(e,t)}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n,currentSupply:o,calculateAmountMode:a}=e;if(t&&!n){const e={tokenName:t};return o&&(e.currentSupply=o),a&&(e.calculateAmountMode=a),this.fetchLaunchpadTokenSpotPrice(e)}if(n&&!t)try{return await this.dexService.fetchTokenPrice({tokenId:n})}catch(e){const t=function(e){if(On(e)&&e.response)return e.response.status}(e);if(400===t||404===t){this.logger.debug(`DEX spot price not available (HTTP ${t}) for tokenId, attempting launchpad fallback`);try{const t=(await this.fetchTokenDetails(n)).name.trim().toLowerCase();if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`);const i={tokenName:t};return o&&(i.currentSupply=o),a&&(i.calculateAmountMode=a),this.fetchLaunchpadTokenSpotPrice(i)}catch(t){throw this.logger.error(`Launchpad fallback failed: ${Un(t)}`),e}}throw e}if(!t&&!n)throw R("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");throw new N("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS")}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;return this.dexService.fetchLaunchpadTokenSpotPrice(t.tokenName,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(!t)throw new Error(I(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,o=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=o.currentSupply,n.reverseBondingCurveMaxFeeFactor=o.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=o.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=o.reverseBondingCurveNetFeeFactor,n.tokenName=e,n}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n=t(e)||this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return po}),o=t(e.tokenId),{collection:a,category:i,type:r,additionalKey:s}=o;return this.galaChainService.fetchTokenBalance({owner:n,collection:a,category:i,additionalKey:s,type:r,instance:"0"})}if(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...n&&{address:n}})).tokens[0];return t?{quantity:t.quantity,collection:t.collection||"Token",category:"Unit",tokenId:`${t.collection||"Token"}|Unit|${t.symbol}|none`,symbol:t.symbol,name:t.name}:null}throw R("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:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:o,privateKey:a,calculateAmountMode:i,currentSupply:r}=e;let s=t;void 0===i&&void 0===r||(s={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==r&&{currentSupply:r}});const c=await this.calculateBuyAmountForGraduation(s),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==o&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=o),void 0!==a&&(l.privateKey=a),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...o}=e;return t.buy(o)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(!n)throw K("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>ma(t,n,"buy",e))}async sell(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...o}=e;return t.sell(o)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(!n)throw K("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>ma(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async postComment(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...o}=e;return t.postComment(o)}return this.validateWallet(),this.launchpadService.postComment(e)}async launchToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...o}=e;return t.launchToken(o)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{pa(n,t);const o=n?.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(o))throw new ha(`Invalid launch data received for transaction ${t}`);const a={transactionId:t,vaultAddress:o.vaultAddress||"",tokenStringKey:o.tokenStringKey||"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:o.creatorAddress||this.getAddress(),timestamp:Date.now(),...n.blockHash&&{blockHash:n.blockHash},...n.gasUsed&&{gasUsed:n.gasUsed}};return"string"==typeof e.tokenImage&&(a.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(a.preBuyQuantity=e.preBuyQuantity),a.vaultAddress&&this.tokenResolverService.set(e.tokenName,a.vaultAddress),a})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...o}=e;return t.uploadTokenImage(o)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n=t(e)||this.getAddress();return this.launchpadService.fetchProfile(n)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n={...e,address:t(e.address)};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...o}=n;return e.updateProfile(o)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n={...e,address:t(e.address)||this.getAddress()};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...o}=n;return e.uploadProfileImage(o)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async retrieveGalaFromFaucet(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n={walletAddress:t(e)||this.getAddress(),amount:"5"};return this.launchpadService.transferFaucets(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n=t(e?.address)||this.getAddress(),o={page:e?.page||1,limit:e?.limit||10,address:n};return e?.tokenName&&(o.tokenName=e.tokenName),e?.search&&(o.search=e.search),this.launchpadService.fetchTokensHeld(o)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(n.tokenName=e.tokenName),e?.search&&(n.search=e.search),this.launchpadService.fetchTokenList(n)}async fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n={...e,recipientAddress:t(e.recipientAddress)};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...o}=n;return e.transferGala(o)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return en}),n={...e,to:t(e.to)};if(n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...o}=n;return e.transferToken(o)}return this.validateWallet(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}getCacheInfo(){return this.launchpadAPI.getCacheStats()}clearCache(e){this.launchpadAPI.clearCache(e)}validateConfiguration(){if(("number"!=typeof this.config.timeout||this.config.timeout<=0||this.config.timeout>3e5)&&(this.logger.warn(`Invalid timeout value: ${this.config.timeout}. Using default 30000ms.`),this.config.timeout=3e4),!this.config.baseUrl)throw G("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw G("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw G(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw G(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw G(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw G(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw G(`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: ${ya.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),ya.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: ${ya.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),ya.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if("completed"!==n.status)throw new ga(e,n.status,n.message);let o;try{o=t(n)}catch(t){if(t instanceof ha)throw t;throw new ha(`Failed to transform WebSocket response for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,o),o}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof ga||t instanceof ha)throw t;throw new ha(`WebSocket confirmation failed for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}}async warmCacheFromPools(e){if(!e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Ea});e.forEach(e=>{if(!n(e))return;const o=t(e,this.logger);o&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,o)})}async getSwapQuoteExactInput(e,t,n){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:n})}async getSwapQuoteExactOutput(e,t,n){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:n})}async executeSwap(e,t,n,o,a,i=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:o,feeTier:a,slippageTolerance:i})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,n){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:n})}async getSwapUserLiquidityPositions(e,t,n,o){let a,i;"string"==typeof n?(a=n,i=o):"object"==typeof n?i=n:o&&(i=o);return await this.gswapService.getUserLiquidityPositions(e,t,a,i)}async getAllSwapUserLiquidityPositions(e,t){const n=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(n))return n;if(n&&"items"in n)return n.items}return n}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t){return this.gswapService.getLiquidityPositionById(e,t)}async fetchSwapPositionDirect(e){return this.gswapService.fetchSwapPositionDirect(e)}async getSwapEstimateRemoveLiquidity(e){return this.gswapService.estimateRemoveLiquidity(e)}async addSwapLiquidityByPrice(e){return this.gswapService.addLiquidityByPrice(e)}async addSwapLiquidityByTicks(e){this.validateWallet();const t={...e,fee:e.feeTier??e.fee};return this.gswapService.addSwapLiquidityByTicks(t)}async removeSwapLiquidity(e){return this.validateWallet(),this.gswapService.removeLiquidity(e)}async collectSwapPositionFees(e){return this.validateWallet(),this.gswapService.collectPositionFees(e)}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onDexPoolCreation(e,t){const n=1e3,o=Math.max(t?.intervalMs??3e4,n);t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const a=t?.minTVL,i=t?.tokens,r=new Map;let s=!0,c=null;let l=0;const u=async()=>{if(s){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.pools.forEach(t=>{const n=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!r.has(n)){if((e=>{if(r.set(e,!0),r.size>1e3){const e=r.keys().next().value;void 0!==e&&r.delete(e)}})(n),a){if((t.token0Tvl+t.token1Tvl)/2<a)return}if(i&&i.length>0){if(!(i.includes(t.token0)||i.includes(t.token1)))return}e(t)}})}catch(e){l++;const t=e instanceof Error?e.message:String(e);l>=5?this.logger.error(`Polling for new DEX pools failed ${l} consecutive times. Last error: ${t}. Continuing to retry...`):l>1?this.logger.warn(`Error polling for new DEX pools (attempt ${l}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(s){const e=Math.min(Math.max(l-1,0),2),t=o*Math.pow(2,e);c=setTimeout(u,t)}}};return u(),()=>{s=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const n=1e3,o=Math.max(t?.intervalMs??3e4,n);t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const a=t?.creatorAddress,i=new Map;let r=!0,s=null;let c=0;const l=async()=>{if(r){try{const t=await this.fetchPools({type:"recent",limit:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.pools.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),a&&t.creatorAddress!==a||e(t))})}catch(e){c++;const t=e instanceof Error?e.message:String(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(r){const e=Math.min(Math.max(c-1,0),2),t=o*Math.pow(2,e);s=setTimeout(l,t)}}};return l(),()=>{r=!1,s&&clearTimeout(s),this.logger.debug("Stopped watching for launchpad token creation")}}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 S({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:n}=require("./services/WebSocketService");n.cleanupAll(e),t.debug("Global cleanup completed")}}ya.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,ya.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,ya.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=Ho.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,ya.DEFAULT_CALCULATE_AMOUNT_MODE=sa.LOCAL;class wa{static generateWallet(){try{const e=n.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 n.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),o=new n.Wallet(t),a=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:a,mnemonic:"test test test test test test test test test test test junk",wallet:o}}throw e}}static fromPrivateKey(e){const t=new n.Wallet(e),o=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:o,mnemonic:"",wallet:t}}static fromMnemonic(e,t=0){try{const o=n.Mnemonic.fromPhrase(e),a=n.HDNodeWallet.fromMnemonic(o,`m/44'/60'/0'/0/${t}`),i=new n.Wallet(a.privateKey),r=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:r,mnemonic:e,wallet:i}}catch(o){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const o=`test-mnemonic-index-${t}-${e}`,a="0x"+Buffer.from(o).toString("hex").padStart(64,"1").slice(0,64),i=new n.Wallet(a),r=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:r,mnemonic:e,wallet:i}}throw o}}static toGalaAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid Ethereum address format: ${e}`);return`eth|${t}`}static toEthereumAddress(e){if(!e.startsWith("eth|"))throw new Error(`Invalid Gala address format: ${e}. Must start with 'eth|'`);const t=e.slice(4);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid address in Gala format: ${e}`);return`0x${t}`}static isValidEthereumAddress(e){try{const t=e.replace(/^0x/i,"");return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){try{if(!e.startsWith("eth|"))return!1;const t=e.slice(4);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static generateMultipleWallets(e=1){if(e<1||e>100)throw new Error("Count must be between 1 and 100");const t=[];if("undefined"!=typeof process&&"test"===process.env.NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++this.testCounter}`,o="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(o))}else for(let n=0;n<e;n++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${e.mnemonic||"Not available"}`];return t?n.splice(3,0,`🔑 Private Key: ${e.privateKey}`):n.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),n.push("═".repeat(50)),n.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),n.push("This is your backup to recover the wallet."),n.join("\n")}}function ka(e){if(void 0===e)return wa.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 wa.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 wa.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?"...":""}"`)}wa.testCounter=0;class va{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,new i(e)),this.CACHE.get(t)}static clearCache(){this.CACHE.clear()}static getCacheStats(){return{size:this.CACHE.size,entries:Array.from(this.CACHE.keys())}}static trimCache(e=1e3){if(this.CACHE.size>e){const t=this.CACHE.size-e,n=Array.from(this.CACHE.keys());for(let e=0;e<t;e++)this.CACHE.delete(n[e])}}}va.CACHE=new Map,va.ZERO=new i(0),va.ONE=new i(1),va.FEE_PIPS=new i(1e6),va.MIN_SQRT_RATIO=new i("4295128739"),va.MAX_SQRT_RATIO=new i("1461446703485210103287273052203988822378723970342");const Ta={maxIterations:100,enableBigNumberCache:!0,roundingMode:i.ROUND_DOWN,debugLogging:!1};class Sa{static calculateSwapDelta(e,t,n={}){const o=Date.now(),a={...Ta,...n};try{const n=this.initializeSwapState(e,t,a);a.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const r=this.computeSwapLoop(n,e,t,a);a.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:r.stepCount,ticksCrossed:r.ticksCrossed.length,priceHitLimit:r.priceHitLimit});const s=this.createUpdatedPool(e.pool,r.state,t,a),c=this.calculateFinalAmounts(n,r.state,t);let l;if(t.actualSqrtPrice){const e=new i(s.sqrtPrice),n=new i(t.actualSqrtPrice);l=e.minus(n).abs().div(n).times(100).toNumber()}const u=Date.now()-o;a.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:u,amount0:c.amount0.toString(),amount1:c.amount1.toString(),driftPercentage:l}),u>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:u,stepCount:r.stepCount,ticksCrossed:r.ticksCrossed.length}),r.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:r.stepCount}),r.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:r.stepCount,ticksCrossed:r.ticksCrossed.length});return{updatedPool:s,updatedTicks:r.updatedTicks,amount0:c.amount0,amount1:c.amount1,feeAmount0:c.feeAmount0,feeAmount1:c.feeAmount1,ticksCrossed:r.ticksCrossed,metadata:{calculationTimeMs:u,swapSteps:r.stepCount,priceHitLimit:r.priceHitLimit,...void 0!==l&&{driftPercentage:l}}}}catch(e){throw this.logger.error("Swap delta calculation failed",e),new Error(`Swap delta calculation failed: ${e.message}`)}}static initializeSwapState(e,t,n){const{pool:o}=e;if(!o.sqrtPrice||!o.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const a=n.enableBigNumberCache?va.getCached.bind(va):e=>new i(e),s="string"==typeof o.sqrtPrice?o.sqrtPrice:new i(o.sqrtPrice).toFixed(0),c="string"==typeof o.liquidity?o.liquidity:new i(o.liquidity).toFixed(0),l=a(s),u=a(c),d=o.tick??0,h=r.sqrtPriceToTick(new i(s)),g=Math.abs(h-d);g>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:d,calculatedTick:h,drift:g,threshold:100});const p=a(t.amountSpecified);no(p,"amountSpecified","for swap operation");const m="string"==typeof o.feeGrowthGlobal1?o.feeGrowthGlobal1:new i(o.feeGrowthGlobal1).toFixed(0),f="string"==typeof o.feeGrowthGlobal0?o.feeGrowthGlobal0:new i(o.feeGrowthGlobal0).toFixed(0),y=t.zeroForOne?a(m):a(f);return{sqrtPrice:l,liquidity:u,tick:d,amountSpecifiedRemaining:p,amountCalculated:va.ZERO,feeGrowthGlobalX:y,protocolFee:va.ZERO}}static computeSwapLoop(e,t,n,o){const{pool:a,tickDataMap:s}=t,c=[],l={};let u=0;const d=n.zeroForOne?va.MIN_SQRT_RATIO:va.MAX_SQRT_RATIO,h=new i("0.000001");for(;e.amountSpecifiedRemaining.gt(h)&&!e.sqrtPrice.eq(d)&&u<o.maxIterations;){u++;const[t,h]=this.findNextInitializedTick(s,e.tick,a.tickSpacing,n.zeroForOne);let g;if(o.debugLogging&&this.logger.debug(`Swap step ${u}`,{currentTick:e.tick,tickNext:t,initialized:h,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),h&&t>=-887272&&t<=887272){const e=r.tickToSqrtPrice(t);g=e instanceof i?e:new i(String(e))}else g=d;const p=n.zeroForOne?i.max(g,d):i.min(g,d),m=this.executeSwapStep(e.sqrtPrice,p,e.liquidity,e.amountSpecifiedRemaining,a.fee,n.exactInput);if(e.sqrtPrice=m.sqrtPriceNext,n.exactInput){const t=m.amountIn.plus(m.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=va.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=va.ZERO)),e.amountCalculated=e.amountCalculated.minus(m.amountOut)}else{m.amountOut.lte(0)?e.amountSpecifiedRemaining=va.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(m.amountOut),e.amountCalculated=e.amountCalculated.plus(m.amountIn.plus(m.feeAmount))}if(e.liquidity.gt(0)){const t=m.feeAmount.div(e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(g)&&h){const a=s[t.toString()];if(!a)throw new Error(`Missing tick data for initialized tick ${t}`);const r=n.zeroForOne?new i(a.liquidityNet).negated():new i(a.liquidityNet);if(e.liquidity=e.liquidity.plus(r),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);c.push(t),l[t.toString()]=a,o.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:r.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(g))e.tick=n.zeroForOne?t-1:t;else{const t=r.sqrtPriceToTick(new i(e.sqrtPrice.toString()));e.tick=t}}if(u>=o.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${o.maxIterations}). Possible infinite loop or very complex swap.`);const g=e.sqrtPrice.eq(d);return{state:e,ticksCrossed:c,priceHitLimit:g,stepCount:u,updatedTicks:l}}static createUpdatedPool(e,t,n,o){const a=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(a.sqrtPrice=t.sqrtPrice.toFixed(0),a.liquidity=t.liquidity.toFixed(0),a.tick=t.tick,n.zeroForOne?a.feeGrowthGlobal1=t.feeGrowthGlobalX.toFixed(0):a.feeGrowthGlobal0=t.feeGrowthGlobalX.toFixed(0),n.zeroForOne){const n=new i(e.protocolFeesToken0);a.protocolFeesToken0=n.plus(t.protocolFee).toFixed(0)}else{const n=new i(e.protocolFeesToken1);a.protocolFeesToken1=n.plus(t.protocolFee).toFixed(0)}return a}static calculateFinalAmounts(e,t,n){let o,a,r,s;if(n.exactInput){const e=new i(n.amountSpecified),c=t.amountCalculated.abs();n.zeroForOne?(o=e.negated(),a=c,r=va.ZERO,s=va.ZERO):(o=c,a=e.negated(),r=va.ZERO,s=va.ZERO)}else{const e=new i(n.amountSpecified),c=t.amountCalculated.abs();n.zeroForOne?(o=c.negated(),a=e,r=va.ZERO,s=va.ZERO):(o=e,a=c.negated(),r=va.ZERO,s=va.ZERO)}const c=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?s=c:r=c,{amount0:o,amount1:a,feeAmount0:r,feeAmount1:s}}static findNextInitializedTick(e,t,n,o){const a=Object.keys(e).map(e=>parseInt(e,10)).sort((e,t)=>e-t);if(0===a.length){return[o?-887272:887272,!1]}if(o){const e=a.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=a.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,o,a,s){to(n),no(o,"amountRemaining","for swap step");const c=[500,3e3,1e4];if(!c.includes(a))throw new Error(`Invalid fee tier: ${a}. Must be one of: ${c.join(", ")}`);const l=r.computeSwapStep(e,t,n,o,a,t.lt(e)),u=l[0],d=l[1],h=l[2],g=l[3],p=i.isBigNumber(u)?u:new i(String(u)),m=i.isBigNumber(d)?d:new i(String(d)),f=i.isBigNumber(h)?h:new i(String(h)),y=i.isBigNumber(g)?g:new i(String(g));return{sqrtPriceStart:e,tickNext:r.sqrtPriceToTick(p),sqrtPriceNext:p,initialised:!1,amountIn:m,amountOut:f,feeAmount:y}}}Sa.logger=new S({debug:!1,context:"SwapDeltaCalculator"});class Aa{static fastValidation(e,t,n,o=Aa.DEFAULT_CONFIG){const a=Date.now();let r=!0;try{const s=new i(e.sqrtPrice),c=new i(t.sqrtPrice);n.zeroForOne?c.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:c.toString(),zeroForOne:n.zeroForOne}),r=!1):c.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:c.toString(),zeroForOne:n.zeroForOne}),r=!1);const l=new i(e.liquidity),u=new i(t.liquidity);if(!l.isZero()){const e=u.minus(l).abs().div(l);e.gt(o.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:l.toString(),updatedLiquidity:u.toString(),changePct:e.times(100).toFixed(2)})}const d=new i(e.feeGrowthGlobal0),h=new i(t.feeGrowthGlobal0),g=new i(e.feeGrowthGlobal1),p=new i(t.feeGrowthGlobal1);n.zeroForOne?p.lt(g)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:g.toString(),updatedFeeGrowth1:p.toString()}),r=!1):h.lt(d)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:d.toString(),updatedFeeGrowth0:h.toString()}),r=!1);const m=new i(e.protocolFeesToken0),f=new i(t.protocolFeesToken0),y=new i(e.protocolFeesToken1),w=new i(t.protocolFeesToken1);f.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:m.toString(),updatedProtocolFees0:f.toString()}),r=!1),w.lt(y)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:y.toString(),updatedProtocolFees1:w.toString()}),r=!1);const k=Date.now()-a;return this.logger.debug("Fast validation completed",{passed:r,elapsedMs:k}),r}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=Aa.DEFAULT_CONFIG){const o=Date.now(),a=[];let s=0;try{if(t.actualSqrtPrice){const o=new i(e.sqrtPrice),r=new i(t.actualSqrtPrice),c=this.calculateDriftPercentage(o,r);s=c,c>100*n.maxDriftThreshold&&a.push(`Price drift detected: ${c.toFixed(4)}% (threshold: ${(100*n.maxDriftThreshold).toFixed(4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:o.toString(),actualSqrtPrice:r.toString(),driftPct:c.toFixed(4)})}const c=new i(e.sqrtPrice),l=new i(2).pow(96),u=c.dividedBy(l),d=r.sqrtPriceToTick(u),h=e.tick??0,g=Math.abs(d-h);g>n.maxTickDrift&&a.push(`Tick/price mismatch: tick=${h}, calculated=${d}, drift=${g}`);const p=new i(e.feeGrowthGlobal0),m=new i(e.feeGrowthGlobal1),f=new i(e.liquidity);try{to(p,m,f)}catch(e){a.push(e.message)}const y=0===a.length,w=!y||s>100*n.maxDriftThreshold,k=Date.now()-o;return this.logger.debug("Moderate validation completed",{isValid:y,shouldRefetch:w,driftPercentage:s,errorCount:a.length,elapsedMs:k}),this.buildValidationResult(y,s,w,a)}catch(e){return this.logger.error("Moderate validation exception",e),this.buildValidationResult(!1,0,!0,[`Exception during validation: ${e.message}`])}}static async fullValidation(e,t,n){const o=Date.now(),a=[];let r=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await n(),c=new i(t.pool.sqrtPrice),l=new i(s.pool.sqrtPrice),u=this.calculateDriftPercentage(c,l);r=Math.max(r,u),u>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&a.push(`Price drift: ${u.toFixed(4)}% (cached: ${c.toString()}, fresh: ${l.toString()})`);const d=new i(t.pool.liquidity),h=new i(s.pool.liquidity),g=this.calculateDriftPercentage(d,h);r=Math.max(r,g),g>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&a.push(`Liquidity drift: ${g.toFixed(4)}% (cached: ${d.toString()}, fresh: ${h.toString()})`);const p=Object.keys(t.tickDataMap).length,m=Object.keys(s.tickDataMap).length;if(m>0){const e=Math.abs(m-p)/m;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&a.push(`Tick data incomplete: cached has ${p} ticks, fresh has ${m} ticks (${(100*e).toFixed(2)}% difference)`)}const f=0===a.length,y=!f,w=Date.now()-o;return this.logger.debug("Full validation completed",{poolKey:e,isValid:f,shouldRefetch:y,maxDriftPercentage:r,priceDrift:u,liquidityDrift:g,cachedTickCount:p,freshTickCount:m,errorCount:a.length,elapsedMs:w}),this.buildValidationResult(f,r,y,a)}catch(t){return this.logger.error("Full validation exception",{poolKey:e,error:t}),this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${t.message}`])}}static calculateDriftPercentage(e,t){if(t.isZero())return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return t.minus(e).abs().div(t).times(100).toNumber()}static buildValidationResult(e,t,n,o=[]){let a;if(n&&o.length>0){const e=o.join(" ").toLowerCase();a=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const i={isValid:e,driftPercentage:t,shouldRefetch:n,validationErrors:o};return void 0!==a&&(i.refetchReason=a),i}}Aa.logger=new S({debug:!1,context:"PoolStateValidator"}),Aa.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class ba{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return g.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){this.logger=new S({debug:t?.debug??!1,context:"PoolStateManager"});const n={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??i.ROUND_DOWN,debug:t?.debug??!1,maxSwapsSinceRefetch:t?.maxSwapsSinceRefetch??50,maxCumulativeDrift:t?.maxCumulativeDrift??5,strictValidation:t?.strictValidation??!1,enablePerformanceWarnings:t?.enablePerformanceWarnings??!0,performanceWarningThreshold:t?.performanceWarningThreshold??100};this.config={...n,...t?.onRefetchNeeded?{onRefetchNeeded:t.onRefetchNeeded}:{}},this.validationConfig=Aa.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:ba.calculatePoolStateHash(this.pool)};if(!Aa.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new Error("Initial pool state validation failed");this.logger.info("PoolStateManager initialized",{pool:{sqrtPrice:this.pool.sqrtPrice.toString(),liquidity:this.pool.liquidity.toString(),tick:this.pool.tick},config:this.config})}async applySwapDelta(e){const t=Date.now();if(this.metadata.processedTransactions.includes(e.transactionId))throw this.logger.warn("Duplicate swap transaction",{transactionId:e.transactionId}),new Error(`Duplicate transaction ID: ${e.transactionId}`);try{const t={pool:this.pool,tickDataMap:this.tickDataMap},n={maxIterations:this.config.maxIterations,enableBigNumberCache:this.config.enableBigNumberCache,roundingMode:this.config.roundingMode,debugLogging:this.config.debug},o=Sa.calculateSwapDelta(t,e,n);this.lastSwapMetrics={calculationTimeMs:o.metadata.calculationTimeMs,swapSteps:o.metadata.swapSteps,timestamp:Date.now()},this.config.enablePerformanceWarnings&&o.metadata.calculationTimeMs>this.config.performanceWarningThreshold&&this.logger.warn("Slow swap calculation",{calculationTimeMs:o.metadata.calculationTimeMs,swapSteps:o.metadata.swapSteps,threshold:this.config.performanceWarningThreshold});if(!Aa.fastValidation(t.pool,o.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new Error("Swap validation failed");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=new i(e.actualAmount0),n=new i(e.actualAmount1),a=o.amount0.minus(t).abs(),r=o.amount1.minus(n).abs(),s=t.isZero()?0:a.div(t.abs()).times(100).toNumber(),c=n.isZero()?0:r.div(n.abs()).times(100).toNumber(),l=Math.max(s,c);l>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:l.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=l)}if((this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift)&&(this.logger.info("Triggering full refetch due to drift accumulation",{swapsSinceRefetch:this.metadata.swapsSinceRefetch,cumulativeDrift:this.metadata.cumulativeDrift.toFixed(2)}),this.config.onRefetchNeeded)){const e=await this.config.onRefetchNeeded(this.pool,this.tickDataMap);this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.metadata.stateHash=ba.calculatePoolStateHash(this.pool),this.logger.info("Full refetch completed",{sqrtPrice:this.pool.sqrtPrice.toString()})}return this.pool=o.updatedPool,Object.assign(this.tickDataMap,o.updatedTicks),this.metadata.swapsSinceRefetch++,this.metadata.stateHash=ba.calculatePoolStateHash(this.pool),this.metadata.processedTransactions.push(e.transactionId),this.metadata.processedTransactions.length>1e3&&(this.metadata.processedTransactions=this.metadata.processedTransactions.slice(-1e3)),this.logger.debug("Swap delta applied",{transactionId:e.transactionId,amount0:o.amount0.toString(),amount1:o.amount1.toString(),sqrtPriceNew:this.pool.sqrtPrice.toString()}),o}catch(n){const o=n instanceof Error?n.message:String(n);if(this.logger.error("Failed to apply swap delta",{transactionId:e.transactionId,error:o}),this.config.strictValidation)throw n;return{updatedPool:this.pool,updatedTicks:{},amount0:new i(0),amount1:new i(0),feeAmount0:new i(0),feeAmount1:new i(0),ticksCrossed:[],metadata:{calculationTimeMs:Date.now()-t,swapSteps:0,priceHitLimit:!1}}}}forceFullRefetch(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.logger.info("Full refetch forced",{sqrtPrice:this.pool.sqrtPrice.toString()})}getPoolState(){return this.pool}getTickDataMap(){return{...this.tickDataMap}}getMetadata(){return{...this.metadata}}getLastSwapMetrics(){if(this.lastSwapMetrics)return{...this.lastSwapMetrics}}isRefetchRecommended(){return this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift}reset(e){this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:ba.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}var Ea=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const o=parseFloat(e.reverseBondingCurveMinFeePortion);isNaN(o)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=o}if(void 0!==e.reverseBondingCurveMaxFeePortion){const o=parseFloat(e.reverseBondingCurveMaxFeePortion);isNaN(o)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=o}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});e.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),n=this.setupWallet(e.privateKey),o={wallet:n.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{}},a=new ya(o),i={sdk:a,wallet:n,config:o};if(!1!==e.autoValidate){const e=await this.validateSetup(a,n);return{...i,validation:e}}return i}static async readOnlySetup(e={}){const t=e.environment||this.detectEnvironment(),n={wallet:void 0,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{}};return{sdk:new ya(n),config:n}}static async validateSetup(e,t){const n=[],o=[],a={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(a.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);a.hasBalance=e>0,a.canTrade=e>=.1,a.canCreateTokens=e>=100,0===e?o.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?o.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&o.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${e instanceof Error?e.message:String(e)}`)}try{const t=await e.fetchPools({type:"recent",page:1,limit:1});t.pools&&0!==t.pools.length||o.push("Pool listing not accessible - some features may be limited")}catch(e){o.push(`Pool access test failed: ${e instanceof Error?e.message:String(e)}`)}return{ready:0===n.length&&a.connectionHealthy,sdk:e,wallet:t||wa.generateWallet(),issues:n,warnings:o,capabilities:a}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(n,{debug:!1,timeout:3e4});break;case"development":Object.assign(n,{debug:!0,timeout:45e3});break;case"testing":Object.assign(n,{debug:!0,timeout:6e4})}switch(t){case"trading":n.timeout=1.5*(n.timeout||3e4);break;case"creation":n.timeout=2*(n.timeout||3e4);break;case"monitoring":n.timeout=.5*(n.timeout||3e4)}return n}static async multiWalletSetup(e,t="development"){const n={};for(const[o,a]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:a,agentId:`multi-wallet-${o}`,autoValidate:!1});n[o]=e}return n}static detectEnvironment(){const e=process.env.NODE_ENV?.toLowerCase();return"development"===e?"development":"test"===e||"testing"===e?"testing":"production"}static setupWallet(e){if(!e){const e=process.env.PRIVATE_KEY;return e?wa.fromPrivateKey(e):wa.generateWallet()}return"generate"===e?wa.generateWallet():wa.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}},e.CALCULATION_MODES=sa,e.COMPOSITE_POOL_FETCH_CONCURRENCY=5,e.ConfigurationError=F,e.DexPoolNotFoundError=O,e.DexQuoteError=U,e.FileValidationError=Kn,e.GALA_DECIMALS=8,e.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},e.GSwapAssetError=L,e.GSwapPoolError=$,e.GSwapQuoteError=C,e.GSwapSwapError=x,e.IMAGE_EXTENSIONS=Ue,e.LAUNCHPAD_TOKEN_DECIMALS=18,e.LaunchpadSDK=ya,e.MAX_CONCURRENT_POOL_FETCHES=5,e.NetworkError=P,e.PAGINATION_DEFAULTS=kn,e.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},e.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},e.PoolStateManager=ba,e.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},e.SDK_VERSION=fa,e.TRADING_TYPES=ra,e.TokenMetadataService=class extends Tn{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}async resolveTokenMetadata(e){const t=this.getCacheKey(e),n=this.cache[t];if(n&&!this.isCacheExpired(n.timestamp))return this.logger.debug(`Using cached metadata for token: ${t}`),n.data;const o=this.extractMetadata(e);return this.cache[t]={data:o,timestamp:Date.now()},o}async getTokenSymbol(e){return(await this.resolveTokenMetadata(e)).symbol}async getTokenDecimals(e){return(await this.resolveTokenMetadata(e)).decimals}clearCache(e){e?(delete this.cache[e],this.logger.debug(`Cleared cache for token: ${e}`)):(this.cache={},this.logger.debug("Cleared all token metadata cache"))}getCacheStats(){const e=Object.keys(this.cache);return{size:e.length,entries:e}}getCacheKey(e){if("string"==typeof e)return e.toLowerCase();return`${e.type||e.symbol||"unknown"}|${e.additionalKey||"none"}`.toLowerCase()}extractMetadata(e){let t,n,o="Token",a="Unit",i="none";if("string"==typeof e)if(e.includes("|")){const r=e.split("|");"Token"===r[0]&&r[2]?(o=r[0],a=r[1]||"Unit",t=r[2],i=r[3]||"none",n=t):(t=r[0],n=t,a=r[1]||"Unit",i=r[3]||"none")}else t=e,n=e;else t=e.type||"unknown",n=e.symbol||e.type||"unknown",o=e.collection||"Token",a=e.category||"Unit",i=e.additionalKey||"none";const r=this.getDecimalsForToken(n);return{symbol:n.toUpperCase(),decimals:r,collection:o,category:a,type:t.toUpperCase(),additionalKey:i,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return Date.now()-e>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}},e.TransactionError=D,e.TransactionFailedError=ga,e.ValidationError=N,e.WebSocketError=ha,e.WebSocketTimeoutError=class extends ha{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},e.addressFormatSchema=te,e.amountMethodSchema=$e,e.amountTypeSchema=xe,e.browserFileSchema=_e,e.bufferFileSchema=Re,e.buyTokensDataSchema=st,e.calculatePreMintDataSchema=pt,e.checkPoolOptionsSchema=Ce,e.commentMessageSchema=we,e.commentPaginationSchema=je,e.createLaunchpadSDK=function(e){e||(e={});const{wallet:t,env:o,config:a={},...i}=e,r={...i,...a},{wallet:s,env:c,config:l,...u}=r;let d;if(t)if("string"==typeof t){d=ka(t).wallet}else{if(!(t instanceof n.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");d=t}else{d=ka().wallet}const h={wallet:d,...o&&{env:o},debug:!1,timeout:3e4,...u};return new ya(h)},e.createLimitSchema=de,e.createPaginatedResultSchema=function(e){return a.z.object({data:a.z.array(e),page:a.z.number().int().min(1),limit:a.z.number().int().min(1),total:a.z.number().int().min(0),totalPages:a.z.number().int().min(0),hasNext:a.z.boolean(),hasPrevious:a.z.boolean()})},e.createPoolStateManager=function(e,t){return new ba(e,t)},e.createTradeDataSchema=rt,e.createWallet=ka,e.ethereumAddressSchema=ne,e.faucetAmountSchema=se,e.fetchGalaBalanceOptionsSchema=et,e.fetchPoolDetailsDataSchema=mt,e.fetchTokenBalanceOptionsSchema=ot,e.fileSizeSchema=me,e.fileUploadSchema=Oe,e.filenameSchema=fe,e.filterByFeeTier=function(e,t){return e.filter(e=>e.feeTier===t)},e.filterByLiquidity=function(e){return e.filter(e=>new i(e.liquidity).isGreaterThan(0))},e.filterByMinLiquidity=function(e,t){const n=new i(t);return e.filter(e=>new i(e.liquidity).isGreaterThanOrEqualTo(n))},e.filterByPoolKey=function(e,t,n,o){const a=t.toUpperCase(),i=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return(t===a&&n===i||t===i&&n===a)&&e.feeTier===o})},e.filterByToken=function(e,t){const n=t.toUpperCase();return e.filter(e=>e.token0.toUpperCase()===n||e.token1.toUpperCase()===n)},e.filterByTokenPair=function(e,t,n){const o=t.toUpperCase(),a=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return t===o&&n===a||t===a&&n===o})},e.flexibleAddressSchema=oe,e.flexibleFileSchema=qe,e.formatGalaForDTO=To,e.formatLaunchpadTokenForDTO=So,e.fullNameSchema=ee,e.getAmountOptionsSchema=gt,e.getEnv=function(e,t){return process.env[e]??t},e.getEnvOrThrow=function(e,t){const n=process.env[e];if(!n){throw new Error(t?`${e} not set in root or local .env (${t})`:`${e} not set in root or local .env`)}return n},e.getTradeOptionsSchema=lt,e.graduateTokenOptionsSchema=Be,e.graphDataOptionsSchema=Le,e.groupByFeeTier=function(e){const t=new Map;return e.forEach(e=>{t.has(e.feeTier)||t.set(e.feeTier,[]),t.get(e.feeTier).push(e)}),t},e.groupByPoolKey=function(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t},e.groupByTokenPair=function(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t},e.imageExtensionSchema=Me,e.imageFilenameSchema=Ge,e.imageMimeTypeSchema=ye,e.imageUploadOptionsSchema=Fe,e.isoDateStringSchema=ke,e.launchTokenDataSchema=Pe,e.loadEnvWithFallback=function(){const e=y.join(process.cwd(),"..","..",".env");w.existsSync(e)&&k.config({path:e});const t=y.join(process.cwd(),".env");w.existsSync(t)&&k.config({path:t})},e.nonNegativeDecimalStringSchema=re,e.optionalUrlSchema=le,e.pageNumberSchema=ue,e.paginationResultMetaSchema=Xe,e.poolFetchTypeSchema=De,e.poolPaginationSchema=We,e.positiveDecimalStringSchema=ie,e.privateKeySchema=Te,e.requireNonNegative=to,e.requirePositive=function(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThanOrEqualTo(0))throw new Error(`Value at index ${t} must be positive, got: ${e.toString()}`)})},e.requirePositiveWithContext=no,e.reverseBondingCurveConfigSchema=Ne,e.reverseBondingCurveConfigurationSchema=ft,e.searchQuerySchema=J,e.sellTokensDataSchema=ct,e.sortByLiquidity=function(e,t="desc"){return[...e].sort((e,n)=>{const o=new i(e.liquidity),a=new i(n.liquidity);return"desc"===t?a.minus(o).toNumber():o.minus(a).toNumber()})},e.standardLimitSchema=he,e.standardPaginationSchema=Ke,e.timestampSchema=ve,e.tokenCategorySchema=Ee,e.tokenCollectionSchema=Ie,e.tokenDescriptionSchema=Z,e.tokenListOptionsSchema=Ye,e.tokenNameSchema=Q,e.tokenSymbolSchema=X,e.tokenUrlsSchema=be,e.tradeCalculationMethodSchema=ht,e.tradeCalculationTypeSchema=dt,e.tradeLimitSchema=pe,e.tradeListParamsSchema=ut,e.tradePaginationSchema=Ve,e.tradePaginationWithFiltersSchema=Qe,e.tradeTypeBackendSchema=it,e.tradeTypeSchema=at,e.transactionIdSchema=Se,e.transferFaucetsDataSchema=Je,e.uniqueKeySchema=Ae,e.updateProfileDataSchema=tt,e.uploadProfileImageOptionsSchema=nt,e.urlSchema=ce,e.userLimitSchema=ge,e.userPaginationSchema=ze,e.userTokenNameSchema=Y,e.userTokenTypeSchema=Ze,e.userTokensPaginationSchema=He,e.validateAddress=Tt,e.validateAmountString=At,e.validateBuyTokensData=Rt,e.validateCalculatePreMintData=zt,e.validateCheckPoolOptions=Ct,e.validateCreateTradeData=_t,e.validateFaucetAmount=bt,e.validateFetchGalaBalanceOptions=Lt,e.validateFetchPoolDetailsData=Vt,e.validateFetchTokenBalanceOptions=Ot,e.validateFullName=Et,e.validateGetAmountOptions=Kt,e.validateGetTradeOptions=Mt,e.validateImageUploadOptions=Dt,e.validateLaunchTokenData=Pt,e.validateSearchQuery=It,e.validateSellTokensData=qt,e.validateTokenDescription=vt,e.validateTokenListOptions=xt,e.validateTokenName=wt,e.validateTokenSymbol=kt,e.validateTokenUrls=Ft,e.validateTradeListParams=Gt,e.validateTransferFaucetsData=$t,e.validateUpdateProfileData=Bt,e.validateUploadProfileImageOptions=Ut,e.validateUserTokenName=Nt,e.validateVaultAddress=St,e.vaultAddressSchema=ae});
|