@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.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"axios";import{ethers as t,Wallet as a,Mnemonic as n,HDNodeWallet as o}from"ethers";import{SigningType as r,SigningClient as i,ChainCallDTO as s,calculatePersonalSignPrefix as c}from"@gala-chain/connect";import{z as l}from"zod";import u from"bignumber.js";import{TokenClassKey as d}from"@gala-chain/api";import{v4 as h}from"uuid";import{io as g}from"socket.io-client";import{PrivateKeySigner as p,GSwap as m}from"@gala-chain/gswap-sdk";if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}var f,y;!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"}(f||(f={}));class w extends Error{constructor(e,t,a){super(t),this.type=e,this.originalError=a,this.name="AuthError"}}class k{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new w(f.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 w(f.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new w(f.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 w)throw e;throw new w(f.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 w(f.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 w(f.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 w)throw e;const t=e instanceof Error?e.message:String(e);throw new w(f.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 w)throw e;throw new w(f.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 w)throw e;throw new w(f.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 w(f.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 w)throw e;throw new w(f.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new w(f.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new w(f.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new w(f.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"}(y||(y={}));class v{constructor(e){this.levelPriority={[y.DEBUG]:0,[y.INFO]:1,[y.WARN]:2,[y.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?y.DEBUG:y.INFO)}debug(e,t){this.log(y.DEBUG,e,t)}info(e,t){this.log(y.INFO,e,t)}warn(e,t){this.log(y.WARN,e,t)}error(e,t){this.log(y.ERROR,e,t)}log(e,t,a){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===y.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 y.DEBUG:return console.debug;case y.INFO:return console.info;case y.WARN:return console.warn;case y.ERROR:return console.error;default:return console.log}}child(e){return new v({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[y.DEBUG]>=this.levelPriority[this.minLevel]}}function A(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 T{constructor(t,a={}){this.auth=t,this.debug=a.debug??!1,this.logger=new v({debug:this.debug,context:"HttpClient"}),this.axios=e.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:A(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};e.data instanceof FormData&&(t.headers&&t.headers["Content-Type"]&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload"));const a=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:a,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const n=await this.axios.request(t);return this.logger.debug("Response:",{status:n.status,data:n.data}),n.data}catch(e){throw this.logger.error("Error:",e),e}}async get(e,t,a){return this.request({method:"GET",url:e,...t&&{params:t},...a&&{headers:a}})}async post(e,t,a){return this.request({method:"POST",url:e,data:t,...a&&{headers:a}})}async put(e,t,a){return this.request({method:"PUT",url:e,data:t,...a&&{headers:a}})}async delete(e,t,a){return this.request({method:"DELETE",url:e,...t&&{params:t},...a&&{headers:a}})}async patch(e,t,a){return this.request({method:"PATCH",url:e,data:t,...a&&{headers:a}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,a){return await this.auth.signTypedData(e,t,a)}async signCustomMessage(e){try{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}}catch(e){throw this.logger.error("Custom signature generation failed:",e),new Error(`Failed to generate custom signature for message: ${e instanceof Error?e.message:"Unknown error"}`)}}async signWithGalaChain(e,t,a=r.SIGN_TYPED_DATA){const n=this.auth.getPrivateKey(),o=new i(n);return await o.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 b="Token name is required and must be a string",E=e=>`Could not find vault address for token: ${e}`;class N extends Error{constructor(e,t,a){super(e),this.field=t,this.code=a,this.name="ValidationError"}}class S extends Error{constructor(e,t,a){super(e),this.statusCode=t,this.originalError=a,this.name="NetworkError"}}class I extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class F extends Error{constructor(e,t,a){super(e),this.transactionId=t,this.code=a,this.name="TransactionError"}}class C extends Error{constructor(e,t,a){super(e),this.originalError=t,this.code=a,this.name="GSwapQuoteError"}}class D extends Error{constructor(e,t,a,n){super(e),this.originalError=t,this.transactionHash=a,this.code=n,this.name="GSwapSwapError"}}class P 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 x extends Error{constructor(e,t,a,n){super(e),this.originalError=t,this.walletAddress=a,this.code=n,this.name="GSwapAssetError"}}class $ extends Error{constructor(e,t,a){super(e),this.originalError=t,this.code=a,this.name="GSwapPositionError"}}function L(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 N(`Page must be a number between ${n} and ${o}`,"page","INVALID_PAGE");if("number"!=typeof t||t<r||t>i)throw new N(`Limit must be a number between ${r} and ${i}`,"limit","INVALID_LIMIT")}const _={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function U(e){return"string"==typeof e&&e.trim().length>0}function B(e){return!(!e||"string"!=typeof e)&&(_.ETH_ADDRESS.test(e)||_.BACKEND_ADDRESS.test(e))}function M(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const O=l.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"),R=l.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"),G=l.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),K=l.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),q=l.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),V=l.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"),W=l.string().regex(_.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),j=l.string().regex(_.ETH_ADDRESS,"Invalid Ethereum address format"),H=l.string().refine(e=>_.BACKEND_ADDRESS.test(e)||_.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),X=l.string().refine(e=>_.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),z=l.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),Q=l.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),Y=l.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),Z=l.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),J=l.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),ee=l.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 te(e=100){return l.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 ae=te(100),ne=te(20),oe=te(20),re=l.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"),ie=l.string().max(255,"Filename must be at most 255 characters"),se=l.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),ce=l.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),le=l.string().datetime("Must be a valid ISO 8601 date string"),ue=l.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),de=l.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),he=l.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"),ge=l.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),pe=l.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"),me=l.string().min(1,"Token category must not be empty").default("Unit"),fe=l.string().min(1,"Token collection must not be empty").default("Token"),ye=l.object({minFeePortion:z,maxFeePortion:z}),we=l.object({tokenName:O,tokenSymbol:R,tokenDescription:G,tokenImage:l.union([l.instanceof(File),l.instanceof(Buffer),l.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Q.default("0"),websiteUrl:J,telegramUrl:J,twitterUrl:J,tokenCategory:me,tokenCollection:fe,reverseBondingCurveConfiguration:ye.optional(),privateKey:de.optional()}),ke=l.object({file:l.union([l.instanceof(File),l.instanceof(Buffer)]),tokenName:O}),ve=l.enum(["recent","popular"]),Ae=l.object({tokenName:O.optional(),symbol:R.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),Te=l.enum(["NATIVE","MEME"]),be=l.enum(["IN","OUT"]),Ee=l.object({from:l.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:l.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:l.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:O}),Ne=l.object({tokenName:O,slippageToleranceFactor:l.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:l.number().min(0).max(1).optional(),privateKey:de.optional()}),Se=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Ie=l.object({file:l.union([l.instanceof(File),l.instanceof(Buffer)]),name:ie,size:re,type:se}),Fe=l.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"),Ce=l.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),De=l.union([Fe,Ce]),Pe=l.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),xe=ie.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Se.includes(t)},`Filename must end with one of: ${Se.join(", ")}`),$e=l.object({page:ee,limit:ae}),Le=l.object({page:ee,limit:ne}),_e=l.object({page:ee,limit:oe}),Ue=l.object({page:ee,limit:te(50)}),Be=$e.extend({type:l.enum(["recent","popular"]).optional(),tokenName:l.string().min(1).max(50).optional(),search:l.string().min(1).max(100).optional()}),Me=Le.extend({tokenName:l.string().min(1).max(50).optional(),search:l.string().min(1).max(100).optional()}),Oe=_e.extend({tradeType:l.enum(["BUY","SELL"]).optional(),tokenName:l.string().min(1).max(50).optional(),userAddress:l.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:l.string().datetime().optional(),endDate:l.string().datetime().optional(),sortOrder:l.enum(["ASC","DESC"]).default("DESC")}),Re=l.object({page:l.number().int().min(1),limit:l.number().int().min(1),total:l.number().int().min(0),totalPages:l.number().int().min(0),hasNext:l.boolean(),hasPrevious:l.boolean()});function Ge(e){return l.object({data:l.array(e),page:l.number().int().min(1),limit:l.number().int().min(1),total:l.number().int().min(0),totalPages:l.number().int().min(0),hasNext:l.boolean(),hasPrevious:l.boolean()})}const Ke=l.enum(["all","DEFI","ASSET"]),qe=Le.extend({type:Ke.optional(),address:H.optional(),search:q.optional(),tokenName:K.optional()}),Ve=l.object({walletAddress:H,amount:Y}),We=l.object({address:H.optional(),refresh:l.boolean().optional()}),je=l.object({profileImage:l.string(),fullName:V,address:H,privateKey:de.optional()}),He=l.object({file:l.union([l.instanceof(File),l.instanceof(Buffer)]),address:H.optional(),privateKey:de.optional()}),Xe=l.object({address:H,tokenId:l.union([l.string(),l.object({collection:l.string(),category:l.string(),type:l.string(),additionalKey:l.string()}),l.object({collection:l.string(),category:l.string(),type:l.string(),additionalKey:l.string(),instance:l.string()})]).optional(),tokenName:K.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),ze=l.enum(["buy","sell"]),Qe=l.enum(["BUY","SELL"]),Ye=l.object({tradeType:ze,tokenAmount:z,vaultAddress:X,userAddress:H,slippageTolerance:z.optional(),deadline:l.number().int().positive().optional()}),Ze=l.object({tokenSymbol:R,nativeTokenQuantity:z,expectedToken:z,maxAcceptableReverseBondingCurveFee:Q.default("0").optional()}),Je=l.object({tokenSymbol:R,tokenQuantity:z,expectedNativeToken:z,maxAcceptableReverseBondingCurveFee:Q.default("0").optional()}),et=_e.extend({tokenName:K.optional()}),tt=l.object({page:l.number().int().min(1).max(1e3).default(1).optional(),limit:l.number().int().min(1).max(20).default(10).optional()}),at=l.enum(["NATIVE","MEME"]),nt=l.enum(["IN","OUT"]),ot=l.object({type:at,method:nt,vaultAddress:X,amount:z}),rt=l.object({nativeTokenQuantity:z}),it=l.object({vaultAddress:X}),st=l.object({minFeePortion:z,maxFeePortion:z});function ct(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 lt=ct(O),ut=ct(R),dt=ct(G),ht=ct(H),gt=ct(X),pt=ct(z),mt=ct(Y),ft=ct(V),yt=ct(q),wt=ct(K),kt=ct(we),vt=ct(pe),At=ct(ke),Tt=ct(Ae),bt=ct(qe),Et=ct(Ve),Nt=ct(We),St=ct(je),It=ct(He),Ft=ct(Xe),Ct=ct(Ye),Dt=ct(Ze),Pt=ct(Je),xt=ct(et),$t=ct(tt),Lt=ct(ot),_t=ct(rt),Ut=ct(it);function Bt(e,t){throw new N(e.join("; "),t,"VALIDATION_ERROR")}function Mt(e){const t=lt(e);!t.success&&t.errors&&Bt(t.errors,"tokenName")}function Ot(e){const t=Be.safeParse(e);t.success||Bt(t.error.errors.map(e=>e.message),"pagination")}function Rt(e){const t=Tt(e);!t.success&&t.errors&&Bt(t.errors,"options")}function Gt(e){const t=Lt(e);!t.success&&t.errors&&Bt(t.errors,"options")}function Kt(e){const t=Ee.safeParse(e);t.success||Bt(t.error.errors.map(e=>e.message),"options")}function qt(e){const t=H.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 Vt(e,t,a=!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 n=parseFloat(e);if(isNaN(n))throw new N(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(n))throw new N(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(n<0)throw new N(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!a&&0===n)throw new N(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var Wt=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=H.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:qt,validateCheckPoolOptions:Rt,validateGetAmountOptions:Gt,validateGetGraphOptions:Kt,validateNumericString:Vt,validatePagination:Ot,validateTokenName:Mt});function jt(e,t){return new N(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Ht(e,t){const a=t||e.charAt(0).toUpperCase()+e.slice(1);return new N(`${a} is required`,e,"REQUIRED_FIELD")}function Xt(e,t,a){const n=a||e.charAt(0).toUpperCase()+e.slice(1);return new N(`${n} must be ${t}`,e,"INVALID_FORMAT")}function zt(e,t,a){return new S(e,t,a)}function Qt(e,t){return new I(e,t)}function Yt(e,t,a){return new F(e,t,a)}function Zt(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 Jt(e,t){return{hasNext:e<t,hasPrevious:e>1}}function ea(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 ta="/launchpad/upload-image",aa="/launchpad/fetch-pool",na="/launchpad/check-pool",oa="/launchpad/get-graph-data",ra="/holders",ia="/launchpad/get-badge/",sa="/trade/",ca="/token/commment",la="/token/commment",ua="/user/profile",da="/user/profile",ha="/user/token-list",ga="/user/token-hold",pa="/user/transfer-faucets",ma=5,fa={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100},ya={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20};class wa{constructor(e,t=!1){this.http=e,this.logger=new v({debug:t,context:this.constructor.name})}}function ka(e,t){return"string"==typeof e[t]}function va(e,t){return void 0===e[t]||"string"==typeof e[t]}function Aa(e,t){return void 0===e[t]||"number"==typeof e[t]}function Ta(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function ba(e){if(!e||"object"!=typeof e)return!1;const t=e;return ka(t,"tokenName")&&Aa(t,"from")&&Aa(t,"to")&&Aa(t,"resolution")}class Ea extends wa{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=A(t),n=await this.http.get(aa,a);ea(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>fa.SAFETY_MAX_PAGES&&(s=!1)}return r}async fetchPools(e={}){const t=e.page||fa.DEFAULT_PAGE,a=e.limit??fa.DEFAULT_LIMIT;let n;if(0!==a&&Ot({page:t,limit:a}),e.tokenName&&Mt(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=fa.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=fa.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){Rt(e),e.tokenName&&Mt(e.tokenName);const t=A(e),a=await this.http.get(na,t);ea(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(!ba(e))throw new N("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(Mt(t),!a||!n||!o)throw new N("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:a,to:n,resolution:o};Kt(r);const i=A(r),s=await this.http.get(oa,i);return ea(s,"Failed to fetch graph data",!0),{dataPoints:s.data}}async fetchTokenDistribution(e){if(!e)throw Ht("tokenName","Token name");Mt(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw jt(e);const a=encodeURIComponent(t),n=await this.http.get(`${ra}/${a}`);ea(n,"Failed to fetch token distribution",!0);const o=n.data;if(!Array.isArray(o))throw zt("Invalid API response: expected array of holders",n.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw zt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw zt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw zt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const r=o.reduce((e,t)=>e.plus(t.quantity),new u(0));return{holders:o.map(e=>{const t=new u(e.quantity),a=r.isZero()?0:t.dividedBy(r).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:a}}),totalSupply:r.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Ht("tokenName","Token name");Mt(e);const t=await this.http.get(ia,{tokenName:e});return ea(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 Na(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 A(r)}const Sa={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class Ia extends wa{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ka(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&va(t,"userAddress")&&Aa(t,"page")&&Aa(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:a,userAddress:n,page:o=fa.DEFAULT_PAGE,limit:r=fa.DEFAULT_LIMIT,startDate:i,endDate:s,sortOrder:c}=e;if(!U(t))throw new N("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");L(o,r,Sa);const l=function(e,t,a){return Na({tokenName:e,page:t,limit:a},{stringifyFields:["page","limit"]})}(t,o,r),u=await this.http.get(sa,l),d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const g=Zt(u,{page:o,limit:r}),p=Jt(g.page,g.totalPages);return{trades:d,...g,...p}}}const Fa=new v({debug:!1,context:"DateUtils"});function Ca(e,t){if(!e)return t||new Date;if(e instanceof Date)return isNaN(e.getTime())?t||new Date:e;try{const a=new Date(e);return isNaN(a.getTime())?(Fa.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):a}catch(a){return Fa.warn(`Date parsing error for "${e}":`,a),t||new Date}}const Da={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class Pa extends wa{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 ka(t,"tokenName")&&Aa(t,"page")&&Aa(t,"limit")}(e))throw new N("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:a=fa.DEFAULT_PAGE,limit:n=fa.DEFAULT_LIMIT}=e;if(!U(t))throw new N("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");L(a,n,Da);const o=await this.poolService.resolveTokenNameToVault(t);if(!o)throw jt(t);const r=Na({vaultAddress:o,page:a,limit:n},{stringifyFields:["page","limit"]}),i=await this.http.get(ca,r);ea(i,"Failed to fetch comments");return{comments:i.data.comments.map(e=>({...e,createdAt:Ca(e.createdAt)})),total:i.data.count}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ka(t,"tokenName")&&ka(t,"content")}(e))throw new N("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:a}=e;if(!U(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>=Da.CONTENT.MIN_LENGTH&&t.length<=Da.CONTENT.MAX_LENGTH}(a))throw new N(`Comment content must be between ${Da.CONTENT.MIN_LENGTH} and ${Da.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const n=await this.poolService.resolveTokenNameToVault(t);if(!n)throw jt(t);const o={userAddress:this.http.getAddress(),vaultAddress:n,content:a};ea(await this.http.post(la,o),"Failed to create comment")}}function xa(e){return e instanceof Error}function $a(e){return xa(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 La(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function _a(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 Xt("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 Ua={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 Ba(e){return!(!e||"string"!=typeof e)&&Ua.USER_ADDRESS.PATTERN.test(e)}const Ma="Update profile";class Oa extends wa{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!Ba(t))throw new N("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const a={userAddress:t};return await this.http.get(ua,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(Ma),o={address:n.address,message:Ma,publickey:n.ethereumAddress,sign:n.signature};ea(await this.http.put(da,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=_a(e.file,"image",a),o=await this.http.request({method:"POST",url:`${ta}?tokenName=${encodeURIComponent(t)}`,data:n,headers:{}});return ea(o,"Image upload failed"),"string"==typeof o.data?o.data:""}catch(e){if(e instanceof N)throw e;throw new N(`Profile image upload failed: ${$a(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(ha,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(ga,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=fa.DEFAULT_PAGE,limit:a=fa.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=Na(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);ea(r,a.errorMessage,!0);const i=(s=r.data)?Array.isArray(s)?s:s.token:[];var s;const c=Zt(r,{page:t.page||fa.DEFAULT_PAGE,limit:t.limit||fa.DEFAULT_LIMIT}),l=Jt(c.page,c.totalPages);return{tokens:i,...c,...l}}validateGetTokenListOptions(e){if(L(e.page,e.limit,Ua),void 0!==e.address&&!Ba(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>=Ua.SEARCH.MIN_LENGTH&&t.length<=Ua.SEARCH.MAX_LENGTH))throw new N(`Search query must be between ${Ua.SEARCH.MIN_LENGTH} and ${Ua.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>=Ua.TOKEN_NAME.MIN_LENGTH&&a.length<=Ua.TOKEN_NAME.MAX_LENGTH))throw new N(`Token name must be between ${Ua.TOKEN_NAME.MIN_LENGTH} and ${Ua.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!Ba(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>=Ua.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=Ua.PROFILE.FULL_NAME.MAX_LENGTH&&Ua.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new N(`Full name must be between ${Ua.PROFILE.FULL_NAME.MIN_LENGTH} and ${Ua.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!Ba(e.address))throw new N("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Ra extends Error{constructor(e,t,a){super(e),this.filename=t,this.mimeType=a,this.name="FileValidationError"}}function Ga(e,t,a){if(!e)throw new Ra("File is required",t,a);if("undefined"!=typeof File&&e instanceof File){const t=Fe.safeParse(e);if(!t.success){const a=t.error.errors.map(e=>e.message).join("; ");throw new Ra(a,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Ra("Filename is required when uploading Buffer objects",t,a);const n=Ce.safeParse(e);if(!n.success){const e=n.error.errors.map(e=>e.message).join("; ");throw new Ra(e,t,a)}if(t.length>255)throw new Ra(`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 Ra(`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 Ra(`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 Ra(`File extension "${r}" does not match MIME type "${a}"`,t,a);return}throw new Ra("File must be a File object (browser) or Buffer (Node.js)",t,a)}class Ka extends wa{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Mt(t);const n=`${t}.png`;Ga(a.file,n,"image/png");try{const e=`${a.tokenName??t}.png`,n=_a(a.file,"image",e),o=await this.http.request({method:"POST",url:`${ta}?tokenName=${encodeURIComponent(a.tokenName??t)}`,data:n,headers:{}});return ea(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 qa extends wa{constructor(e,t=!1){super(e,t)}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount};ea(await this.http.post(pa,t),"Faucet transfer failed")}validateTransferFaucetsData(e){if(!Ba(e.walletAddress))throw new N("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!Ua.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 Va{constructor(e,t=!1){this.http=e,this.poolService=new Ea(e,t),this.tradeService=new Ia(e,t),this.commentService=new Pa(e,this.poolService,t),this.userService=new Oa(e,t),this.imageService=new Ka(e,t),this.faucetService=new qa(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 Mt(e)}}const Wa={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var ja;!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"}(ja||(ja={}));class Ha extends Error{constructor(e,t,a){super(e),this.type=t,this.details=a,this.name="TransferError"}}class Xa{static validateAmount(e){if(parseFloat(e)<=0)throw new Ha("Transfer amount must be positive",ja.INVALID_AMOUNT,{amount:e})}static validateUniqueKey(e){if(e){if(e.length>Wa.MAX_UNIQUE_KEY_LENGTH)throw new N(`Unique key too long. Maximum length: ${Wa.MAX_UNIQUE_KEY_LENGTH}`);if(!Wa.UNIQUE_KEY_PATTERN.test(e))throw new Ha('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',ja.INVALID_AMOUNT,{uniqueKey:e})}}}class za extends s{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 za({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 za({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 Qa{constructor(e){this.wallet=e}static generateUniqueKey(){return`${Date.now()}_${Math.random().toString(36).substring(2,8)}`}async signTransferToken(e){const t={name:"GalaChain",chainId:1},a={TransferToken:[{name:"from",type:"string"},{name:"to",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstance",type:"TokenInstance"},{name:"uniqueKey",type:"string"}],TokenInstance:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]};return{signature:await this.wallet.signTypedData(t,a,e),domain:t,types:a,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const a=e.replace("0x","");return`eth|${t.getAddress(`0x${a}`).replace("0x","")}`}static fromGalaChainAddress(e){return e.startsWith("eth|")?e.substring(4):e}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){const t=e.split("$");if(4!==t.length)throw new Error(`Invalid token class key format: ${e}. Expected format: collection$category$type$additionalKey`);return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3],instance:"0"}}}function Ya(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")}var Za=Object.freeze({__proto__:null,normalizeToTokenInstanceKey:Ya});const Ja="gala-transfer-successful",en="token-transfer-successful",tn="transfer-successful-no-id";class an extends wa{constructor(e,t,a,n=!1,o){super(e,n),this.wallet=t,this.tokenResolver=a,this.publicAxios=o,this.signatureHelper=t?new Qa(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 zt(`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 zt(`Failed to fetch launch token fee: Status ${e.Status}`,e.Status);return e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.vaultAddress)throw new 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(1!==t.Status||!t.Data||0===t.Data.length)return null;const a=t.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!a||"0"===a.quantity)return null;const n=`${a.collection}|${a.category}|${a.additionalKey}|${a.type}`;return{quantity:a.quantity,collection:a.collection,category:a.category,tokenId:n}}catch(e){throw zt(`Failed to fetch token balance from GalaChain: ${$a(e)}`,void 0,xa(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Ya(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 zt(`Failed to fetch token class from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw zt(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return n.Data[0]}catch(e){if(La(e)&&404===e.response?.status)throw zt("Token not found on GalaChain",404,xa(e)?e:void 0);const t=$a(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw zt(`Failed to fetch token class from GalaChain: ${t}`,void 0,xa(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new Ha("Wallet required for GALA transfer operations",ja.WALLET_REQUIRED);try{const t=M(e.recipientAddress),a=M(this.wallet.address),n=za.forGALA(a,t,e.amount,e.uniqueKey),o=await this.signatureHelper.signTransferToken(n.toSigningPayload()),r=new za({...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 Ha("Wallet required for token transfer operations",ja.WALLET_REQUIRED);try{const t=M(e.to),a=M(this.wallet.address);let n;if(e.tokenId)n=Ya(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 Ha("Must provide either tokenId or tokenName for token identification",ja.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const o=new za({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 za({...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 Ha)throw t;throw new Ha(`Failed to resolve token class key for '${e}': ${$a(t)}`,ja.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(!B(e.recipientAddress))throw new Ha("Invalid recipient address format",ja.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Xa.validateAmount(e.amount),Xa.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(!B(e.to))throw new Ha("Invalid recipient address format",ja.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Ha("Must provide either tokenId or tokenName for token identification",ja.TOKEN_NOT_FOUND);if(e.tokenName&&!Wa.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Ha("Invalid token name format",ja.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Xa.validateAmount(e.amount),Xa.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Ha(`Token '${e}' not found or not available for transfer`,ja.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 Ha)throw t;throw new Ha(`Failed to resolve token '${e}': ${$a(t)}`,ja.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){const[t,a]=e.split("|");if(!a)throw new Ha(`Invalid vault address format: missing token components. Address: ${e}`,ja.TOKEN_NOT_FOUND);const n=a.split("$");if(n.length<4)throw new Ha(`Invalid vault address format: insufficient token components. Expected 4+, got ${n.length}. Address: ${e}`,ja.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?Ja:en:tn}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Ha("Transfer succeeded but transaction ID could not be extracted",ja.NETWORK_ERROR)}handleTransferError(e,t,a){if(e instanceof Ha)return e;if(e instanceof N)return new Ha(e.message,ja.INVALID_AMOUNT);if(La(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t)return new Ha(("string"==typeof n?.message?n.message:void 0)||"Invalid transfer request",ja.INVALID_AMOUNT);if(403===t)return new Ha("Insufficient balance for transfer",ja.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in a&&(e.tokenName=a.tokenName),new Ha("Token not found",ja.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new Ha("Transfer request timed out",ja.NETWORK_ERROR);const n=$a(e);return new Ha(n||t,ja.NETWORK_ERROR)}}function nn(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}class on{constructor(e,t,a,n=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=a,this.logger=new v({debug:n,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:a}=e;if(!t&&!a)throw Ht("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&a)throw new N("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 N("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw Ht("tokenId","Token ID");try{const t=Ya(e),a=nn(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${a}`),!this.dexBackendHttp)throw zt("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 N("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 N(`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 N)throw e;throw zt(`Failed to fetch DEX spot price: ${$a(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,a){if(!e||"string"!=typeof e)throw new Error(b);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: ${$a(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 zt("GALA price not available");const r=Number(n.amount)/1e18;if(r<=0)throw new N(`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 zt(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw zt(`Failed to calculate launchpad token spot price for ${e}: ${$a(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw zt("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 N||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw zt(`Failed to fetch token details from GalaChain for ${e}: ${$a(t)}`,500)}}}const rn=8,sn=18,cn={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"};function ln(e,t=18){const a=parseFloat(e);if(0===a)return"0";return a.toFixed(t).replace(/\.?0+$/,"")}function un(e){return ln(e,8)}function dn(e){return ln(e,18)}function hn(e){return{maxAcceptableReverseBondingCurveFee:un(e.maxAcceptableReverseBondingCurveFee)}}new v({debug:!1,context:"NumberUtils"});const gn={BuyNativeDto:class extends s{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=un(t),this.expectedToken=dn(a),this.extraFees=hn(n)}},BuyExactDto:class extends s{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=dn(t),this.expectedNativeToken=un(a),this.extraFees=hn(n)}},SellExactDto:class extends s{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=dn(t),this.expectedNativeToken=un(a),this.extraFees=hn(n)}},SellNativeDto:class extends s{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=un(t),this.expectedToken=dn(a),this.extraFees=hn(n)}}};var pn,mn,fn;!function(e){e[e.METAMASK=0]="METAMASK",e[e.TRUST_WALLET=1]="TRUST_WALLET",e[e.GALA_WALLET=2]="GALA_WALLET"}(pn||(pn={}));class yn{constructor(e,t=!1){this.walletProvider=e,this.debug=t,this.logger=new v({debug:t,context:"SignatureService"})}async signDTO(e,t,a,n=pn.METAMASK){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,walletPreference:n,dtoKeys:Object.keys(e)});const o=this.generateEIP712Types(t,e),r=c(e),i={...e,prefix:r};let s,l,u;switch(n){case pn.GALA_WALLET:({signature:s,domain:l}=await this.signWithGalaWallet(o,i,t,a));break;case pn.TRUST_WALLET:s=await this.signWithTrustWallet(i),l={name:"ethereum",chainId:1};break;case pn.METAMASK:default:({signature:s,domain:l}=await this.signWithMetaMask(o,i))}return u=n===pn.TRUST_WALLET?{...i,signature:s}:{...e,signature:s,types:o,domain:l},this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(u),signatureLength:s.length}),u}catch(e){this.logger.error("❌ Signature generation failed:",e);throw Yt(`Failed to sign DTO: ${$a(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 Yt(`MetaMask/ethers signing failed: ${$a(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 Yt(`TrustWallet signing failed: ${$a(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 Yt(`GalaWallet signing failed: ${$a(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 N(`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 N(`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 pn.METAMASK;const e=window;return e.gala?pn.GALA_WALLET:e.trustWallet?.isTrust?pn.TRUST_WALLET:(e.ethereum,pn.METAMASK)}}class wn{constructor(e=!1){this.debug=e,this.logger=new v({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=$a(e);throw new N(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new d;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 d;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 Ht("vaultAddress","Vault address");const t=e.split("$");if(t.length<3)throw Xt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");const a=t[2];if(!a||0===a.trim().length)throw new N(`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 Ht("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Xt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Xt("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw Xt("vaultAddress",'having at least 5 parts separated by "$"');const a=t[2];if(!a||!/^[A-Za-z]{1,10}$/.test(a))throw Xt("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 Xt("stringKey","format: collection$category$type$additionalKey (4 parts)");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}}function kn(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 u(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 r;switch(a){case"buy-native":case"sell-exact":r=n.minus(o);break;case"buy-exact":case"sell-native":r=n.plus(o);break;default:throw new Error(`Unknown operation type: ${a}`)}return r.isLessThan(0)&&(r=new u(0)),r.toFixed()}class vn extends wa{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 yn(n,a),this.tokenKeyService=new wn(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 Ht("bundleData","Bundle data");if(!e.signedDto)throw Ht("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw Ht("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Xt("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 Xt("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(La(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 $a(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw Ht("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 Ht("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 N("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=kn(o,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:o,slippageFactor:r,adjustedMinTokens:e});const t=new gn.BuyNativeDto(s,a,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",s)}{if(!o)throw new N("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=kn(o,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:o,slippageFactor:r,adjustedMaxGalaCost:e});const t=new gn.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 N("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=kn(o,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:o,slippageFactor:r,adjustedMinGala:e});const t=new gn.SellExactDto(s,a,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellExactToken",s)}{if(!o)throw new N("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=kn(o,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:o,slippageFactor:r,adjustedMaxTokensToSell:e});const t=new gn.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 jt(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=kn(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 Ht("userAddress","User address")}async executeBundleTransaction(e,t,a){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${h()}-${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"}(mn||(mn={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(fn||(fn={}));const An={[mn.PROCESSED]:fn.COMPLETED,[mn.COMPLETED]:fn.COMPLETED,[mn.SUCCESS]:fn.COMPLETED,[mn.FAILED]:fn.FAILED,[mn.ERROR]:fn.FAILED,[mn.PROCESSING]:fn.PROCESSING,[mn.PENDING]:fn.PENDING};class Tn{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 v({debug:t,context:"WebSocketService"}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof g||(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=g(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts||5,reconnectionDelay:this.config.reconnectDelay||2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectCount=0,e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.debug&&(this.socket.onAny((e,...t)=>{this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0)}catch(e){t(e)}})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const a=setTimeout(()=>{if(this.listeners.has(e)){const a={transactionId:e,status:fn.TIMEOUT,message:"Transaction monitoring timeout - no response after 60 seconds",timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e}`),t(a),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},6e4);if(this.timeouts.set(e,a),this.socket&&this.socket.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,a=>{this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(a,null,2));const n=a,o=n?.data,r=n?.status||n?.Status||o?.status||o?.Status;let i=n?.message||n?.Message||o?.message||o?.Message||n?.error||o?.error;i&&"string"==typeof i||(i=r===mn.FAILED||r===mn.ERROR?"Transaction failed - check transaction details":r===mn.COMPLETED||r===mn.PROCESSED||r===mn.SUCCESS?"Transaction completed successfully":r?`Transaction status: ${r}`:"Unknown transaction status");const s=n?.blockHash||o?.blockHash,c=n?.gasUsed||o?.gasUsed,l={transactionId:e,status:this.mapSocketStatus(r),message:"string"==typeof i?i:"Transaction update received",timestamp:Date.now(),...s&&{blockHash:s},...c&&{gasUsed:c}};if(this.logger.debug(`📡 Mapped status for ${e}: ${r} -> ${l.status}`),this.logger.debug(`📡 Final message: "${i}"`),t(l),l.status===fn.COMPLETED||l.status===fn.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${l.status})`)}});else{const a={transactionId:e,status:fn.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(a),this.listeners.delete(e),this.timeouts.delete(e)}}async waitForTransaction(e){return new Promise((t,a)=>{this.monitorTransaction(e,e=>{e.status===fn.COMPLETED?t(e):e.status!==fn.FAILED&&e.status!==fn.TIMEOUT||a(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return An[t]||fn.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 bn{constructor(e,t=!1){this.poolService=e,this.cache=new Map,this.logger=new v({debug:t,context:"TokenResolverService"})}async resolveTokenToVault(e){if(!U(e))throw new N("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 jt(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 Xt("vaultAddress","format: service|Token$Unit$...$launchpad","Vault address");const a=t[1].split("$");if(a.length<4)throw Xt("vaultAddress","at least 4 parts after service|","Vault address");return{collection:a[0],category:a[1],type:a[2],additionalKey:a[3]}}}class En{constructor(e,t=!1,a){this.httpClient=e,this.tokenResolverService=a,this.logger=new v({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 zt(`Failed to resolve token name '${e}': ${$a(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 Za}),n=a(t),o=nn(`${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 zt(`Failed to fetch price history: ${$a(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw zt("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw zt("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 Nn{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 Sn{constructor(e,t){if(this.tokenConverter=new Nn,this.logger=new v({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 p(e.privateKey);this.gswap=new m({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 m({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 C(`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 C(`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 u(e.estimatedOutput),o=new u(1).minus(e.slippageTolerance||.01),r=n.multipliedBy(o),i=(await this.gswap.swaps.swap(t,a,e.feeTier,{exactIn:e.inputAmount,amountOutMinimum:r.toFixed()})).transactionId;if(!i)throw new Error("Failed to get transaction ID from swap result");this.logger.debug("Swap submitted, monitoring transaction",{transactionId:i,fromToken:e.fromToken,toToken:e.toToken}),this.webSocketService.isConnected()||await this.webSocketService.connect();const s=await this.webSocketService.waitForTransaction(i);return{transactionId:s.transactionId,status:s.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(s.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}catch(e){this.logger.error("Failed to execute swap",e);const t=e;throw new D(`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,r=a||n||o||"";if(!r||""===r.trim()){const r=[];throw a||r.push("tokenInstance"),n||r.push("tokenClassKey"),o||r.push("type"),new x(`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(r)}catch(a){throw new x(`Cannot convert token identifier for asset "${t.symbol||"UNKNOWN"}". Invalid token format: "${r}". 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(r),symbol:t.symbol||t.type||"UNKNOWN",balance:new u(t.balance||0).toFixed(),decimals:t.decimals||18}})}catch(t){this.logger.error("Failed to fetch user assets",t);const a=t;throw new x(`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 r=new u(0),i=0;for(const s of o)try{const e=await this.gswap.pools.getPoolData(a,n,s);e&&(r=r.plus(new u(e.liquidity||0)),i++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:s})}return{tokenA:e,tokenB:t,liquidity:r.toFixed(),feeTiers:o,swapCount:i}}catch(a){this.logger.warn("Failed to fetch pool info",a);const n=a;return this.logger.debug("Pool error details",{error:new P(`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 $(`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 $(`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 $(`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 $(`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 $(`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 $(`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 $(`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 $(`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),r=await this.gswap.pools.getPoolData(n,o,a),i=this.calculatePriceFromSqrtPriceX96(new u(r.sqrtPriceX96));return{tokenA:e,tokenB:t,feeTier:a,liquidity:r.liquidity.toString(),sqrtPriceX96:r.sqrtPriceX96.toString(),tick:r.tick,feeGrowthGlobal0X128:r.feeGrowthGlobal0X128.toString(),feeGrowthGlobal1X128:r.feeGrowthGlobal1X128.toString(),currentPrice:i.toFixed()}}catch(e){throw this.logger.error("Failed to get pool data",e),new P(`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 u(n.currentPrice);return{tokenA:e,tokenB:t,feeTier:a,price:o.toFixed(),invertedPrice:new u(1).dividedBy(o).toFixed(),tick:n.tick,liquidity:n.liquidity}}catch(e){throw this.logger.error("Failed to calculate spot price",e),new P(`Failed to calculate spot price: ${e?.message||String(e)}`,e)}}async calculateOptimalPositionSize(e,t,a,n,o,r,i){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:n,desiredAmount1:o});const s=(await this.getPoolData(e,t,a)).tick,c=this.calculateLiquidityFromAmount0(new u(n),r,Math.min(i,s)),l=this.calculateLiquidityFromAmount1(new u(o),Math.max(r,s),i),d=u.min(c,l),h=this.calculateAmount0FromLiquidity(d,r,s),g=this.calculateAmount1FromLiquidity(d,s,i),p=new u(n),m=new u(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 $(`Failed to calculate optimal position: ${e?.message||String(e)}`,e)}}async validatePositionParameters(e,t,a,n,o,r,i){const s=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:n,tickUpper:o});const l=[500,3e3,1e4];l.includes(a)||s.push(`Invalid fee tier: ${a}. Must be one of: ${l.join(", ")}`);const d=this.getTickSpacing(a);let h;n%d!==0&&s.push(`tickLower must be multiple of ${d}`),o%d!==0&&s.push(`tickUpper must be multiple of ${d}`),n>=o&&s.push(`tickLower (${n}) must be less than tickUpper (${o})`);try{h=await this.getPoolData(e,t,a)}catch{return s.push(`Pool not found for ${e}/${t} at fee tier ${a}`),{valid:!1,errors:s,warnings:c,gasEstimate:0}}const g=new u(r),p=new u(i);(g.isNaN()||g.isNegative())&&s.push("amount0 must be a valid positive number"),(p.isNaN()||p.isNegative())&&s.push("amount1 must be a valid positive number");const m=h.tick;(m<n||m>o)&&c.push("Position is out of current price range - will not earn fees until price moves into range");new u(h.liquidity).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const f=0===s.length?35e4:0;return{valid:0===s.length,errors:s,warnings:c,gasEstimate:f,tickSpacing:d,currentTick:m,poolLiquidity:h.liquidity}}catch(e){return s.includes(e.message)||s.push(`Validation failed: ${e?.message||String(e)}`),{valid:!1,errors:s,warnings:c,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 r=this.getTickSpacing(o),i=new u(a),s=new u(n);if(i.gte(s))throw new Error("minPrice must be less than maxPrice");const c=Math.floor(Math.log(i.toNumber())/Math.log(1.0001)),l=Math.ceil(Math.log(s.toNumber())/Math.log(1.0001)),d=Math.floor(c/r)*r,h=Math.ceil(l/r)*r,g=Math.pow(1.0001,d),p=Math.pow(1.0001,h),m=new u(g),f=new u(p);return{tokenA:e,tokenB:t,feeTier:o,tickLower:d,tickUpper:h,tickSpacing:r,requestedMinPrice:a,requestedMaxPrice:n,actualMinPrice:m.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:m.minus(i).dividedBy(i).multipliedBy(100).toFixed(4),maxPriceDeviation:f.minus(s).dividedBy(s).multipliedBy(100).toFixed(4)}}}catch(e){throw this.logger.error("Failed to calculate ticks for price",e),new $(`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),r=Math.pow(1.0001,n);let i;try{i=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const s=new u(o),c=new u(r);return{tokenA:e,tokenB:t,tickLower:a,tickUpper:n,minPrice:s.toFixed(8),maxPrice:c.toFixed(8),currentPrice:i,priceRange:`${s.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:n-a}}catch(e){throw this.logger.error("Failed to calculate price for ticks",e),new $(`Failed to calculate prices: ${e?.message||String(e)}`,e)}}calculateExecutionPrice(e,t){try{const a=new u(e),n=new u(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 u(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new u(0)}}calculateLiquidityFromAmount0(e,t,a){try{const n=new u(Math.pow(1.0001,t/2)),o=new u(Math.pow(1.0001,a/2));return e.multipliedBy(n).multipliedBy(o).dividedBy(o.minus(n))}catch{return new u(0)}}calculateLiquidityFromAmount1(e,t,a){try{const n=new u(Math.pow(1.0001,t/2)),o=new u(Math.pow(1.0001,a/2));return e.dividedBy(o.minus(n))}catch{return new u(0)}}calculateAmount0FromLiquidity(e,t,a){try{const n=new u(Math.pow(1.0001,t/2)),o=new u(Math.pow(1.0001,a/2));return e.multipliedBy(o.minus(n)).dividedBy(n.multipliedBy(o))}catch{return new u(0)}}calculateAmount1FromLiquidity(e,t,a){try{const n=new u(Math.pow(1.0001,t/2)),o=new u(Math.pow(1.0001,a/2));return e.multipliedBy(o.minus(n))}catch{return new u(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 In{}In.BASE_PRICE=1650667151e-14,In.PRICE_SCALING_FACTOR=1166069e-12,In.TRADING_FEE_FACTOR=.001,In.GAS_FEE="1",In.MIN_UNBONDING_FEE_FACTOR=0,In.MAX_UNBONDING_FEE_FACTOR=.5,In.NET_UNBONDING_FEE_FACTOR=.5,In.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class Fn{constructor(e=!1){this.cache=new Map,this.logger=new v({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>=Fn.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||In.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)}}Fn.MAX_CACHE_SIZE=1e4;class Cn extends wa{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=fa.DEFAULT_PAGE,limit:r=fa.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 Dn(e){const t=function(e){const t=kt(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 Pn="/api/asset/launchpad-contract/CallNativeTokenIn",xn="/api/asset/launchpad-contract/CallNativeTokenOut",$n="/api/asset/launchpad-contract/CallMemeTokenIn",Ln="/api/asset/launchpad-contract/CallMemeTokenOut";class _n extends s{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 Un(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 Bn={NATIVE:"native",EXACT:"exact"},Mn={RECENT:"recent",POPULAR:"popular"},On={LOCAL:"local",EXTERNAL:"external"};class Rn{static calculateBuyWithExact(e,t){const a=parseFloat(e),n=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:s}=In,c=this.roundUp(o*(Math.exp((n+a)*r)-Math.exp(n*r))/r,8),l=new u(c).multipliedBy(i).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:s}}static calculateBuyWithNative(e,t){const a=parseFloat(e),n=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:s}=In,c=Math.log(a*r/o+Math.exp(n*r))/r-n,l=new u(c).multipliedBy(i).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:s}}static calculateSellWithExact(e,t,a,n,o){const r=parseFloat(e),i=parseFloat(t),s=parseFloat(a),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:h}=In,g=c*(Math.exp(i*l)-Math.exp((i-r)*l))/l,p=new u(g),m=n+i/s*(o-n),f=p.multipliedBy(m).toFixed(8,u.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 r=parseFloat(e),i=parseFloat(t),s=parseFloat(a),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:h}=In,g=i-Math.log(Math.exp(i*l)-r*l/c)/l,p=new u(r),m=n+i/s*(o-n),f=p.multipliedBy(m).toFixed(8,u.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 Gn{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 Fn}addIfDefined(e,t,a){return void 0!==a&&(e[t]=a),e}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Mt(t);const n=`${t}.png`;Ga(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 Xt("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 zt(n.message||"Image upload failed - no URL returned",n.status);return n.data.imageUrl}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw 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){Ot(e),e.tokenName&&Mt(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=A(t),n=await this.http.get("/launchpad/fetch-pool",a);if(!0===n.error||200!==n.status||!n.data)throw zt(n.message||"Failed to fetch pools",n.status);let 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 no});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(Gt(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:Pn,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:xn,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:$n,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:Ln,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};throw Xt("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(!Un(e))throw zt("Malformed response data from GalaChain gateway");if(1!==e.Status)throw zt(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:n,extraFees: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){Rt(e),e.tokenName&&Mt(e.tokenName);const t=A(e),a=await this.http.get("/launchpad/check-pool",t);if(!0===a.error||200!==a.status)throw zt(a.message||"Failed to check pool",a.status);const n=a.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.exists??!1}async fetchVolumeData(e){if(!ba(e))throw new N("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(Mt(t),!a||!n||!o)throw new N("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:a,to:n,resolution:o};Kt(r);const i=A(r),s=await this.http.get("/launchpad/get-graph-data",i);if(!0===s.error||200!==s.status||!s.data)throw zt(s.message||"Failed to fetch graph data",s.status);return{dataPoints:s.data}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const 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 N("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 N(`Invalid calculation mode "${r}". 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(!a||"string"!=typeof a)throw new N("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Bn.NATIVE&&n!==Bn.EXACT)throw new N('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 N(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Bn.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 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(!a||"string"!=typeof a)throw new N("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Bn.EXACT&&n!==Bn.NATIVE)throw new N('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 N(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Bn.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 N("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Bn.NATIVE&&n!==Bn.EXACT)throw new N('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==o&&Vt(o,"currentSupply");const r=!o;if(r&&!t)throw new N("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&Mt(t);let i=o;if(r){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return n===Bn.EXACT?Rn.calculateBuyWithExact(a,i):Rn.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 N("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Bn.EXACT&&n!==Bn.NATIVE)throw new N('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==o&&Vt(o,"currentSupply");const c=!o||!r||void 0===i||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&&Mt(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===Bn.EXACT?Rn.calculateSellWithExact(a,l,u,h,d):Rn.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 ka(t,"tokenName")&&Ta(t)&&va(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:a,calculateAmountMode:n,currentSupply:o}=t;Mt(a);const r=await this.tokenResolver.resolveTokenToVault(a);if(!r)throw new N(E(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 zt(`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 N(`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");Dn(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:a}=e.reverseBondingCurveConfiguration,n=Number(t),o=Number(a);if(isNaN(n)||isNaN(o)||n<=0||o<=0||n>=o)throw new N("Reverse bonding curve configuration must have valid min/max fee portions with min < max","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG")}let a="";if(e.tokenImage)if(e.tokenImage instanceof File||Buffer.isBuffer(e.tokenImage)){const t=await this.uploadImageByTokenName({tokenName:e.tokenName,options:{file:e.tokenImage,tokenName:e.tokenName}});if(!t)throw zt("Image upload failed: No URL returned");a=t}else"string"==typeof e.tokenImage&&(a=e.tokenImage);const n=`galaswap - operation - ${h()}-${Date.now()}-${this.http.getAddress()}`,o={tokenName:e.tokenName.trim(),tokenSymbol:e.tokenSymbol.trim().toUpperCase(),tokenDescription:e.tokenDescription.trim(),tokenImage:a.trim(),preBuyQuantity:t.toString(),websiteUrl:e.websiteUrl||"",telegramUrl:e.telegramUrl||"",twitterUrl:e.twitterUrl||"",tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:n};e.reverseBondingCurveConfiguration&&(o.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const i=new _n(o),s=await this.http.signWithGalaChain("CreateSale",i,r.SIGN_TYPED_DATA),{signature:c,types:l,domain:u,prefix:d}=s,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:c,types:l,domain:u,...d&&{prefix:d},...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 zt(w.message||"Token launch failed");return w.data}async fetchTokenDistribution(e){if(!e)throw Ht("tokenName","Token name");Mt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new N(E(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const a=encodeURIComponent(t),n=await this.http.get(`/holders/${a}`);if(!0===n.error||200!==n.status||!n.data)throw zt(n.message||"Failed to fetch token distribution",n.status);const o=n.data;if(!Array.isArray(o))throw zt("Invalid API response: expected array of holders",n.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw zt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw zt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw zt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const r=o.reduce((e,t)=>e.plus(t.quantity),new u(0));return{holders:o.map(e=>{const t=new u(e.quantity),a=r.isZero()?0:t.dividedBy(r).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:a}}),totalSupply:r.toFixed(),totalHolders:o.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw Ht("tokenName","Token name");Mt(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw zt(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:a,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const 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 N("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(!Un(a))throw zt("Malformed response data from GalaChain gateway");if(1!==a.Status)throw zt(`GalaChain calculation failed with status ${a.Status}`,a.Status);const{calculatedQuantity:n,extraFees: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 N(E(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 zt(`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){Mt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new N(E(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 zt(`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 qt(e)}validateTokenName(e){return Mt(e)}validatePagination(e){return Ot(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 Ht("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),a=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&a.push({symbol:e.symbol,price:e.currentPrices.usd})}),a}catch(e){throw zt(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return ka(t,"tokenName")&&Ta(t)&&va(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:a,calculateAmountMode:n,currentSupply:o}=t;if(!a||"string"!=typeof a)throw Ht("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 zt("GALA price not available");const i=Number(t.amount);if(i<=0)throw new N(`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 Kn={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 qn(e){return Kn[e]}class Vn extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Wn extends Vn{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class jn 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 Hn(e,t){if(!e)throw new Vn(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Vn(`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 Vn(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Xn(e,t,a,n){Hn(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 Vn(`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 zn="3.31.0";class Qn{constructor(t){this.wallet=t.wallet;let a=null;a=t.env?qn(t.env):t.baseUrl?.includes("prod")?qn("PROD"):qn("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,...t},this.logger=new v({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===t.slippageToleranceFactor?Qn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(t.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===t.maxAcceptableReverseBondingCurveFeeSlippageFactor?Qn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(t.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=t.calculateAmountMode||Qn.DEFAULT_CALCULATE_AMOUNT_MODE,this.auth=new k({wallet:t.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new T(this.auth,this.config),this.galaChainHttp=new T(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new T(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new T(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new T(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=e.create({baseURL:this.config.galaChainBaseUrl,timeout:this.config.timeout||3e4,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.cache=new Fn(t.debug||!1),this.launchpadService=new Va(this.http),this.tokenResolverService=new bn(this.launchpadService.poolService),this.launchpadAPI=new Gn(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new an(this.galaChainHttp,t.wallet,this.tokenResolverService,t.debug||!1,this.galaChainPublicAxios),this.dexService=new on(this.dexBackendHttp,this.cache,this.galaChainService,t.debug||!1),this.bundleService=new vn(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,t.wallet,t.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Tn({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new En(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.gswapService=new Sn({privateKey:t.wallet?.privateKey,walletAddress:t.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl},this.websocketService),this.dexPoolService=new Cn(this.dexBackendHttp,this.config.dexBackendBaseUrl,t.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(e),n={...this.config,wallet:t};return new Qn(n)}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,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode}}getVersion(){return zn}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(La(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: ${$a(t)}`),e}}throw e}if(!t&&!a)throw Ht("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 fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(!t)throw new Error(E(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 Wt}),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 Wt}),a=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Za}),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 Ht("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 Yt("No transaction ID returned from buy operation");return this.waitForConfirmation(a,t=>Xn(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 Yt("No transaction ID returned from sell operation");return this.waitForConfirmation(a,t=>Xn(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=>{Hn(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 Vn(`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 Wt}),a=t(e)||this.getAddress();return this.launchpadService.fetchProfile(a)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Wt}),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 Wt}),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 Wt}),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 Wt}),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 Wt}),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 Wt}),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 Wt}),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: ${Qn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Qn.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: ${Qn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Qn.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 jn(e,a.status,a.message);let n;try{n=t(a)}catch(t){if(t instanceof Vn)throw t;throw new Vn(`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 jn||t instanceof Vn)throw t;throw new Vn(`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 no});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 v({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:a}=require("./services/WebSocketService");a.cleanupAll(e),t.debug("Global cleanup completed")}}Qn.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Qn.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Qn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=In.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Qn.DEFAULT_CALCULATE_AMOUNT_MODE=On.LOCAL;class Yn{static generateWallet(){try{const e=a.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(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(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(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 r=n.fromPhrase(e),i=o.fromMnemonic(r,`m/44'/60'/0'/0/${t}`),s=new a(i.privateKey),c=this.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:c,mnemonic:e,wallet:s}}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(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 Zn(e){if(void 0===e)return Yn.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 Yn.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 Yn.fromMnemonic(t);throw new Error(`Unable to detect input format. Expected:\n- Private key: 64 hexadecimal characters (with or without 0x prefix)\n- Mnemonic: 12 or 24 space-separated words\nReceived: "${t.slice(0,50)}${t.length>50?"...":""}"`)}function Jn(e){const{wallet:t,env:n,config:o={}}=e||{};let r;if(t)if("string"==typeof t){r=Zn(t).wallet}else{if(!(t instanceof a))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");r=t}else{r=Zn().wallet}const i={wallet:r,...n&&{env:n},debug:!1,timeout:3e4,...o};return new Qn(i)}Yn.testCounter=0;class eo{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 Qn(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 Qn(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||Yn.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?Yn.fromPrivateKey(e):Yn.generateWallet()}return"generate"===e?Yn.generateWallet():Yn.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}}const to={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"};class ao{constructor(){this.cache={},this.cacheExpiry=36e5,this.logger=new v({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`)}}var no=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}});export{eo as AgentConfig,On as CALCULATION_MODES,I as ConfigurationError,Ra as FileValidationError,rn as GALA_DECIMALS,cn as GALA_TOKEN_CLASS_KEY,x as GSwapAssetError,P as GSwapPoolError,C as GSwapQuoteError,D as GSwapSwapError,Se as IMAGE_EXTENSIONS,sn as LAUNCHPAD_TOKEN_DECIMALS,Qn as LaunchpadSDK,ma as MAX_CONCURRENT_POOL_FETCHES,S as NetworkError,fa as PAGINATION_DEFAULTS,ya as POOL_FETCH_CONFIG,Mn as POOL_TYPES,to as QUERY_FIELD_NAMES,fn as SDKTransactionStatus,zn as SDK_VERSION,Bn as TRADING_TYPES,ao as TokenMetadataService,F as TransactionError,jn as TransactionFailedError,N as ValidationError,Vn as WebSocketError,Wn as WebSocketTimeoutError,W as addressFormatSchema,be as amountMethodSchema,Te as amountTypeSchema,Fe as browserFileSchema,Ce as bufferFileSchema,Ze as buyTokensDataSchema,rt as calculatePreMintDataSchema,Ae as checkPoolOptionsSchema,ce as commentMessageSchema,Ue as commentPaginationSchema,Jn as createLaunchpadSDK,te as createLimitSchema,Ge as createPaginatedResultSchema,Ye as createTradeDataSchema,Zn as createWallet,j as ethereumAddressSchema,Y as faucetAmountSchema,We as fetchGalaBalanceOptionsSchema,it as fetchPoolDetailsDataSchema,Xe as fetchTokenBalanceOptionsSchema,re as fileSizeSchema,Ie as fileUploadSchema,ie as filenameSchema,H as flexibleAddressSchema,De as flexibleFileSchema,un as formatGalaForDTO,dn as formatLaunchpadTokenForDTO,V as fullNameSchema,ot as getAmountOptionsSchema,et as getTradeOptionsSchema,Ne as graduateTokenOptionsSchema,Ee as graphDataOptionsSchema,Pe as imageExtensionSchema,xe as imageFilenameSchema,se as imageMimeTypeSchema,ke as imageUploadOptionsSchema,le as isoDateStringSchema,we as launchTokenDataSchema,Q as nonNegativeDecimalStringSchema,J as optionalUrlSchema,ee as pageNumberSchema,Re as paginationResultMetaSchema,ve as poolFetchTypeSchema,Be as poolPaginationSchema,z as positiveDecimalStringSchema,de as privateKeySchema,ye as reverseBondingCurveConfigSchema,st as reverseBondingCurveConfigurationSchema,q as searchQuerySchema,Je as sellTokensDataSchema,ae as standardLimitSchema,$e as standardPaginationSchema,ue as timestampSchema,me as tokenCategorySchema,fe as tokenCollectionSchema,G as tokenDescriptionSchema,qe as tokenListOptionsSchema,O as tokenNameSchema,R as tokenSymbolSchema,pe as tokenUrlsSchema,nt as tradeCalculationMethodSchema,at as tradeCalculationTypeSchema,oe as tradeLimitSchema,tt as tradeListParamsSchema,_e as tradePaginationSchema,Oe as tradePaginationWithFiltersSchema,Qe as tradeTypeBackendSchema,ze as tradeTypeSchema,he as transactionIdSchema,Ve as transferFaucetsDataSchema,ge as uniqueKeySchema,je as updateProfileDataSchema,He as uploadProfileImageOptionsSchema,Z as urlSchema,ne as userLimitSchema,Le as userPaginationSchema,K as userTokenNameSchema,Ke as userTokenTypeSchema,Me as userTokensPaginationSchema,ht as validateAddress,pt as validateAmountString,Dt as validateBuyTokensData,_t as validateCalculatePreMintData,Tt as validateCheckPoolOptions,Ct as validateCreateTradeData,mt as validateFaucetAmount,Nt as validateFetchGalaBalanceOptions,Ut as validateFetchPoolDetailsData,Ft as validateFetchTokenBalanceOptions,ft as validateFullName,Lt as validateGetAmountOptions,xt as validateGetTradeOptions,At as validateImageUploadOptions,kt as validateLaunchTokenData,yt as validateSearchQuery,Pt as validateSellTokensData,dt as validateTokenDescription,bt as validateTokenListOptions,lt as validateTokenName,ut as validateTokenSymbol,vt as validateTokenUrls,$t as validateTradeListParams,Et as validateTransferFaucetsData,St as validateUpdateProfileData,It as validateUploadProfileImageOptions,wt as validateUserTokenName,gt as validateVaultAddress,X as vaultAddressSchema};
|
|
1
|
+
import e from"axios";import{ethers as t,Wallet as n,Mnemonic as o,HDNodeWallet as i}from"ethers";import{SigningType as a,SigningClient as r,ChainCallDTO as s,calculatePersonalSignPrefix as c}from"@gala-chain/connect";import{z as l}from"zod";import u from"bignumber.js";import{sqrtPriceToTick as d,tickToSqrtPrice as h,getLiquidityForAmounts as g,getAmountsForLiquidity as p,liquidity0 as m,liquidity1 as f,getAmount0Delta as y,getAmount1Delta as w,Pool as k,TickData as v,CompositePoolDto as T,GetCompositePoolDto as b,QuoteExactAmountDto as A,quoteExactAmount as S,computeSwapStep as E}from"@gala-chain/dex";import{TokenClassKey as I,TokenBalance as N}from"@gala-chain/api";import{v4 as P}from"uuid";import{io as F}from"socket.io-client";import*as C from"path";import*as D from"fs";import*as x from"dotenv";import $ from"crypto";if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}var L,B;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(L||(L={}));class U extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class O{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new U(L.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 U(L.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new U(L.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 U)throw e;throw new U(L.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 U(L.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new U(L.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 U)throw e;const t=e instanceof Error?e.message:String(e);throw new U(L.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}`,i=await this.wallet.signMessage(o);return{"x-signature":i,"x-address":this.formatAddress(this.wallet.address),"x-message":o,"x-timestamp":n.toString()}}catch(e){if(e instanceof U)throw e;throw new U(L.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 U)throw e;throw new U(L.SIGNATURE_FAILED,"Failed to sign typed data",e instanceof Error?e:new Error(String(e)))}}async generateCustomSignature(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new U(L.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 U)throw e;throw new U(L.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new U(L.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new U(L.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new U(L.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(B||(B={}));class _{constructor(e){this.levelPriority={[B.DEBUG]:0,[B.INFO]:1,[B.WARN]:2,[B.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?B.DEBUG:B.INFO)}debug(e,t){this.log(B.DEBUG,e,t)}info(e,t){this.log(B.INFO,e,t)}warn(e,t){this.log(B.WARN,e,t)}error(e,t){this.log(B.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===B.DEBUG&&!this.debugEnabled)return;const o=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==n?n instanceof Error?i(`${o} ${t}`,n.message,n.stack):i(`${o} ${t}`,n):i(`${o} ${t}`)}getConsoleMethod(e){switch(e){case B.DEBUG:return console.debug;case B.INFO:return console.info;case B.WARN:return console.warn;case B.ERROR:return console.error;default:return console.log}}child(e){return new _({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[B.DEBUG]>=this.levelPriority[this.minLevel]}}function R(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 M{constructor(t,n={}){this.auth=t,this.debug=n.debug??!1,this.logger=new _({debug:this.debug,context:"HttpClient"}),this.axios=e.create({baseURL:n.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:n.timeout||3e4,headers:{Accept:"application/json",...n.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:R(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=a.SIGN_TYPED_DATA){const o=this.auth.getPrivateKey(),i=new r(o);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 q="Token name is required and must be a string",G=e=>`Could not find vault address for token: ${e}`;class K extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class V extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class j extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class W extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class H extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class z extends Error{constructor(e,t,n,o){super(e),this.originalError=t,this.transactionHash=n,this.code=o,this.name="GSwapSwapError"}}class Q extends Error{constructor(e,t,n,o,i){super(e),this.originalError=t,this.tokenA=n,this.tokenB=o,this.code=i,this.name="GSwapPoolError"}}class X extends Error{constructor(e,t,n,o){super(e),this.originalError=t,this.walletAddress=n,this.code=o,this.name="GSwapAssetError"}}class Z extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class Y extends K{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class J extends K{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function ee(e,t){return new K(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function te(e,t){const n=t||e.charAt(0).toUpperCase()+e.slice(1);return new K(`${n} is required`,e,"REQUIRED_FIELD")}function ne(e,t,n){const o=n||e.charAt(0).toUpperCase()+e.slice(1);return new K(`${o} must be ${t}`,e,"INVALID_FORMAT")}function oe(e,t,n){return new V(e,t,n)}function ie(e,t){return new j(e,t)}function ae(e,t,n){return new W(e,t,n)}function re(e,t,n){const{MIN_PAGE:o,MAX_PAGE:i,MIN_LIMIT:a,MAX_LIMIT:r}=n.PAGINATION;if("number"!=typeof e||e<o||e>i)throw new K(`Page must be a number between ${o} and ${i}`,"page","INVALID_PAGE");if("number"!=typeof t||t<a||t>r)throw new K(`Limit must be a number between ${a} and ${r}`,"limit","INVALID_LIMIT")}const se={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function ce(e){return"string"==typeof e&&e.trim().length>0}function le(e){return!(!e||"string"!=typeof e)&&(se.ETH_ADDRESS.test(e)||se.BACKEND_ADDRESS.test(e))}function ue(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const de=l.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"),he=l.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"),ge=l.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),pe=l.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),me=l.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),fe=l.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"),ye=l.string().regex(se.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),we=l.string().regex(se.ETH_ADDRESS,"Invalid Ethereum address format"),ke=l.string().refine(e=>se.BACKEND_ADDRESS.test(e)||se.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),ve=l.string().refine(e=>se.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Te=l.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),be=l.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),Ae=l.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),Se=l.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Ee=l.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Ie=l.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 Ne(e=100){return l.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 Pe=Ne(100),Fe=Ne(20),Ce=Ne(20),De=l.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"),xe=l.string().max(255,"Filename must be at most 255 characters"),$e=l.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Le=l.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),Be=l.string().datetime("Must be a valid ISO 8601 date string"),Ue=l.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Oe=l.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),_e=l.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"),Re=l.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Me=l.object({websiteUrl:Ee,telegramUrl:Ee,twitterUrl:Ee}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),qe=l.string().min(1,"Token category must not be empty").default("Unit"),Ge=l.string().min(1,"Token collection must not be empty").default("Token"),Ke=l.object({minFeePortion:Te,maxFeePortion:Te}),Ve=l.object({tokenName:de,tokenSymbol:he,tokenDescription:ge,tokenImage:l.union([l.instanceof(File),l.instanceof(Buffer),l.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:be.default("0"),websiteUrl:Ee,telegramUrl:Ee,twitterUrl:Ee,tokenCategory:qe,tokenCollection:Ge,reverseBondingCurveConfiguration:Ke.optional(),privateKey:Oe.optional()}),je=l.object({file:l.union([l.instanceof(File),l.instanceof(Buffer)]),tokenName:de}),We=l.enum(["recent","popular"]),He=l.object({tokenName:de.optional(),symbol:he.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),ze=l.enum(["NATIVE","MEME"]),Qe=l.enum(["IN","OUT"]),Xe=l.object({from:l.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:l.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:l.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:de}),Ze=l.object({tokenName:de,slippageToleranceFactor:l.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:l.number().min(0).max(1).optional(),privateKey:Oe.optional()}),Ye=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Je=l.object({file:l.union([l.instanceof(File),l.instanceof(Buffer)]),name:xe,size:De,type:$e}),et=l.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"),tt=l.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),nt=l.union([et,tt]),ot=l.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),it=xe.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Ye.includes(t)},`Filename must end with one of: ${Ye.join(", ")}`),at=l.object({page:Ie,limit:Pe}),rt=l.object({page:Ie,limit:Fe}),st=l.object({page:Ie,limit:Ce}),ct=l.object({page:Ie,limit:Ne(50)}),lt=at.extend({type:l.enum(["recent","popular"]).optional(),tokenName:l.string().min(1).max(50).optional(),search:l.string().min(1).max(100).optional()}),ut=rt.extend({tokenName:l.string().min(1).max(50).optional(),search:l.string().min(1).max(100).optional()}),dt=st.extend({tradeType:l.enum(["BUY","SELL"]).optional(),tokenName:l.string().min(1).max(50).optional(),userAddress:l.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:l.string().datetime().optional(),endDate:l.string().datetime().optional(),sortOrder:l.enum(["ASC","DESC"]).default("DESC")}),ht=l.object({page:l.number().int().min(1),limit:l.number().int().min(1),total:l.number().int().min(0),totalPages:l.number().int().min(0),hasNext:l.boolean(),hasPrevious:l.boolean()});function gt(e){return l.object({data:l.array(e),page:l.number().int().min(1),limit:l.number().int().min(1),total:l.number().int().min(0),totalPages:l.number().int().min(0),hasNext:l.boolean(),hasPrevious:l.boolean()})}const pt=l.enum(["all","DEFI","ASSET"]),mt=rt.extend({type:pt.optional(),address:ke.optional(),search:me.optional(),tokenName:pe.optional()}),ft=l.object({walletAddress:ke,amount:Ae}),yt=l.object({address:ke.optional(),refresh:l.boolean().optional()}),wt=l.object({profileImage:l.string(),fullName:fe,address:ke,privateKey:Oe.optional()}),kt=l.object({file:l.union([l.instanceof(File),l.instanceof(Buffer)]),address:ke.optional(),privateKey:Oe.optional()}),vt=l.object({address:ke,tokenId:l.union([l.string(),l.object({collection:l.string(),category:l.string(),type:l.string(),additionalKey:l.string()}),l.object({collection:l.string(),category:l.string(),type:l.string(),additionalKey:l.string(),instance:l.string()})]).optional(),tokenName:pe.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),Tt=l.enum(["buy","sell"]),bt=l.enum(["BUY","SELL"]),At=l.object({tradeType:Tt,tokenAmount:Te,vaultAddress:ve,userAddress:ke,slippageTolerance:Te.optional(),deadline:l.number().int().positive().optional()}),St=l.object({tokenSymbol:he,nativeTokenQuantity:Te,expectedToken:Te,maxAcceptableReverseBondingCurveFee:be.default("0").optional()}),Et=l.object({tokenSymbol:he,tokenQuantity:Te,expectedNativeToken:Te,maxAcceptableReverseBondingCurveFee:be.default("0").optional()}),It=st.extend({tokenName:pe.optional()}),Nt=l.object({page:l.number().int().min(1).max(1e3).default(1).optional(),limit:l.number().int().min(1).max(20).default(10).optional()}),Pt=l.enum(["NATIVE","MEME"]),Ft=l.enum(["IN","OUT"]),Ct=l.object({type:Pt,method:Ft,vaultAddress:ve,amount:Te}),Dt=l.object({nativeTokenQuantity:Te}),xt=l.object({vaultAddress:ve}),$t=l.object({minFeePortion:Te,maxFeePortion:Te});function Lt(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 Bt=Lt(de),Ut=Lt(he),Ot=Lt(ge),_t=Lt(ke),Rt=Lt(ve),Mt=Lt(Te),qt=Lt(Ae),Gt=Lt(fe),Kt=Lt(me),Vt=Lt(pe),jt=Lt(Ve),Wt=Lt(Me),Ht=Lt(je),zt=Lt(He),Qt=Lt(mt),Xt=Lt(ft),Zt=Lt(yt),Yt=Lt(wt),Jt=Lt(kt),en=Lt(vt),tn=Lt(At),nn=Lt(St),on=Lt(Et),an=Lt(It),rn=Lt(Nt),sn=Lt(Ct),cn=Lt(Dt),ln=Lt(xt);function un(e,t){throw new K(e.join("; "),t,"VALIDATION_ERROR")}function dn(e){const t=Bt(e);!t.success&&t.errors&&un(t.errors,"tokenName")}function hn(e){const t=lt.safeParse(e);t.success||un(t.error.errors.map(e=>e.message),"pagination")}function gn(e){const t=zt(e);!t.success&&t.errors&&un(t.errors,"options")}function pn(e){const t=sn(e);!t.success&&t.errors&&un(t.errors,"options")}function mn(e){const t=Xe.safeParse(e);t.success||un(t.error.errors.map(e=>e.message),"options")}function fn(e){const t=ke.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 yn(e,t,n=!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 o=parseFloat(e);if(isNaN(o))throw new K(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new K(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(o<0)throw new K(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new K(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var wn=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=ke.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:fn,validateCheckPoolOptions:gn,validateGetAmountOptions:pn,validateGetGraphOptions:mn,validateNumericString:yn,validatePagination:hn,validateTokenName:dn});function kn(e,t){const n=e,o=Number(n.page)||t.page,i=Number(n.limit)||t.limit,a=n.data,r=Number(n.total)||Number(a?.count)||0;return{page:o,limit:i,total:r,totalPages:Math.ceil(r/i)}}function vn(e,t){return{hasNext:e<t,hasPrevious:e>1}}function Tn(e,t,n=!1){const o=!0===e.error||200!==e.status,i=n&&!e.data;if(o||i)throw new Error(e.message||t)}const bn="/launchpad/upload-image",An="/launchpad/fetch-pool",Sn="/launchpad/check-pool",En="/launchpad/get-graph-data",In="/holders",Nn="/launchpad/get-badge/",Pn="/trade/",Fn="/token/commment",Cn="/token/commment",Dn="/user/profile",xn="/user/profile",$n="/user/token-list",Ln="/user/token-hold",Bn="/user/transfer-faucets",Un=5,On={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100},_n={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20};class Rn{constructor(e,t=!1){this.http=e,this.logger=new _({debug:t,context:this.constructor.name})}}class Mn{constructor(e=!1){this.logger=new _({debug:e,context:this.constructor.name})}}function qn(e,t){return"string"==typeof e[t]}function Gn(e,t){return void 0===e[t]||"string"==typeof e[t]}function Kn(e,t){return void 0===e[t]||"number"==typeof e[t]}function Vn(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function jn(e){if(!e||"object"!=typeof e)return!1;const t=e;return qn(t,"tokenName")&&Kn(t,"from")&&Kn(t,"to")&&Kn(t,"resolution")}class Wn extends Rn{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=R(t),o=await this.http.get(An,n);if(!o)throw oe("No response from pool service",500);Tn(o,"Failed to fetch pools",!0);const i=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at||e.createdAt||""}));else{const 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),a=o.data.count??o.data.total??0;return{pools:i,total:a,totalPages:e.limit>0?Math.ceil(a/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:n,pageSize:o,...i}=e,a=[];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({...i,page:e,limit:o}));(await Promise.all(n)).forEach(e=>{a.push(...e.pools)})}return a}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({...i,page:e,limit:o})),n=await Promise.all(t);for(const e of n){if(0===e.pools.length){s=!1;break}a.push(...e.pools)}r+=e.length,r>On.SAFETY_MAX_PAGES&&(s=!1)}return a}async fetchPools(e={}){const t=e.page||On.DEFAULT_PAGE,n=e.limit??On.DEFAULT_LIMIT;let o;if(0!==n&&hn({page:t,limit:n}),e.tokenName&&dn(e.tokenName),"recent"===e.type?o="RECENT":"popular"===e.type&&(o="POPULAR"),n>0&&n<=20){const i=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...o&&{type:o},page:t,limit:n});return{pools:i.pools,page:t,limit:n,total:i.total,totalPages:i.totalPages,hasNext:t<i.totalPages,hasPrevious:t>1}}if(0===n){const t=On.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}),i=[...n.pools];if(n.pools.length>0){const a=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});i.push(...a)}return{pools:i,page:1,limit:i.length,total:n.total||i.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const i=On.BACKEND_MAX_PAGE_SIZE,a=Math.ceil(n/i),r=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...o&&{type:o},page:t,limit:i}),s=[...r.pools],c=Math.min(a,r.totalPages-t+1);if(c>1){const n=t+c-1,a=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...o&&{type:o},startPage:t+1,totalPages:n,pageSize:i});s.push(...a)}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){gn(e),e.tokenName&&dn(e.tokenName);const t=R(e),n=await this.http.get(Sn,t);if(!n)throw oe("No response from pool service",500);Tn(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(!jn(e))throw new K("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:o,resolution:i}=e;if(dn(t),!n||!o||!i)throw new K("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const a={tokenName:t,from:n,to:o,resolution:i};mn(a);const r=R(a),s=await this.http.get(En,r);if(!s)throw oe("No response from pool service",500);return Tn(s,"Failed to fetch graph data",!0),{dataPoints:s.data}}async fetchTokenDistribution(e){if(!e)throw te("tokenName","Token name");dn(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw ee(e);const n=encodeURIComponent(t),o=await this.http.get(`${In}/${n}`);if(!o)throw oe("No response from pool service",500);Tn(o,"Failed to fetch token distribution",!0);const i=o.data;if(!Array.isArray(i))throw oe("Invalid API response: expected array of holders",o.status);for(const e of i){if(!e.owner||"string"!=typeof e.owner)throw oe("Invalid holder data: missing or invalid owner field",o.status);if(!e.quantity||"string"!=typeof e.quantity)throw oe("Invalid holder data: missing or invalid quantity field",o.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw oe(`Invalid holder quantity: "${e.quantity}"`,o.status)}const a=i.reduce((e,t)=>e.plus(t.quantity),new u(0));return{holders:i.map(e=>{const t=new u(e.quantity),n=a.isZero()?0:t.dividedBy(a).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:a.toFixed(),totalHolders:i.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw te("tokenName","Token name");dn(e);const t=await this.http.get(Nn,{tokenName:e});if(!t)throw oe("No response from pool service",500);return Tn(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:o}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===o);return i?.isActive||!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(t.pools&&Array.isArray(t.pools)&&t.pools.length>0)return t.pools[0].vaultAddress||null;if(t.pools&&"object"==typeof t.pools){const e=t.pools.tokens;return e?.vaultAddress||null}return null}catch{return null}}}function Hn(e,t={}){const{stringifyFields:n=[],optionalFields:o=[],fieldMappings:i={}}=t,a={};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=i[e],c=s?String(s):t;n.includes(e)?a[c]=String(r):a[c]=r}return R(a)}const zn={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class Qn extends Rn{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return qn(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Gn(t,"userAddress")&&Kn(t,"page")&&Kn(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:n,userAddress:o,page:i=On.DEFAULT_PAGE,limit:a=On.DEFAULT_LIMIT,startDate:r,endDate:s,sortOrder:c}=e;if(!ce(t))throw new K("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");re(i,a,zn);const l=function(e,t,n){return Hn({tokenName:e,page:t,limit:n},{stringifyFields:["page","limit"]})}(t,i,a),u=await this.http.get(Pn,l);if(!u)throw new K("No response from trade service","response","NO_RESPONSE");const d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const g=kn(u,{page:i,limit:a}),p=vn(g.page,g.totalPages);return{trades:d,...g,...p}}}const Xn=new _({debug:!1,context:"DateUtils"});function Zn(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())?(Xn.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):n}catch(n){return Xn.warn(`Date parsing error for "${e}":`,n),t||new Date}}const Yn={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class Jn extends Rn{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 qn(t,"tokenName")&&Kn(t,"page")&&Kn(t,"limit")}(e))throw new K("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:n=On.DEFAULT_PAGE,limit:o=On.DEFAULT_LIMIT}=e;if(!ce(t))throw new K("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");re(n,o,Yn);const i=await this.poolService.resolveTokenNameToVault(t);if(!i)throw ee(t);const a=Hn({vaultAddress:i,page:n,limit:o},{stringifyFields:["page","limit"]}),r=await this.http.get(Fn,a);if(!r)throw new K("No response from comment service","response","NO_RESPONSE");if(Tn(r,"Failed to fetch comments"),!r.data)throw new K("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 K("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:Zn(e.createdAt)})),total:r.data.count||0}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return qn(t,"tokenName")&&qn(t,"content")}(e))throw new K("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:n}=e;if(!ce(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>=Yn.CONTENT.MIN_LENGTH&&t.length<=Yn.CONTENT.MAX_LENGTH}(n))throw new K(`Comment content must be between ${Yn.CONTENT.MIN_LENGTH} and ${Yn.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const o=await this.poolService.resolveTokenNameToVault(t);if(!o)throw ee(t);const i=this.http.getAddress();if(!i)throw new K("User address not available - wallet not configured","userAddress","NO_WALLET");const a={userAddress:i,vaultAddress:o,content:n},r=await this.http.post(Cn,a);if(!r)throw new K("No response from comment service","response","NO_RESPONSE");Tn(r,"Failed to create comment")}}function eo(e){return e instanceof Error}function to(e){return eo(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 no(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function oo(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 ne("file","a File object (browser) or Buffer (Node.js)");{const i=new Blob([e],{type:"image/png"});o.append(t,i,n)}}return o}const io={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 ao(e){return!(!e||"string"!=typeof e)&&io.USER_ADDRESS.PATTERN.test(e)}const ro="Update profile";class so extends Rn{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!ao(t))throw new K("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const n={userAddress:t},o=await this.http.get(Dn,n);if(!o)throw new K("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(ro);if(!o)throw new K("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const i={address:o.address,message:ro,publickey:o.ethereumAddress,sign:o.signature},a=await this.http.put(xn,n,i);if(!a)throw new K("No response from user service","response","NO_RESPONSE");Tn(a,"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new K("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,o=oo(e.file,"image",n),i=await this.http.request({method:"POST",url:`${bn}?tokenName=${encodeURIComponent(t)}`,data:o,headers:{}});if(!i)throw new K("No response from user service","response","NO_RESPONSE");return Tn(i,"Image upload failed"),"string"==typeof i.data?i.data:""}catch(e){if(e instanceof K)throw e;throw new K(`Profile image upload failed: ${to(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest($n,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(Ln,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=On.DEFAULT_PAGE,limit:n=On.DEFAULT_LIMIT,search:o,tokenName:i}=e,a=this.http.getAddress();if(!a)throw new K("Wallet address not available - wallet not configured","address","NO_WALLET");const r={type:"DEFI",address:a,page:t,limit:n};return void 0!==o&&(r.search=o),void 0!==i&&(r.tokenName=i),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},i=Hn(n.includeType?{...o,type:"all"!==t.type&&t.type?t.type:"DEFI"}:o,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),a=await this.http.get(e,i);if(!a)throw new K("No response from user service","response","NO_RESPONSE");Tn(a,n.errorMessage,!0);const r=(s=a.data)?Array.isArray(s)?s:s.token:[];var s;const c=kn(a,{page:t.page||On.DEFAULT_PAGE,limit:t.limit||On.DEFAULT_LIMIT}),l=vn(c.page,c.totalPages);return{tokens:r,...c,...l}}validateGetTokenListOptions(e){if(re(e.page,e.limit,io),void 0!==e.address&&!ao(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>=io.SEARCH.MIN_LENGTH&&t.length<=io.SEARCH.MAX_LENGTH))throw new K(`Search query must be between ${io.SEARCH.MIN_LENGTH} and ${io.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>=io.TOKEN_NAME.MIN_LENGTH&&n.length<=io.TOKEN_NAME.MAX_LENGTH))throw new K(`Token name must be between ${io.TOKEN_NAME.MIN_LENGTH} and ${io.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!ao(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>=io.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=io.PROFILE.FULL_NAME.MAX_LENGTH&&io.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new K(`Full name must be between ${io.PROFILE.FULL_NAME.MIN_LENGTH} and ${io.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!ao(e.address))throw new K("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class co extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function lo(e,t,n){if(!e)throw new co("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=et.safeParse(e);if(!t.success){const n=t.error.errors.map(e=>e.message).join("; ");throw new co(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new co("Filename is required when uploading Buffer objects",t,n);const o=tt.safeParse(e);if(!o.success){const e=o.error.errors.map(e=>e.message).join("; ");throw new co(e,t,n)}if(t.length>255)throw new co(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,n);const i=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!i.includes(n))throw new co(`Invalid file type "${n}" is not allowed. Allowed types: ${i.join(", ")}`,t,n);const a=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(a))throw new co(`File extension "${a}" 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"}}(a);if(s!==n&&"application/octet-stream"!==s)throw new co(`File extension "${a}" does not match MIME type "${n}"`,t,n);return}throw new co("File must be a File object (browser) or Buffer (Node.js)",t,n)}class uo extends Rn{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;dn(t);const o=`${t}.png`;lo(n.file,o,"image/png");try{const e=`${n.tokenName??t}.png`,o=oo(n.file,"image",e),i=await this.http.request({method:"POST",url:`${bn}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:o,headers:{}});if(!i)throw ie("No response from image upload service","response");return Tn(i,"Image upload failed"),"string"==typeof i.data?i.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw ie("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class ho extends Rn{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(Bn,t);if(!n)throw new K("No response from faucet service","response","NO_RESPONSE");Tn(n,"Faucet transfer failed")}validateTransferFaucetsData(e){if(!ao(e.walletAddress))throw new K("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!io.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 go{constructor(e,t=!1){this.http=e,this.poolService=new Wn(e,t),this.tradeService=new Qn(e,t),this.commentService=new Jn(e,this.poolService,t),this.userService=new so(e,t),this.imageService=new uo(e,t),this.faucetService=new ho(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 dn(e)}}const po={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var mo;!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"}(mo||(mo={}));class fo extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function yo(e,t="0"){return new u(null==e||""===e?t:e)}function wo(e){return h(e)}function ko(e){const t=yo(e),n=new u(2).pow(96),o=t.sqrt().times(n);return d(o)}function vo(e,t=!1){const n=yo(e),o=new u(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.isLessThanOrEqualTo(0))throw new Error(`Value at index ${t} must be positive, got: ${e.toString()}`)})}function bo(...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 Ao(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 So{static validateAmount(e){const t=new u(e);try{Ao(t,"amount","for transfer")}catch(t){throw new fo(t.message,mo.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(e){if(e.length>po.MAX_UNIQUE_KEY_LENGTH)throw new K(`Unique key too long. Maximum length: ${po.MAX_UNIQUE_KEY_LENGTH}`);if(!po.UNIQUE_KEY_PATTERN.test(e))throw new fo('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',mo.INVALID_AMOUNT,{uniqueKey:e})}}}class Eo{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 No(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,i,...a]=t;if(!n||!o||!i)throw new Error("Collection, category, and type must be non-empty");const r=a.join("$");if(!r)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:o,type:i,additionalKey:r}}catch(t){throw new K(`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 Po extends s{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,i){let a;if("string"==typeof o){a={...No(o),instance:"0"}}else a={collection:o.collection,category:o.category,type:o.type,additionalKey:o.additionalKey,instance:"0"};return new Po({from:e,to:t,quantity:n,tokenInstance:a,uniqueKey:i||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,n,o){return new Po({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 Fo{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 n=e.replace("0x","");return`eth|${t.getAddress(`0x${n}`).replace("0x","")}`}static fromGalaChainAddress(e){return e.startsWith("eth|")?e.substring(4):e}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...No(e),instance:"0"}}}function Co(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")}function Do(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 i=o.slice(3,-1),a=i.length>0?i.join("$"):o[3];return{collection:o[0],category:o[1],type:o[2],additionalKey:a}}catch(t){throw new K(`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 xo(e){return{...Do(e),instance:"0"}}function $o(e){return Do(e).type}var Lo=Object.freeze({__proto__:null,extractTokenSymbolFromVault:$o,normalizeToTokenInstanceKey:Co,parseVaultAddressToTokenClassKey:Do,parseVaultAddressToTokenInstance:xo});const Bo="gala-transfer-successful",Uo="token-transfer-successful",Oo="transfer-successful-no-id";class _o extends Rn{constructor(e,t,n,o=!1,i){super(e,o),this.wallet=t,this.tokenResolver=n,this.publicAxios=i,this.signatureHelper=t?new Fo(t):void 0}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw oe("No response from GalaChain service",500);if(1!==t.Status)throw oe(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const n=t.Data.reverseBondingCurveConfiguration,o=n?.minFeePortion??"0",i=n?.maxFeePortion??"0",a=(await import("bignumber.js")).default,r=!new a(o).isZero()||!new a(i).isZero(),s=t.Data;return s.reverseBondingCurveMinFeePortion=o,s.reverseBondingCurveMaxFeePortion=i,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 oe("No response from GalaChain service",500);if(1!==e.Status)throw oe(`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(!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 oe(`Failed to fetch token balance from GalaChain: ${to(e)}`,void 0,eo(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Co(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 oe(`Failed to fetch token class from GalaChain: Status ${o.Status}${o.Message?` - ${o.Message}`:""}`,o.Status);if(!o.Data||0===o.Data.length)throw oe(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return o.Data[0]}catch(e){if(no(e)&&404===e.response?.status)throw oe("Token not found on GalaChain",404,eo(e)?e:void 0);const t=to(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw oe(`Failed to fetch token class from GalaChain: ${t}`,void 0,eo(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw new K("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 oe(`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 oe("No token supply data found for requested token classes",404);return n.Data}catch(e){if(no(e)&&404===e.response?.status)throw oe("Token supply data not found on GalaChain",404,eo(e)?e:void 0);const t=to(e);if(t.includes("Token")||t.includes("Status")||t.includes("tokenClasses"))throw e;throw oe(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,eo(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new fo("Wallet required for GALA transfer operations",mo.WALLET_REQUIRED);try{const t=ue(e.recipientAddress),n=ue(this.wallet.address),o=Po.forGALA(n,t,e.amount,e.uniqueKey),i=await this.signatureHelper.signTransferToken(o.toSigningPayload()),a=new Po({...o.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(a,null,2));const r=await this.http.post("/api/asset/token-contract/TransferToken",a);if(!r)throw new fo("No response from GalaChain transfer service",mo.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 fo("Wallet required for token transfer operations",mo.WALLET_REQUIRED);try{const t=ue(e.to),n=ue(this.wallet.address);let o;if(e.tokenId)o=Co(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 fo("Must provide either tokenId or tokenName for token identification",mo.TOKEN_NOT_FOUND);o=await this.resolveTokenInstance(e.tokenName)}const i=new Po({from:n,to:t,quantity:e.amount,tokenInstance:o,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),a=await this.signatureHelper.signTransferToken(i.toSigningPayload()),r=new Po({...i.toSigningPayload(),signedPayload:a});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 fo("No response from GalaChain transfer service",mo.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 fo)throw t;throw new fo(`Failed to resolve token class key for '${e}': ${to(t)}`,mo.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(!le(e.recipientAddress))throw new fo("Invalid recipient address format",mo.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});So.validateAmount(e.amount),So.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(!le(e.to))throw new fo("Invalid recipient address format",mo.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new fo("Must provide either tokenId or tokenName for token identification",mo.TOKEN_NOT_FOUND);if(e.tokenName&&!po.TOKEN_NAME_PATTERN.test(e.tokenName))throw new fo("Invalid token name format",mo.TOKEN_NOT_FOUND,{tokenName:e.tokenName});So.validateAmount(e.amount),So.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new fo(`Token '${e}' not found or not available for transfer`,mo.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 fo)throw t;throw new fo(`Failed to resolve token '${e}': ${to(t)}`,mo.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){try{return xo(e)}catch(e){if(e instanceof K)throw new fo(`Invalid vault address format: ${e.message}`,mo.TOKEN_NOT_FOUND);throw new fo(`Failed to parse vault address: ${e instanceof Error?e.message:String(e)}`,mo.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?Bo:Uo:Oo}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new fo("Transfer succeeded but transaction ID could not be extracted",mo.NETWORK_ERROR)}handleTransferError(e,t,n){if(e instanceof fo)return e;if(e instanceof K)return new fo(e.message,mo.INVALID_AMOUNT);if(no(e)&&e.response){const t=e.response.status,o=e.response.data;if(400===t)return new fo(("string"==typeof o?.message?o.message:void 0)||"Invalid transfer request",mo.INVALID_AMOUNT);if(403===t)return new fo("Insufficient balance for transfer",mo.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new fo("Token not found",mo.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new fo("Transfer request timed out",mo.NETWORK_ERROR);const o=to(e);return new fo(o||t,mo.NETWORK_ERROR)}}class Ro{constructor(e,t,n,o=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=n,this.logger=new _({debug:o,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e;if(!t&&!n)throw te("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&n)throw new K("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 K("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw te("tokenId","Token ID");try{const t=Co(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 oe("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 K("Invalid price response: data must be a string, got "+typeof o.data,"data","INVALID_RESPONSE");const i=parseFloat(o.data);if(isNaN(i))throw new K(`Invalid price value: could not parse "${o.data}" as number`,"data","INVALID_CALCULATION");const a=`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`;let r;try{if(this.cache){const e=this.cache.getByTokenId(a);if(e?.symbol)return r=e.symbol,this.logger.debug(`DEX spot price for ${r} (cached): $${i}`),{symbol:r,price:i}}this.logger.debug(`Symbol cache miss for ${a}, fetching from API`);r=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(a,{symbol:r}),this.logger.debug(`Cached symbol for ${a}: ${r}`)),this.logger.debug(`DEX spot price for ${r}: $${i}`)}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): $${i}`)}return{symbol:r,price:i}}catch(e){if(e instanceof K)throw e;throw oe(`Failed to fetch DEX spot price: ${to(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!e||"string"!=typeof e)throw new Error(q);try{if(n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const n=`${t.sellingToken.collection}|${t.sellingToken.category}|${t.sellingToken.type}|${t.sellingToken.additionalKey}`;return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${to(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const o=await t({tokenName:e,amount:"1",type:"native"}),i=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(!i)throw oe("GALA price not available");const a=Number(o.amount)/1e18;if(a<=0)throw new K(`Invalid token amount calculation: ${a}`,"amount","INVALID_CALCULATION");const r=i.price/a;return{symbol:e.toUpperCase(),price:r}}catch(t){if(t instanceof Error)throw oe(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw oe(`Failed to calculate launchpad token spot price for ${e}: ${to(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw oe("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 K||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw oe(`Failed to fetch token details from GalaChain for ${e}: ${to(t)}`,500)}}}const Mo=8,qo=18,Go={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"};function Ko(e,t=18){const n=parseFloat(e);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Vo(e){return Ko(e,8)}function jo(e){return Ko(e,18)}function Wo(e){return{maxAcceptableReverseBondingCurveFee:Vo(e.maxAcceptableReverseBondingCurveFee)}}new _({debug:!1,context:"NumberUtils"});const Ho={BuyNativeDto:class extends s{constructor(e,t,n="0",o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Vo(t),this.expectedToken=jo(n),this.extraFees=Wo(o)}},BuyExactDto:class extends s{constructor(e,t,n,o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=jo(t),this.expectedNativeToken=Vo(n),this.extraFees=Wo(o)}},SellExactDto:class extends s{constructor(e,t,n="0",o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=jo(t),this.expectedNativeToken=Vo(n),this.extraFees=Wo(o)}},SellNativeDto:class extends s{constructor(e,t,n,o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Vo(t),this.expectedToken=jo(n),this.extraFees=Wo(o)}}};class zo extends Mn{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),o=c(e),i={...e,prefix:o},{signature:a,domain:r}=await this.signWithEthersWallet(n,i),s={...e,signature:a,types:n,domain:r};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(s),signatureLength:a.length}),s}catch(e){this.logger.error("❌ Signature generation failed:",e);throw ae(`Failed to sign DTO: ${to(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 ie("Wallet provider does not support typed data signing","walletProvider");{const i=await this.walletProvider.getNetwork();n={name:i.name,chainId:Number(i.chainId)},o=await this.walletProvider.signTypedData(n,e,t)}}return{signature:o,domain:n}}catch(e){throw ae(`Ethers.js signing failed: ${to(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const o=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),i=(e,t,o,a=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const r=i(e,t[0],o,!0);return a||n[o].push({name:e,type:(r??e)+"[]"}),r?r+"[]":void 0}if("object"==typeof t&&null!==t){if(n[e])throw new K(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).forEach(([t,n])=>{i(t,n,e)}),a||n[o].push({name:e,type:e}),e}{let i;switch(typeof t){case"string":i="string";break;case"number":i="uint256";break;case"boolean":i="bool";break;default:throw new K(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return a||n[o].push({name:e,type:i}),i}}};return Object.entries(o).forEach(([t,n])=>{i(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class Qo extends Mn{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(),i=`$service$${n.toStringKey()}$launchpad`,a=`$tokenBalance$${n.toStringKey()}$${e}`,r=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${o.toStringKey()}$${e}`,c=[i,a,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=to(e);throw new K(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new I;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;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 te("vaultAddress","Vault address");try{const t=$o(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof K)throw ne("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!e||"string"!=typeof e)throw te("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw ne("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw ne("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw ne("vaultAddress",'having at least 5 parts separated by "$"');const n=t[2];if(!n||!/^[A-Za-z]{1,10}$/.test(n))throw ne("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 No(e)}catch(e){if(e instanceof K)throw ne("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Xo(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 u(e);if(o.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const i=o.multipliedBy(t);let a;switch(n){case"buy-native":case"sell-exact":a=o.minus(i);break;case"buy-exact":case"sell-native":a=o.plus(i);break;default:throw new Error(`Unknown operation type: ${n}`)}return a.isLessThan(0)&&(a=new u(0)),a.toFixed()}class Zo extends Rn{constructor(e,t,n=!1,o,i,a=.05,r=.01){super(e,n),this.tokenResolver=t,this.walletProvider=o,this.userAddress=i,this.defaultSlippageToleranceFactor=a,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=r,this.bundleEndpoint="/bundle",o&&i&&(this.signatureService=new zo(o,n),this.tokenKeyService=new Qo(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 te("bundleData","Bundle data");if(!e.signedDto)throw te("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw te("method","Method name");if(!Array.isArray(e.stringsInstructions))throw ne("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 ne("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(no(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 to(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw te("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 te("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:i}=e,{effectiveSlippageFactor:a,effectiveMaxFee:r,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===o){if(!i)throw new K("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xo(i,a,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:a,adjustedMinTokens:e});const t=new Ho.BuyNativeDto(s,n,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"BuyWithNative",s)}{if(!i)throw new K("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xo(i,a,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:a,adjustedMaxGalaCost:e});const t=new Ho.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:i}=e,{effectiveSlippageFactor:a,effectiveMaxFee:r,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===o){if(!i)throw new K("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xo(i,a,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:a,adjustedMinGala:e});const t=new Ho.SellExactDto(s,n,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"SellExactToken",s)}{if(!i)throw new K("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Xo(i,a,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:a,adjustedMaxTokensToSell:e});const t=new Ho.SellNativeDto(s,n,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"SellWithNative",s)}}async prepareTradingOperation(e,t,n,o){const{effectiveSlippageFactor:i,effectiveMaxFee:a}=this.calculateEffectiveSlippage(t,n,o),r=await this.resolveTokenNameToVault(e);if(!r)throw ee(e);return{effectiveSlippageFactor:i,effectiveMaxFee:a,vaultAddress:r}}calculateEffectiveSlippage(e,t,n){const o=n??this.defaultSlippageToleranceFactor,i=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let a=e||"0";return e&&(a=Xo(e,i,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:i,adjustedMaxFee:a})),{effectiveSlippageFactor:o,effectiveFeeSlippageFactor:i,effectiveMaxFee:a}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw ie("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw te("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${P()}-${Date.now()}-${this.userAddress}`;const o=await this.signatureService.signDTO(e,t,this.userAddress),i=this.tokenKeyService.generateStringsInstructions(n),a={stringsInstructions:i,method:t,signedDto:o};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:i,dtoKeys:Object.keys(o)});const r=await this.submitTransaction(a);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 Yo,Jo;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Yo||(Yo={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(Jo||(Jo={}));const ei={[Yo.PROCESSED]:Jo.COMPLETED,[Yo.COMPLETED]:Jo.COMPLETED,[Yo.SUCCESS]:Jo.COMPLETED,[Yo.FAILED]:Jo.FAILED,[Yo.ERROR]:Jo.FAILED,[Yo.PROCESSING]:Jo.PROCESSING,[Yo.PENDING]:Jo.PENDING};class ti extends Mn{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 F||(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=F(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 i=setTimeout(()=>{this.eventBuffer.has(e)&&(this.logger.debug(`📡 [Event Buffer] Cleaning up orphaned event for ${e}`),this.eventBuffer.delete(e),this.eventBufferTimeouts.delete(e))},3e4);this.eventBufferTimeouts.set(e,i)}}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0}catch(e){t(e)}})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=this.eventBuffer.get(e);if(n){this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)});const o=this.eventBufferTimeouts.get(e);o&&(clearTimeout(o),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e)}const o=this.config.timeout||3e5,i=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(o/1e3),i={transactionId:e,status:Jo.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(i),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},o);if(this.timeouts.set(e,i),this.socket&&this.socket.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:Jo.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const o=t,i=o?.data,a=o?.status||o?.Status||i?.status||i?.Status;let r=o?.message||o?.Message||i?.message||i?.Message||o?.error||i?.error;r&&"string"==typeof r||(r=a===Yo.FAILED||a===Yo.ERROR?"Transaction failed - check transaction details":a===Yo.COMPLETED||a===Yo.PROCESSED||a===Yo.SUCCESS?"Transaction completed successfully":a?`Transaction status: ${a}`:"Unknown transaction status");const s=o?.blockHash||i?.blockHash,c=o?.gasUsed||i?.gasUsed,l=o?.Data||i?.Data,u={transactionId:e,status:this.mapSocketStatus(a),message:"string"==typeof r?r:"Transaction update received",timestamp:Date.now(),...s&&{blockHash:s},...c&&{gasUsed:c},...l&&{data:l}};if(this.logger.debug(`📡 Mapped status for ${e}: ${a} -> ${u.status}`),this.logger.debug(`📡 Final message: "${r}"`),n(u),u.status===Jo.COMPLETED||u.status===Jo.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${u.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===Jo.COMPLETED?t(e):e.status!==Jo.FAILED&&e.status!==Jo.TIMEOUT||n(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return ei[t]||Jo.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 ni extends Mn{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!ce(e))throw new K("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 ee(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 Do(e)}catch(e){if(e instanceof K)throw ne("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}async function oi(e,t={}){const{maxPages:n=1e4,logger:o,pageSize:i=20}=t,a=[];let r=1,s=!0,c=0;for(;s&&r<=n;){o&&o.debug(`Auto-pagination: fetching page ${r} with limit ${i}`);const t=await e(r,i);if(!t||!Array.isArray(t.items)){o&&o.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.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: ${a.length}, total count: ${c}`),{items:a,total:c}}function ii(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 ai extends Rn{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw ie("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 ie("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 ie(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Do(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 oe(`Failed to resolve token name '${e}': ${to(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 ie("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return Lo}),o=n(t),i=Io(`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`),{from:a,to:r,sortOrder:s="DESC",page:c=1,limit:l=10}=e,u={token:i,page:String(c),limit:String(l)};a&&(u.from=a.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 ${i}, page ${c}, limit ${l}`);const h=await this.http.get("/price-oracle/fetch-price",u);if(!h)throw oe("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 oe(`Failed to fetch price history: ${to(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw oe("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw oe("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,i=n.totalPages??1;return{snapshots:t,page:o,limit:n.pageSize??50,total:n.totalItems??0,totalPages:i,hasNext:o<i,hasPrevious:o>1}}async fetchAllPriceHistory(e){this.logger.debug("Fetching all price history with options:",e);const t=await oi((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 ii(t.items,t.total,"snapshots")}validateOptions(e){const{from:t,to:n,sortOrder:o,page:i=1,limit:a=10}=e;if(function(e,t,n,o={}){const{description:i="parameter",treatEmptyAsNull:a=!0}=o,r=e[t],s=e[n],c=null!=r&&(!a||""!==r),l=null!=s&&(!a||""!==s);if(!c&&!l)throw ie(`Either ${t} or ${n} must be provided (${i})`,n);if(c&&l)throw ie(`Cannot provide both ${t} and ${n}. Provide exactly one (${i}).`,n)}(e,"tokenName","tokenId",{description:"token identifier"}),t&&!(t instanceof Date)&&isNaN(new Date(t).getTime()))throw ie("from must be a valid Date","from");if(n&&!(n instanceof Date)&&isNaN(new Date(n).getTime()))throw ie("to must be a valid Date","to");if(o&&"ASC"!==o&&"DESC"!==o)throw ie('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(i)||i<1)throw ie("page must be a positive integer","page");if(!Number.isInteger(a)||a<1||a>50)throw ie("limit must be between 1 and 50","limit")}}function ri(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new K("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:o,additionalKey:i}=e;if(!t||"string"!=typeof t)throw new K("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!n||"string"!=typeof n)throw new K("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!o||"string"!=typeof o)throw new K("Token.type must be a non-empty string, got "+typeof o,"token.type","MISSING_OR_INVALID_TYPE");if(!i||"string"!=typeof i)throw new K("Token.additionalKey must be a non-empty string, got "+typeof i,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:o,additionalKey:i}}(e);if(!e)throw new K(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new K("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,i,...a]=t;if(!n||!o||!i)throw new Error("Collection, category, and type must be non-empty");const r=a.join("|");if(!r)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:o,type:i,additionalKey:r}}catch(t){const n=e.split("|");throw new K(`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],i=t[t.length-3],a=t.slice(0,t.length-3).join("$");if(!(a&&i&&o&&n))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:a,category:i,type:o,additionalKey:n}}catch(t){const n=e.split("$");throw new K(`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 K(`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 si extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function ci(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 li{constructor(t){this.client=e.create({baseURL:t.baseUrl,timeout:t.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 si(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 si(t.status,"Invalid positions response format: positions must be an array",n);for(const e of n.positions)if(!ci(e))throw new si(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 si(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 si(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 si(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new si(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new si(e.Status,e.Message??"Gateway error",e.Data)}handleError(t,n){if(t instanceof si)return t;if(e.isAxiosError(t)){const e=t.response?.status??500,o=t.response?.data?.Message??t.message,i=t.response?.data?.Data??void 0;return new si(e,`${n}: ${o}`,i)}return new si(500,`${n}: ${t instanceof Error?t.message:String(t)}`)}}class ui{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){try{if(!e||"string"!=typeof e)throw new si(400,"Invalid wallet address");const o=Math.max(1,Math.floor(n/t)+1),i={};i.address=e,i.page=o,i.limit=t;const a=await this.http.get("/user/assets",i);if(!a||"object"!=typeof a)throw new si(500,"Invalid response format: not an object");const r=a.data;if(!r||"object"!=typeof r)throw new si(500,"Invalid response format: missing data wrapper");const s=r.token;if(!Array.isArray(s))throw new si(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 si(500,"Invalid asset in response: asset must be an object");const t=e;if("string"!=typeof t.symbol||"string"!=typeof t.name)throw new si(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 si(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 si)return e;if(e instanceof Error&&e instanceof Error&&"response"in e){const n=e,o=n.response?.status??500,i=n.response?.data?.message??n.response?.data?.Message??n.message,a=n.response?.data?.Data??n.response?.data?.data??void 0;return n.response,new si(o,`${t}: ${i}`,a)}return new si(500,`${t}: ${e instanceof Error?e.message:String(e)}`)}}const di=10;class hi extends Mn{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new Eo,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 li({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new ui(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 u(e.amount).isLessThanOrEqualTo(0))throw new H("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new H("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 i;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:n,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),i=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),r=new u(i.currentSqrtPrice),s=new u(i.newSqrtPrice),c=r.gt(s)?r.minus(s).dividedBy(r):new u(0),l=new u(i.amount0),d=new u(i.amount1),h=String(i.amount0),g=String(i.amount1),p=l.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()":l.toFixed(),"amount1BN.toFixed()":d.toFixed(),"amount0BN.s (sign flag)":l.s,"amount1BN.s (sign flag)":d.s});const f=p?m?l:d:l;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:a,priceImpact:c.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,y),currentSqrtPrice:i.currentSqrtPrice,newSqrtPrice:i.newSqrtPrice}}catch(e){i=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e?.message})}throw i||new H("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",H,e)}}async getSwapQuoteExactOutput(e){try{if(new u(e.amount).isLessThanOrEqualTo(0))throw new H("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new H("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 i;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:n,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),i=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),r=new u(i.currentSqrtPrice),s=new u(i.newSqrtPrice),c=r.gt(s)?r.minus(s).dividedBy(r):new u(0),l=o.pool.token0,d="string"==typeof l?l.split("|")[0]:l?.tokenName||l,h=n.split("|")[0]===d?i.amount1:i.amount0,g=h.toFixed?.()||String(h);return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:g,estimatedOutput:e.amount,feeTier:a,priceImpact:c.toFixed(),executionPrice:this.calculateExecutionPrice(g,e.amount),currentSqrtPrice:i.currentSqrtPrice,newSqrtPrice:i.newSqrtPrice}}catch(e){i=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:e?.message})}throw i||new H("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",H,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=yo(e),o=new u(1).minus(t);return n.multipliedBy(o)}(e.estimatedOutput,e.slippageTolerance||.01),i=this.getWalletAddress();if(!i)throw new Error("Wallet address required for swap execution");let a;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});a=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:a,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:t?.message})}const r={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:o.toFixed(),feeTier:e.feeTier,walletAddress:i,slippageTolerance:e.slippageTolerance||.01};void 0!==a&&(r.currentSqrtPrice=a);const s=await this.sendSwapToBundler(r);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:s,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();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){const t=e;this.handleGSwapError("Failed to execute swap",z,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:ri(`${t}|Unit|none|none`),symbol:t,balance:(n=e.quantity||e.balance||0,void 0!==o?yo(n).toFixed(o):yo(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",X,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 oi((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",X,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),i=[500,3e3,1e4];let a=new u(0),r=0;for(const s of i)try{const e=await this.gatewayClient.getPoolData({tokenA:n,tokenB:o,feeTier:s});e&&(a=a.plus(new u(e.liquidity||0)),r++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:s})}return{tokenA:e,tokenB:t,liquidity:a.toFixed(),feeTiers:i,swapCount:r}}catch(n){this.logger.warn("Failed to fetch pool info",n);const o=n;return this.logger.debug("Pool error details",{error:new Q(`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()),i=this.chunkArray(o,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:i.length,concurrency:t});const a=new Map;for(let e=0;e<i.length;e++){const t=i[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?a.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return a}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 ri(e)}catch(t){if(t instanceof Error&&t.message?.includes("Plain token string"))return this.logger.debug("Using default TokenClassKey for simple token symbol",{token:e}),{collection:"Token",category:"Unit",type:e,additionalKey:"none"};throw t}}async getUserLiquidityPositions(t,n=10,o,i){try{this.logger.debug("Fetching user liquidity positions",{ownerAddress:t,limit:n,bookmark:o});const a=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,r={user:t,limit:n,bookmark:o||""};this.logger.debug("Sending position query request",{endpoint:a,payload:r});const s=await e.post(a,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(e=>this.normalizePositionResponse(e,t));let h;this.logger.debug("Retrieved liquidity positions",{count:d.length,hasNextBookmark:!!u,nextBookmark:u}),i?.withPrices&&d.length>0&&(h=await this.fetchPositionPrices(d));const g={items:d};return void 0!==u&&(g.nextBookmark=u),void 0!==h&&(g.prices=h),g}catch(e){if(e&&"object"==typeof e&&"response"in e){const n=e;this.logger.error("Position query failed with HTTP error",{status:n.response?.status,statusText:n.response?.statusText,data:n.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:t})}this.handleGSwapError("Failed to fetch user liquidity positions",Z,e)}}async getAllSwapUserLiquidityPositions(e,t){try{this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const n=async t=>{const n=await this.getUserLiquidityPositions(e,di,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},o=await async function(e,t={}){const{maxPages:n=1e4,logger:o,pageSize:i=20}=t,a=[];let r,s=0;for(;s<n;){o&&o.debug(`Auto-pagination (bookmark): fetching page ${s+1} with pageSize ${i}`,{bookmark:r});const t=await e(r,i);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}a.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<i;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:i,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: ${a.length}`,{pageCount:s}),{items:a,total:a.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:di}),i=o.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:i.length}),t?.withPrices&&i.length>0){return{items:i,prices:await this.fetchPositionPrices(i)}}return i}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",Z,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),i=(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(!i||"object"!=typeof i||!("positionId"in i)&&!("id"in i))throw new Error("Invalid position data returned from API");const a=this.normalizePositionResponse(i,e);return this.logger.debug("Retrieved liquidity position",{positionId:a.positionId}),a}catch(e){this.handleGSwapError("Failed to fetch liquidity position",Z,e)}}async getLiquidityPositionById(e,t){try{let n;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t});let o=null;const i=5,a=2e3;for(let e=1;e<=i;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<i){this.logger.warn("Position not yet indexed, retrying",{attempt:e,positionId:t,resultType:typeof n}),await new Promise(e=>setTimeout(e,a));continue}o=new Error("Position not found after retries")}catch(n){if(e<i){this.logger.warn("Error fetching position, retrying",{attempt:e,positionId:t,error:n instanceof Error?n.message:n}),await new Promise(e=>setTimeout(e,a));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",Z,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 i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!i.ok){if(404===i.status)throw new Error("Position not found (HTTP 404): No position exists for this compound key");if(400===i.status)throw new Error("Invalid parameters (HTTP 400): Check token format, fee (500|3000|10000), and tick ranges");throw new Error(`HTTP ${i.status}: ${i.statusText}`)}const a=await i.json();if(1!==a.Status||!a.Data)throw new Error(`Position not found: ${a.Message||"API returned no position data"}`);const r=this.normalizePositionResponse(a.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",Z,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",Z,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 i=new u(e.minPrice),a=new u(e.maxPrice),r=Math.floor(ko(i)),s=Math.ceil(ko(a)),c=Math.floor(r/o)*o,l=Math.ceil(s/o)*o;this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:c,tickUpper:l,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?ri(e.token0):e.token0,g="string"==typeof e.token1?ri(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${c}-${l}`,walletAddress:d});const p=await this.sendAddLiquidityToBundler({token0:h,token1:g,fee:e.fee,tickLower:c,tickUpper:l,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 i=(await this.getUserLiquidityPositions(t,10)).items;if(i&&i.length>0){const t=e.token0.split("|")[0].toUpperCase(),a=e.token1.split("|")[0].toUpperCase(),r=[];for(const n of i){if(!n||!n.positionId)continue;const o=n.token0?.toUpperCase(),i=n.token1?.toUpperCase();if(!o||!i)continue;const s=o===t&&i===a||o===a&&i===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:i.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}let i=o;if(n)try{i=await this.getLiquidityPositionById(d,n)}catch(e){}return{...m,...i,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",Z,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?ri(e.token0):e.token0,o="string"==typeof e.token1?ri(e.token1):e.token1;await this.ensureWebSocketConnected();const i=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:i});const a=this.webSocketService.waitForTransaction(i),r={transactionId:i};if(r.positionId&&i){this.logger.info("Position ID returned directly from backend",{transactionId:i,positionId:r.positionId});const e=await a;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,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(i)}}}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(i)}}}}if(i){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:i});const n=await a;let o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,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:di});const n=3,i=5e3,a=3e3;let r=[];for(let c=1;c<=n;c++){const l=1===c?i:a;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:di});if(r=(await this.getUserLiquidityPositions(t,di)).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(),i=[];for(const o of r){if(!o||!o.positionId)continue;const a=o.token0?.toUpperCase(),r=o.token1?.toUpperCase();if(!a||!r){this.logger.debug("Skipping position with empty tokens",{positionId:o.positionId});continue}const s=a===t&&r===n||a===n&&r===t,c=o.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:o.positionId,tokens:`${a}/${r}`,tokensMatch:s,fee:o.feeTier,feeMatches:c}),s&&c&&i.push(o)}if(i.length>0){s=i[i.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(i)}}}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",Z,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?ri(e.token0):e.token0,n="string"==typeof e.token1?ri(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 i=this.webSocketService.waitForTransaction(o);return this.monitorBundlerTransaction(o,i,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",Z,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?ri(e.token0):e.token0,n="string"==typeof e.token1?ri(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 i=this.webSocketService.waitForTransaction(o);return this.monitorBundlerTransaction(o,i,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",Z,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:o,gswapToken1:i}=this.convertTokenPair(e,t),a=await this.gatewayClient.getPoolData({tokenA:o,tokenB:i,feeTier:n}),r=this.calculatePriceFromSqrtPriceX96(new u(a.sqrtPriceX96));return{tokenA:e,tokenB:t,feeTier:n,liquidity:a.liquidity.toString(),sqrtPriceX96:a.sqrtPriceX96.toString(),tick:a.tick,feeGrowthGlobal0X128:a.feeGrowthGlobal0X128.toString(),feeGrowthGlobal1X128:a.feeGrowthGlobal1X128.toString(),currentPrice:r.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",Q,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),i=yo(o.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:vo(i,!0),tick:o.tick,liquidity:o.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",Q,e)}}async calculateOptimalPositionSize(e,t,n,o,i,a,r){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:o,desiredAmount1:i});const s=(await this.getPoolData(e,t,n)).tick,c=h(a),l=h(s),d=h(r),m=g(new u(o),new u(i),c,l,d),f=p(m,l,c,d),y=f[0],w=f[1],k=new u(o),v=new u(i);return{amount0:y.toFixed(),amount1:w.toFixed(),liquidity:m.toFixed(),ratio:y.dividedBy(w).toFixed(),utilizationPercent:{amount0:y.dividedBy(k).multipliedBy(100).toFixed(2),amount1:w.dividedBy(v).multipliedBy(100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",Z,e)}}async validatePositionParameters(e,t,n,o,i,a,r){const s=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:o,tickUpper:i});const l=[500,3e3,1e4];l.includes(n)||s.push(`Invalid fee tier: ${n}. Must be one of: ${l.join(", ")}`);const d=this.getTickSpacing(n);let h;o%d!==0&&s.push(`tickLower must be multiple of ${d}`),i%d!==0&&s.push(`tickUpper must be multiple of ${d}`),o>=i&&s.push(`tickLower (${o}) must be less than tickUpper (${i})`);try{h=await this.getPoolData(e,t,n)}catch{return s.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:s,warnings:c,gasEstimate:0}}const g=new u(a),p=new u(r);if(g.isNaN()||p.isNaN())s.push("Amounts must be valid numbers");else try{bo(g,p)}catch(e){s.push(`Liquidity amounts must be non-negative: ${e.message}`)}const m=h.tick;(m<o||m>i)&&c.push("Position is out of current price range - will not earn fees until price moves into range");new u(h.liquidity).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const f=0===s.length?35e4:0;return{valid:0===s.length,errors:s,warnings:c,gasEstimate:f,tickSpacing:d,currentTick:m,poolLiquidity:h.liquidity}}catch(e){const t=e;return s.includes(t?.message||"")||s.push(`Validation failed: ${t?.message||String(e)}`),{valid:!1,errors:s,warnings:c,gasEstimate:0}}}async calculateTicksForPrice(e,t,n,o,i){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:o});const a=this.getTickSpacing(i),r=new u(n),s=new u(o);if(r.gte(s))throw new Error("minPrice must be less than maxPrice");const c=Math.floor(ko(r)),l=Math.ceil(ko(s)),d=Math.floor(c/a)*a,h=Math.ceil(l/a)*a,g=Math.pow(1.0001,d),p=Math.pow(1.0001,h),m=new u(g),f=new u(p);return{tokenA:e,tokenB:t,feeTier:i,tickLower:d,tickUpper:h,tickSpacing:a,requestedMinPrice:n,requestedMaxPrice:o,actualMinPrice:m.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:m.minus(r).dividedBy(r).multipliedBy(100).toFixed(4),maxPriceDeviation:f.minus(s).dividedBy(s).multipliedBy(100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",Z,e)}}async calculatePriceForTicks(e,t,n,o){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:o});const i=Math.pow(1.0001,n),a=Math.pow(1.0001,o);let r;try{r=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const s=new u(i),c=new u(a);return{tokenA:e,tokenB:t,tickLower:n,tickUpper:o,minPrice:s.toFixed(8),maxPrice:c.toFixed(8),currentPrice:r,priceRange:`${s.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:o-n}}catch(e){this.handleGSwapError("Failed to calculate price for ticks",Z,e)}}calculateExecutionPrice(e,t){try{const n=new u(e),o=new u(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 u(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new u(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return new u(0)}}async getPoolSlot0(t,n,o){try{this.logger.debug("Fetching pool slot0 data",{token0:t,token1:n,fee:o});const i="string"==typeof t?ri(t):t,a="string"==typeof n?ri(n):n,r=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetSlot0`,s=await e.post(r,{token0:i,token1:a,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 Q("GetSlot0 API returned unexpected status",{httpStatus:s.status,apiStatus:s.data?.Status});const c=s.data.Data||{},l={sqrtPrice:c.sqrtPrice||"0",tick:c.tick||0,liquidity:c.liquidity||"0",grossPoolLiquidity:c.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:l.sqrtPrice,tick:l.tick,liquidity:l.liquidity}),l}catch(e){this.handleGSwapError("Failed to fetch pool slot0 data",Q,e,{token0:t,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 u(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",Q,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,n){try{const o=wo(t),i=wo(n);return m(e,o,i)}catch{return new u(0)}}calculateLiquidityFromAmount1(e,t,n){try{const o=wo(t),i=wo(n);return f(e,o,i)}catch{return new u(0)}}calculateAmount0FromLiquidity(e,t,n){try{const o=wo(t),i=wo(n);return y(o,i,e)}catch{return new u(0)}}calculateAmount1FromLiquidity(e,t,n){try{const o=wo(t),i=wo(n);return w(o,i,e)}catch{return new u(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(n){if(!this.privateKey)throw new Error("GSwapService: AddLiquidity requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:n.token0.type,token1:n.token1.type,fee:n.fee,tickRange:`${n.tickLower}-${n.tickUpper}`});const o=`galaswap - operation - ${P()}-${Date.now()}-${n.owner}`,i={token0:n.token0,token1:n.token1,fee:n.fee,owner:n.owner,tickLower:n.tickLower,tickUpper:n.tickUpper,amount0Desired:n.amount0Desired,amount1Desired:n.amount1Desired,amount0Min:n.amount0Min,amount1Min:n.amount1Min,positionId:"",uniqueKey:o},a=new t.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},c=this.calculatePersonalSignPrefix(i),l={...i,prefix:c},u=await a.signTypedData(s,r,l),d={...l,signature:u,types:r,domain:s};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:d.signature?.substring(0,20)+"...",prefix:d.prefix,tickLower:i.tickLower,tickUpper:i.tickUpper});const h=this.buildLiquidityStringsInstructions(n.token0,n.token1,n.fee,n.owner),g=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),p=await g.post("/bundle",{method:"AddLiquidity",signedDto:d,stringsInstructions:h}),m=p.data?.data||p.data?.transactionId||p.data?.id;if(!m)throw this.logger.error("Bundler response structure",{status:p.status,data:p.data,dataType:typeof p.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(p.data)}`);return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:m}),m}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(n,o,i,a,r,s,c,l,u){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const d=new t.Wallet(this.privateKey),h=await d.getAddress(),g=`galaswap - operation - ${P()}-${Date.now()}-${h}`,p={tickLower:n,tickUpper:o,amount:i,token0:a,token1:r,fee:s,amount0Min:c,amount1Min:l,positionId:u,uniqueKey:g},m={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"}]},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(a,r,s,h);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:n,tickUpper:o,amount:i,fee:s,positionId:u,transactionId:g});const b=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),A=await b.post("/bundle",{method:"RemoveLiquidity",signedDto:v,stringsInstructions:T}),S=A.data?.data||A.data?.transactionId||A.data?.id;if(!S)throw this.logger.error("Bundler response structure",{status:A.status,data:A.data,dataType:typeof A.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(A.data)}`);return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:S}),S}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(n,o,i,a,r,s,c,l){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const u=new t.Wallet(this.privateKey),d=await u.getAddress(),h=`galaswap - operation - ${P()}-${Date.now()}-${d}`,g={token0:n,token1:o,fee:i,amount0Requested:a,amount1Requested:r,tickLower:s,tickUpper:c,positionId:l,uniqueKey:h},p={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},f=this.calculatePersonalSignPrefix(g),y={...g,prefix:f},w=await u.signTypedData(m,p,y),k={...y,signature:w,types:p,domain:m},v=this.buildLiquidityStringsInstructions(n,o,i,d);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:i,amount0Requested:a,amount1Requested:r,tickLower:s,tickUpper:c,positionId:l,transactionId:h});const T=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),b=await T.post("/bundle",{method:"CollectPositionFees",signedDto:k,stringsInstructions:v}),A=b.data?.data||b.data?.transactionId||b.data?.id;if(!A)throw this.logger.error("Bundler response structure",{status:b.status,data:b.data,dataType:typeof b.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(b.data)}`);return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:A}),A}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(n){if(!this.privateKey)throw new Error("GSwapService: Swap requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const o=[500,3e3,1e4];if(!o.includes(n.feeTier))throw new Error(`GSwapService: Invalid fee tier ${n.feeTier}. Must be one of: ${o.join(", ")} (basis points)`);try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof n.fromToken?n.fromToken:n.fromToken.type,toToken:"string"==typeof n.toToken?n.toToken:n.toToken.type,inputAmount:n.inputAmount,minOutput:n.minOutput,feeTier:n.feeTier});let o=n.fromToken,i=n.toToken;"string"==typeof o&&(o=ri(o)),"string"==typeof i&&(i=ri(i));const a=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`,r=`${i.collection}|${i.category}|${i.type}|${i.additionalKey}`,s=a<r?[o,i,a,r]:[i,o,r,a],[c,l,d,h]=s,g="string"==typeof n.fromToken?ri(n.fromToken):n.fromToken,p=`${g.collection}|${g.category}|${g.type}|${g.additionalKey}`,m=p===d,f=`galaswap - operation - ${P()}-${Date.now()}-${n.walletAddress}`;let y;if(!n.currentSqrtPrice)throw new Error("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation");const w=new u(n.currentSqrtPrice);y=m?w.multipliedBy(.01).toString():w.multipliedBy(100).toString(),this.logger.debug("Using relative price bounds for sqrtPriceLimit",{currentSqrtPrice:n.currentSqrtPrice,zeroForOne:m,sqrtPriceLimit:y,direction:m?"token0→token1 (downward)":"token1→token0 (upward)",reason:"amountOutMinimum provides slippage protection, sqrtPriceLimit sets wide boundaries"});const k={token0:c,token1:l,fee:n.feeTier,amount:new u(n.inputAmount).toFixed(),zeroForOne:m,sqrtPriceLimit:y,recipient:n.walletAddress,amountOutMinimum:new u(n.minOutput).multipliedBy(-1).toFixed(),uniqueKey:f};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:d,orderedToken1String:h,fromTokenStr:p,zeroForOne:m?`TRUE (${d} → ${h})`:`FALSE (${h} → ${d})`,inputAmount:n.inputAmount,expectedOutput:n.minOutput,slippageTolerance:100*(n.slippageTolerance||.01)+"%",currentSqrtPrice:n.currentSqrtPrice,swapDto:{amount:k.amount,zeroForOne:k.zeroForOne,sqrtPriceLimit:k.sqrtPriceLimit,amountOutMinimum:k.amountOutMinimum}});const v=new t.Wallet(this.privateKey),T={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"}]},b={name:"ethereum",chainId:1},A=this.calculatePersonalSignPrefix(k),S={...k,prefix:A},E=await v.signTypedData(b,T,S),I={...S,signature:E,types:T,domain:b};this.logger.debug("Swap DTO signed",{signature:I.signature?.substring(0,20)+"...",prefix:I.prefix,zeroForOne:k.zeroForOne});const N=this.buildLiquidityStringsInstructions(c,l,n.feeTier,n.walletAddress),F=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),C=await F.post("/bundle",{method:"Swap",signedDto:I,stringsInstructions:N}),D=C.data?.data||C.data?.transactionId||C.data?.id;if(!D)throw this.logger.error("Bundler response structure",{status:C.status,data:C.data,dataType:typeof C.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(C.data)}`);return this.logger.debug("Swap transaction sent to bundler",{transactionId:D,inputAmount:n.inputAmount,minOutput:n.minOutput}),D}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,o){const i=`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`,a=`$${t.collection}$${t.category}$${t.type}$${t.additionalKey}`,r=`$pool${i}${a}$${n}`;return[r,`$userPosition${o}`,`$tokenBalance${i}${o}`,`$tokenBalance${a}${o}`,`$tokenBalance${i}${r}`,`$tokenBalance${a}${r}`]}handleGSwapError(e,t,n,o){this.logger.error(e,n);const i=this.extractGSwapErrorCode(n),a=n,r=[`${e}: ${a?.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)),i&&r.push(i),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 gi{}gi.BASE_PRICE=1650667151e-14,gi.PRICE_SCALING_FACTOR=1166069e-12,gi.TRADING_FEE_FACTOR=.001,gi.GAS_FEE="1",gi.MIN_UNBONDING_FEE_FACTOR=0,gi.MAX_UNBONDING_FEE_FACTOR=.5,gi.NET_UNBONDING_FEE_FACTOR=.5,gi.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class pi extends Mn{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>=pi.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||gi.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 i=0;i+=2*o.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(i+=8),i+=8,n.vaultAddress&&(i+=2*n.vaultAddress.length),n.maxSupply&&(i+=2*n.maxSupply.length),n.symbol&&(i+=2*n.symbol.length),i+=32,t+=i}),{totalTokens:this.cache.size,cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.get(t)||null}setByTokenId(e,t){const n=`token:${e.toLowerCase().trim()}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.has(t)}}pi.MAX_CACHE_SIZE=1e4;class mi extends Rn{constructor(e,t,n=void 0,o=5,i=!1){super(e,i),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),i=await Promise.allSettled(o.map(e=>e.task));for(let e=0;e<o.length;e++){const t=o[e],a=i[e],r=n.get(t.poolIndex)||{};"fulfilled"===a.status&&a.value&&(t.isToken0?r.token0Price=a.value:r.token1Price=a.value),n.set(t.poolIndex,r)}}const o=e.map((e,t)=>{const o=n.get(t)||{},i={...e};return void 0!==o.token0Price&&(i.token0Price=o.token0Price),void 0!==o.token1Price&&(i.token1Price=o.token1Price),i}),i=o.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:i,failed:e.length-i}),o}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:o="desc",page:i=On.DEFAULT_PAGE,limit:a=On.DEFAULT_LIMIT,withPrices:r=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:o,page:i,limit:a,withPrices:r});const s=new URLSearchParams({page:i.toString(),limit:Math.min(a,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(a,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:i,limit:o,total:n,totalPages:s,hasNext:i<s,hasPrevious:i>1}}catch(e){throw this.logger.error("Failed to fetch DEX pools",{error:e,url:c}),e}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=await oi((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}),ii(t.items,t.total,"pools")}}function fi(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,i,...a]=t;if(!n||!o||!i)throw new Error("Collection, category, and type must be non-empty");const r=a.join("|");if(!r)throw new Error("AdditionalKey must be non-empty");return{collection:n,category:o,type:i,additionalKey:r}}catch(t){throw new K(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}const yi=5;class wi extends Rn{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 Y("token0 must be a non-empty string",{token0:e});if(!t||"string"!=typeof t)throw new Y("token1 must be a non-empty string",{token1:t});const o=e.split("|"),i=t.split("|");if(4!==o.length)throw new Y("token0 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token0:e});if(4!==i.length)throw new Y("token1 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token1:t});const a=[500,3e3,1e4];if(!Number.isInteger(n)||!a.includes(n))throw new Y(`fee must be one of: ${a.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!e||"string"!=typeof e)throw new Y("amount must be a non-empty string",{amount:e});const t=new u(e);try{Ao(t,"amount","for quote calculation")}catch(t){throw new Y(t.message,{amount:e})}}convertTokenClassKey(e){const t=new I;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:i}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:o}),this.validateFetchCompositePoolDataInput(t,n,o);try{const e=fi(t),a=fi(n),r=this.convertTokenClassKey(e),s=this.convertTokenClassKey(a),c=new b(r,s,o),l=`${i||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,d=await this.http.post(l,c);if(!d||1!==d.Status)throw new J(`Pool not found: ${t}/${n} with fee ${o}`);const h=function(e){return{pool:e.pool,tickDataMap:e.tickDataMap,token0Balance:e.token0Balance,token1Balance:e.token1Balance,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals,compositePoolDto:e}}(function(e){const t=new k(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,new u(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=new u(e.pool.grossPoolLiquidity),t.liquidity=new u(e.pool.liquidity),t.feeGrowthGlobal0=new u(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=new u(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=new u(e.pool.protocolFeesToken0),t.protocolFeesToken1=new u(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=new u(e.pool.maxLiquidityPerTick);const n={};Object.keys(e.tickDataMap).forEach(t=>{const o=e.tickDataMap[t],i=new v(o.poolHash,o.tick);i.initialised=o.initialised,i.liquidityNet=new u(o.liquidityNet),i.liquidityGross=new u(o.liquidityGross),i.feeGrowthOutside0=new u(o.feeGrowthOutside0),i.feeGrowthOutside1=new u(o.feeGrowthOutside1),n[t]=i});const o={...e.token0Balance},i=new N(o);i.quantity=new u(e.token0Balance.quantity);const a={...e.token1Balance},r=new N(a);return r.quantity=new u(e.token1Balance.quantity),new T(t,n,i,r,e.token0Decimals,e.token1Decimals)}(d.Data),d.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:o,liquidity:h.pool.liquidity.toString()}),h}catch(e){if(e instanceof J)throw e;throw this.logger.error("Failed to fetch composite pool data",e),new Y(`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:i}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:o,amount:i}),this.validateQuoteAmount(i),!t)throw new Y("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0,a=fi(n),r=fi(o),s=this.convertTokenClassKey(a),c=this.convertTokenClassKey(r),l=new A(s,c,t.pool.fee,new u(i),e,t.compositePoolDto),d=await S(void 0,l);return this.logger.debug("Local quote calculated",{amount0:d.amount0,amount1:d.amount1}),{amount0:d.amount0.toString(),amount1:d.amount1.toString(),currentSqrtPrice:d.currentSqrtPrice.toString(),newSqrtPrice:d.newSqrtPrice.toString()}}catch(e){throw this.logger.error("Local quote calculation failed",e),new Y(`Local quote calculation failed: ${e.message}`,{fromToken:n,toToken:o,amount:i})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:o,amount:i}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:o,amount:i}),this.validateQuoteAmount(i),!t)throw new Y("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0,a=fi(n),r=fi(o),s=this.convertTokenClassKey(a),c=this.convertTokenClassKey(r),l=new A(s,c,t.pool.fee,new u(i),e,void 0),d=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,h=await this.http.post(d,l);if(!h||1!==h.Status)throw new Y("External quote failed: "+(h?.Message||"Unknown error"));const g=h.Data;return this.logger.debug("External quote calculated",{amount0:g.amount0,amount1:g.amount1}),{amount0:g.amount0.toString(),amount1:g.amount1.toString(),currentSqrtPrice:g.currentSqrtPrice.toString(),newSqrtPrice:g.newSqrtPrice.toString()}}catch(e){throw this.logger.error("External quote calculation failed",e),new Y(`External quote calculation failed: ${e.message}`,{fromToken:n,toToken:o,amount:i})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}function ki(e){const t=function(e){const t=jt(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 vi="/api/asset/launchpad-contract/CallNativeTokenIn",Ti="/api/asset/launchpad-contract/CallNativeTokenOut",bi="/api/asset/launchpad-contract/CallMemeTokenIn",Ai="/api/asset/launchpad-contract/CallMemeTokenOut";class Si extends s{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 Ei(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 Ii={NATIVE:"native",EXACT:"exact"},Ni={RECENT:"recent",POPULAR:"popular"},Pi={LOCAL:"local",EXTERNAL:"external"};class Fi{static calculateBuyWithExact(e,t){const n=parseFloat(e),o=parseFloat(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:a,TRADING_FEE_FACTOR:r,GAS_FEE:s}=gi,c=this.roundUp(i*(Math.exp((o+n)*a)-Math.exp(o*a))/a,8),l=new u(c).multipliedBy(r).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:s}}static calculateBuyWithNative(e,t){const n=parseFloat(e),o=parseFloat(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:a,TRADING_FEE_FACTOR:r,GAS_FEE:s}=gi,c=Math.log(n*a/i+Math.exp(o*a))/a-o,l=new u(c).multipliedBy(r).toFixed();return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:s}}static calculateSellWithExact(e,t,n,o,i){const a=parseFloat(e),r=parseFloat(t),s=parseFloat(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:h}=gi,g=c*(Math.exp(r*l)-Math.exp((r-a)*l))/l,p=new u(g),m=o+r/s*(i-o),f=p.multipliedBy(m).toFixed(8,u.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,n,o,i){const a=parseFloat(e),r=parseFloat(t),s=parseFloat(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:h}=gi,g=r-Math.log(Math.exp(r*l)-a*l/c)/l,p=new u(a),m=o+r/s*(i-o),f=p.multipliedBy(m).toFixed(8,u.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 Ci{constructor(e,t,n,o,i,a,r="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=o,this.galaChainHttp=i,this.dexApiHttp=a,this.defaultCalculateAmountMode=r,this.metadataCache=new pi}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;dn(t);const o=`${t}.png`;lo(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 ne("file","a File object (browser) or Buffer (Node.js)");{const o=`${n.tokenName||t}.png`,i=new Blob([n.file],{type:"image/png"});e.append("image",i,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 oe(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 ie("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){hn(e),e.tokenName&&dn(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=R(t),o=await this.http.get("/launchpad/fetch-pool",n);if(!0===o.error||200!==o.status||!o.data)throw oe(o.message||"Failed to fetch pools",o.status);let i=[];const a=(await import("bignumber.js")).default;if(o.data.tokens)if(Array.isArray(o.data.tokens))i=o.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",o=!new a(t).isZero()||!new a(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 a(t).isZero()||!new a(n).isZero();i=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}]}else o.data.pools&&Array.isArray(o.data.pools)&&(i=o.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",o=!new a(t).isZero()||!new a(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 da});i.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:i,page:l,limit:u,total:c,totalPages:d,hasNext:l<d,hasPrevious:l>1}}async _getAmount(e){if(pn(e),!this.galaChainHttp)throw ie("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:vi,body:{vaultAddress:n,tokenQuantity:o,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:Ti,body:{vaultAddress:n,tokenQuantity:o,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:bi,body:{vaultAddress:n,nativeTokenQuantity:o,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:Ai,body:{vaultAddress:n,nativeTokenQuantity:o,IsPreMint:!1}};throw ne("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(!Ei(e))throw oe("Malformed response data from GalaChain gateway");if(1!==e.Status)throw oe(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:o,extraFees:i}=e.Data;return{amount:o,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.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){gn(e),e.tokenName&&dn(e.tokenName);const t=R(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw oe(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(!jn(e))throw new K("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:o,resolution:i}=e;if(dn(t),!n||!o||!i)throw new K("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const a={tokenName:t,from:n,to:o,resolution:i};mn(a);const r=R(a),s=await this.http.get("/launchpad/get-graph-data",r);if(!0===s.error||200!==s.status||!s.data)throw oe(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 K("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:n,type:o,currentSupply:i}=e,a=e.mode??this.defaultCalculateAmountMode;if("local"!==a&&"external"!==a)throw new K(`Invalid calculation mode "${a}". 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(!n||"string"!=typeof n)throw new K("Amount is required and must be a string","amount","INVALID_AMOUNT");if(o!==Ii.NATIVE&&o!==Ii.EXACT)throw new K('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===a?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:o}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:o},"currentSupply",i))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:o}=e,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw new K(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return o===Ii.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:i,amount:n}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:i,amount:n})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:o,currentSupply:i,maxSupply:a,reverseBondingCurveMaxFeeFactor:r,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(!n||"string"!=typeof n)throw new K("Amount is required and must be a string","amount","INVALID_AMOUNT");if(o!==Ii.EXACT&&o!==Ii.NATIVE)throw new K('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!==i&&{currentSupply:i},...void 0!==a&&{maxSupply:a},...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,i=await this.tokenResolver.resolveTokenToVault(t);if(!i)throw new K(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return o===Ii.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:i,amount:n}):this._getAmount({type:"MEME",method:"IN",vaultAddress:i,amount:n})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:o,currentSupply:i}=e;if(!n||"string"!=typeof n)throw new K("Amount is required and must be a string","amount","INVALID_AMOUNT");if(o!==Ii.NATIVE&&o!==Ii.EXACT)throw new K('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==i&&yn(i,"currentSupply");const a=!i;if(a&&!t)throw new K("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&dn(t);let r=i;if(a){r=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return o===Ii.EXACT?Fi.calculateBuyWithExact(n,r):Fi.calculateBuyWithNative(n,r)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:o,currentSupply:i,maxSupply:a,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:s}=e;if(!n||"string"!=typeof n)throw new K("Amount is required and must be a string","amount","INVALID_AMOUNT");if(o!==Ii.EXACT&&o!==Ii.NATIVE)throw new K('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==i&&yn(i,"currentSupply");const c=!i||!a||void 0===r||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&&dn(t);let l=i,u=a,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===Ii.EXACT?Fi.calculateSellWithExact(n,l,u,h,d):Fi.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 qn(t,"tokenName")&&Vn(t)&&Gn(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:n,calculateAmountMode:o,currentSupply:i}=t;dn(n);const a=await this.tokenResolver.resolveTokenToVault(n);if(!a)throw new K(G(n),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw ie("GalaChain HTTP client not configured");const r=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:a});if(1!==r.Status)throw oe(`Failed to fetch pool details: Status ${r.Status}`,r.Status);const s=r.Data,c=(await import("bignumber.js")).default,l=i??new c(s.maxSupply).minus(s.sellingTokenQuantity).toFixed(),u=s.sellingTokenQuantity;if("0"===u)throw new K(`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 ie("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");ki(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:n}=e.reverseBondingCurveConfiguration,o=Number(t),i=Number(n);if(isNaN(o)||isNaN(i)||o<=0||i<=0||o>=i)throw new K("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 oe("Image upload failed: No URL returned");n=t}else"string"==typeof e.tokenImage&&(n=e.tokenImage);const o=`galaswap - operation - ${P()}-${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:o};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 Si(i),s=await this.http.signWithGalaChain("CreateSale",r,a.SIGN_TYPED_DATA),{signature:c,types:l,domain:u,prefix:d}=s,h={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:c,types:l,domain:u,...d&&{prefix:d},...r.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:r.reverseBondingCurveConfiguration}},g=`${e.tokenName.trim()}$Unit$none$none`,p="GALA$Unit$none$none";let m;if(parseFloat(t)>0){const e=`$service$${g}$launchpad`;m=[e,`$token$${g}$${e}`,`$tokenBalance$${g}$${e}`,`$tokenBalance$${g}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`]}else{const e=`$service$${g}$launchpad`;m=[e,`$token$${g}$${e}`,`$tokenBalance$${g}$${e}`]}const f={signedDto:h,stringsInstructions:m,method:"CreateSale"},y=await this.bundleHttp.post("/bundle",f);if(y.error||!y.data)throw oe(y.message||"Token launch failed");return y.data}async fetchTokenDistribution(e){if(!e)throw te("tokenName","Token name");dn(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new K(G(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 oe(o.message||"Failed to fetch token distribution",o.status);const i=o.data;if(!Array.isArray(i))throw oe("Invalid API response: expected array of holders",o.status);for(const e of i){if(!e.owner||"string"!=typeof e.owner)throw oe("Invalid holder data: missing or invalid owner field",o.status);if(!e.quantity||"string"!=typeof e.quantity)throw oe("Invalid holder data: missing or invalid quantity field",o.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw oe(`Invalid holder quantity: "${e.quantity}"`,o.status)}const a=i.reduce((e,t)=>e.plus(t.quantity),new u(0));return{holders:i.map(e=>{const t=new u(e.quantity),n=a.isZero()?0:t.dividedBy(a).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:n}}),totalSupply:a.toFixed(),totalHolders:i.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw te("tokenName","Token name");dn(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw oe(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 i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===o);return i?.isActive||!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.nativeTokenQuantity&&(void 0===t.vaultAddress||"string"==typeof t.vaultAddress)}(e))throw new K("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw ie("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(!Ei(n))throw oe("Malformed response data from GalaChain gateway");if(1!==n.Status)throw oe(`GalaChain calculation failed with status ${n.Status}`,n.Status);const{calculatedQuantity:o,extraFees:i}=n.Data;return{amount:o,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(e){if(e instanceof Error){const t=new Error(`Pre-mint calculation failed: ${e.message}`);throw e.stack&&(t.stack=e.stack),t}throw new Error(`Pre-mint calculation failed: ${String(e)}`)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new K(G(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw ie("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw oe(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const o=n.Data,i=new(0,(await import("bignumber.js")).default)(o.maxSupply).minus(o.sellingTokenQuantity).toFixed(),a=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:i,remainingTokens:a,maxSupply:r,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}}async fetchCurrentSupply(e){dn(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new K(G(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw ie("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw oe(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const o=n.Data,i=new(0,(await import("bignumber.js")).default)(o.maxSupply).minus(o.sellingTokenQuantity).toFixed(),a=o.maxSupply;return this.metadataCache.set(e,{maxSupply:a}),i}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return fn(e)}validateTokenName(e){return dn(e)}validatePagination(e){return hn(e)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw ie("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw te("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 oe(`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 qn(t,"tokenName")&&Vn(t)&&Gn(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:n,calculateAmountMode:o,currentSupply:i}=t;if(!n||"string"!=typeof n)throw te("tokenName","Token name (string)");try{const e={tokenName:n,amount:"1",type:"native",...void 0!==o&&{mode:o},...void 0!==i&&{currentSupply:i}},t=await this.calculateBuyAmount(e),a=(await this.fetchTokenPrice("GALA"))[0];if(!a)throw oe("GALA price not available");const r=Number(t.amount);if(r<=0)throw new K(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const s=a.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 Di={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 xi(e){return Di[e]}class $i extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Li extends $i{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Bi 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 Ui(e,t){if(!e)throw new $i(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new $i(`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 $i(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Oi(e,t,n,o){Ui(e,t);const i=e,a=i.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(a))throw new $i(`Invalid trade data received for transaction ${t}`);const r={transactionId:t,type:n,method:"native"===o.type?"native":"exact",inputAmount:a.inputQuantity||o.amount,outputAmount:a.outputQuantity||o.expectedAmount||"0",totalFees:a.totalFees||"0",tokenName:o.tokenName,vaultAddress:a.vaultAddress||"",timestamp:Date.now()};return void 0!==i.blockHash&&(r.blockHash=i.blockHash),void 0!==i.gasUsed&&(r.gasUsed=i.gasUsed),void 0!==o.slippageToleranceFactor&&(r.slippageTolerance=o.slippageToleranceFactor),r}const _i="4.0.0";class Ri{constructor(t){this.wallet=t.wallet;let n=null,o="STAGE";t.env?(o=t.env,n=xi(t.env)):t.baseUrl?.includes("prod")?(o="PROD",n=xi("PROD")):(o="STAGE",n=xi("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,...t},this.logger=new _({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===t.slippageToleranceFactor?Ri.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(t.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===t.maxAcceptableReverseBondingCurveFeeSlippageFactor?Ri.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(t.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=t.calculateAmountMode||Ri.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=t.pricingConcurrency||5,this.auth=new O({wallet:t.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new M(this.auth,this.config),this.galaChainHttp=new M(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new M(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new M(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new M(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=e.create({baseURL:this.config.galaChainBaseUrl,timeout:this.config.timeout||3e4,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.cache=new pi(t.debug||!1),this.launchpadService=new go(this.http),this.tokenResolverService=new ni(this.launchpadService.poolService),this.launchpadAPI=new Ci(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new _o(this.galaChainHttp,t.wallet,this.tokenResolverService,t.debug||!1,this.galaChainPublicAxios),this.dexService=new Ro(this.dexBackendHttp,this.cache,this.galaChainService,t.debug||!1),this.bundleService=new Zo(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,t.wallet,t.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new ti({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new ai(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new wi(this.galaChainHttp,this.config.galaChainBaseUrl,t.debug||!1,t.dexQuoteNetworkTimeout||3e4),this.gswapService=new hi({privateKey:t.wallet?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,galaChainBaseUrl:this.config.galaChainBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new mi(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,t.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw ie("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw ie('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new n(e),o={...this.config,wallet:t};return new Ri(o)}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,environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode}}getVersion(){return _i}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw ie("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:i}=e;if(t&&!n){const e={tokenName:t};return o&&(e.currentSupply=o),i&&(e.calculateAmountMode=i),this.fetchLaunchpadTokenSpotPrice(e)}if(n&&!t)try{return await this.dexService.fetchTokenPrice({tokenId:n})}catch(e){const t=function(e){if(no(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 a={tokenName:t};return o&&(a.currentSupply=o),i&&(a.calculateAmountMode=i),this.fetchLaunchpadTokenSpotPrice(a)}catch(t){throw this.logger.error(`Launchpad fallback failed: ${to(t)}`),e}}throw e}if(!t&&!n)throw te("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 fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(!t)throw new Error(G(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 wn}),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 wn}),n=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Lo}),o=t(e.tokenId),{collection:i,category:a,type:r,additionalKey:s}=o;return this.galaChainService.fetchTokenBalance({owner:n,collection:i,category:a,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 te("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:i,calculateAmountMode:a,currentSupply:r}=e;let s=t;void 0===a&&void 0===r||(s={tokenName:t,...void 0!==a&&{calculateAmountMode:a},...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!==i&&(l.privateKey=i),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey: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 ae("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Oi(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 ae("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Oi(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=>{Ui(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 $i(`Invalid launch data received for transaction ${t}`);const i={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&&(i.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(i.preBuyQuantity=e.preBuyQuantity),i.vaultAddress&&this.tokenResolverService.set(e.tokenName,i.vaultAddress),i})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey: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 wn}),n=t(e)||this.getAddress();return this.launchpadService.fetchProfile(n)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return wn}),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 wn}),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 wn}),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 wn}),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 wn}),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 wn}),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 wn}),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 ie("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw ie("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw ie(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw ie(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw ie(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw ie(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw ie(`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: ${Ri.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Ri.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: ${Ri.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Ri.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 Bi(e,n.status,n.message);let o;try{o=t(n)}catch(t){if(t instanceof $i)throw t;throw new $i(`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 Bi||t instanceof $i)throw t;throw new $i(`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 da});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,i,a=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:o,feeTier:i,slippageTolerance:a})}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 i,a;"string"==typeof n?(i=n,a=o):"object"==typeof n?a=n:o&&(a=o);return await this.gswapService.getUserLiquidityPositions(e,t,i,a)}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 i=t?.minTVL,a=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),i){if((t.token0Tvl+t.token1Tvl)/2<i)return}if(a&&a.length>0){if(!(a.includes(t.token0)||a.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 i=t?.creatorAddress,a=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=>{a.has(t.tokenName)||((e=>{if(a.set(e,!0),a.size>1e3){const e=a.keys().next().value;void 0!==e&&a.delete(e)}})(t.tokenName),i&&t.creatorAddress!==i||e(t))})}catch(e){c++;const t=e instanceof Error?e.message:String(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(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 _({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:n}=require("./services/WebSocketService");n.cleanupAll(e),t.debug("Global cleanup completed")}}Ri.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Ri.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Ri.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=gi.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Ri.DEFAULT_CALCULATE_AMOUNT_MODE=Pi.LOCAL;class Mi{static generateWallet(){try{const e=n.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(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(t),i=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:i,mnemonic:"test test test test test test test test test test test junk",wallet:o}}throw e}}static fromPrivateKey(e){const t=new n(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 a=o.fromPhrase(e),r=i.fromMnemonic(a,`m/44'/60'/0'/0/${t}`),s=new n(r.privateKey),c=this.toGalaAddress(s.address);return{privateKey:s.privateKey,address:s.address,galaAddress:c,mnemonic:e,wallet:s}}catch(o){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const o=`test-mnemonic-index-${t}-${e}`,i="0x"+Buffer.from(o).toString("hex").padStart(64,"1").slice(0,64),a=new n(i),r=this.toGalaAddress(a.address);return{privateKey:a.privateKey,address:a.address,galaAddress:r,mnemonic:e,wallet:a}}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 qi(e){if(void 0===e)return Mi.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 Mi.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 Mi.fromMnemonic(t);throw new Error(`Unable to detect input format. Expected:\n- Private key: 64 hexadecimal characters (with or without 0x prefix)\n- Mnemonic: 12 or 24 space-separated words\nReceived: "${t.slice(0,50)}${t.length>50?"...":""}"`)}function Gi(e){e||(e={});const{wallet:t,env:o,config:i={},...a}=e,r={...a,...i},{wallet:s,env:c,config:l,...u}=r;let d;if(t)if("string"==typeof t){d=qi(t).wallet}else{if(!(t instanceof n))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");d=t}else{d=qi().wallet}const h={wallet:d,...o&&{env:o},debug:!1,timeout:3e4,...u};return new Ri(h)}function Ki(){const e=C.join(process.cwd(),"..","..",".env");D.existsSync(e)&&x.config({path:e});const t=C.join(process.cwd(),".env");D.existsSync(t)&&x.config({path:t})}function Vi(e,t){const n=process.env[e];if(!n){throw new Error(t?`${e} not set in root or local .env (${t})`:`${e} not set in root or local .env`)}return n}function ji(e,t){return process.env[e]??t}Mi.testCounter=0;class Wi{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||{}},i=new Ri(o),a={sdk:i,wallet:n,config:o};if(!1!==e.autoValidate){const e=await this.validateSetup(i,n);return{...a,validation:e}}return a}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 Ri(n),config:n}}static async validateSetup(e,t){const n=[],o=[],i={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(i.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);i.hasBalance=e>0,i.canTrade=e>=.1,i.canCreateTokens=e>=100,0===e?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&&i.connectionHealthy,sdk:e,wallet:t||Mi.generateWallet(),issues:n,warnings:o,capabilities:i}}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,i]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:i,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?Mi.fromPrivateKey(e):Mi.generateWallet()}return"generate"===e?Mi.generateWallet():Mi.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}}function Hi(e){return e.filter(e=>new u(e.liquidity).isGreaterThan(0))}function zi(e,t){const n=new u(t);return e.filter(e=>new u(e.liquidity).isGreaterThanOrEqualTo(n))}function Qi(e,t="desc"){return[...e].sort((e,n)=>{const o=new u(e.liquidity),i=new u(n.liquidity);return"desc"===t?i.minus(o).toNumber():o.minus(i).toNumber()})}function Xi(e,t,n){const o=t.toUpperCase(),i=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return t===o&&n===i||t===i&&n===o})}function Zi(e,t){const n=t.toUpperCase();return e.filter(e=>e.token0.toUpperCase()===n||e.token1.toUpperCase()===n)}function Yi(e,t){return e.filter(e=>e.feeTier===t)}function Ji(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t}function ea(e){const t=new Map;return e.forEach(e=>{t.has(e.feeTier)||t.set(e.feeTier,[]),t.get(e.feeTier).push(e)}),t}function ta(e,t,n,o){const i=t.toUpperCase(),a=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return(t===i&&n===a||t===a&&n===i)&&e.feeTier===o})}function na(e){const t=new Map;return e.forEach(e=>{const n=`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`;t.has(n)||t.set(n,[]),t.get(n).push(e)}),t}const oa={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"};class ia{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,new u(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])}}}ia.CACHE=new Map,ia.ZERO=new u(0),ia.ONE=new u(1),ia.FEE_PIPS=new u(1e6),ia.MIN_SQRT_RATIO=new u("4295128739"),ia.MAX_SQRT_RATIO=new u("1461446703485210103287273052203988822378723970342");const aa={maxIterations:100,enableBigNumberCache:!0,roundingMode:u.ROUND_DOWN,debugLogging:!1};class ra{static calculateSwapDelta(e,t,n={}){const o=Date.now(),i={...aa,...n};try{const n=this.initializeSwapState(e,t,i);i.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const a=this.computeSwapLoop(n,e,t,i);i.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:a.stepCount,ticksCrossed:a.ticksCrossed.length,priceHitLimit:a.priceHitLimit});const r=this.createUpdatedPool(e.pool,a.state,t,i),s=this.calculateFinalAmounts(n,a.state,t);let c;if(t.actualSqrtPrice){const e=new u(r.sqrtPrice),n=new u(t.actualSqrtPrice);c=e.minus(n).abs().div(n).times(100).toNumber()}const l=Date.now()-o;i.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:l,amount0:s.amount0.toString(),amount1:s.amount1.toString(),driftPercentage:c}),l>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:l,stepCount:a.stepCount,ticksCrossed:a.ticksCrossed.length}),a.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:a.stepCount}),a.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:a.stepCount,ticksCrossed:a.ticksCrossed.length});return{updatedPool:r,updatedTicks:a.updatedTicks,amount0:s.amount0,amount1:s.amount1,feeAmount0:s.feeAmount0,feeAmount1:s.feeAmount1,ticksCrossed:a.ticksCrossed,metadata:{calculationTimeMs:l,swapSteps:a.stepCount,priceHitLimit:a.priceHitLimit,...void 0!==c&&{driftPercentage:c}}}}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 i=n.enableBigNumberCache?ia.getCached.bind(ia):e=>new u(e),a="string"==typeof o.sqrtPrice?o.sqrtPrice:new u(o.sqrtPrice).toFixed(0),r="string"==typeof o.liquidity?o.liquidity:new u(o.liquidity).toFixed(0),s=i(a),c=i(r),l=o.tick??0,h=d(new u(a)),g=Math.abs(h-l);g>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:l,calculatedTick:h,drift:g,threshold:100});const p=i(t.amountSpecified);Ao(p,"amountSpecified","for swap operation");const m="string"==typeof o.feeGrowthGlobal1?o.feeGrowthGlobal1:new u(o.feeGrowthGlobal1).toFixed(0),f="string"==typeof o.feeGrowthGlobal0?o.feeGrowthGlobal0:new u(o.feeGrowthGlobal0).toFixed(0),y=t.zeroForOne?i(m):i(f);return{sqrtPrice:s,liquidity:c,tick:l,amountSpecifiedRemaining:p,amountCalculated:ia.ZERO,feeGrowthGlobalX:y,protocolFee:ia.ZERO}}static computeSwapLoop(e,t,n,o){const{pool:i,tickDataMap:a}=t,r=[],s={};let c=0;const l=n.zeroForOne?ia.MIN_SQRT_RATIO:ia.MAX_SQRT_RATIO,g=new u("0.000001");for(;e.amountSpecifiedRemaining.gt(g)&&!e.sqrtPrice.eq(l)&&c<o.maxIterations;){c++;const[t,g]=this.findNextInitializedTick(a,e.tick,i.tickSpacing,n.zeroForOne);let p;if(o.debugLogging&&this.logger.debug(`Swap step ${c}`,{currentTick:e.tick,tickNext:t,initialized:g,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),g&&t>=-887272&&t<=887272){const e=h(t);p=e instanceof u?e:new u(String(e))}else p=l;const m=n.zeroForOne?u.max(p,l):u.min(p,l),f=this.executeSwapStep(e.sqrtPrice,m,e.liquidity,e.amountSpecifiedRemaining,i.fee,n.exactInput);if(e.sqrtPrice=f.sqrtPriceNext,n.exactInput){const t=f.amountIn.plus(f.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=ia.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=ia.ZERO)),e.amountCalculated=e.amountCalculated.minus(f.amountOut)}else{f.amountOut.lte(0)?e.amountSpecifiedRemaining=ia.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(f.amountOut),e.amountCalculated=e.amountCalculated.plus(f.amountIn.plus(f.feeAmount))}if(e.liquidity.gt(0)){const t=f.feeAmount.div(e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(p)&&g){const i=a[t.toString()];if(!i)throw new Error(`Missing tick data for initialized tick ${t}`);const c=n.zeroForOne?new u(i.liquidityNet).negated():new u(i.liquidityNet);if(e.liquidity=e.liquidity.plus(c),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);r.push(t),s[t.toString()]=i,o.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:c.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(p))e.tick=n.zeroForOne?t-1:t;else{const t=d(new u(e.sqrtPrice.toString()));e.tick=t}}if(c>=o.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${o.maxIterations}). Possible infinite loop or very complex swap.`);const p=e.sqrtPrice.eq(l);return{state:e,ticksCrossed:r,priceHitLimit:p,stepCount:c,updatedTicks:s}}static createUpdatedPool(e,t,n,o){const i=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(i.sqrtPrice=t.sqrtPrice.toFixed(0),i.liquidity=t.liquidity.toFixed(0),i.tick=t.tick,n.zeroForOne?i.feeGrowthGlobal1=t.feeGrowthGlobalX.toFixed(0):i.feeGrowthGlobal0=t.feeGrowthGlobalX.toFixed(0),n.zeroForOne){const n=new u(e.protocolFeesToken0);i.protocolFeesToken0=n.plus(t.protocolFee).toFixed(0)}else{const n=new u(e.protocolFeesToken1);i.protocolFeesToken1=n.plus(t.protocolFee).toFixed(0)}return i}static calculateFinalAmounts(e,t,n){let o,i,a,r;if(n.exactInput){const e=new u(n.amountSpecified),s=t.amountCalculated.abs();n.zeroForOne?(o=e.negated(),i=s,a=ia.ZERO,r=ia.ZERO):(o=s,i=e.negated(),a=ia.ZERO,r=ia.ZERO)}else{const e=new u(n.amountSpecified),s=t.amountCalculated.abs();n.zeroForOne?(o=s.negated(),i=e,a=ia.ZERO,r=ia.ZERO):(o=e,i=s.negated(),a=ia.ZERO,r=ia.ZERO)}const s=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?r=s:a=s,{amount0:o,amount1:i,feeAmount0:a,feeAmount1:r}}static findNextInitializedTick(e,t,n,o){const i=Object.keys(e).map(e=>parseInt(e,10)).sort((e,t)=>e-t);if(0===i.length){return[o?-887272:887272,!1]}if(o){const e=i.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=i.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,o,i,a){bo(n),Ao(o,"amountRemaining","for swap step");const r=[500,3e3,1e4];if(!r.includes(i))throw new Error(`Invalid fee tier: ${i}. Must be one of: ${r.join(", ")}`);const s=E(e,t,n,o,i,t.lt(e)),c=s[0],l=s[1],h=s[2],g=s[3],p=u.isBigNumber(c)?c:new u(String(c)),m=u.isBigNumber(l)?l:new u(String(l)),f=u.isBigNumber(h)?h:new u(String(h)),y=u.isBigNumber(g)?g:new u(String(g));return{sqrtPriceStart:e,tickNext:d(p),sqrtPriceNext:p,initialised:!1,amountIn:m,amountOut:f,feeAmount:y}}}ra.logger=new _({debug:!1,context:"SwapDeltaCalculator"});class sa{static fastValidation(e,t,n,o=sa.DEFAULT_CONFIG){const i=Date.now();let a=!0;try{const r=new u(e.sqrtPrice),s=new u(t.sqrtPrice);n.zeroForOne?s.gte(r)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:r.toString(),updatedSqrtPrice:s.toString(),zeroForOne:n.zeroForOne}),a=!1):s.lte(r)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:r.toString(),updatedSqrtPrice:s.toString(),zeroForOne:n.zeroForOne}),a=!1);const c=new u(e.liquidity),l=new u(t.liquidity);if(!c.isZero()){const e=l.minus(c).abs().div(c);e.gt(o.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:c.toString(),updatedLiquidity:l.toString(),changePct:e.times(100).toFixed(2)})}const d=new u(e.feeGrowthGlobal0),h=new u(t.feeGrowthGlobal0),g=new u(e.feeGrowthGlobal1),p=new u(t.feeGrowthGlobal1);n.zeroForOne?p.lt(g)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:g.toString(),updatedFeeGrowth1:p.toString()}),a=!1):h.lt(d)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:d.toString(),updatedFeeGrowth0:h.toString()}),a=!1);const m=new u(e.protocolFeesToken0),f=new u(t.protocolFeesToken0),y=new u(e.protocolFeesToken1),w=new u(t.protocolFeesToken1);f.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:m.toString(),updatedProtocolFees0:f.toString()}),a=!1),w.lt(y)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:y.toString(),updatedProtocolFees1:w.toString()}),a=!1);const k=Date.now()-i;return this.logger.debug("Fast validation completed",{passed:a,elapsedMs:k}),a}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=sa.DEFAULT_CONFIG){const o=Date.now(),i=[];let a=0;try{if(t.actualSqrtPrice){const o=new u(e.sqrtPrice),r=new u(t.actualSqrtPrice),s=this.calculateDriftPercentage(o,r);a=s,s>100*n.maxDriftThreshold&&i.push(`Price drift detected: ${s.toFixed(4)}% (threshold: ${(100*n.maxDriftThreshold).toFixed(4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:o.toString(),actualSqrtPrice:r.toString(),driftPct:s.toFixed(4)})}const r=new u(e.sqrtPrice),s=new u(2).pow(96),c=r.dividedBy(s),l=d(c),h=e.tick??0,g=Math.abs(l-h);g>n.maxTickDrift&&i.push(`Tick/price mismatch: tick=${h}, calculated=${l}, drift=${g}`);const p=new u(e.feeGrowthGlobal0),m=new u(e.feeGrowthGlobal1),f=new u(e.liquidity);try{bo(p,m,f)}catch(e){i.push(e.message)}const y=0===i.length,w=!y||a>100*n.maxDriftThreshold,k=Date.now()-o;return this.logger.debug("Moderate validation completed",{isValid:y,shouldRefetch:w,driftPercentage:a,errorCount:i.length,elapsedMs:k}),this.buildValidationResult(y,a,w,i)}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(),i=[];let a=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const r=await n(),s=new u(t.pool.sqrtPrice),c=new u(r.pool.sqrtPrice),l=this.calculateDriftPercentage(s,c);a=Math.max(a,l),l>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&i.push(`Price drift: ${l.toFixed(4)}% (cached: ${s.toString()}, fresh: ${c.toString()})`);const d=new u(t.pool.liquidity),h=new u(r.pool.liquidity),g=this.calculateDriftPercentage(d,h);a=Math.max(a,g),g>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&i.push(`Liquidity drift: ${g.toFixed(4)}% (cached: ${d.toString()}, fresh: ${h.toString()})`);const p=Object.keys(t.tickDataMap).length,m=Object.keys(r.tickDataMap).length;if(m>0){const e=Math.abs(m-p)/m;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&i.push(`Tick data incomplete: cached has ${p} ticks, fresh has ${m} ticks (${(100*e).toFixed(2)}% difference)`)}const f=0===i.length,y=!f,w=Date.now()-o;return this.logger.debug("Full validation completed",{poolKey:e,isValid:f,shouldRefetch:y,maxDriftPercentage:a,priceDrift:l,liquidityDrift:g,cachedTickCount:p,freshTickCount:m,errorCount:i.length,elapsedMs:w}),this.buildValidationResult(f,a,y,i)}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 i;if(n&&o.length>0){const e=o.join(" ").toLowerCase();i=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const a={isValid:e,driftPercentage:t,shouldRefetch:n,validationErrors:o};return void 0!==i&&(a.refetchReason=i),a}}sa.logger=new _({debug:!1,context:"PoolStateValidator"}),sa.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class ca{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return $.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){this.logger=new _({debug:t?.debug??!1,context:"PoolStateManager"});const n={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??u.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=sa.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:ca.calculatePoolStateHash(this.pool)};if(!sa.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=ra.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(!sa.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 u(e.actualAmount0),n=new u(e.actualAmount1),i=o.amount0.minus(t).abs(),a=o.amount1.minus(n).abs(),r=t.isZero()?0:i.div(t.abs()).times(100).toNumber(),s=n.isZero()?0:a.div(n.abs()).times(100).toNumber(),c=Math.max(r,s);c>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:c.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=c)}if((this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift)&&(this.logger.info("Triggering full refetch due to drift accumulation",{swapsSinceRefetch:this.metadata.swapsSinceRefetch,cumulativeDrift:this.metadata.cumulativeDrift.toFixed(2)}),this.config.onRefetchNeeded)){const e=await this.config.onRefetchNeeded(this.pool,this.tickDataMap);this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.metadata.stateHash=ca.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=ca.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 u(0),amount1:new u(0),feeAmount0:new u(0),feeAmount1:new u(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:ca.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}function la(e,t){return new ca(e,t)}class ua extends Mn{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",i="Unit",a="none";if("string"==typeof e)if(e.includes("|")){const r=e.split("|");"Token"===r[0]&&r[2]?(o=r[0],i=r[1]||"Unit",t=r[2],a=r[3]||"none",n=t):(t=r[0],n=t,i=r[1]||"Unit",a=r[3]||"none")}else t=e,n=e;else t=e.type||"unknown",n=e.symbol||e.type||"unknown",o=e.collection||"Token",i=e.category||"Unit",a=e.additionalKey||"none";const r=this.getDecimalsForToken(n);return{symbol:n.toUpperCase(),decimals:r,collection:o,category:i,type:t.toUpperCase(),additionalKey:a,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`)}}var da=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}});export{Wi as AgentConfig,Pi as CALCULATION_MODES,yi as COMPOSITE_POOL_FETCH_CONCURRENCY,j as ConfigurationError,J as DexPoolNotFoundError,Y as DexQuoteError,co as FileValidationError,Mo as GALA_DECIMALS,Go as GALA_TOKEN_CLASS_KEY,X as GSwapAssetError,Q as GSwapPoolError,H as GSwapQuoteError,z as GSwapSwapError,Ye as IMAGE_EXTENSIONS,qo as LAUNCHPAD_TOKEN_DECIMALS,Ri as LaunchpadSDK,Un as MAX_CONCURRENT_POOL_FETCHES,V as NetworkError,On as PAGINATION_DEFAULTS,_n as POOL_FETCH_CONFIG,Ni as POOL_TYPES,ca as PoolStateManager,oa as QUERY_FIELD_NAMES,Jo as SDKTransactionStatus,_i as SDK_VERSION,Ii as TRADING_TYPES,ua as TokenMetadataService,W as TransactionError,Bi as TransactionFailedError,K as ValidationError,$i as WebSocketError,Li as WebSocketTimeoutError,ye as addressFormatSchema,Qe as amountMethodSchema,ze as amountTypeSchema,et as browserFileSchema,tt as bufferFileSchema,St as buyTokensDataSchema,Dt as calculatePreMintDataSchema,He as checkPoolOptionsSchema,Le as commentMessageSchema,ct as commentPaginationSchema,Gi as createLaunchpadSDK,Ne as createLimitSchema,gt as createPaginatedResultSchema,la as createPoolStateManager,At as createTradeDataSchema,qi as createWallet,we as ethereumAddressSchema,Ae as faucetAmountSchema,yt as fetchGalaBalanceOptionsSchema,xt as fetchPoolDetailsDataSchema,vt as fetchTokenBalanceOptionsSchema,De as fileSizeSchema,Je as fileUploadSchema,xe as filenameSchema,Yi as filterByFeeTier,Hi as filterByLiquidity,zi as filterByMinLiquidity,ta as filterByPoolKey,Zi as filterByToken,Xi as filterByTokenPair,ke as flexibleAddressSchema,nt as flexibleFileSchema,Vo as formatGalaForDTO,jo as formatLaunchpadTokenForDTO,fe as fullNameSchema,Ct as getAmountOptionsSchema,ji as getEnv,Vi as getEnvOrThrow,It as getTradeOptionsSchema,Ze as graduateTokenOptionsSchema,Xe as graphDataOptionsSchema,ea as groupByFeeTier,na as groupByPoolKey,Ji as groupByTokenPair,ot as imageExtensionSchema,it as imageFilenameSchema,$e as imageMimeTypeSchema,je as imageUploadOptionsSchema,Be as isoDateStringSchema,Ve as launchTokenDataSchema,Ki as loadEnvWithFallback,be as nonNegativeDecimalStringSchema,Ee as optionalUrlSchema,Ie as pageNumberSchema,ht as paginationResultMetaSchema,We as poolFetchTypeSchema,lt as poolPaginationSchema,Te as positiveDecimalStringSchema,Oe as privateKeySchema,bo as requireNonNegative,To as requirePositive,Ao as requirePositiveWithContext,Ke as reverseBondingCurveConfigSchema,$t as reverseBondingCurveConfigurationSchema,me as searchQuerySchema,Et as sellTokensDataSchema,Qi as sortByLiquidity,Pe as standardLimitSchema,at as standardPaginationSchema,Ue as timestampSchema,qe as tokenCategorySchema,Ge as tokenCollectionSchema,ge as tokenDescriptionSchema,mt as tokenListOptionsSchema,de as tokenNameSchema,he as tokenSymbolSchema,Me as tokenUrlsSchema,Ft as tradeCalculationMethodSchema,Pt as tradeCalculationTypeSchema,Ce as tradeLimitSchema,Nt as tradeListParamsSchema,st as tradePaginationSchema,dt as tradePaginationWithFiltersSchema,bt as tradeTypeBackendSchema,Tt as tradeTypeSchema,_e as transactionIdSchema,ft as transferFaucetsDataSchema,Re as uniqueKeySchema,wt as updateProfileDataSchema,kt as uploadProfileImageOptionsSchema,Se as urlSchema,Fe as userLimitSchema,rt as userPaginationSchema,pe as userTokenNameSchema,pt as userTokenTypeSchema,ut as userTokensPaginationSchema,_t as validateAddress,Mt as validateAmountString,nn as validateBuyTokensData,cn as validateCalculatePreMintData,zt as validateCheckPoolOptions,tn as validateCreateTradeData,qt as validateFaucetAmount,Zt as validateFetchGalaBalanceOptions,ln as validateFetchPoolDetailsData,en as validateFetchTokenBalanceOptions,Gt as validateFullName,sn as validateGetAmountOptions,an as validateGetTradeOptions,Ht as validateImageUploadOptions,jt as validateLaunchTokenData,Kt as validateSearchQuery,on as validateSellTokensData,Ot as validateTokenDescription,Qt as validateTokenListOptions,Bt as validateTokenName,Ut as validateTokenSymbol,Wt as validateTokenUrls,rn as validateTradeListParams,Xt as validateTransferFaucetsData,Yt as validateUpdateProfileData,Jt as validateUploadProfileImageOptions,Vt as validateUserTokenName,Rt as validateVaultAddress,ve as vaultAddressSchema};
|