@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.
Files changed (115) hide show
  1. package/API.md +524 -4
  2. package/CHANGELOG.md +92 -0
  3. package/EXAMPLES.md +845 -0
  4. package/README.md +421 -14
  5. package/dist/LaunchpadSDK.d.ts +435 -18
  6. package/dist/LaunchpadSDK.d.ts.map +1 -1
  7. package/dist/api/LaunchpadAPI.d.ts.map +1 -1
  8. package/dist/api/dto/TransferTokenDto.d.ts.map +1 -1
  9. package/dist/constants/version.generated.d.ts +1 -1
  10. package/dist/constants/version.generated.d.ts.map +1 -1
  11. package/dist/helpers/sdk.d.ts +1 -0
  12. package/dist/helpers/sdk.d.ts.map +1 -1
  13. package/dist/index.cjs.js +1 -1
  14. package/dist/index.d.ts +10 -3
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.esm.js +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/services/BaseService.d.ts +32 -3
  19. package/dist/services/BaseService.d.ts.map +1 -1
  20. package/dist/services/BundleService.d.ts.map +1 -1
  21. package/dist/services/CommentService.d.ts.map +1 -1
  22. package/dist/services/DexBackendClient.d.ts +46 -0
  23. package/dist/services/DexBackendClient.d.ts.map +1 -0
  24. package/dist/services/DexPoolService.d.ts +54 -12
  25. package/dist/services/DexPoolService.d.ts.map +1 -1
  26. package/dist/services/DexQuoteService.d.ts +288 -0
  27. package/dist/services/DexQuoteService.d.ts.map +1 -0
  28. package/dist/services/DexService.d.ts.map +1 -1
  29. package/dist/services/FaucetService.d.ts.map +1 -1
  30. package/dist/services/GSwapService.d.ts +519 -44
  31. package/dist/services/GSwapService.d.ts.map +1 -1
  32. package/dist/services/GalaChainGatewayClient.d.ts +89 -0
  33. package/dist/services/GalaChainGatewayClient.d.ts.map +1 -0
  34. package/dist/services/GalaChainService.d.ts +26 -0
  35. package/dist/services/GalaChainService.d.ts.map +1 -1
  36. package/dist/services/ImageService.d.ts.map +1 -1
  37. package/dist/services/PoolService.d.ts.map +1 -1
  38. package/dist/services/PoolStateManager.d.ts +176 -0
  39. package/dist/services/PoolStateManager.d.ts.map +1 -0
  40. package/dist/services/PriceHistoryService.d.ts +4 -5
  41. package/dist/services/PriceHistoryService.d.ts.map +1 -1
  42. package/dist/services/SignatureService.d.ts +15 -38
  43. package/dist/services/SignatureService.d.ts.map +1 -1
  44. package/dist/services/TokenClassKeyService.d.ts +3 -4
  45. package/dist/services/TokenClassKeyService.d.ts.map +1 -1
  46. package/dist/services/TokenMetadataCache.d.ts +2 -2
  47. package/dist/services/TokenMetadataCache.d.ts.map +1 -1
  48. package/dist/services/TokenMetadataService.d.ts +3 -3
  49. package/dist/services/TokenMetadataService.d.ts.map +1 -1
  50. package/dist/services/TokenResolverService.d.ts +2 -2
  51. package/dist/services/TokenResolverService.d.ts.map +1 -1
  52. package/dist/services/TradeService.d.ts.map +1 -1
  53. package/dist/services/UserService.d.ts.map +1 -1
  54. package/dist/services/WebSocketService.d.ts +100 -2
  55. package/dist/services/WebSocketService.d.ts.map +1 -1
  56. package/dist/services/__mocks__/logger.mock.d.ts +17 -0
  57. package/dist/services/__mocks__/logger.mock.d.ts.map +1 -0
  58. package/dist/types/common.d.ts +2 -0
  59. package/dist/types/common.d.ts.map +1 -1
  60. package/dist/types/composite-pool.dto.d.ts +103 -0
  61. package/dist/types/composite-pool.dto.d.ts.map +1 -0
  62. package/dist/types/dex-pool.dto.d.ts +56 -5
  63. package/dist/types/dex-pool.dto.d.ts.map +1 -1
  64. package/dist/types/dto.d.ts +6 -6
  65. package/dist/types/dto.d.ts.map +1 -1
  66. package/dist/types/eip712-types.d.ts +140 -0
  67. package/dist/types/eip712-types.d.ts.map +1 -0
  68. package/dist/types/galachain-api.types.d.ts +206 -0
  69. package/dist/types/galachain-api.types.d.ts.map +1 -0
  70. package/dist/types/gswap-responses.types.d.ts +366 -0
  71. package/dist/types/gswap-responses.types.d.ts.map +1 -0
  72. package/dist/types/gswap.dto.d.ts +58 -3
  73. package/dist/types/gswap.dto.d.ts.map +1 -1
  74. package/dist/types/launchpad.dto.d.ts +57 -0
  75. package/dist/types/launchpad.dto.d.ts.map +1 -1
  76. package/dist/types/pool-state-delta.dto.d.ts +246 -0
  77. package/dist/types/pool-state-delta.dto.d.ts.map +1 -0
  78. package/dist/types/pool-state-manager-config.dto.d.ts +103 -0
  79. package/dist/types/pool-state-manager-config.dto.d.ts.map +1 -0
  80. package/dist/utils/SignatureHelper.d.ts.map +1 -1
  81. package/dist/utils/auto-pagination.d.ts +206 -0
  82. package/dist/utils/auto-pagination.d.ts.map +1 -0
  83. package/dist/utils/bignumber-helpers.d.ts +336 -0
  84. package/dist/utils/bignumber-helpers.d.ts.map +1 -0
  85. package/dist/utils/bignumber-pool-cache.d.ts +169 -0
  86. package/dist/utils/bignumber-pool-cache.d.ts.map +1 -0
  87. package/dist/utils/composite-pool-converter.d.ts +121 -0
  88. package/dist/utils/composite-pool-converter.d.ts.map +1 -0
  89. package/dist/utils/errors.d.ts +86 -0
  90. package/dist/utils/errors.d.ts.map +1 -1
  91. package/dist/utils/http.d.ts.map +1 -1
  92. package/dist/utils/load-env.d.ts +31 -0
  93. package/dist/utils/load-env.d.ts.map +1 -0
  94. package/dist/utils/pool-pair-parser.d.ts +55 -0
  95. package/dist/utils/pool-pair-parser.d.ts.map +1 -0
  96. package/dist/utils/pool-state-validator.d.ts +207 -0
  97. package/dist/utils/pool-state-validator.d.ts.map +1 -0
  98. package/dist/utils/position-filters.d.ts +253 -0
  99. package/dist/utils/position-filters.d.ts.map +1 -0
  100. package/dist/utils/swap-delta-calculator.d.ts +231 -0
  101. package/dist/utils/swap-delta-calculator.d.ts.map +1 -0
  102. package/dist/utils/tick-crossing-handler.d.ts +250 -0
  103. package/dist/utils/tick-crossing-handler.d.ts.map +1 -0
  104. package/dist/utils/token-format-converter.d.ts +85 -6
  105. package/dist/utils/token-format-converter.d.ts.map +1 -1
  106. package/dist/utils/token-parser.d.ts +235 -0
  107. package/dist/utils/token-parser.d.ts.map +1 -0
  108. package/dist/utils/tokenNormalizer.d.ts +66 -0
  109. package/dist/utils/tokenNormalizer.d.ts.map +1 -1
  110. package/dist/utils/transfer-validation.d.ts.map +1 -1
  111. package/dist/utils/validation-helpers.d.ts +75 -0
  112. package/dist/utils/validation-helpers.d.ts.map +1 -1
  113. package/package.json +36 -15
  114. package/dist/utils/tokenFormatConverter.d.ts +0 -53
  115. package/dist/utils/tokenFormatConverter.d.ts.map +0 -1
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t,a=require("axios"),n=require("ethers"),o=require("@gala-chain/connect"),r=require("zod"),i=require("bignumber.js"),s=require("@gala-chain/api"),c=require("uuid"),l=require("socket.io-client"),u=require("@gala-chain/gswap-sdk");if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(e||(e={}));class d extends Error{constructor(e,t,a){super(t),this.type=e,this.originalError=a,this.name="AuthError"}}class h{constructor(t){if(this.wallet=t.wallet,this.messagePrefix=t.messagePrefix||"Create a GalaChain Wallet",""===t.messagePrefix)throw new d(e.SIGNATURE_FAILED,"Message prefix cannot be empty")}hasWallet(){return void 0!==this.wallet}setWallet(t){if(void 0!==t){if("object"!=typeof t||!("address"in t))throw new d(e.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!t.address||"string"!=typeof t.address)throw new d(e.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=t}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(t){if(t instanceof d)throw t;throw new d(e.SIGNATURE_FAILED,"Failed to generate signature for authentication",t instanceof Error?t:new Error(String(t)))}}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 d(e.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(t){const a=t.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(a))throw new d(e.INVALID_ADDRESS,`Invalid Ethereum address format: ${t}`);return`eth|${a}`}async signMessage(t){this.validateWallet();try{return{message:t,signature:await this.wallet.signMessage(t),address:this.wallet.address,timestamp:Date.now()}}catch(t){if(t instanceof d)throw t;const a=t instanceof Error?t.message:String(t);throw new d(e.SIGNATURE_FAILED,a,t instanceof Error?t:new Error(String(t)))}}async generateAuthHeaders(t,a){this.validateWallet();try{const e=Date.now(),n=`${this.messagePrefix} ${a.toUpperCase()} ${t} ${e}`,o=await this.wallet.signMessage(n);return{"x-signature":o,"x-address":this.formatAddress(this.wallet.address),"x-message":n,"x-timestamp":e.toString()}}catch(t){if(t instanceof d)throw t;throw new d(e.SIGNATURE_FAILED,"Failed to generate authentication headers",t instanceof Error?t:new Error(String(t)))}}async signTypedData(t,a,n){this.validateWallet();try{return await this.wallet.signTypedData(t,a,n)}catch(t){if(t instanceof d)throw t;throw new d(e.SIGNATURE_FAILED,"Failed to sign typed data",t instanceof Error?t:new Error(String(t)))}}async generateCustomSignature(t){if(!t||"string"!=typeof t||0===t.trim().length)throw new d(e.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const e=await this.wallet.signMessage(t);return{message:t,signature:e,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(t){if(t instanceof d)throw t;throw new d(e.SIGNATURE_FAILED,"Failed to generate custom message signature",t instanceof Error?t:new Error(String(t)))}}validateWallet(){if(!this.wallet)throw new d(e.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new d(e.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new d(e.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(t||(t={}));class g{constructor(e){this.levelPriority={[t.DEBUG]:0,[t.INFO]:1,[t.WARN]:2,[t.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?t.DEBUG:t.INFO)}debug(e,a){this.log(t.DEBUG,e,a)}info(e,a){this.log(t.INFO,e,a)}warn(e,a){this.log(t.WARN,e,a)}error(e,a){this.log(t.ERROR,e,a)}log(e,a,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===t.DEBUG&&!this.debugEnabled)return;const o=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,r=this.getConsoleMethod(e);void 0!==n?n instanceof Error?r(`${o} ${a}`,n.message,n.stack):r(`${o} ${a}`,n):r(`${o} ${a}`)}getConsoleMethod(e){switch(e){case t.DEBUG:return console.debug;case t.INFO:return console.info;case t.WARN:return console.warn;case t.ERROR:return console.error;default:return console.log}}child(e){return new g({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[t.DEBUG]>=this.levelPriority[this.minLevel]}}function p(e){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 m{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new g({debug:this.debug,context:"HttpClient"}),this.axios=a.create({baseURL:t.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:t.timeout||3e4,headers:{Accept:"application/json",...t.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:p(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};e.data instanceof FormData&&(t.headers&&t.headers["Content-Type"]&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload"));const a=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:a,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const n=await this.axios.request(t);return this.logger.debug("Response:",{status:n.status,data:n.data}),n.data}catch(e){throw this.logger.error("Error:",e),e}}async get(e,t,a){return this.request({method:"GET",url:e,...t&&{params:t},...a&&{headers:a}})}async post(e,t,a){return this.request({method:"POST",url:e,data:t,...a&&{headers:a}})}async put(e,t,a){return this.request({method:"PUT",url:e,data:t,...a&&{headers:a}})}async delete(e,t,a){return this.request({method:"DELETE",url:e,...t&&{params:t},...a&&{headers:a}})}async patch(e,t,a){return this.request({method:"PATCH",url:e,data:t,...a&&{headers:a}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,a){return await this.auth.signTypedData(e,t,a)}async signCustomMessage(e){try{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}}catch(e){throw this.logger.error("Custom signature generation failed:",e),new Error(`Failed to generate custom signature for message: ${e instanceof Error?e.message:"Unknown error"}`)}}async signWithGalaChain(e,t,a=o.SigningType.SIGN_TYPED_DATA){const n=this.auth.getPrivateKey(),r=new o.SigningClient(n);return await r.sign(e,t,a)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{try{if(e.headers||(e.headers={}),this.auth.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),e}catch(e){throw this.logger.error("Failed to add signature:",e),e}},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{if(e.response){const t={message:e.response.data?.message||e.message,error:e.response.data?.error,statusCode:e.response.status,details:e.response.data?.details,timestamp:e.response.data?.timestamp,path:e.response.data?.path};e.launchpadError=t,this.logger.error("Backend error:",t)}else e.request?this.logger.error("Network error:",e.message):this.logger.error("Request setup error:",e.message);return Promise.reject(e)})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}const f="Token name is required and must be a string",y=e=>`Could not find vault address for token: ${e}`;class w extends Error{constructor(e,t,a){super(e),this.field=t,this.code=a,this.name="ValidationError"}}class k extends Error{constructor(e,t,a){super(e),this.statusCode=t,this.originalError=a,this.name="NetworkError"}}class v extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class A extends Error{constructor(e,t,a){super(e),this.transactionId=t,this.code=a,this.name="TransactionError"}}class T extends Error{constructor(e,t,a){super(e),this.originalError=t,this.code=a,this.name="GSwapQuoteError"}}class S extends Error{constructor(e,t,a,n){super(e),this.originalError=t,this.transactionHash=a,this.code=n,this.name="GSwapSwapError"}}class E 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 b extends Error{constructor(e,t,a,n){super(e),this.originalError=t,this.walletAddress=a,this.code=n,this.name="GSwapAssetError"}}class N extends Error{constructor(e,t,a){super(e),this.originalError=t,this.code=a,this.name="GSwapPositionError"}}function I(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 w(`Page must be a number between ${n} and ${o}`,"page","INVALID_PAGE");if("number"!=typeof t||t<r||t>i)throw new w(`Limit must be a number between ${r} and ${i}`,"limit","INVALID_LIMIT")}const F={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function x(e){return"string"==typeof e&&e.trim().length>0}function C(e){return!(!e||"string"!=typeof e)&&(F.ETH_ADDRESS.test(e)||F.BACKEND_ADDRESS.test(e))}function D(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const P=r.z.string().min(3,"Token name must be at least 3 characters").max(20,"Token name must be at most 20 characters").regex(/^[a-zA-Z0-9]{3,20}$/,"Token name can only contain letters and numbers"),$=r.z.string().min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),L=r.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),_=r.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),U=r.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),B=r.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),M=r.z.string().regex(F.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),O=r.z.string().regex(F.ETH_ADDRESS,"Invalid Ethereum address format"),R=r.z.string().refine(e=>F.BACKEND_ADDRESS.test(e)||F.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),G=r.z.string().refine(e=>F.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),K=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),q=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),z=r.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),V=r.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),W=r.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),j=r.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function H(e=100){return r.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const X=H(100),Q=H(20),Y=H(20),Z=r.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),J=r.z.string().max(255,"Filename must be at most 255 characters"),ee=r.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),te=r.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),ae=r.z.string().datetime("Must be a valid ISO 8601 date string"),ne=r.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),oe=r.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),re=r.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),ie=r.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),se=r.z.object({websiteUrl:W,telegramUrl:W,twitterUrl:W}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),ce=r.z.string().min(1,"Token category must not be empty").default("Unit"),le=r.z.string().min(1,"Token collection must not be empty").default("Token"),ue=r.z.object({minFeePortion:K,maxFeePortion:K}),de=r.z.object({tokenName:P,tokenSymbol:$,tokenDescription:L,tokenImage:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer),r.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:q.default("0"),websiteUrl:W,telegramUrl:W,twitterUrl:W,tokenCategory:ce,tokenCollection:le,reverseBondingCurveConfiguration:ue.optional(),privateKey:oe.optional()}),he=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),tokenName:P}),ge=r.z.enum(["recent","popular"]),pe=r.z.object({tokenName:P.optional(),symbol:$.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),me=r.z.enum(["NATIVE","MEME"]),fe=r.z.enum(["IN","OUT"]),ye=r.z.object({from:r.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:r.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:r.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:P}),we=r.z.object({tokenName:P,slippageToleranceFactor:r.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:r.z.number().min(0).max(1).optional(),privateKey:oe.optional()}),ke=[".png",".jpg",".jpeg",".gif",".webp",".svg"],ve=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),name:J,size:Z,type:ee}),Ae=r.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),Te=r.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Se=r.z.union([Ae,Te]),Ee=r.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),be=J.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return ke.includes(t)},`Filename must end with one of: ${ke.join(", ")}`),Ne=r.z.object({page:j,limit:X}),Ie=r.z.object({page:j,limit:Q}),Fe=r.z.object({page:j,limit:Y}),xe=r.z.object({page:j,limit:H(50)}),Ce=Ne.extend({type:r.z.enum(["recent","popular"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),De=Ie.extend({tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),Pe=Fe.extend({tradeType:r.z.enum(["BUY","SELL"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),userAddress:r.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:r.z.string().datetime().optional(),endDate:r.z.string().datetime().optional(),sortOrder:r.z.enum(["ASC","DESC"]).default("DESC")}),$e=r.z.object({page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()});const Le=r.z.enum(["all","DEFI","ASSET"]),_e=Ie.extend({type:Le.optional(),address:R.optional(),search:U.optional(),tokenName:_.optional()}),Ue=r.z.object({walletAddress:R,amount:z}),Be=r.z.object({address:R.optional(),refresh:r.z.boolean().optional()}),Me=r.z.object({profileImage:r.z.string(),fullName:B,address:R,privateKey:oe.optional()}),Oe=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),address:R.optional(),privateKey:oe.optional()}),Re=r.z.object({address:R,tokenId:r.z.union([r.z.string(),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string()}),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string(),instance:r.z.string()})]).optional(),tokenName:_.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),Ge=r.z.enum(["buy","sell"]),Ke=r.z.enum(["BUY","SELL"]),qe=r.z.object({tradeType:Ge,tokenAmount:K,vaultAddress:G,userAddress:R,slippageTolerance:K.optional(),deadline:r.z.number().int().positive().optional()}),ze=r.z.object({tokenSymbol:$,nativeTokenQuantity:K,expectedToken:K,maxAcceptableReverseBondingCurveFee:q.default("0").optional()}),Ve=r.z.object({tokenSymbol:$,tokenQuantity:K,expectedNativeToken:K,maxAcceptableReverseBondingCurveFee:q.default("0").optional()}),We=Fe.extend({tokenName:_.optional()}),je=r.z.object({page:r.z.number().int().min(1).max(1e3).default(1).optional(),limit:r.z.number().int().min(1).max(20).default(10).optional()}),He=r.z.enum(["NATIVE","MEME"]),Xe=r.z.enum(["IN","OUT"]),Qe=r.z.object({type:He,method:Xe,vaultAddress:G,amount:K}),Ye=r.z.object({nativeTokenQuantity:K}),Ze=r.z.object({vaultAddress:G}),Je=r.z.object({minFeePortion:K,maxFeePortion:K});function et(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 tt=et(P),at=et($),nt=et(L),ot=et(R),rt=et(G),it=et(K),st=et(z),ct=et(B),lt=et(U),ut=et(_),dt=et(de),ht=et(se),gt=et(he),pt=et(pe),mt=et(_e),ft=et(Ue),yt=et(Be),wt=et(Me),kt=et(Oe),vt=et(Re),At=et(qe),Tt=et(ze),St=et(Ve),Et=et(We),bt=et(je),Nt=et(Qe),It=et(Ye),Ft=et(Ze);function xt(e,t){throw new w(e.join("; "),t,"VALIDATION_ERROR")}function Ct(e){const t=tt(e);!t.success&&t.errors&&xt(t.errors,"tokenName")}function Dt(e){const t=Ce.safeParse(e);t.success||xt(t.error.errors.map(e=>e.message),"pagination")}function Pt(e){const t=pt(e);!t.success&&t.errors&&xt(t.errors,"options")}function $t(e){const t=Nt(e);!t.success&&t.errors&&xt(t.errors,"options")}function Lt(e){const t=ye.safeParse(e);t.success||xt(t.error.errors.map(e=>e.message),"options")}function _t(e){const t=R.safeParse(e);if(!t.success)throw new w("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Ut(e,t,a=!0){if(!e||""===e.trim())throw new w(`${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 w(`${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 w(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(n))throw new w(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(n<0)throw new w(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!a&&0===n)throw new w(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var Bt=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=R.safeParse(e);if(!t.success)throw new w(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:_t,validateCheckPoolOptions:Pt,validateGetAmountOptions:$t,validateGetGraphOptions:Lt,validateNumericString:Ut,validatePagination:Dt,validateTokenName:Ct});function Mt(e,t){return new w(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Ot(e,t){const a=t||e.charAt(0).toUpperCase()+e.slice(1);return new w(`${a} is required`,e,"REQUIRED_FIELD")}function Rt(e,t,a){const n=a||e.charAt(0).toUpperCase()+e.slice(1);return new w(`${n} must be ${t}`,e,"INVALID_FORMAT")}function Gt(e,t,a){return new k(e,t,a)}function Kt(e,t){return new v(e,t)}function qt(e,t,a){return new A(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 Vt(e,t){return{hasNext:e<t,hasPrevious:e>1}}function Wt(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 jt="/launchpad/upload-image",Ht="/launchpad/fetch-pool",Xt="/launchpad/check-pool",Qt="/launchpad/get-graph-data",Yt="/holders",Zt="/launchpad/get-badge/",Jt="/trade/",ea="/token/commment",ta="/token/commment",aa="/user/profile",na="/user/profile",oa="/user/token-list",ra="/user/token-hold",ia="/user/transfer-faucets",sa={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};class ca{constructor(e,t=!1){this.http=e,this.logger=new g({debug:t,context:this.constructor.name})}}function la(e,t){return"string"==typeof e[t]}function ua(e,t){return void 0===e[t]||"string"==typeof e[t]}function da(e,t){return void 0===e[t]||"number"==typeof e[t]}function ha(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function ga(e){if(!e||"object"!=typeof e)return!1;const t=e;return la(t,"tokenName")&&da(t,"from")&&da(t,"to")&&da(t,"resolution")}class pa extends ca{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=p(t),n=await this.http.get(Ht,a);Wt(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>sa.SAFETY_MAX_PAGES&&(s=!1)}return r}async fetchPools(e={}){const t=e.page||sa.DEFAULT_PAGE,a=e.limit??sa.DEFAULT_LIMIT;let n;if(0!==a&&Dt({page:t,limit:a}),e.tokenName&&Ct(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=sa.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=sa.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){Pt(e),e.tokenName&&Ct(e.tokenName);const t=p(e),a=await this.http.get(Xt,t);Wt(a,"Failed to check pool");const n=a.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.exists??!1}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!ga(e))throw new w("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(Ct(t),!a||!n||!o)throw new w("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:a,to:n,resolution:o};Lt(r);const i=p(r),s=await this.http.get(Qt,i);return Wt(s,"Failed to fetch graph data",!0),{dataPoints:s.data}}async fetchTokenDistribution(e){if(!e)throw Ot("tokenName","Token name");Ct(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw Mt(e);const a=encodeURIComponent(t),n=await this.http.get(`${Yt}/${a}`);Wt(n,"Failed to fetch token distribution",!0);const o=n.data;if(!Array.isArray(o))throw Gt("Invalid API response: expected array of holders",n.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw Gt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw Gt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw Gt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const r=o.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:o.map(e=>{const t=new i(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 Ot("tokenName","Token name");Ct(e);const t=await this.http.get(Zt,{tokenName:e});return Wt(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 ma(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 p(r)}const fa={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class ya extends ca{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return la(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&ua(t,"userAddress")&&da(t,"page")&&da(t,"limit")}(e))throw new w("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=sa.DEFAULT_PAGE,limit:r=sa.DEFAULT_LIMIT,startDate:i,endDate:s,sortOrder:c}=e;if(!x(t))throw new w("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");I(o,r,fa);const l=function(e,t,a){return ma({tokenName:e,page:t,limit:a},{stringifyFields:["page","limit"]})}(t,o,r),u=await this.http.get(Jt,l),d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const g=zt(u,{page:o,limit:r}),p=Vt(g.page,g.totalPages);return{trades:d,...g,...p}}}const wa=new g({debug:!1,context:"DateUtils"});function ka(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())?(wa.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):a}catch(a){return wa.warn(`Date parsing error for "${e}":`,a),t||new Date}}const va={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class Aa extends ca{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 la(t,"tokenName")&&da(t,"page")&&da(t,"limit")}(e))throw new w("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:a=sa.DEFAULT_PAGE,limit:n=sa.DEFAULT_LIMIT}=e;if(!x(t))throw new w("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");I(a,n,va);const o=await this.poolService.resolveTokenNameToVault(t);if(!o)throw Mt(t);const r=ma({vaultAddress:o,page:a,limit:n},{stringifyFields:["page","limit"]}),i=await this.http.get(ea,r);Wt(i,"Failed to fetch comments");return{comments:i.data.comments.map(e=>({...e,createdAt:ka(e.createdAt)})),total:i.data.count}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return la(t,"tokenName")&&la(t,"content")}(e))throw new w("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:a}=e;if(!x(t))throw new w("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>=va.CONTENT.MIN_LENGTH&&t.length<=va.CONTENT.MAX_LENGTH}(a))throw new w(`Comment content must be between ${va.CONTENT.MIN_LENGTH} and ${va.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const n=await this.poolService.resolveTokenNameToVault(t);if(!n)throw Mt(t);const o={userAddress:this.http.getAddress(),vaultAddress:n,content:a};Wt(await this.http.post(ta,o),"Failed to create comment")}}function Ta(e){return e instanceof Error}function Sa(e){return Ta(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 Ea(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function ba(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 Rt("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 Na={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20},USER_ADDRESS:{PATTERN:/^eth\|[0-9a-fA-F]{40}$/},TOKEN_NAME:{MIN_LENGTH:1,MAX_LENGTH:50},SEARCH:{MIN_LENGTH:1,MAX_LENGTH:100},FAUCET_AMOUNT:{POSITIVE_NON_ZERO_DECIMAL:/^(?!0+(\.0+)?$)\d+(\.\d+)?$/},PROFILE:{FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}}};function Ia(e){return!(!e||"string"!=typeof e)&&Na.USER_ADDRESS.PATTERN.test(e)}const Fa="Update profile";class xa extends ca{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!Ia(t))throw new w("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const a={userAddress:t};return await this.http.get(aa,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(Fa),o={address:n.address,message:Fa,publickey:n.ethereumAddress,sign:n.signature};Wt(await this.http.put(na,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=ba(e.file,"image",a),o=await this.http.request({method:"POST",url:`${jt}?tokenName=${encodeURIComponent(t)}`,data:n,headers:{}});return Wt(o,"Image upload failed"),"string"==typeof o.data?o.data:""}catch(e){if(e instanceof w)throw e;throw new w(`Profile image upload failed: ${Sa(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(oa,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(ra,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=sa.DEFAULT_PAGE,limit:a=sa.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=ma(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);Wt(r,a.errorMessage,!0);const i=(s=r.data)?Array.isArray(s)?s:s.token:[];var s;const c=zt(r,{page:t.page||sa.DEFAULT_PAGE,limit:t.limit||sa.DEFAULT_LIMIT}),l=Vt(c.page,c.totalPages);return{tokens:i,...c,...l}}validateGetTokenListOptions(e){if(I(e.page,e.limit,Na),void 0!==e.address&&!Ia(e.address))throw new w("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(void 0!==e.search&&e.search.trim().length>0&&!((t=e.search)&&"string"==typeof t&&t.length>=Na.SEARCH.MIN_LENGTH&&t.length<=Na.SEARCH.MAX_LENGTH))throw new w(`Search query must be between ${Na.SEARCH.MIN_LENGTH} and ${Na.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,a;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((a=e.tokenName)&&"string"==typeof a&&a.length>=Na.TOKEN_NAME.MIN_LENGTH&&a.length<=Na.TOKEN_NAME.MAX_LENGTH))throw new w(`Token name must be between ${Na.TOKEN_NAME.MIN_LENGTH} and ${Na.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!Ia(e.address))throw new w("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=Na.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=Na.PROFILE.FULL_NAME.MAX_LENGTH&&Na.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new w(`Full name must be between ${Na.PROFILE.FULL_NAME.MIN_LENGTH} and ${Na.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!Ia(e.address))throw new w("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Ca extends Error{constructor(e,t,a){super(e),this.filename=t,this.mimeType=a,this.name="FileValidationError"}}function Da(e,t,a){if(!e)throw new Ca("File is required",t,a);if("undefined"!=typeof File&&e instanceof File){const t=Ae.safeParse(e);if(!t.success){const a=t.error.errors.map(e=>e.message).join("; ");throw new Ca(a,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Ca("Filename is required when uploading Buffer objects",t,a);const n=Te.safeParse(e);if(!n.success){const e=n.error.errors.map(e=>e.message).join("; ");throw new Ca(e,t,a)}if(t.length>255)throw new Ca(`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 Ca(`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 Ca(`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 Ca(`File extension "${r}" does not match MIME type "${a}"`,t,a);return}throw new Ca("File must be a File object (browser) or Buffer (Node.js)",t,a)}class Pa extends ca{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Ct(t);const n=`${t}.png`;Da(a.file,n,"image/png");try{const e=`${a.tokenName??t}.png`,n=ba(a.file,"image",e),o=await this.http.request({method:"POST",url:`${jt}?tokenName=${encodeURIComponent(a.tokenName??t)}`,data:n,headers:{}});return Wt(o,"Image upload failed"),"string"==typeof o.data?o.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw Kt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class $a extends ca{constructor(e,t=!1){super(e,t)}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount};Wt(await this.http.post(ia,t),"Faucet transfer failed")}validateTransferFaucetsData(e){if(!Ia(e.walletAddress))throw new w("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!Na.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new w("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class La{constructor(e,t=!1){this.http=e,this.poolService=new pa(e,t),this.tradeService=new ya(e,t),this.commentService=new Aa(e,this.poolService,t),this.userService=new xa(e,t),this.imageService=new Pa(e,t),this.faucetService=new $a(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 Ct(e)}}const _a={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var Ua;!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"}(Ua||(Ua={}));class Ba extends Error{constructor(e,t,a){super(e),this.type=t,this.details=a,this.name="TransferError"}}class Ma{static validateAmount(e){if(parseFloat(e)<=0)throw new Ba("Transfer amount must be positive",Ua.INVALID_AMOUNT,{amount:e})}static validateUniqueKey(e){if(e){if(e.length>_a.MAX_UNIQUE_KEY_LENGTH)throw new w(`Unique key too long. Maximum length: ${_a.MAX_UNIQUE_KEY_LENGTH}`);if(!_a.UNIQUE_KEY_PATTERN.test(e))throw new Ba('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Ua.INVALID_AMOUNT,{uniqueKey:e})}}}class Oa extends o.ChainCallDTO{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,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 Oa({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 Oa({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 Ra{constructor(e){this.wallet=e}static generateUniqueKey(){return`${Date.now()}_${Math.random().toString(36).substring(2,8)}`}async signTransferToken(e){const t={name:"GalaChain",chainId:1},a={TransferToken:[{name:"from",type:"string"},{name:"to",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstance",type:"TokenInstance"},{name:"uniqueKey",type:"string"}],TokenInstance:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]};return{signature:await this.wallet.signTypedData(t,a,e),domain:t,types:a,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const t=e.replace("0x","");return`eth|${n.ethers.getAddress(`0x${t}`).replace("0x","")}`}static fromGalaChainAddress(e){return e.startsWith("eth|")?e.substring(4):e}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){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 Ga(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new w(`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 w(`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 w("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 w(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}var Ka=Object.freeze({__proto__:null,normalizeToTokenInstanceKey:Ga});const qa="gala-transfer-successful",za="token-transfer-successful",Va="transfer-successful-no-id";class Wa extends ca{constructor(e,t,a,n=!1,o){super(e,n),this.wallet=t,this.tokenResolver=a,this.publicAxios=o,this.signatureHelper=t?new Ra(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 Gt(`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 Gt(`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 w("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new w("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new w("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 Gt(`Failed to fetch token balance from GalaChain: ${Sa(e)}`,void 0,Ta(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Ga(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 Gt(`Failed to fetch token class from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw Gt(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return n.Data[0]}catch(e){if(Ea(e)&&404===e.response?.status)throw Gt("Token not found on GalaChain",404,Ta(e)?e:void 0);const t=Sa(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw Gt(`Failed to fetch token class from GalaChain: ${t}`,void 0,Ta(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new Ba("Wallet required for GALA transfer operations",Ua.WALLET_REQUIRED);try{const t=D(e.recipientAddress),a=D(this.wallet.address),n=Oa.forGALA(a,t,e.amount,e.uniqueKey),o=await this.signatureHelper.signTransferToken(n.toSigningPayload()),r=new Oa({...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 Ba("Wallet required for token transfer operations",Ua.WALLET_REQUIRED);try{const t=D(e.to),a=D(this.wallet.address);let n;if(e.tokenId)n=Ga(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 Ba("Must provide either tokenId or tokenName for token identification",Ua.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const o=new Oa({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 Oa({...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 Ba)throw t;throw new Ba(`Failed to resolve token class key for '${e}': ${Sa(t)}`,Ua.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 w("Invalid GALA transfer data: missing required fields");if(!C(e.recipientAddress))throw new Ba("Invalid recipient address format",Ua.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Ma.validateAmount(e.amount),Ma.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 w("Invalid token transfer data: missing required fields");if(!C(e.to))throw new Ba("Invalid recipient address format",Ua.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Ba("Must provide either tokenId or tokenName for token identification",Ua.TOKEN_NOT_FOUND);if(e.tokenName&&!_a.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Ba("Invalid token name format",Ua.TOKEN_NOT_FOUND,{tokenName:e.tokenName});Ma.validateAmount(e.amount),Ma.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Ba(`Token '${e}' not found or not available for transfer`,Ua.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 Ba)throw t;throw new Ba(`Failed to resolve token '${e}': ${Sa(t)}`,Ua.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){const[t,a]=e.split("|");if(!a)throw new Ba(`Invalid vault address format: missing token components. Address: ${e}`,Ua.TOKEN_NOT_FOUND);const n=a.split("$");if(n.length<4)throw new Ba(`Invalid vault address format: insufficient token components. Expected 4+, got ${n.length}. Address: ${e}`,Ua.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?qa:za:Va}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Ba("Transfer succeeded but transaction ID could not be extracted",Ua.NETWORK_ERROR)}handleTransferError(e,t,a){if(e instanceof Ba)return e;if(e instanceof w)return new Ba(e.message,Ua.INVALID_AMOUNT);if(Ea(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t)return new Ba(("string"==typeof n?.message?n.message:void 0)||"Invalid transfer request",Ua.INVALID_AMOUNT);if(403===t)return new Ba("Insufficient balance for transfer",Ua.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in a&&(e.tokenName=a.tokenName),new Ba("Token not found",Ua.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new Ba("Transfer request timed out",Ua.NETWORK_ERROR);const n=Sa(e);return new Ba(n||t,Ua.NETWORK_ERROR)}}function ja(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}class Ha{constructor(e,t,a,n=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=a,this.logger=new g({debug:n,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:a}=e;if(!t&&!a)throw Ot("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&a)throw new w("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 w("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw Ot("tokenId","Token ID");try{const t=Ga(e),a=ja(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${a}`),!this.dexBackendHttp)throw Gt("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 w("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 w(`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 w)throw e;throw Gt(`Failed to fetch DEX spot price: ${Sa(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,a){if(!e||"string"!=typeof e)throw new Error(f);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: ${Sa(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 Gt("GALA price not available");const r=Number(n.amount)/1e18;if(r<=0)throw new w(`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 Gt(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw Gt(`Failed to calculate launchpad token spot price for ${e}: ${Sa(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw Gt("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 w||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw Gt(`Failed to fetch token details from GalaChain for ${e}: ${Sa(t)}`,500)}}}function Xa(e,t=18){const a=parseFloat(e);if(0===a)return"0";return a.toFixed(t).replace(/\.?0+$/,"")}function Qa(e){return Xa(e,8)}function Ya(e){return Xa(e,18)}function Za(e){return{maxAcceptableReverseBondingCurveFee:Qa(e.maxAcceptableReverseBondingCurveFee)}}new g({debug:!1,context:"NumberUtils"});class Ja extends o.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Qa(t),this.expectedToken=Ya(a),this.extraFees=Za(n)}}class en extends o.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Ya(t),this.expectedNativeToken=Qa(a),this.extraFees=Za(n)}}class tn extends o.ChainCallDTO{constructor(e,t,a="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Ya(t),this.expectedNativeToken=Qa(a),this.extraFees=Za(n)}}class an extends o.ChainCallDTO{constructor(e,t,a,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Qa(t),this.expectedToken=Ya(a),this.extraFees=Za(n)}}const nn={BuyNativeDto:Ja,BuyExactDto:en,SellExactDto:tn,SellNativeDto:an};var on,rn,sn;!function(e){e[e.METAMASK=0]="METAMASK",e[e.TRUST_WALLET=1]="TRUST_WALLET",e[e.GALA_WALLET=2]="GALA_WALLET"}(on||(on={}));class cn{constructor(e,t=!1){this.walletProvider=e,this.debug=t,this.logger=new g({debug:t,context:"SignatureService"})}async signDTO(e,t,a,n=on.METAMASK){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,walletPreference:n,dtoKeys:Object.keys(e)});const r=this.generateEIP712Types(t,e),i=o.calculatePersonalSignPrefix(e),s={...e,prefix:i};let c,l,u;switch(n){case on.GALA_WALLET:({signature:c,domain:l}=await this.signWithGalaWallet(r,s,t,a));break;case on.TRUST_WALLET:c=await this.signWithTrustWallet(s),l={name:"ethereum",chainId:1};break;case on.METAMASK:default:({signature:c,domain:l}=await this.signWithMetaMask(r,s))}return u=n===on.TRUST_WALLET?{...s,signature:c}:{...e,signature:c,types:r,domain:l},this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(u),signatureLength:c.length}),u}catch(e){this.logger.error("❌ Signature generation failed:",e);throw qt(`Failed to sign DTO: ${Sa(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 Kt("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 qt(`MetaMask/ethers signing failed: ${Sa(e)}`)}}async signWithTrustWallet(e){try{const a=(t=e,JSON.stringify(t));let n;if(!this.walletProvider.signMessage)throw Kt("Wallet provider does not support signMessage","walletProvider");return n=await this.walletProvider.signMessage(a),n}catch(e){throw qt(`TrustWallet signing failed: ${Sa(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 Kt("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 qt(`GalaWallet signing failed: ${Sa(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 w(`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 w(`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 on.METAMASK;const e=window;return e.gala?on.GALA_WALLET:e.trustWallet?.isTrust?on.TRUST_WALLET:(e.ethereum,on.METAMASK)}}class ln{constructor(e=!1){this.debug=e,this.logger=new g({debug:e,context:"TokenClassKeyService"})}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),a=this.createTokenInstance(t),n=this.createGalaInstance(),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=Sa(e);throw new w(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new s.TokenClassKey;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new s.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!e||"string"!=typeof e)throw Ot("vaultAddress","Vault address");const t=e.split("$");if(t.length<3)throw Rt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");const a=t[2];if(!a||0===a.trim().length)throw new w(`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 Ot("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Rt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Rt("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw Rt("vaultAddress",'having at least 5 parts separated by "$"');const a=t[2];if(!a||!/^[A-Za-z]{1,10}$/.test(a))throw Rt("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 Rt("stringKey","format: collection$category$type$additionalKey (4 parts)");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3]}}}function un(e,t,a){if(t<0||t>1)throw new Error(`Invalid slippage tolerance factor: ${t}. Must be between 0 and 1 (e.g., 0.05 for 5%)`);const n=new i(e);if(n.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const 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 i(0)),r.toFixed()}class dn extends ca{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 cn(n,a),this.tokenKeyService=new ln(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 Ot("bundleData","Bundle data");if(!e.signedDto)throw Ot("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw Ot("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Rt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new w("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Rt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new w(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new w(`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(Ea(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 Sa(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw Ot("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 Ot("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 w("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=un(o,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:o,slippageFactor:r,adjustedMinTokens:e});const t=new nn.BuyNativeDto(s,a,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",s)}{if(!o)throw new w("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=un(o,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:o,slippageFactor:r,adjustedMaxGalaCost:e});const t=new nn.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 w("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=un(o,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:o,slippageFactor:r,adjustedMinGala:e});const t=new nn.SellExactDto(s,a,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellExactToken",s)}{if(!o)throw new w("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=un(o,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:o,slippageFactor:r,adjustedMaxTokensToSell:e});const t=new nn.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 Mt(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=un(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 Kt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw Ot("userAddress","User address")}async executeBundleTransaction(e,t,a){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${c.v4()}-${Date.now()}-${this.userAddress}`;const n=await this.signatureService.signDTO(e,t,this.userAddress),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"}(rn||(rn={})),exports.SDKTransactionStatus=void 0,(sn=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",sn.PROCESSING="processing",sn.COMPLETED="completed",sn.FAILED="failed",sn.TIMEOUT="timeout";const hn={[rn.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[rn.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[rn.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[rn.FAILED]:exports.SDKTransactionStatus.FAILED,[rn.ERROR]:exports.SDKTransactionStatus.FAILED,[rn.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[rn.PENDING]:exports.SDKTransactionStatus.PENDING};class gn{constructor(e,t=!1){this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.reconnectCount=0,this.hasOnAnyListener=!1,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.logger=new g({debug:t,context:"WebSocketService"}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof l.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{try{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');return this.logger.error("❌ Socket.IO connection failed:",e.message),void t(e)}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=l.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts||5,reconnectionDelay:this.config.reconnectDelay||2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectCount=0,e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.debug&&(this.socket.onAny((e,...t)=>{this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0)}catch(e){t(e)}})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const a=setTimeout(()=>{if(this.listeners.has(e)){const a={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:"Transaction monitoring timeout - no response after 60 seconds",timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e}`),t(a),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},6e4);if(this.timeouts.set(e,a),this.socket&&this.socket.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,a=>{this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(a,null,2));const n=a,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===rn.FAILED||r===rn.ERROR?"Transaction failed - check transaction details":r===rn.COMPLETED||r===rn.PROCESSED||r===rn.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===exports.SDKTransactionStatus.COMPLETED||l.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${l.status})`)}});else{const a={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(a),this.listeners.delete(e),this.timeouts.delete(e)}}async waitForTransaction(e){return new Promise((t,a)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||a(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return hn[t]||exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectCount<this.config.reconnectAttempts?(this.reconnectCount++,this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectCount}/${this.config.reconnectAttempts}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.config.reconnectDelay)):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected"))}isConnected(){return this.socket?.connected||!1}getSocket(){return this.socket}}class pn{constructor(e,t=!1){this.poolService=e,this.cache=new Map,this.logger=new g({debug:t,context:"TokenResolverService"})}async resolveTokenToVault(e){if(!x(e))throw new w("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 Mt(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 Rt("vaultAddress","format: service|Token$Unit$...$launchpad","Vault address");const a=t[1].split("$");if(a.length<4)throw Rt("vaultAddress","at least 4 parts after service|","Vault address");return{collection:a[0],category:a[1],type:a[2],additionalKey:a[3]}}}class mn{constructor(e,t=!1,a){this.httpClient=e,this.tokenResolverService=a,this.logger=new g({debug:t,context:"PriceHistoryService"})}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw Kt("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 Kt("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 Kt(`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 Kt(`Invalid vault address format: ${t}. Expected service|Token$Unit$...`,"vaultAddress");const n=a[1].split("$");if(n.length<4)throw Kt(`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 Gt(`Failed to resolve token name '${e}': ${Sa(t)}`,500)}}async fetchPriceHistory(e){if(this.logger.debug("Fetching price history from DEX Backend API with options:",e),!this.httpClient)throw Kt("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 Kt("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:a}=await Promise.resolve().then(function(){return Ka}),n=a(t),o=ja(`${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 Gt(`Failed to fetch price history: ${Sa(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw Gt("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw Gt("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 Kt("Either tokenName or tokenId must be provided","tokenId");if(n&&o)throw Kt("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 Kt("from must be a valid Date","from");if(i&&!(i instanceof Date)&&isNaN(new Date(i).getTime()))throw Kt("to must be a valid Date","to");if(s&&"ASC"!==s&&"DESC"!==s)throw Kt('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(c)||c<1)throw Kt("page must be a positive integer","page");if(!Number.isInteger(l)||l<1||l>50)throw Kt("limit must be between 1 and 50","limit")}}class fn{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 yn{constructor(e,t){if(this.tokenConverter=new fn,this.logger=new g({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 u.PrivateKeySigner(e.privateKey);this.gswap=new u.GSwap({signer:t,walletAddress:e.walletAddress,gatewayBaseUrl:e.gatewayBaseUrl,bundlerBaseUrl:e.bundlerBaseUrl,dexBackendBaseUrl:e.dexBackendBaseUrl}),this.logger.debug("GSwap initialized in full-access mode")}catch(e){throw this.logger.error("Failed to initialize GSwap with signer",e),new Error("Failed to initialize GSwap SDK with signer")}else this.gswap=new u.GSwap({gatewayBaseUrl:e.gatewayBaseUrl,bundlerBaseUrl:e.bundlerBaseUrl,dexBackendBaseUrl:e.dexBackendBaseUrl}),this.logger.debug("GSwap initialized in read-only mode")}async getSwapQuoteExactInput(e){try{this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),a=this.tokenConverter.toLaunchpadFormat(e.toToken),n=await this.gswap.quoting.quoteExactInput(t,a,e.amount);return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:n.outTokenAmount.toFixed(),feeTier:n.feeTier,priceImpact:n.priceImpact.toString(),executionPrice:this.calculateExecutionPrice(e.amount,n.outTokenAmount)}}catch(e){this.logger.error("Failed to get swap quote",e);const t=e;throw new T(`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 T(`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 i(e.estimatedOutput),o=new i(1).minus(e.slippageTolerance||.01),r=n.multipliedBy(o),s=(await this.gswap.swaps.swap(t,a,e.feeTier,{exactIn:e.inputAmount,amountOutMinimum:r.toFixed()})).transactionId;if(!s)throw new Error("Failed to get transaction ID from swap result");this.logger.debug("Swap submitted, monitoring transaction",{transactionId:s,fromToken:e.fromToken,toToken:e.toToken}),this.webSocketService.isConnected()||await this.webSocketService.connect();const c=await this.webSocketService.waitForTransaction(s);return{transactionId:c.transactionId,status:c.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(c.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(s)}}}catch(e){this.logger.error("Failed to execute swap",e);const t=e;throw new S(`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 b(`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 b(`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 i(t.balance||0).toFixed(),decimals:t.decimals||18}})}catch(t){this.logger.error("Failed to fetch user assets",t);const a=t;throw new b(`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 i(0),s=0;for(const c of o)try{const e=await this.gswap.pools.getPoolData(a,n,c);e&&(r=r.plus(new i(e.liquidity||0)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:c})}return{tokenA:e,tokenB:t,liquidity:r.toFixed(),feeTiers:o,swapCount:s}}catch(a){this.logger.warn("Failed to fetch pool info",a);const n=a;return this.logger.debug("Pool error details",{error:new E(`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 N(`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 N(`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 N(`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 N(`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 N(`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 N(`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 N(`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 N(`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),s=this.calculatePriceFromSqrtPriceX96(new i(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:s.toFixed()}}catch(e){throw this.logger.error("Failed to get pool data",e),new E(`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 i(n.currentPrice);return{tokenA:e,tokenB:t,feeTier:a,price:o.toFixed(),invertedPrice:new i(1).dividedBy(o).toFixed(),tick:n.tick,liquidity:n.liquidity}}catch(e){throw this.logger.error("Failed to calculate spot price",e),new E(`Failed to calculate spot price: ${e?.message||String(e)}`,e)}}async calculateOptimalPositionSize(e,t,a,n,o,r,s){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:n,desiredAmount1:o});const c=(await this.getPoolData(e,t,a)).tick,l=this.calculateLiquidityFromAmount0(new i(n),r,Math.min(s,c)),u=this.calculateLiquidityFromAmount1(new i(o),Math.max(r,c),s),d=i.min(l,u),h=this.calculateAmount0FromLiquidity(d,r,c),g=this.calculateAmount1FromLiquidity(d,c,s),p=new i(n),m=new i(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 N(`Failed to calculate optimal position: ${e?.message||String(e)}`,e)}}async validatePositionParameters(e,t,a,n,o,r,s){const c=[],l=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:n,tickUpper:o});const u=[500,3e3,1e4];u.includes(a)||c.push(`Invalid fee tier: ${a}. Must be one of: ${u.join(", ")}`);const d=this.getTickSpacing(a);let h;n%d!==0&&c.push(`tickLower must be multiple of ${d}`),o%d!==0&&c.push(`tickUpper must be multiple of ${d}`),n>=o&&c.push(`tickLower (${n}) must be less than tickUpper (${o})`);try{h=await this.getPoolData(e,t,a)}catch{return c.push(`Pool not found for ${e}/${t} at fee tier ${a}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}const g=new i(r),p=new i(s);(g.isNaN()||g.isNegative())&&c.push("amount0 must be a valid positive number"),(p.isNaN()||p.isNegative())&&c.push("amount1 must be a valid positive number");const m=h.tick;(m<n||m>o)&&l.push("Position is out of current price range - will not earn fees until price moves into range");new i(h.liquidity).lt("1000000")&&l.push("Low pool liquidity - consider higher slippage tolerance");const f=0===c.length?35e4:0;return{valid:0===c.length,errors:c,warnings:l,gasEstimate:f,tickSpacing:d,currentTick:m,poolLiquidity:h.liquidity}}catch(e){return c.includes(e.message)||c.push(`Validation failed: ${e?.message||String(e)}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}}async calculateTicksForPrice(e,t,a,n,o){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:a,maxPrice:n});const r=this.getTickSpacing(o),s=new i(a),c=new i(n);if(s.gte(c))throw new Error("minPrice must be less than maxPrice");const l=Math.floor(Math.log(s.toNumber())/Math.log(1.0001)),u=Math.ceil(Math.log(c.toNumber())/Math.log(1.0001)),d=Math.floor(l/r)*r,h=Math.ceil(u/r)*r,g=Math.pow(1.0001,d),p=Math.pow(1.0001,h),m=new i(g),f=new i(p);return{tokenA:e,tokenB:t,feeTier:o,tickLower:d,tickUpper:h,tickSpacing:r,requestedMinPrice:a,requestedMaxPrice:n,actualMinPrice:m.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:m.minus(s).dividedBy(s).multipliedBy(100).toFixed(4),maxPriceDeviation:f.minus(c).dividedBy(c).multipliedBy(100).toFixed(4)}}}catch(e){throw this.logger.error("Failed to calculate ticks for price",e),new N(`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 s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const c=new i(o),l=new i(r);return{tokenA:e,tokenB:t,tickLower:a,tickUpper:n,minPrice:c.toFixed(8),maxPrice:l.toFixed(8),currentPrice:s,priceRange:`${c.toFixed(4)} - ${l.toFixed(4)}`,tickSpread:n-a}}catch(e){throw this.logger.error("Failed to calculate price for ticks",e),new N(`Failed to calculate prices: ${e?.message||String(e)}`,e)}}calculateExecutionPrice(e,t){try{const a=new i(e),n=new i(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 i(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new i(0)}}calculateLiquidityFromAmount0(e,t,a){try{const n=new i(Math.pow(1.0001,t/2)),o=new i(Math.pow(1.0001,a/2));return e.multipliedBy(n).multipliedBy(o).dividedBy(o.minus(n))}catch{return new i(0)}}calculateLiquidityFromAmount1(e,t,a){try{const n=new i(Math.pow(1.0001,t/2)),o=new i(Math.pow(1.0001,a/2));return e.dividedBy(o.minus(n))}catch{return new i(0)}}calculateAmount0FromLiquidity(e,t,a){try{const n=new i(Math.pow(1.0001,t/2)),o=new i(Math.pow(1.0001,a/2));return e.multipliedBy(o.minus(n)).dividedBy(n.multipliedBy(o))}catch{return new i(0)}}calculateAmount1FromLiquidity(e,t,a){try{const n=new i(Math.pow(1.0001,t/2)),o=new i(Math.pow(1.0001,a/2));return e.multipliedBy(o.minus(n))}catch{return new i(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 wn{}wn.BASE_PRICE=1650667151e-14,wn.PRICE_SCALING_FACTOR=1166069e-12,wn.TRADING_FEE_FACTOR=.001,wn.GAS_FEE="1",wn.MIN_UNBONDING_FEE_FACTOR=0,wn.MAX_UNBONDING_FEE_FACTOR=.5,wn.NET_UNBONDING_FEE_FACTOR=.5,wn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class kn{constructor(e=!1){this.cache=new Map,this.logger=new g({debug:e,context:"TokenMetadataCache"})}getLRUKey(){const e=this.cache.keys().next().value;return void 0!==e?e:null}normalizeTokenName(e){return e.trim().toLowerCase().replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}updateCacheEntry(e,t){const a=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=kn.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||wn.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)}}kn.MAX_CACHE_SIZE=1e4;class vn extends ca{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=sa.DEFAULT_PAGE,limit:r=sa.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 An(e){const t=function(e){const t=dt(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 Tn="/api/asset/launchpad-contract/CallNativeTokenIn",Sn="/api/asset/launchpad-contract/CallNativeTokenOut",En="/api/asset/launchpad-contract/CallMemeTokenIn",bn="/api/asset/launchpad-contract/CallMemeTokenOut";class Nn extends o.ChainCallDTO{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,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 In(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 Fn={NATIVE:"native",EXACT:"exact"},xn={LOCAL:"local",EXTERNAL:"external"};class Cn{static calculateBuyWithExact(e,t){const a=parseFloat(e),n=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:s,GAS_FEE:c}=wn,l=this.roundUp(o*(Math.exp((n+a)*r)-Math.exp(n*r))/r,8),u=new i(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateBuyWithNative(e,t){const a=parseFloat(e),n=parseFloat(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:s,GAS_FEE:c}=wn,l=Math.log(a*r/o+Math.exp(n*r))/r-n,u=new i(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateSellWithExact(e,t,a,n,o){const r=parseFloat(e),s=parseFloat(t),c=parseFloat(a),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=wn,g=l*(Math.exp(s*u)-Math.exp((s-r)*u))/u,p=new i(g),m=n+s/c*(o-n),f=p.multipliedBy(m).toFixed(8,i.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,a,n,o){const r=parseFloat(e),s=parseFloat(t),c=parseFloat(a),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=wn,g=s-Math.log(Math.exp(s*u)-r*u/l)/u,p=new i(r),m=n+s/c*(o-n),f=p.multipliedBy(m).toFixed(8,i.ROUND_UP),y=p.multipliedBy(d).toFixed();return{amount:g.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static roundUp(e,t){const a=Math.pow(10,t);return Math.ceil(e*a)/a}}class Dn{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 kn}addIfDefined(e,t,a){return void 0!==a&&(e[t]=a),e}async uploadImageByTokenName(e){const{tokenName:t,options:a}=e;Ct(t);const n=`${t}.png`;Da(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 Rt("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 Gt(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 Kt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){Dt(e),e.tokenName&&Ct(e.tokenName);const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const a=p(t),n=await this.http.get("/launchpad/fetch-pool",a);if(!0===n.error||200!==n.status||!n.data)throw Gt(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 Kn});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($t(e),!this.galaChainHttp)throw Kt("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:Tn,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:Sn,body:{vaultAddress:a,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:En,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:bn,body:{vaultAddress:a,nativeTokenQuantity:n,IsPreMint:!1}};throw Rt("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(!In(e))throw Gt("Malformed response data from GalaChain gateway");if(1!==e.Status)throw Gt(`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){Pt(e),e.tokenName&&Ct(e.tokenName);const t=p(e),a=await this.http.get("/launchpad/check-pool",t);if(!0===a.error||200!==a.status)throw Gt(a.message||"Failed to check pool",a.status);const n=a.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.exists??!1}async fetchVolumeData(e){if(!ga(e))throw new w("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(Ct(t),!a||!n||!o)throw new w("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:a,to:n,resolution:o};Lt(r);const i=p(r),s=await this.http.get("/launchpad/get-graph-data",i);if(!0===s.error||200!==s.status||!s.data)throw Gt(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 w("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 w(`Invalid calculation mode "${r}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new w("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!a||"string"!=typeof a)throw new w("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Fn.NATIVE&&n!==Fn.EXACT)throw new w('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 w(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Fn.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 w(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new w("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!a||"string"!=typeof a)throw new w("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Fn.EXACT&&n!==Fn.NATIVE)throw new w('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 w(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===Fn.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 w("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Fn.NATIVE&&n!==Fn.EXACT)throw new w('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==o&&Ut(o,"currentSupply");const r=!o;if(r&&!t)throw new w("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&Ct(t);let i=o;if(r){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return n===Fn.EXACT?Cn.calculateBuyWithExact(a,i):Cn.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 w("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==Fn.EXACT&&n!==Fn.NATIVE)throw new w('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==o&&Ut(o,"currentSupply");const c=!o||!r||void 0===i||void 0===s;if(c&&!t)throw new w("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&Ct(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===Fn.EXACT?Cn.calculateSellWithExact(a,l,u,h,d):Cn.calculateSellWithNative(a,l,u,h,d)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return la(t,"tokenName")&&ha(t)&&ua(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:a,calculateAmountMode:n,currentSupply:o}=t;Ct(a);const r=await this.tokenResolver.resolveTokenToVault(a);if(!r)throw new w(y(a),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw Kt("GalaChain HTTP client not configured");const i=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:r});if(1!==i.Status)throw Gt(`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 w(`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 Kt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");An(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new w("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 w("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 Gt("Image upload failed: No URL returned");a=t}else"string"==typeof e.tokenImage&&(a=e.tokenImage);const n=`galaswap - operation - ${c.v4()}-${Date.now()}-${this.http.getAddress()}`,r={tokenName:e.tokenName.trim(),tokenSymbol:e.tokenSymbol.trim().toUpperCase(),tokenDescription:e.tokenDescription.trim(),tokenImage:a.trim(),preBuyQuantity:t.toString(),websiteUrl:e.websiteUrl||"",telegramUrl:e.telegramUrl||"",twitterUrl:e.twitterUrl||"",tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:n};e.reverseBondingCurveConfiguration&&(r.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const i=new Nn(r),s=await this.http.signWithGalaChain("CreateSale",i,o.SigningType.SIGN_TYPED_DATA),{signature:l,types:u,domain:d,prefix:h}=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:l,types:u,domain:d,...h&&{prefix:h},...i.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:i.reverseBondingCurveConfiguration}},p=`${e.tokenName.trim()}$Unit$none$none`,m="GALA$Unit$none$none";let f;if(parseFloat(t)>0){const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${p}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`]}else{const e=`$service$${p}$launchpad`;f=[e,`$token$${p}$${e}`,`$tokenBalance$${p}$${e}`]}const y={signedDto:g,stringsInstructions:f,method:"CreateSale"},k=await this.bundleHttp.post("/bundle",y);if(k.error||!k.data)throw Gt(k.message||"Token launch failed");return k.data}async fetchTokenDistribution(e){if(!e)throw Ot("tokenName","Token name");Ct(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new w(y(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const a=encodeURIComponent(t),n=await this.http.get(`/holders/${a}`);if(!0===n.error||200!==n.status||!n.data)throw Gt(n.message||"Failed to fetch token distribution",n.status);const o=n.data;if(!Array.isArray(o))throw Gt("Invalid API response: expected array of holders",n.status);for(const e of o){if(!e.owner||"string"!=typeof e.owner)throw Gt("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw Gt("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw Gt(`Invalid holder quantity: "${e.quantity}"`,n.status)}const r=o.reduce((e,t)=>e.plus(t.quantity),new i(0));return{holders:o.map(e=>{const t=new i(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 Ot("tokenName","Token name");Ct(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw Gt(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 w("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw Kt("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(!In(a))throw Gt("Malformed response data from GalaChain gateway");if(1!==a.Status)throw Gt(`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 w(y(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw Kt("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==a.Status)throw Gt(`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){Ct(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new w(y(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw Kt("GalaChain HTTP client not configured");const a=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==a.Status)throw Gt(`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 _t(e)}validateTokenName(e){return Ct(e)}validatePagination(e){return Dt(e)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw Kt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw Ot("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 Gt(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return la(t,"tokenName")&&ha(t)&&ua(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:a,calculateAmountMode:n,currentSupply:o}=t;if(!a||"string"!=typeof a)throw Ot("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 Gt("GALA price not available");const i=Number(t.amount);if(i<=0)throw new w(`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 Pn={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 $n(e){return Pn[e]}class Ln extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class _n 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 Un(e,t){if(!e)throw new Ln(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Ln(`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 Ln(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Bn(e,t,a,n){Un(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 Ln(`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 Mn="3.31.0";class On{constructor(e){this.wallet=e.wallet;let t=null;t=e.env?$n(e.env):e.baseUrl?.includes("prod")?$n("PROD"):$n("STAGE"),this.config={baseUrl:t.launchpadBaseUrl,galaChainBaseUrl:t.galaChainBaseUrl,bundleBaseUrl:t.bundleBaseUrl,webSocketUrl:t.webSocketUrl,dexApiBaseUrl:t.dexApiBaseUrl,dexBackendBaseUrl:t.dexBackendBaseUrl,launchpadFrontendUrl:t.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new g({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?On.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?On.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode||On.DEFAULT_CALCULATE_AMOUNT_MODE,this.auth=new h({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new 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=a.create({baseURL:this.config.galaChainBaseUrl,timeout:this.config.timeout||3e4,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.cache=new kn(e.debug||!1),this.launchpadService=new La(this.http),this.tokenResolverService=new pn(this.launchpadService.poolService),this.launchpadAPI=new Dn(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new Wa(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug||!1,this.galaChainPublicAxios),this.dexService=new Ha(this.dexBackendHttp,this.cache,this.galaChainService,e.debug||!1),this.bundleService=new dn(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,e.wallet,e.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new gn({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new mn(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.gswapService=new yn({privateKey:e.wallet?.privateKey,walletAddress:e.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl},this.websocketService),this.dexPoolService=new vn(this.dexBackendHttp,this.config.dexBackendBaseUrl,e.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw Kt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Kt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new n.Wallet(e),a={...this.config,wallet:t};return new On(a)}getAddress(){return this.validateWallet(),this.auth.getAddress()}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw new w("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 w("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 Mn}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw Kt("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(Ea(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: ${Sa(t)}`),e}}throw e}if(!t&&!a)throw Ot("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");throw new w("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(y(e));const a=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return a.currentSupply=n.currentSupply,a.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,a.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,a.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,a.tokenName=e,a}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bt}),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 Bt}),a=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Ka}),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 Ot("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 qt("No transaction ID returned from buy operation");return this.waitForConfirmation(a,t=>Bn(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 qt("No transaction ID returned from sell operation");return this.waitForConfirmation(a,t=>Bn(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=>{Un(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 Ln(`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 Bt}),a=t(e)||this.getAddress();return this.launchpadService.fetchProfile(a)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Bt}),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 Bt}),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 Bt}),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 Bt}),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 Bt}),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 Bt}),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 Bt}),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 Kt("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw Kt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Kt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Kt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw Kt(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Kt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Kt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=parseFloat(String(e));return isNaN(t)||t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${e}, using default: ${On.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),On.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=parseFloat(String(e));return isNaN(t)||t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${e}, using default: ${On.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),On.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const a=await this.websocketService.waitForTransaction(e);if("completed"!==a.status)throw new _n(e,a.status,a.message);let n;try{n=t(a)}catch(t){if(t instanceof Ln)throw t;throw new Ln(`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 _n||t instanceof Ln)throw t;throw new Ln(`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 Kn});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 g({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:a}=require("./services/WebSocketService");a.cleanupAll(e),t.debug("Global cleanup completed")}}On.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,On.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,On.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=wn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,On.DEFAULT_CALCULATE_AMOUNT_MODE=xn.LOCAL;class Rn{static generateWallet(){try{const e=n.Wallet.createRandom();if(!e.mnemonic?.phrase)throw new Error("Failed to generate wallet with mnemonic phrase");const t=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:t,mnemonic:e.mnemonic.phrase,wallet:new n.Wallet(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,t="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),a=new n.Wallet(t),o=this.toGalaAddress(a.address);return{privateKey:a.privateKey,address:a.address,galaAddress:o,mnemonic:"test test test test test test test test test test test junk",wallet:a}}throw e}}static fromPrivateKey(e){const t=new n.Wallet(e),a=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:a,mnemonic:"",wallet:t}}static fromMnemonic(e,t=0){try{const a=n.Mnemonic.fromPhrase(e),o=n.HDNodeWallet.fromMnemonic(a,`m/44'/60'/0'/0/${t}`),r=new n.Wallet(o.privateKey),i=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}catch(a){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const a=`test-mnemonic-index-${t}-${e}`,o="0x"+Buffer.from(a).toString("hex").padStart(64,"1").slice(0,64),r=new n.Wallet(o),i=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}throw a}}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 Gn(e){if(void 0===e)return Rn.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 Rn.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 Rn.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?"...":""}"`)}Rn.testCounter=0;var Kn=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}});exports.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),a=this.setupWallet(e.privateKey),n={wallet:a.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{}},o=new On(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 On(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||Rn.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?Rn.fromPrivateKey(e):Rn.generateWallet()}return"generate"===e?Rn.generateWallet():Rn.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}},exports.CALCULATION_MODES=xn,exports.ConfigurationError=v,exports.FileValidationError=Ca,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.GSwapAssetError=b,exports.GSwapPoolError=E,exports.GSwapQuoteError=T,exports.GSwapSwapError=S,exports.IMAGE_EXTENSIONS=ke,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LaunchpadSDK=On,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.NetworkError=k,exports.PAGINATION_DEFAULTS=sa,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},exports.SDK_VERSION=Mn,exports.TRADING_TYPES=Fn,exports.TokenMetadataService=class{constructor(){this.cache={},this.cacheExpiry=36e5,this.logger=new g({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`)}},exports.TransactionError=A,exports.TransactionFailedError=_n,exports.ValidationError=w,exports.WebSocketError=Ln,exports.WebSocketTimeoutError=class extends Ln{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.addressFormatSchema=M,exports.amountMethodSchema=fe,exports.amountTypeSchema=me,exports.browserFileSchema=Ae,exports.bufferFileSchema=Te,exports.buyTokensDataSchema=ze,exports.calculatePreMintDataSchema=Ye,exports.checkPoolOptionsSchema=pe,exports.commentMessageSchema=te,exports.commentPaginationSchema=xe,exports.createLaunchpadSDK=function(e){const{wallet:t,env:a,config:o={}}=e||{};let r;if(t)if("string"==typeof t){r=Gn(t).wallet}else{if(!(t instanceof n.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");r=t}else{r=Gn().wallet}const i={wallet:r,...a&&{env:a},debug:!1,timeout:3e4,...o};return new On(i)},exports.createLimitSchema=H,exports.createPaginatedResultSchema=function(e){return r.z.object({data:r.z.array(e),page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()})},exports.createTradeDataSchema=qe,exports.createWallet=Gn,exports.ethereumAddressSchema=O,exports.faucetAmountSchema=z,exports.fetchGalaBalanceOptionsSchema=Be,exports.fetchPoolDetailsDataSchema=Ze,exports.fetchTokenBalanceOptionsSchema=Re,exports.fileSizeSchema=Z,exports.fileUploadSchema=ve,exports.filenameSchema=J,exports.flexibleAddressSchema=R,exports.flexibleFileSchema=Se,exports.formatGalaForDTO=Qa,exports.formatLaunchpadTokenForDTO=Ya,exports.fullNameSchema=B,exports.getAmountOptionsSchema=Qe,exports.getTradeOptionsSchema=We,exports.graduateTokenOptionsSchema=we,exports.graphDataOptionsSchema=ye,exports.imageExtensionSchema=Ee,exports.imageFilenameSchema=be,exports.imageMimeTypeSchema=ee,exports.imageUploadOptionsSchema=he,exports.isoDateStringSchema=ae,exports.launchTokenDataSchema=de,exports.nonNegativeDecimalStringSchema=q,exports.optionalUrlSchema=W,exports.pageNumberSchema=j,exports.paginationResultMetaSchema=$e,exports.poolFetchTypeSchema=ge,exports.poolPaginationSchema=Ce,exports.positiveDecimalStringSchema=K,exports.privateKeySchema=oe,exports.reverseBondingCurveConfigSchema=ue,exports.reverseBondingCurveConfigurationSchema=Je,exports.searchQuerySchema=U,exports.sellTokensDataSchema=Ve,exports.standardLimitSchema=X,exports.standardPaginationSchema=Ne,exports.timestampSchema=ne,exports.tokenCategorySchema=ce,exports.tokenCollectionSchema=le,exports.tokenDescriptionSchema=L,exports.tokenListOptionsSchema=_e,exports.tokenNameSchema=P,exports.tokenSymbolSchema=$,exports.tokenUrlsSchema=se,exports.tradeCalculationMethodSchema=Xe,exports.tradeCalculationTypeSchema=He,exports.tradeLimitSchema=Y,exports.tradeListParamsSchema=je,exports.tradePaginationSchema=Fe,exports.tradePaginationWithFiltersSchema=Pe,exports.tradeTypeBackendSchema=Ke,exports.tradeTypeSchema=Ge,exports.transactionIdSchema=re,exports.transferFaucetsDataSchema=Ue,exports.uniqueKeySchema=ie,exports.updateProfileDataSchema=Me,exports.uploadProfileImageOptionsSchema=Oe,exports.urlSchema=V,exports.userLimitSchema=Q,exports.userPaginationSchema=Ie,exports.userTokenNameSchema=_,exports.userTokenTypeSchema=Le,exports.userTokensPaginationSchema=De,exports.validateAddress=ot,exports.validateAmountString=it,exports.validateBuyTokensData=Tt,exports.validateCalculatePreMintData=It,exports.validateCheckPoolOptions=pt,exports.validateCreateTradeData=At,exports.validateFaucetAmount=st,exports.validateFetchGalaBalanceOptions=yt,exports.validateFetchPoolDetailsData=Ft,exports.validateFetchTokenBalanceOptions=vt,exports.validateFullName=ct,exports.validateGetAmountOptions=Nt,exports.validateGetTradeOptions=Et,exports.validateImageUploadOptions=gt,exports.validateLaunchTokenData=dt,exports.validateSearchQuery=lt,exports.validateSellTokensData=St,exports.validateTokenDescription=nt,exports.validateTokenListOptions=mt,exports.validateTokenName=tt,exports.validateTokenSymbol=at,exports.validateTokenUrls=ht,exports.validateTradeListParams=bt,exports.validateTransferFaucetsData=ft,exports.validateUpdateProfileData=wt,exports.validateUploadProfileImageOptions=kt,exports.validateUserTokenName=ut,exports.validateVaultAddress=rt,exports.vaultAddressSchema=G;
1
+ "use strict";var e=require("axios"),t=require("ethers"),o=require("@gala-chain/connect"),n=require("zod"),a=require("bignumber.js"),i=require("@gala-chain/dex"),r=require("@gala-chain/api"),s=require("uuid"),c=require("socket.io-client"),l=require("path"),u=require("fs"),d=require("dotenv"),h=require("crypto");function p(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(o){if("default"!==o){var n=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,n.get?n:{enumerable:!0,get:function(){return e[o]}})}}),t.default=e,Object.freeze(t)}var g,m,f=p(l),y=p(u),w=p(d);if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(g||(g={}));class k extends Error{constructor(e,t,o){super(t),this.type=e,this.originalError=o,this.name="AuthError"}}class v{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix||"Create a GalaChain Wallet",""===e.messagePrefix)throw new k(g.SIGNATURE_FAILED,"Message prefix cannot be empty")}hasWallet(){return void 0!==this.wallet}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new k(g.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(!e.address||"string"!=typeof e.address)throw new k(g.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,o=await this.wallet.signMessage(t);return{message:t,signature:o,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof k)throw e;throw new k(g.SIGNATURE_FAILED,"Failed to generate signature for authentication",e instanceof Error?e:new Error(String(e)))}}getAddress(){return this.validateWallet(),this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.validateWallet(),this.wallet.address}getPrivateKey(){if(this.validateWallet(),!this.wallet.privateKey)throw new k(g.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new k(g.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`);return`eth|${t}`}async signMessage(e){this.validateWallet();try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){if(e instanceof k)throw e;const t=e instanceof Error?e.message:String(e);throw new k(g.SIGNATURE_FAILED,t,e instanceof Error?e:new Error(String(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const o=Date.now(),n=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${o}`,a=await this.wallet.signMessage(n);return{"x-signature":a,"x-address":this.formatAddress(this.wallet.address),"x-message":n,"x-timestamp":o.toString()}}catch(e){if(e instanceof k)throw e;throw new k(g.SIGNATURE_FAILED,"Failed to generate authentication headers",e instanceof Error?e:new Error(String(e)))}}async signTypedData(e,t,o){this.validateWallet();try{return await this.wallet.signTypedData(e,t,o)}catch(e){if(e instanceof k)throw e;throw new k(g.SIGNATURE_FAILED,"Failed to sign typed data",e instanceof Error?e:new Error(String(e)))}}async generateCustomSignature(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new k(g.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){if(e instanceof k)throw e;throw new k(g.SIGNATURE_FAILED,"Failed to generate custom message signature",e instanceof Error?e:new Error(String(e)))}}validateWallet(){if(!this.wallet)throw new k(g.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.wallet.address)throw new k(g.WALLET_NOT_CONNECTED,"Wallet address is not available");if(!this.wallet.privateKey&&!this.wallet.signMessage)throw new k(g.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(m||(m={}));class T{constructor(e){this.levelPriority={[m.DEBUG]:0,[m.INFO]:1,[m.WARN]:2,[m.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context||"SDK",this.minLevel=e.minLevel||(e.debug?m.DEBUG:m.INFO)}debug(e,t){this.log(m.DEBUG,e,t)}info(e,t){this.log(m.INFO,e,t)}warn(e,t){this.log(m.WARN,e,t)}error(e,t){this.log(m.ERROR,e,t)}log(e,t,o){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===m.DEBUG&&!this.debugEnabled)return;const n=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,a=this.getConsoleMethod(e);void 0!==o?o instanceof Error?a(`${n} ${t}`,o.message,o.stack):a(`${n} ${t}`,o):a(`${n} ${t}`)}getConsoleMethod(e){switch(e){case m.DEBUG:return console.debug;case m.INFO:return console.info;case m.WARN:return console.warn;case m.ERROR:return console.error;default:return console.log}}child(e){return new T({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[m.DEBUG]>=this.levelPriority[this.minLevel]}}function S(e){if(!e||"object"!=typeof e)return{};const t={};for(const[o,n]of Object.entries(e))null!=n&&("string"==typeof n?t[o]=n:"number"==typeof n||"boolean"==typeof n?t[o]=n.toString():Array.isArray(n)?t[o]=n.join(","):t[o]="object"==typeof n?JSON.stringify(n):String(n));return t}class A{constructor(t,o={}){this.auth=t,this.debug=o.debug??!1,this.logger=new T({debug:this.debug,context:"HttpClient"}),this.axios=e.create({baseURL:o.baseUrl||"https://lpad-backend-dev1.defi.gala.com",timeout:o.timeout||3e4,headers:{Accept:"application/json",...o.headers}}),this.setupInterceptors()}async request(e){try{const t={method:e.method,url:e.url,data:e.data,...e.params&&{params:S(e.params)},...e.headers&&{headers:e.headers},...e.timeout&&{timeout:e.timeout}};e.headers&&this.logger.debug("Custom headers provided:",e.headers),e.data instanceof FormData&&(t.headers&&t.headers["Content-Type"]&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload"));const o=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:o,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]||"not set"});const n=await this.axios.request(t);return this.logger.debug("Response:",{status:n.status,data:n.data}),n.data}catch(e){throw this.logger.error("Error:",e),e}}async get(e,t,o){return this.request({method:"GET",url:e,...t&&{params:t},...o&&{headers:o}})}async post(e,t,o){return this.request({method:"POST",url:e,data:t,...o&&{headers:o}})}async put(e,t,o){return this.request({method:"PUT",url:e,data:t,...o&&{headers:o}})}async delete(e,t,o){return this.request({method:"DELETE",url:e,...t&&{params:t},...o&&{headers:o}})}async patch(e,t,o){return this.request({method:"PATCH",url:e,data:t,...o&&{headers:o}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,o){return await this.auth.signTypedData(e,t,o)}async signCustomMessage(e){try{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}}catch(e){throw this.logger.error("Custom signature generation failed:",e),new Error(`Failed to generate custom signature for message: ${e instanceof Error?e.message:"Unknown error"}`)}}async signWithGalaChain(e,t,n=o.SigningType.SIGN_TYPED_DATA){const a=this.auth.getPrivateKey(),i=new o.SigningClient(a);return await i.sign(e,t,n)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{try{if(e.headers||(e.headers={}),this.auth.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request headers being sent:",e.headers),e}catch(e){throw this.logger.error("Failed to add signature:",e),e}},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{if(e.response){const t={message:e.response.data?.message||e.message,error:e.response.data?.error,statusCode:e.response.status,details:e.response.data?.details,timestamp:e.response.data?.timestamp,path:e.response.data?.path};e.launchpadError=t,this.logger.error("Backend error:",t)}else e.request?this.logger.error("Network error:",e.message):this.logger.error("Request setup error:",e.message);return Promise.reject(e)})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}const b="Token name is required and must be a string",E=e=>`Could not find vault address for token: ${e}`;class I extends Error{constructor(e,t,o){super(e),this.field=t,this.code=o,this.name="ValidationError"}}class N extends Error{constructor(e,t,o){super(e),this.statusCode=t,this.originalError=o,this.name="NetworkError"}}class P extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class x extends Error{constructor(e,t,o){super(e),this.transactionId=t,this.code=o,this.name="TransactionError"}}class F extends Error{constructor(e,t,o){super(e),this.originalError=t,this.code=o,this.name="GSwapQuoteError"}}class D extends Error{constructor(e,t,o,n){super(e),this.originalError=t,this.transactionHash=o,this.code=n,this.name="GSwapSwapError"}}class C extends Error{constructor(e,t,o,n,a){super(e),this.originalError=t,this.tokenA=o,this.tokenB=n,this.code=a,this.name="GSwapPoolError"}}class $ extends Error{constructor(e,t,o,n){super(e),this.originalError=t,this.walletAddress=o,this.code=n,this.name="GSwapAssetError"}}class L extends Error{constructor(e,t,o){super(e),this.originalError=t,this.code=o,this.name="GSwapPositionError"}}class B extends I{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class U extends I{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function O(e,t){return new I(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function _(e,t){const o=t||e.charAt(0).toUpperCase()+e.slice(1);return new I(`${o} is required`,e,"REQUIRED_FIELD")}function R(e,t,o){const n=o||e.charAt(0).toUpperCase()+e.slice(1);return new I(`${n} must be ${t}`,e,"INVALID_FORMAT")}function q(e,t,o){return new N(e,t,o)}function M(e,t){return new P(e,t)}function G(e,t,o){return new x(e,t,o)}function K(e,t,o){const{MIN_PAGE:n,MAX_PAGE:a,MIN_LIMIT:i,MAX_LIMIT:r}=o.PAGINATION;if("number"!=typeof e||e<n||e>a)throw new I(`Page must be a number between ${n} and ${a}`,"page","INVALID_PAGE");if("number"!=typeof t||t<i||t>r)throw new I(`Limit must be a number between ${i} and ${r}`,"limit","INVALID_LIMIT")}const z={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|[0-9a-fA-F]{40}$/};function V(e){return"string"==typeof e&&e.trim().length>0}function W(e){return!(!e||"string"!=typeof e)&&(z.ETH_ADDRESS.test(e)||z.BACKEND_ADDRESS.test(e))}function j(e){return e.startsWith("0x")?`eth|${e.slice(2)}`:e}const H=n.z.string().min(3,"Token name must be at least 3 characters").max(20,"Token name must be at most 20 characters").regex(/^[a-zA-Z0-9]{3,20}$/,"Token name can only contain letters and numbers"),Q=n.z.string().min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),X=n.z.string().min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Z=n.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Y=n.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),J=n.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),ee=n.z.string().regex(z.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),te=n.z.string().regex(z.ETH_ADDRESS,"Invalid Ethereum address format"),oe=n.z.string().refine(e=>z.BACKEND_ADDRESS.test(e)||z.ETH_ADDRESS.test(e),"Address must be either eth|[40-hex-chars] or 0x[40-hex-chars] format").transform(e=>e.startsWith("0x")?`eth|${e.slice(2)}`:e),ne=n.z.string().refine(e=>z.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),ae=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>0,"Amount must be greater than zero"),ie=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>parseFloat(e)>=0,"Amount must be zero or greater"),re=n.z.string().regex(/^(?!0+(\.0+)?$)\d+(\.\d+)?$/,"Amount must be a positive, non-zero number"),se=n.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),ce=n.z.string().optional().refine(e=>!e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),le=n.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function ue(e=100){return n.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const de=ue(100),he=ue(20),pe=ue(20),ge=n.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),me=n.z.string().max(255,"Filename must be at most 255 characters"),fe=n.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),ye=n.z.string().min(1,"Comment message is required").max(500,"Comment must be at most 500 characters"),we=n.z.string().datetime("Must be a valid ISO 8601 date string"),ke=n.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),ve=n.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Te=n.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),Se=n.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Ae=n.z.object({websiteUrl:ce,telegramUrl:ce,twitterUrl:ce}).refine(e=>e.websiteUrl||e.telegramUrl||e.twitterUrl,"At least one social URL (website, telegram, or twitter) is required"),be=n.z.string().min(1,"Token category must not be empty").default("Unit"),Ee=n.z.string().min(1,"Token collection must not be empty").default("Token"),Ie=n.z.object({minFeePortion:ae,maxFeePortion:ae}),Ne=n.z.object({tokenName:H,tokenSymbol:Q,tokenDescription:X,tokenImage:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer),n.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:ie.default("0"),websiteUrl:ce,telegramUrl:ce,twitterUrl:ce,tokenCategory:be,tokenCollection:Ee,reverseBondingCurveConfiguration:Ie.optional(),privateKey:ve.optional()}),Pe=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),tokenName:H}),xe=n.z.enum(["recent","popular"]),Fe=n.z.object({tokenName:H.optional(),symbol:Q.optional()}).refine(e=>e.tokenName||e.symbol,"At least one of tokenName or symbol is required"),De=n.z.enum(["NATIVE","MEME"]),Ce=n.z.enum(["IN","OUT"]),$e=n.z.object({from:n.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:n.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:n.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:H}),Le=n.z.object({tokenName:H,slippageToleranceFactor:n.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:n.z.number().min(0).max(1).optional(),privateKey:ve.optional()}),Be=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Ue=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),name:me,size:ge,type:fe}),Oe=n.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),_e=n.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Re=n.z.union([Oe,_e]),qe=n.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Me=me.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Be.includes(t)},`Filename must end with one of: ${Be.join(", ")}`),Ge=n.z.object({page:le,limit:de}),Ke=n.z.object({page:le,limit:he}),ze=n.z.object({page:le,limit:pe}),Ve=n.z.object({page:le,limit:ue(50)}),We=Ge.extend({type:n.z.enum(["recent","popular"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),je=Ke.extend({tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),He=ze.extend({tradeType:n.z.enum(["BUY","SELL"]).optional(),tokenName:n.z.string().min(1).max(50).optional(),userAddress:n.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:n.z.string().datetime().optional(),endDate:n.z.string().datetime().optional(),sortOrder:n.z.enum(["ASC","DESC"]).default("DESC")}),Qe=n.z.object({page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()});const Xe=n.z.enum(["all","DEFI","ASSET"]),Ze=Ke.extend({type:Xe.optional(),address:oe.optional(),search:Y.optional(),tokenName:Z.optional()}),Ye=n.z.object({walletAddress:oe,amount:re}),Je=n.z.object({address:oe.optional(),refresh:n.z.boolean().optional()}),et=n.z.object({profileImage:n.z.string(),fullName:J,address:oe,privateKey:ve.optional()}),tt=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),address:oe.optional(),privateKey:ve.optional()}),ot=n.z.object({address:oe,tokenId:n.z.union([n.z.string(),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string()}),n.z.object({collection:n.z.string(),category:n.z.string(),type:n.z.string(),additionalKey:n.z.string(),instance:n.z.string()})]).optional(),tokenName:Z.optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),nt=n.z.enum(["buy","sell"]),at=n.z.enum(["BUY","SELL"]),it=n.z.object({tradeType:nt,tokenAmount:ae,vaultAddress:ne,userAddress:oe,slippageTolerance:ae.optional(),deadline:n.z.number().int().positive().optional()}),rt=n.z.object({tokenSymbol:Q,nativeTokenQuantity:ae,expectedToken:ae,maxAcceptableReverseBondingCurveFee:ie.default("0").optional()}),st=n.z.object({tokenSymbol:Q,tokenQuantity:ae,expectedNativeToken:ae,maxAcceptableReverseBondingCurveFee:ie.default("0").optional()}),ct=ze.extend({tokenName:Z.optional()}),lt=n.z.object({page:n.z.number().int().min(1).max(1e3).default(1).optional(),limit:n.z.number().int().min(1).max(20).default(10).optional()}),ut=n.z.enum(["NATIVE","MEME"]),dt=n.z.enum(["IN","OUT"]),ht=n.z.object({type:ut,method:dt,vaultAddress:ne,amount:ae}),pt=n.z.object({nativeTokenQuantity:ae}),gt=n.z.object({vaultAddress:ne}),mt=n.z.object({minFeePortion:ae,maxFeePortion:ae});function ft(e){return t=>{const o=e.safeParse(t);return{success:o.success,data:o.success?o.data:void 0,errors:o.success?void 0:o.error.errors.map(e=>e.message)}}}const yt=ft(H),wt=ft(Q),kt=ft(X),vt=ft(oe),Tt=ft(ne),St=ft(ae),At=ft(re),bt=ft(J),Et=ft(Y),It=ft(Z),Nt=ft(Ne),Pt=ft(Ae),xt=ft(Pe),Ft=ft(Fe),Dt=ft(Ze),Ct=ft(Ye),$t=ft(Je),Lt=ft(et),Bt=ft(tt),Ut=ft(ot),Ot=ft(it),_t=ft(rt),Rt=ft(st),qt=ft(ct),Mt=ft(lt),Gt=ft(ht),Kt=ft(pt),zt=ft(gt);function Vt(e,t){throw new I(e.join("; "),t,"VALIDATION_ERROR")}function Wt(e){const t=yt(e);!t.success&&t.errors&&Vt(t.errors,"tokenName")}function jt(e){const t=We.safeParse(e);t.success||Vt(t.error.errors.map(e=>e.message),"pagination")}function Ht(e){const t=Ft(e);!t.success&&t.errors&&Vt(t.errors,"options")}function Qt(e){const t=Gt(e);!t.success&&t.errors&&Vt(t.errors,"options")}function Xt(e){const t=$e.safeParse(e);t.success||Vt(t.error.errors.map(e=>e.message),"options")}function Zt(e){const t=oe.safeParse(e);if(!t.success)throw new I("Ethereum address must be 40 hex characters (with or without 0x prefix)","ethereumAddress","INVALID_FORMAT");return t.data}function Yt(e,t,o=!0){if(!e||""===e.trim())throw new I(`${t} cannot be empty or whitespace-only. Provide a valid numeric string or omit the parameter to auto-fetch.`,t,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new I(`${t} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,t,"INVALID_NUMERIC_STRING");const n=parseFloat(e);if(isNaN(n))throw new I(`${t} must be a valid numeric string. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!isFinite(n))throw new I(`${t} must be a finite number. Cannot be Infinity or -Infinity.`,t,"INVALID_NUMERIC_STRING");if(n<0)throw new I(`${t} must be non-negative. Received: "${e}"`,t,"INVALID_NUMERIC_STRING");if(!o&&0===n)throw new I(`${t} must be greater than zero. Received: "${e}"`,t,"INVALID_NUMERIC_STRING")}var Jt=Object.freeze({__proto__:null,normalizeAddressInput:function(e){if(!e)return;const t=oe.safeParse(e);if(!t.success)throw new I(`Invalid address format: ${e}. Must be either "0x..." (Ethereum) or "eth|..." (GalaChain) format`,"address","INVALID_FORMAT");return t.data},toBackendAddressFormat:Zt,validateCheckPoolOptions:Ht,validateGetAmountOptions:Qt,validateGetGraphOptions:Xt,validateNumericString:Yt,validatePagination:jt,validateTokenName:Wt});function eo(e,t){const o=e,n=Number(o.page)||t.page,a=Number(o.limit)||t.limit,i=o.data,r=Number(o.total)||Number(i?.count)||0;return{page:n,limit:a,total:r,totalPages:Math.ceil(r/a)}}function to(e,t){return{hasNext:e<t,hasPrevious:e>1}}function oo(e,t,o=!1){const n=!0===e.error||200!==e.status,a=o&&!e.data;if(n||a)throw new Error(e.message||t)}const no="/launchpad/upload-image",ao="/launchpad/fetch-pool",io="/launchpad/check-pool",ro="/launchpad/get-graph-data",so="/holders",co="/launchpad/get-badge/",lo="/trade/",uo="/token/commment",ho="/token/commment",po="/user/profile",go="/user/profile",mo="/user/token-list",fo="/user/token-hold",yo="/user/transfer-faucets",wo={DEFAULT_PAGE:1,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100};class ko{constructor(e,t=!1){this.http=e,this.logger=new T({debug:t,context:this.constructor.name})}}class vo{constructor(e=!1){this.logger=new T({debug:e,context:this.constructor.name})}}function To(e,t){return"string"==typeof e[t]}function So(e,t){return void 0===e[t]||"string"==typeof e[t]}function Ao(e,t){return void 0===e[t]||"number"==typeof e[t]}function bo(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}function Eo(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&Ao(t,"from")&&Ao(t,"to")&&Ao(t,"resolution")}class Io extends ko{constructor(e,t=!1){super(e,t)}async fetchSinglePage(e){const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const o=S(t),n=await this.http.get(ao,o);if(!n)throw q("No response from pool service",500);oo(n,"Failed to fetch pools",!0);const a=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at||e.createdAt||""}));else{const o=e.tokens;t=[{...o,createdAt:o.created_at||o.createdAt||""}]}else e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at||e.createdAt||""})));return t}(n.data),i=n.data.count??n.data.total??0;return{pools:a,total:i,totalPages:e.limit>0?Math.ceil(i/e.limit):1}}async fetchMultiplePages(e){const{startPage:t,totalPages:o,pageSize:n,...a}=e,i=[];if(o&&o>=t){const e=[];for(let n=t;n<=o;n++)e.push(n);for(let t=0;t<e.length;t+=5){const o=e.slice(t,t+5).map(e=>this.fetchSinglePage({...a,page:e,limit:n}));(await Promise.all(o)).forEach(e=>{i.push(...e.pools)})}return i}let r=t,s=!0;for(;s;){const e=[];for(let t=0;t<5&&s;t++)e.push(r+t);const t=e.map(e=>this.fetchSinglePage({...a,page:e,limit:n})),o=await Promise.all(t);for(const e of o){if(0===e.pools.length){s=!1;break}i.push(...e.pools)}r+=e.length,r>wo.SAFETY_MAX_PAGES&&(s=!1)}return i}async fetchPools(e={}){const t=e.page||wo.DEFAULT_PAGE,o=e.limit??wo.DEFAULT_LIMIT;let n;if(0!==o&&jt({page:t,limit:o}),e.tokenName&&Wt(e.tokenName),"recent"===e.type?n="RECENT":"popular"===e.type&&(n="POPULAR"),o>0&&o<=20){const a=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:o});return{pools:a.pools,page:t,limit:o,total:a.total,totalPages:a.totalPages,hasNext:t<a.totalPages,hasPrevious:t>1}}if(0===o){const t=wo.BACKEND_MAX_PAGE_SIZE,o=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:1,limit:t}),a=[...o.pools];if(o.pools.length>0){const i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:2,totalPages:o.totalPages>1?o.totalPages:null,pageSize:t});a.push(...i)}return{pools:a,page:1,limit:a.length,total:o.total||a.length,totalPages:1,hasNext:!1,hasPrevious:!1}}const a=wo.BACKEND_MAX_PAGE_SIZE,i=Math.ceil(o/a),r=await this.fetchSinglePage({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},page:t,limit:a}),s=[...r.pools],c=Math.min(i,r.totalPages-t+1);if(c>1){const o=t+c-1,i=await this.fetchMultiplePages({...e.search&&{search:e.search},...e.tokenName&&{tokenName:e.tokenName},...n&&{type:n},startPage:t+1,totalPages:o,pageSize:a});s.push(...i)}const l=s.slice(0,o);return{pools:l,page:t,limit:o,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){Ht(e),e.tokenName&&Wt(e.tokenName);const t=S(e),o=await this.http.get(io,t);if(!o)throw q("No response from pool service",500);oo(o,"Failed to check pool");const n=o.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.exists??!1}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!Eo(e))throw new I("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:o,to:n,resolution:a}=e;if(Wt(t),!o||!n||!a)throw new I("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:o,to:n,resolution:a};Xt(i);const r=S(i),s=await this.http.get(ro,r);if(!s)throw q("No response from pool service",500);return oo(s,"Failed to fetch graph data",!0),{dataPoints:s.data}}async fetchTokenDistribution(e){if(!e)throw _("tokenName","Token name");Wt(e);const t=await this.resolveTokenNameToVault(e);if(!t)throw O(e);const o=encodeURIComponent(t),n=await this.http.get(`${so}/${o}`);if(!n)throw q("No response from pool service",500);oo(n,"Failed to fetch token distribution",!0);const i=n.data;if(!Array.isArray(i))throw q("Invalid API response: expected array of holders",n.status);for(const e of i){if(!e.owner||"string"!=typeof e.owner)throw q("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw q("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw q(`Invalid holder quantity: "${e.quantity}"`,n.status)}const r=i.reduce((e,t)=>e.plus(t.quantity),new a(0));return{holders:i.map(e=>{const t=new a(e.quantity),o=r.isZero()?0:t.dividedBy(r).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:o}}),totalSupply:r.toFixed(),totalHolders:i.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw _("tokenName","Token name");Wt(e);const t=await this.http.get(co,{tokenName:e});if(!t)throw q("No response from pool service",500);return oo(t,"Failed to fetch token badges",!0),{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:o,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const a=("volume"===o?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return a?.isActive||!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(t.pools&&Array.isArray(t.pools)&&t.pools.length>0)return t.pools[0].vaultAddress||null;if(t.pools&&"object"==typeof t.pools){const e=t.pools.tokens;return e?.vaultAddress||null}return null}catch{return null}}}function No(e,t={}){const{stringifyFields:o=[],optionalFields:n=[],fieldMappings:a={}}=t,i={};for(const[t,r]of Object.entries(e)){const e=t;if(n.includes(e)&&void 0===r)continue;if(n.includes(e)&&"string"==typeof r&&0===r.trim().length)continue;const s=a[e],c=s?String(s):t;o.includes(e)?i[c]=String(r):i[c]=r}return S(i)}const Po={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:20}};class xo extends ko{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&So(t,"userAddress")&&Ao(t,"page")&&Ao(t,"limit")}(e))throw new I("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, page?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:o,userAddress:n,page:a=wo.DEFAULT_PAGE,limit:i=wo.DEFAULT_LIMIT,startDate:r,endDate:s,sortOrder:c}=e;if(!V(t))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");K(a,i,Po);const l=function(e,t,o){return No({tokenName:e,page:t,limit:o},{stringifyFields:["page","limit"]})}(t,a,i),u=await this.http.get(lo,l);if(!u)throw new I("No response from trade service","response","NO_RESPONSE");const d=(h=u.data)?Array.isArray(h)?h:h.trades:[];var h;const p=eo(u,{page:a,limit:i}),g=to(p.page,p.totalPages);return{trades:d,...p,...g}}}const Fo=new T({debug:!1,context:"DateUtils"});function Do(e,t){if(!e)return t||new Date;if(e instanceof Date)return isNaN(e.getTime())?t||new Date:e;try{const o=new Date(e);return isNaN(o.getTime())?(Fo.warn(`Invalid date string received: "${e}". Using fallback.`),t||new Date):o}catch(o){return Fo.warn(`Date parsing error for "${e}":`,o),t||new Date}}const Co={PAGINATION:{MIN_PAGE:1,MAX_PAGE:1e3,MIN_LIMIT:1,MAX_LIMIT:50},CONTENT:{MIN_LENGTH:1,MAX_LENGTH:500}};class $o extends ko{constructor(e,t,o=!1){super(e,o),this.poolService=t}async fetchComments(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&Ao(t,"page")&&Ao(t,"limit")}(e))throw new I("Invalid options provided. Expected { tokenName: string, page?: number, limit?: number }","options","INVALID_OPTIONS");const{tokenName:t,page:o=wo.DEFAULT_PAGE,limit:n=wo.DEFAULT_LIMIT}=e;if(!V(t))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");K(o,n,Co);const a=await this.poolService.resolveTokenNameToVault(t);if(!a)throw O(t);const i=No({vaultAddress:a,page:o,limit:n},{stringifyFields:["page","limit"]}),r=await this.http.get(uo,i);if(!r)throw new I("No response from comment service","response","NO_RESPONSE");if(oo(r,"Failed to fetch comments"),!r.data)throw new I("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 I("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:Do(e.createdAt)})),total:r.data.count||0}}async postComment(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&To(t,"content")}(e))throw new I("Invalid options provided. Expected { tokenName: string, content: string }","options","INVALID_OPTIONS");const{tokenName:t,content:o}=e;if(!V(t))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if(!function(e){if(!e||"string"!=typeof e)return!1;const t=e.trim();return t.length>=Co.CONTENT.MIN_LENGTH&&t.length<=Co.CONTENT.MAX_LENGTH}(o))throw new I(`Comment content must be between ${Co.CONTENT.MIN_LENGTH} and ${Co.CONTENT.MAX_LENGTH} characters`,"content","INVALID_CONTENT");const n=await this.poolService.resolveTokenNameToVault(t);if(!n)throw O(t);const a=this.http.getAddress();if(!a)throw new I("User address not available - wallet not configured","userAddress","NO_WALLET");const i={userAddress:a,vaultAddress:n,content:o},r=await this.http.post(ho,i);if(!r)throw new I("No response from comment service","response","NO_RESPONSE");oo(r,"Failed to create comment")}}function Lo(e){return e instanceof Error}function Bo(e){return Lo(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function Uo(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Oo(e,t="image",o){const n=new FormData;if("undefined"!=typeof File&&e instanceof File)n.append(t,e);else{if(!Buffer.isBuffer(e))throw R("file","a File object (browser) or Buffer (Node.js)");{const a=new Blob([e],{type:"image/png"});n.append(t,a,o)}}return n}const _o={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 Ro(e){return!(!e||"string"!=typeof e)&&_o.USER_ADDRESS.PATTERN.test(e)}const qo="Update profile";class Mo extends ko{constructor(e,t=!1){super(e,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(!t||!Ro(t))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");const o={userAddress:t},n=await this.http.get(po,o);if(!n)throw new I("No response from user service","response","NO_RESPONSE");return n}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!t||""===t.trim())try{const o=await this.fetchProfile(e.address);t=o.data?.profileImage||""}catch{t=""}const o={profileImage:t,fullName:e.fullName,userAddress:e.address},n=await this.http.signCustomMessage(qo);if(!n)throw new I("Failed to generate signature - wallet not configured","signature","NO_SIGNATURE");const a={address:n.address,message:qo,publickey:n.ethereumAddress,sign:n.signature},i=await this.http.put(go,o,a);if(!i)throw new I("No response from user service","response","NO_RESPONSE");oo(i,"Profile update failed")}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(!t)throw new I("Wallet address not available - wallet not configured","address","NO_WALLET");try{const o=`profile-image-${t}.png`,n=Oo(e.file,"image",o),a=await this.http.request({method:"POST",url:`${no}?tokenName=${encodeURIComponent(t)}`,data:n,headers:{}});if(!a)throw new I("No response from user service","response","NO_RESPONSE");return oo(a,"Image upload failed"),"string"==typeof a.data?a.data:""}catch(e){if(e instanceof I)throw e;throw new I(`Profile image upload failed: ${Bo(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(mo,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(fo,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{page:t=wo.DEFAULT_PAGE,limit:o=wo.DEFAULT_LIMIT,search:n,tokenName:a}=e,i=this.http.getAddress();if(!i)throw new I("Wallet address not available - wallet not configured","address","NO_WALLET");const r={type:"DEFI",address:i,page:t,limit:o};return void 0!==n&&(r.search=n),void 0!==a&&(r.tokenName=a),this.fetchTokenList(r)}async buildFetchRequest(e,t,o){this.validateGetTokenListOptions(t);const n={page:t.page,limit:t.limit,address:t.address,search:t.search,tokenName:t.tokenName},a=No(o.includeType?{...n,type:"all"!==t.type&&t.type?t.type:"DEFI"}:n,{stringifyFields:["page","limit"],optionalFields:["address","search","tokenName"]}),i=await this.http.get(e,a);if(!i)throw new I("No response from user service","response","NO_RESPONSE");oo(i,o.errorMessage,!0);const r=(s=i.data)?Array.isArray(s)?s:s.token:[];var s;const c=eo(i,{page:t.page||wo.DEFAULT_PAGE,limit:t.limit||wo.DEFAULT_LIMIT}),l=to(c.page,c.totalPages);return{tokens:r,...c,...l}}validateGetTokenListOptions(e){if(K(e.page,e.limit,_o),void 0!==e.address&&!Ro(e.address))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(void 0!==e.search&&e.search.trim().length>0&&!((t=e.search)&&"string"==typeof t&&t.length>=_o.SEARCH.MIN_LENGTH&&t.length<=_o.SEARCH.MAX_LENGTH))throw new I(`Search query must be between ${_o.SEARCH.MIN_LENGTH} and ${_o.SEARCH.MAX_LENGTH} characters`,"search","INVALID_SEARCH");var t,o;if(void 0!==e.tokenName&&e.tokenName.trim().length>0&&!((o=e.tokenName)&&"string"==typeof o&&o.length>=_o.TOKEN_NAME.MIN_LENGTH&&o.length<=_o.TOKEN_NAME.MAX_LENGTH))throw new I(`Token name must be between ${_o.TOKEN_NAME.MIN_LENGTH} and ${_o.TOKEN_NAME.MAX_LENGTH} characters`,"tokenName","INVALID_TOKEN_NAME")}validateUpdateProfileData(e){if(!Ro(e.address))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!((t=e.fullName)&&"string"==typeof t&&t.length>=_o.PROFILE.FULL_NAME.MIN_LENGTH&&t.length<=_o.PROFILE.FULL_NAME.MAX_LENGTH&&_o.PROFILE.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw new I(`Full name must be between ${_o.PROFILE.FULL_NAME.MIN_LENGTH} and ${_o.PROFILE.FULL_NAME.MAX_LENGTH} characters`,"fullName","INVALID_FULL_NAME");var t}validateUploadProfileImageOptions(e){if(e.address&&!Ro(e.address))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS")}}class Go extends Error{constructor(e,t,o){super(e),this.filename=t,this.mimeType=o,this.name="FileValidationError"}}function Ko(e,t,o){if(!e)throw new Go("File is required",t,o);if("undefined"!=typeof File&&e instanceof File){const t=Oe.safeParse(e);if(!t.success){const o=t.error.errors.map(e=>e.message).join("; ");throw new Go(o,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(!t)throw new Go("Filename is required when uploading Buffer objects",t,o);const n=_e.safeParse(e);if(!n.success){const e=n.error.errors.map(e=>e.message).join("; ");throw new Go(e,t,o)}if(t.length>255)throw new Go(`Filename length ${t.length} exceeds maximum allowed length of 255 characters`,t,o);const a=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!a.includes(o))throw new Go(`Invalid file type "${o}" is not allowed. Allowed types: ${a.join(", ")}`,t,o);const i=function(e){if(!e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),r=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!r.includes(i))throw new Go(`File extension "${i}" is not allowed. Allowed extensions: ${r.join(", ")}`,t,o);const s=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(s!==o&&"application/octet-stream"!==s)throw new Go(`File extension "${i}" does not match MIME type "${o}"`,t,o);return}throw new Go("File must be a File object (browser) or Buffer (Node.js)",t,o)}class zo extends ko{constructor(e,t=!1){super(e,t)}async uploadImageByTokenName(e){const{tokenName:t,options:o}=e;Wt(t);const n=`${t}.png`;Ko(o.file,n,"image/png");try{const e=`${o.tokenName??t}.png`,n=Oo(o.file,"image",e),a=await this.http.request({method:"POST",url:`${no}?tokenName=${encodeURIComponent(o.tokenName??t)}`,data:n,headers:{}});if(!a)throw M("No response from image upload service","response");return oo(a,"Image upload failed"),"string"==typeof a.data?a.data:""}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw M("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}class Vo extends ko{constructor(e,t=!1){super(e,t)}async transferFaucets(e){this.validateTransferFaucetsData(e);const t={userAddress:e.walletAddress,amount:e.amount},o=await this.http.post(yo,t);if(!o)throw new I("No response from faucet service","response","NO_RESPONSE");oo(o,"Faucet transfer failed")}validateTransferFaucetsData(e){if(!Ro(e.walletAddress))throw new I("Address must be in format: eth|[40-hex-chars]","address","INVALID_ADDRESS");if(!(t=e.amount)||"string"!=typeof t||!_o.FAUCET_AMOUNT.POSITIVE_NON_ZERO_DECIMAL.test(t))throw new I("Amount must be a positive decimal string greater than zero","amount","INVALID_AMOUNT");var t}}class Wo{constructor(e,t=!1){this.http=e,this.poolService=new Io(e,t),this.tradeService=new xo(e,t),this.commentService=new $o(e,this.poolService,t),this.userService=new Mo(e,t),this.imageService=new zo(e,t),this.faucetService=new Vo(e,t)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async fetchComments(e){return this.commentService.fetchComments(e)}async postComment(e){return this.commentService.postComment(e)}async fetchProfile(e){return this.userService.fetchProfile(e)}async updateProfile(e){return this.userService.updateProfile(e)}async uploadProfileImage(e){return this.userService.uploadProfileImage(e)}async fetchTokenList(e){return this.userService.fetchTokenList(e)}async fetchTokensHeld(e){return this.userService.fetchTokensHeld(e)}async fetchTokensCreated(e={}){return this.userService.fetchTokensCreated(e)}async transferFaucets(e){return this.faucetService.transferFaucets(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return Wt(e)}}const jo={MAX_UNIQUE_KEY_LENGTH:64,UNIQUE_KEY_PATTERN:/^(galaswap-operation-|galaconnect-operation-)/,TOKEN_NAME_PATTERN:/^[a-zA-Z0-9]+$/};var Ho;!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"}(Ho||(Ho={}));class Qo extends Error{constructor(e,t,o){super(e),this.type=t,this.details=o,this.name="TransferError"}}function Xo(e,t="0"){return new a(null==e||""===e?t:e)}function Zo(e){return i.tickToSqrtPrice(e)}function Yo(e){const t=Xo(e),o=new a(2).pow(96),n=t.sqrt().times(o);return i.sqrtPriceToTick(n)}function Jo(e,t=!1){const o=Xo(e),n=new a(1).dividedBy(o);return t?n.toFixed():n}function en(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThan(0))throw new Error(`Value at index ${t} must be non-negative, got: ${e.toString()}`)})}function tn(e,t,o){if(e.isNaN())throw new Error(`${t} must be a valid number, got: NaN`);if(!e.isFinite()){const n=o?`${t} must be finite ${o}, got: ${e.toString()}`:`${t} must be finite, got: ${e.toString()}`;throw new Error(n)}if(e.isLessThanOrEqualTo(0)){const n=o?`${t} must be positive ${o}, got: ${e.toString()}`:`${t} must be positive, got: ${e.toString()}`;throw new Error(n)}}class on{static validateAmount(e){const t=new a(e);try{tn(t,"amount","for transfer")}catch(t){throw new Qo(t.message,Ho.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(e){if(e.length>jo.MAX_UNIQUE_KEY_LENGTH)throw new I(`Unique key too long. Maximum length: ${jo.MAX_UNIQUE_KEY_LENGTH}`);if(!jo.UNIQUE_KEY_PATTERN.test(e))throw new Qo('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Ho.INVALID_AMOUNT,{uniqueKey:e})}}}class nn{toLaunchpadFormat(e){if(!e)return"unknown|Unit|none|none";if("string"==typeof e)return e.includes("|")?e:`${e}|Unit|none|none`;return`${e.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 o=("Token"===t[0]||"Collection"===t[0])&&t[2]?t[2]:t[0];return{collection:t[0]||"Token",category:t[1]||"Unit",type:o,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 an(e){if(!e||"string"!=typeof e)throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function rn(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected at least 4 parts separated by $, got ${t.length}`);const[o,n,a,...i]=t;if(!o||!n||!a)throw new Error("Collection, category, and type must be non-empty");const r=i.join("$");if(!r)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:n,type:a,additionalKey:r}}catch(t){throw new I(`Invalid dollar-delimited token: "${e}". Expected format: "Token$Unit$SYMBOL$additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"dollarToken","INVALID_DOLLAR_DELIMITED_TOKEN_FORMAT")}}class sn extends o.ChainCallDTO{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,o,n,a){let i;if("string"==typeof n){i={...rn(n),instance:"0"}}else i={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new sn({from:e,to:t,quantity:o,tokenInstance:i,uniqueKey:a||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}static forGALA(e,t,o,n){return new sn({from:e,to:t,quantity:o,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:n||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`})}getTokenClassKey(){return`${this.tokenInstance.collection}$${this.tokenInstance.category}$${this.tokenInstance.type}$${this.tokenInstance.additionalKey}`}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}class cn{constructor(e){this.wallet=e}static generateUniqueKey(){return`${Date.now()}_${Math.random().toString(36).substring(2,8)}`}async signTransferToken(e){const t={name:"GalaChain",chainId:1},o={TransferToken:[{name:"from",type:"string"},{name:"to",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstance",type:"TokenInstance"},{name:"uniqueKey",type:"string"}],TokenInstance:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]};return{signature:await this.wallet.signTypedData(t,o,e),domain:t,types:o,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){const o=e.replace("0x","");return`eth|${t.ethers.getAddress(`0x${o}`).replace("0x","")}`}static fromGalaChainAddress(e){return e.startsWith("eth|")?e.substring(4):e}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...rn(e),instance:"0"}}}function ln(e){if("string"==typeof e){const t=e.split("|");if(t.length<4)throw new I(`Invalid tokenId string format: "${e}". Expected format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");if(!(t[0]&&t[1]&&t[2]&&t[3]))throw new I(`Invalid tokenId string format: "${e}". All components (collection, category, type, additionalKey) must be non-empty`,"tokenId","INVALID_TOKEN_ID_FORMAT");return{collection:t[0],category:t[1],type:t[2],additionalKey:t[3],instance:t[4]||"0"}}if("object"==typeof e&&null!==e){if(!(e.collection&&e.category&&e.type&&e.additionalKey))throw new I("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return"instance"in e&&void 0!==e.instance?e:{...e,instance:"0"}}throw new I(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function un(e){try{const[t,o]=e.split("|");if(!o)throw new Error("Missing token part after service");const n=o.split("$");if(n.length<4)throw new Error(`Invalid vault address format. Expected at least 4 parts separated by $, got ${n.length}`);if(!(n[0]&&n[1]&&n[2]&&n[3]))throw new Error("All vault address components (collection, category, type, additionalKey) must be non-empty");const a=n.slice(3,-1),i=a.length>0?a.join("$"):n[3];return{collection:n[0],category:n[1],type:n[2],additionalKey:i}}catch(t){throw new I(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${t instanceof Error?t.message:String(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}function dn(e){return{...un(e),instance:"0"}}function hn(e){return un(e).type}var pn=Object.freeze({__proto__:null,extractTokenSymbolFromVault:hn,normalizeToTokenInstanceKey:ln,parseVaultAddressToTokenClassKey:un,parseVaultAddressToTokenInstance:dn});const gn="gala-transfer-successful",mn="token-transfer-successful",fn="transfer-successful-no-id";class yn extends ko{constructor(e,t,o,n=!1,a){super(e,n),this.wallet=t,this.tokenResolver=o,this.publicAxios=a,this.signatureHelper=t?new cn(t):void 0}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);if(!t)throw q("No response from GalaChain service",500);if(1!==t.Status)throw q(`Failed to fetch pool details: Status ${t.Status}`,t.Status);const o=t.Data.reverseBondingCurveConfiguration,n=o?.minFeePortion??"0",a=o?.maxFeePortion??"0",i=(await import("bignumber.js")).default,r=!new i(n).isZero()||!new i(a).isZero(),s=t.Data;return s.reverseBondingCurveMinFeePortion=n,s.reverseBondingCurveMaxFeePortion=a,s.hasReverseBondingCurveFee=r,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});if(!e)throw q("No response from GalaChain service",500);if(1!==e.Status)throw q(`Failed to fetch launch token fee: Status ${e.Status}`,e.Status);return e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!(t=e)||"object"!=typeof t||"string"!=typeof t.vaultAddress)throw new I("Invalid fetch pool details data: missing required fields","data","INVALID_TYPE");var t;if(!e.vaultAddress||"string"!=typeof e.vaultAddress)throw new I("Vault address is required and must be a string","vaultAddress","INVALID_VAULT_ADDRESS");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new I("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e){try{const t=await this.http.post("/api/asset/token-contract/FetchBalances",e);if(!t)return null;if(1!==t.Status||!t.Data||0===t.Data.length)return null;const o=t.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!o||"0"===o.quantity)return null;const n=`${o.collection}|${o.category}|${o.additionalKey}|${o.type}`;return{quantity:o.quantity,collection:o.collection,category:o.category,tokenId:n}}catch(e){throw q(`Failed to fetch token balance from GalaChain: ${Bo(e)}`,void 0,Lo(e)?e:void 0)}}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?ln(e):e,o={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]},n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",o)).data;if(1!==n.Status)throw q(`Failed to fetch token class from GalaChain: Status ${n.Status}${n.Message?` - ${n.Message}`:""}`,n.Status);if(!n.Data||0===n.Data.length)throw q(`Token not found on GalaChain: ${t.collection}|${t.category}|${t.type}|${t.additionalKey}`,404);return n.Data[0]}catch(e){if(Uo(e)&&404===e.response?.status)throw q("Token not found on GalaChain",404,Lo(e)?e:void 0);const t=Bo(e);if(t.includes("Token not found")||t.includes("Status"))throw e;throw q(`Failed to fetch token class from GalaChain: ${t}`,void 0,Lo(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(!e||0===e.length)throw new I("tokenClasses array must not be empty");const t={tokenClasses:e},o=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(1!==o.Status)throw q(`Failed to fetch token classes with supply from GalaChain: Status ${o.Status}${o.Message?` - ${o.Message}`:""}`,o.Status);if(!o.Data||0===o.Data.length)throw q("No token supply data found for requested token classes",404);return o.Data}catch(e){if(Uo(e)&&404===e.response?.status)throw q("Token supply data not found on GalaChain",404,Lo(e)?e:void 0);const t=Bo(e);if(t.includes("Token")||t.includes("Status")||t.includes("tokenClasses"))throw e;throw q(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,Lo(e)?e:void 0)}}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new Qo("Wallet required for GALA transfer operations",Ho.WALLET_REQUIRED);try{const t=j(e.recipientAddress),o=j(this.wallet.address),n=sn.forGALA(o,t,e.amount,e.uniqueKey),a=await this.signatureHelper.signTransferToken(n.toSigningPayload()),i=new sn({...n.toSigningPayload(),signedPayload:a});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(i,null,2));const r=await this.http.post("/api/asset/token-contract/TransferToken",i);if(!r)throw new Qo("No response from GalaChain transfer service",Ho.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 Qo("Wallet required for token transfer operations",Ho.WALLET_REQUIRED);try{const t=j(e.to),o=j(this.wallet.address);let n;if(e.tokenId)n=ln(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",JSON.stringify(n,null,2));else{if(!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Ho.TOKEN_NOT_FOUND);n=await this.resolveTokenInstance(e.tokenName)}const a=new sn({from:o,to:t,quantity:e.amount,tokenInstance:n,uniqueKey:e.uniqueKey||`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}),i=await this.signatureHelper.signTransferToken(a.toSigningPayload()),r=new sn({...a.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(r,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",r);if(!s)throw new Qo("No response from GalaChain transfer service",Ho.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"token")}catch(t){throw this.handleTransferError(t,"Token transfer failed",e)}}async resolveTokenClassKey(e){try{const t=await this.tokenResolver.resolveTokenClassKey(e);return this.logger.debug(`[DEBUG] Token class key resolution for '${e}':`,JSON.stringify(t,null,2)),t}catch(t){if(t instanceof Qo)throw t;throw new Qo(`Failed to resolve token class key for '${e}': ${Bo(t)}`,Ho.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 I("Invalid GALA transfer data: missing required fields");if(!W(e.recipientAddress))throw new Qo("Invalid recipient address format",Ho.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});on.validateAmount(e.amount),on.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.to&&t.to.trim().length>0&&"string"==typeof t.amount&&t.amount.trim().length>0&&(void 0!==t.tokenId||"string"==typeof t.tokenName&&t.tokenName.trim().length>0)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new I("Invalid token transfer data: missing required fields");if(!W(e.to))throw new Qo("Invalid recipient address format",Ho.INVALID_RECIPIENT,{recipientAddress:e.to});if(!e.tokenId&&!e.tokenName)throw new Qo("Must provide either tokenId or tokenName for token identification",Ho.TOKEN_NOT_FOUND);if(e.tokenName&&!jo.TOKEN_NAME_PATTERN.test(e.tokenName))throw new Qo("Invalid token name format",Ho.TOKEN_NOT_FOUND,{tokenName:e.tokenName});on.validateAmount(e.amount),on.validateUniqueKey(e.uniqueKey)}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new Qo(`Token '${e}' not found or not available for transfer`,Ho.TOKEN_NOT_FOUND,{tokenName:e});const o=this.resolveTokenInstanceFromVaultAddress(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}':\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(o,null,2)}`),o}catch(t){if(t instanceof Qo)throw t;throw new Qo(`Failed to resolve token '${e}': ${Bo(t)}`,Ho.TOKEN_NOT_FOUND,{tokenName:e})}}resolveTokenInstanceFromVaultAddress(e){try{return dn(e)}catch(e){if(e instanceof I)throw new Qo(`Invalid vault address format: ${e.message}`,Ho.TOKEN_NOT_FOUND);throw new Qo(`Failed to parse vault address: ${e instanceof Error?e.message:String(e)}`,Ho.TOKEN_NOT_FOUND)}}extractTransactionIdFromResponse(e,t){if(e&&"object"==typeof e){if("Status"in e&&1===e.Status&&"Data"in e){const o=e;return Array.isArray(o.Data)&&o.Data.length>0?"gala"===t?gn:mn:fn}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId)return e.transactionId}throw new Qo("Transfer succeeded but transaction ID could not be extracted",Ho.NETWORK_ERROR)}handleTransferError(e,t,o){if(e instanceof Qo)return e;if(e instanceof I)return new Qo(e.message,Ho.INVALID_AMOUNT);if(Uo(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t)return new Qo(("string"==typeof n?.message?n.message:void 0)||"Invalid transfer request",Ho.INVALID_AMOUNT);if(403===t)return new Qo("Insufficient balance for transfer",Ho.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in o&&(e.tokenName=o.tokenName),new Qo("Token not found",Ho.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===e.code||"ETIMEDOUT"===e.code))return new Qo("Transfer request timed out",Ho.NETWORK_ERROR);const n=Bo(e);return new Qo(n||t,Ho.NETWORK_ERROR)}}class wn{constructor(e,t,o,n=!1){this.dexBackendHttp=e,this.cache=t,this.galaChainService=o,this.logger=new T({debug:n,context:"DexService"})}async fetchTokenPrice(e){const{tokenName:t,tokenId:o}=e;if(!t&&!o)throw _("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");if(t&&o)throw new I("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS");if(o)return this.logger.debug(`Fetching spot price by tokenId: ${o}`),this._fetchDexTokenSpotPrice(o);throw new I("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(!e)throw _("tokenId","Token ID");try{const t=ln(e),o=an(`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`);if(this.logger.debug(`Fetching DEX spot price for token: ${o}`),!this.dexBackendHttp)throw q("DEX Backend API client not configured");const n=await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:o}});if(!n.data||"string"!=typeof n.data)throw new I("Invalid price response: data must be a string, got "+typeof n.data,"data","INVALID_RESPONSE");const a=parseFloat(n.data);if(isNaN(a))throw new I(`Invalid price value: could not parse "${n.data}" as number`,"data","INVALID_CALCULATION");const i=`${t.collection}|${t.category}|${t.type}|${t.additionalKey}`;let r;try{if(this.cache){const e=this.cache.getByTokenId(i);if(e?.symbol)return r=e.symbol,this.logger.debug(`DEX spot price for ${r} (cached): $${a}`),{symbol:r,price:a}}this.logger.debug(`Symbol cache miss for ${i}, fetching from API`);r=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(i,{symbol:r}),this.logger.debug(`Cached symbol for ${i}: ${r}`)),this.logger.debug(`DEX spot price for ${r}: $${a}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to type field: ${e instanceof Error?e.message:String(e)}`),r=t.type.toUpperCase(),this.logger.debug(`DEX spot price for ${r} (fallback): $${a}`)}return{symbol:r,price:a}}catch(e){if(e instanceof I)throw e;throw q(`Failed to fetch DEX spot price: ${Bo(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,o){if(!e||"string"!=typeof e)throw new Error(b);try{if(o)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await o(e);if(t&&t.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const o=`${t.sellingToken.collection}|${t.sellingToken.category}|${t.sellingToken.type}|${t.sellingToken.additionalKey}`;return this._fetchDexTokenSpotPrice(o)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Bo(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),a=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(!a)throw q("GALA price not available");const i=Number(n.amount)/1e18;if(i<=0)throw new I(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const r=a.price/i;return{symbol:e.toUpperCase(),price:r}}catch(t){if(t instanceof Error)throw q(`Failed to calculate launchpad token spot price for ${e}: ${t.message}`);throw q(`Failed to calculate launchpad token spot price for ${e}: ${Bo(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw q("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),o={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey,symbol:t.symbol,decimals:t.decimals,name:t.name,image:t.image,description:t.description,network:t.network,...void 0!==t.contractAddress&&{contractAddress:t.contractAddress}};return this.logger.debug(`Fetched token details for ${t.symbol} from GalaChain`),o}catch(t){if((t instanceof I||t instanceof Error)&&("NetworkError"===t.name||t.message.includes("Token not found")))throw t;throw q(`Failed to fetch token details from GalaChain for ${e}: ${Bo(t)}`,500)}}}function kn(e,t=18){const o=parseFloat(e);if(0===o)return"0";return o.toFixed(t).replace(/\.?0+$/,"")}function vn(e){return kn(e,8)}function Tn(e){return kn(e,18)}function Sn(e){return{maxAcceptableReverseBondingCurveFee:vn(e.maxAcceptableReverseBondingCurveFee)}}new T({debug:!1,context:"NumberUtils"});class An extends o.ChainCallDTO{constructor(e,t,o="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=vn(t),this.expectedToken=Tn(o),this.extraFees=Sn(n)}}class bn extends o.ChainCallDTO{constructor(e,t,o,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Tn(t),this.expectedNativeToken=vn(o),this.extraFees=Sn(n)}}class En extends o.ChainCallDTO{constructor(e,t,o="0",n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Tn(t),this.expectedNativeToken=vn(o),this.extraFees=Sn(n)}}class In extends o.ChainCallDTO{constructor(e,t,o,n={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=vn(t),this.expectedToken=Tn(o),this.extraFees=Sn(n)}}const Nn={BuyNativeDto:An,BuyExactDto:bn,SellExactDto:En,SellNativeDto:In};class Pn extends vo{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,n){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const n=this.generateEIP712Types(t,e),a=o.calculatePersonalSignPrefix(e),i={...e,prefix:a},{signature:r,domain:s}=await this.signWithEthersWallet(n,i),c={...e,signature:r,types:n,domain:s};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(c),signatureLength:r.length}),c}catch(e){this.logger.error("❌ Signature generation failed:",e);throw G(`Failed to sign DTO: ${Bo(e)}`)}}async signWithEthersWallet(e,t){try{let o,n;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)o={name:"ethereum",chainId:1},n=await this.walletProvider.signTypedData(o,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw M("Wallet provider does not support typed data signing","walletProvider");{const a=await this.walletProvider.getNetwork();o={name:a.name,chainId:Number(a.chainId)},n=await this.walletProvider.signTypedData(o,e,t)}}return{signature:n,domain:o}}catch(e){throw G(`Ethers.js signing failed: ${Bo(e)}`)}}generateEIP712Types(e,t){const o={};o[e]=[];const n=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),a=(e,t,n,i=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const r=a(e,t[0],n,!0);return i||o[n].push({name:e,type:(r??e)+"[]"}),r?r+"[]":void 0}if("object"==typeof t&&null!==t){if(o[e])throw new I(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return o[e]=[],Object.entries(t).forEach(([t,o])=>{a(t,o,e)}),i||o[n].push({name:e,type:e}),e}{let a;switch(typeof t){case"string":a="string";break;case"number":a="uint256";break;case"boolean":a="bool";break;default:throw new I(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return i||o[n].push({name:e,type:a}),a}}};return Object.entries(n).forEach(([t,o])=>{a(t,o,e)}),this.logger.debug("📝 Generated EIP-712 types:",o),o}}class xn extends vo{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),o=this.createTokenInstance(t),n=this.createGalaInstance(),a=`$service$${o.toStringKey()}$launchpad`,i=`$tokenBalance$${o.toStringKey()}$${e}`,r=`$tokenBalance$${o.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,c=[a,i,r,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=Bo(e);throw new I(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new r.TokenClassKey;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new r.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!e||"string"!=typeof e)throw _("vaultAddress","Vault address");try{const t=hn(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof I)throw R("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!e||"string"!=typeof e)throw _("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw R("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw R("vaultAddress",'ending with "$launchpad"');const t=e.split("$");if(t.length<5)throw R("vaultAddress",'having at least 5 parts separated by "$"');const o=t[2];if(!o||!/^[A-Za-z]{1,10}$/.test(o))throw R("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,o,n){return`${e}$${t}$${o}$${n}`}parseTokenClassKeyString(e){try{return rn(e)}catch(e){if(e instanceof I)throw R("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Fn(e,t,o){if(t<0||t>1)throw new Error(`Invalid slippage tolerance factor: ${t}. Must be between 0 and 1 (e.g., 0.05 for 5%)`);const n=new a(e);if(n.isNaN())throw new Error(`Invalid expected amount: ${e}. Must be a valid number`);if(0===t)return e;const i=n.multipliedBy(t);let r;switch(o){case"buy-native":case"sell-exact":r=n.minus(i);break;case"buy-exact":case"sell-native":r=n.plus(i);break;default:throw new Error(`Unknown operation type: ${o}`)}return r.isLessThan(0)&&(r=new a(0)),r.toFixed()}class Dn extends ko{constructor(e,t,o=!1,n,a,i=.05,r=.01){super(e,o),this.tokenResolver=t,this.walletProvider=n,this.userAddress=a,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=r,this.bundleEndpoint="/bundle",n&&a&&(this.signatureService=new Pn(n,o),this.tokenKeyService=new xn(o))}async submitTransaction(e){try{this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)}),this.validateBundleData(e);const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});const o=await this.http.post(this.bundleEndpoint,t);return o?(this.logger.debug("📥 Bundle API response:",{success:o.success,hasData:!!o.data,error:o.error}),this.handleBundleResponse(o)):{success:!1,error:"No response from bundle API"}}catch(e){return this.logger.error("❌ Bundle transaction submission failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}validateBundleData(e){if(!e)throw _("bundleData","Bundle data");if(!e.signedDto)throw _("signedDto","Signed DTO");if(!e.method||"string"!=typeof e.method)throw _("method","Method name");if(!Array.isArray(e.stringsInstructions))throw R("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new I("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw R("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new I(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!e.startsWith("$"))throw new I(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT")}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){if(e.data&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",e.data),{success:!0,data:e.data};const t=e.error||e.message||"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",t),{success:!1,error:t}}formatErrorMessage(e){if("string"==typeof e)return e;if(Uo(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 Bo(e)||"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!e||"string"!=typeof e)throw _("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 _("transactionId","Transaction ID");this.logger.debug("🚫 Cancelling transaction:",e);const t=await this.http.delete(`${this.bundleEndpoint}/${e}`);return t?(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t}):{success:!1,error:"No response from transaction cancellation"}}catch(e){return this.logger.error("❌ Failed to cancel transaction:",e),{success:!1,error:this.formatErrorMessage(e)}}}async getHealthStatus(){try{this.logger.debug("🏥 Checking bundle service health");const e=await this.http.get(`${this.bundleEndpoint}/health`);return e?(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e}):{success:!1,error:"No response from bundle service health check"}}catch(e){return this.logger.error("❌ Bundle service health check failed:",e),{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:o,type:n,expectedAmount:a}=e,{effectiveSlippageFactor:i,effectiveMaxFee:r,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===n){if(!a)throw new I("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Fn(a,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:a,slippageFactor:i,adjustedMinTokens:e});const t=new Nn.BuyNativeDto(s,o,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"BuyWithNative",s)}{if(!a)throw new I("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Fn(a,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:a,slippageFactor:i,adjustedMaxGalaCost:e});const t=new Nn.BuyExactDto(s,o,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"BuyExactToken",s)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:o,type:n,expectedAmount:a}=e,{effectiveSlippageFactor:i,effectiveMaxFee:r,vaultAddress:s}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===n){if(!a)throw new I("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Fn(a,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:a,slippageFactor:i,adjustedMinGala:e});const t=new Nn.SellExactDto(s,o,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"SellExactToken",s)}{if(!a)throw new I("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Fn(a,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:a,slippageFactor:i,adjustedMaxTokensToSell:e});const t=new Nn.SellNativeDto(s,o,e,{maxAcceptableReverseBondingCurveFee:r});return await this.executeBundleTransaction(t,"SellWithNative",s)}}async prepareTradingOperation(e,t,o,n){const{effectiveSlippageFactor:a,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,o,n),r=await this.resolveTokenNameToVault(e);if(!r)throw O(e);return{effectiveSlippageFactor:a,effectiveMaxFee:i,vaultAddress:r}}calculateEffectiveSlippage(e,t,o){const n=o??this.defaultSlippageToleranceFactor,a=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e||"0";return e&&(i=Fn(e,a,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:a,adjustedMaxFee:i})),{effectiveSlippageFactor:n,effectiveFeeSlippageFactor:a,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw M("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(!this.userAddress)throw _("userAddress","User address")}async executeBundleTransaction(e,t,o){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${s.v4()}-${Date.now()}-${this.userAddress}`;const n=await this.signatureService.signDTO(e,t,this.userAddress),a=this.tokenKeyService.generateStringsInstructions(o),i={stringsInstructions:a,method:t,signedDto:n};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:a,dtoKeys:Object.keys(n)});const r=await this.submitTransaction(i);if(r.success&&r.data)return this.logger.debug("✅ Bundle transaction submitted:",r.data),{success:!0,data:{transactionId:r.data,message:"Transaction submitted successfully. Monitor WebSocket for completion."}};throw new Error(String(r.error||"Bundle transaction failed"))}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}var Cn,$n;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Cn||(Cn={})),exports.SDKTransactionStatus=void 0,($n=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",$n.PROCESSING="processing",$n.COMPLETED="completed",$n.FAILED="failed",$n.TIMEOUT="timeout";const Ln={[Cn.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[Cn.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[Cn.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[Cn.FAILED]:exports.SDKTransactionStatus.FAILED,[Cn.ERROR]:exports.SDKTransactionStatus.FAILED,[Cn.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[Cn.PENDING]:exports.SDKTransactionStatus.PENDING};class Bn extends vo{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.reconnectCount=0,this.hasOnAnyListener=!1,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof c.io||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{try{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');return this.logger.error("❌ Socket.IO connection failed:",e.message),void t(e)}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=c.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts||5,reconnectionDelay:this.config.reconnectDelay||2e3}),this.socket.on("connect",()=>{this.logger.debug("✅ Socket.IO connected successfully:",this.socket?.id),this.logger.debug("📡 Connected to bundle backend WebSocket:",this.config.url),this.logger.debug("🔗 Ready to monitor transaction updates"),this.reconnectCount=0,e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const o=t[0],n=o.status||o.Status;if(n&&"string"==typeof n){if(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${n}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE){const e=this.eventBuffer.keys().next().value;if(e){const t=this.eventBufferTimeouts.get(e);t&&(clearTimeout(t),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e),this.logger.warn(`📡 [Event Buffer] Buffer full (${this.MAX_BUFFER_SIZE}), dropped oldest: ${e}`)}}this.eventBuffer.set(e,o);const t=this.eventBufferTimeouts.get(e);t&&clearTimeout(t);const a=setTimeout(()=>{this.eventBuffer.has(e)&&(this.logger.debug(`📡 [Event Buffer] Cleaning up orphaned event for ${e}`),this.eventBuffer.delete(e),this.eventBufferTimeouts.delete(e))},3e4);this.eventBufferTimeouts.set(e,a)}}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0}catch(e){t(e)}})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const o=this.eventBuffer.get(e);if(o){this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,o,t)});const n=this.eventBufferTimeouts.get(e);n&&(clearTimeout(n),this.eventBufferTimeouts.delete(e)),this.eventBuffer.delete(e)}const n=this.config.timeout||3e5,a=setTimeout(()=>{if(this.listeners.has(e)){const o=Math.round(n/1e3),a={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${o} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${o}s)`),t(a),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},n);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,o=>{this.processTransactionEvent(e,o,t)});else{const o={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(o),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,o){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const n=t,a=n?.data,i=n?.status||n?.Status||a?.status||a?.Status;let r=n?.message||n?.Message||a?.message||a?.Message||n?.error||a?.error;r&&"string"==typeof r||(r=i===Cn.FAILED||i===Cn.ERROR?"Transaction failed - check transaction details":i===Cn.COMPLETED||i===Cn.PROCESSED||i===Cn.SUCCESS?"Transaction completed successfully":i?`Transaction status: ${i}`:"Unknown transaction status");const s=n?.blockHash||a?.blockHash,c=n?.gasUsed||a?.gasUsed,l=n?.Data||a?.Data,u={transactionId:e,status:this.mapSocketStatus(i),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}: ${i} -> ${u.status}`),this.logger.debug(`📡 Final message: "${r}"`),o(u),u.status===exports.SDKTransactionStatus.COMPLETED||u.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${u.status})`)}}async waitForTransaction(e){return new Promise((t,o)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||o(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Ln[t]||exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectCount<this.config.reconnectAttempts?(this.reconnectCount++,this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectCount}/${this.config.reconnectAttempts}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.config.reconnectDelay)):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.eventBufferTimeouts.forEach(e=>{clearTimeout(e)}),this.eventBufferTimeouts.clear(),this.logger.debug("🧹 Cleared event buffer and timeouts"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected"))}isConnected(){return this.socket?.connected||!1}getSocket(){return this.socket}}class Un extends vo{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!V(e))throw new I("Token name is required and must be a non-empty string","tokenName","INVALID_TOKEN_NAME");const t=e.trim().toLowerCase(),o=this.get(t);if(o)return o;try{const o=await this.poolService.resolveTokenNameToVault(e);return o&&this.set(t,o),o}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(!t)throw O(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(e.toLowerCase())||null}set(e,t){this.cache.set(e.toLowerCase(),t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}preWarm(e){for(const{tokenName:t,vaultAddress:o}of e)this.set(t,o)}parseVaultAddressToTokenClassKey(e){try{return un(e)}catch(e){if(e instanceof I)throw R("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}async function On(e,t={}){const{maxPages:o=1e4,logger:n,pageSize:a=20}=t,i=[];let r=1,s=!0,c=0;for(;s&&r<=o;){n&&n.debug(`Auto-pagination: fetching page ${r} with limit ${a}`);const t=await e(r,a);if(!t||!Array.isArray(t.items)){n&&n.warn("Auto-pagination: received invalid result structure, stopping");break}if(i.push(...t.items),c=t.total,n&&n.debug(`Auto-pagination: page ${r} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){n&&n.debug(`Auto-pagination: no items returned on page ${r}, exiting loop`);break}s=t.hasNext,r++}return r>o&&n&&n.warn(`Auto-pagination: exceeded maxPages limit of ${o}, stopping iteration`),n&&n.debug(`Auto-pagination: completed with total items: ${i.length}, total count: ${c}`),{items:i,total:c}}function _n(e,t=e.length,o="items"){return{...{page:1,limit:e.length||0,total:t,totalPages:Math.ceil(t/(e.length||1))||1,hasNext:!1,hasPrevious:!1},[o]:e}}class Rn extends ko{constructor(e,t=!1,o){super(e,t),this.tokenResolverService=o}async fetchTokenClassKeyByTokenName(e){if(!this.tokenResolverService)throw M("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 M("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 M(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const o=un(t),n=`${o.collection}|${o.category}|${o.type}|${o.additionalKey}`;return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(t instanceof Error&&t.message.includes("ConfigurationError"))throw t;throw q(`Failed to resolve token name '${e}': ${Bo(t)}`,500)}}async fetchPriceHistory(e){this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e);try{let t=e.tokenId;if(e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const o=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=o,this.logger.debug(`Resolved to token ID: ${o}`)}if(!t)throw M("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:o}=await Promise.resolve().then(function(){return pn}),n=o(t),a=an(`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`),{from:i,to:r,sortOrder:s="DESC",page:c=1,limit:l=10}=e,u={token:a,page:String(c),limit:String(l)};i&&(u.from=i.toISOString()),r&&(u.to=r.toISOString());const d=function(e){if(e)return e.toLowerCase()}(s);d&&(u.order=d),this.logger.debug(`Querying price snapshots for token ${a}, page ${c}, limit ${l}`);const h=await this.http.get("/price-oracle/fetch-price",u);if(!h)throw q("No response from price history service",500);const p=this.transformApiResponseToPriceHistory(h);return this.logger.debug(`Found ${p.snapshots.length} price snapshots, total ${p.total}`),p}catch(e){if(e instanceof Error&&(e.message.includes("ConfigurationError")||e.message.includes("NetworkError")))throw e;throw q(`Failed to fetch price history: ${Bo(e)}`,500)}}transformApiResponseToPriceHistory(e){if(!e?.data?.data||!Array.isArray(e.data.data))throw q("Invalid API response: missing or invalid data.data array",500);if(!e?.data?.meta)throw q("Invalid API response: missing data.meta pagination info",500);const t=e.data.data.map(e=>({price:e.price,timestamp:new Date(e.createdAt),tokenId:`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`})),o=e.data.meta,n=o.currentPage??1,a=o.totalPages??1;return{snapshots:t,page:n,limit:o.pageSize??50,total:o.totalItems??0,totalPages:a,hasNext:n<a,hasPrevious:n>1}}async fetchAllPriceHistory(e){this.logger.debug("Fetching all price history with options:",e);const t=await On((t,o)=>this.fetchPriceHistory({...e,page:t,limit:o}).then(e=>({items:e.snapshots,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:50});return _n(t.items,t.total,"snapshots")}validateOptions(e){const{from:t,to:o,sortOrder:n,page:a=1,limit:i=10}=e;if(function(e,t,o,n={}){const{description:a="parameter",treatEmptyAsNull:i=!0}=n,r=e[t],s=e[o],c=null!=r&&(!i||""!==r),l=null!=s&&(!i||""!==s);if(!c&&!l)throw M(`Either ${t} or ${o} must be provided (${a})`,o);if(c&&l)throw M(`Cannot provide both ${t} and ${o}. Provide exactly one (${a}).`,o)}(e,"tokenName","tokenId",{description:"token identifier"}),t&&!(t instanceof Date)&&isNaN(new Date(t).getTime()))throw M("from must be a valid Date","from");if(o&&!(o instanceof Date)&&isNaN(new Date(o).getTime()))throw M("to must be a valid Date","to");if(n&&"ASC"!==n&&"DESC"!==n)throw M('sortOrder must be either "ASC" or "DESC"',"sortOrder");if(!Number.isInteger(a)||a<1)throw M("page must be a positive integer","page");if(!Number.isInteger(i)||i<1||i>50)throw M("limit must be between 1 and 50","limit")}}function qn(e){if("object"==typeof e&&null!==e)return function(e){if(!e||"object"!=typeof e)throw new I("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:o,type:n,additionalKey:a}=e;if(!t||"string"!=typeof t)throw new I("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!o||"string"!=typeof o)throw new I("Token.category must be a non-empty string, got "+typeof o,"token.category","MISSING_OR_INVALID_CATEGORY");if(!n||"string"!=typeof n)throw new I("Token.type must be a non-empty string, got "+typeof n,"token.type","MISSING_OR_INVALID_TYPE");if(!a||"string"!=typeof a)throw new I("Token.additionalKey must be a non-empty string, got "+typeof a,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:o,type:n,additionalKey:a}}(e);if(!e)throw new I(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new I("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(e.includes("|"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected 4+ parts separated by |, got ${t.length}`);const[o,n,a,...i]=t;if(!o||!n||!a)throw new Error("Collection, category, and type must be non-empty");const r=i.join("|");if(!r)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:n,type:a,additionalKey:r}}catch(t){const o=e.split("|");throw new I(`Invalid pipe-delimited token: "${e}" (${o.length} parts). Expected format: "collection|category|type|additionalKey" (4 parts minimum). Received: [${o.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_PIPE_DELIMITED_TOKEN")}}(e);if(e.includes("$"))return function(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("$");if(t.length<4)throw new Error(`Invalid dollar-delimited token format. Expected 4+ parts separated by $, got ${t.length}`);const o=t[t.length-1],n=t[t.length-2],a=t[t.length-3],i=t.slice(0,t.length-3).join("$");if(!(i&&a&&n&&o))throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:a,type:n,additionalKey:o}}catch(t){const o=e.split("$");throw new I(`Invalid dollar-delimited token: "${e}" (${o.length} parts). Expected format: "collection$category$type$additionalKey" (4 parts minimum). Received: [${o.map(e=>`"${e}"`).join(", ")}]. Error: ${t instanceof Error?t.message:String(t)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e);throw new I(`Plain token string "${e}" (length: ${e.length}) is not allowed - tokens must be delimited with | or $. Expected format: "GALA|Unit|none|none" or "GALA$Unit$none$none". Input: "${e}"`,"token","PLAIN_STRING_NOT_ALLOWED")}class Mn extends Error{constructor(e,t,o){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=o,this.name="ApiError"}}function Gn(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 Kn{constructor(t){this.client=e.create({baseURL:t.baseUrl,timeout:t.timeout??3e4})}async getPoolData(e){try{const o=await this.client.post("/api/asset/dexv3-contract/GetPoolData",e);this.validateResponse(o.data);const n=o.data.Data;if(!("object"==typeof(t=n)&&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 Mn(o.status,"Invalid pool data response format",n);return n}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 o=t.data.Data;if(!Array.isArray(o.positions))throw new Mn(t.status,"Invalid positions response format: positions must be an array",o);for(const e of o.positions)if(!Gn(e))throw new Mn(t.status,"Invalid position in response",e);return o}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 o=t.data.Data;if(!Array.isArray(o.positions)||0===o.positions.length)throw new Mn(404,`Position not found: ${e}`);const n={Data:o.positions[0],Status:t.status};return void 0!==t.data.Message&&(n.Message=t.data.Message),n}catch(t){throw this.handleError(t,`getPositionById(${e})`)}}async getRemoveLiquidityEstimation(e){try{const t=await this.client.post("/api/asset/dexv3-contract/GetRemoveLiquidityEstimation",e);this.validateResponse(t.data);const o=t.data.Data;if("string"!=typeof o.amount0||"string"!=typeof o.amount1||"string"!=typeof o.fee0||"string"!=typeof o.fee1)throw new Mn(t.status,"Invalid removal estimation response format",o);return o}catch(e){throw this.handleError(e,"getRemoveLiquidityEstimation")}}validateResponse(e){if(!e||"object"!=typeof e)throw new Mn(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new Mn(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new Mn(e.Status,e.Message??"Gateway error",e.Data)}handleError(t,o){if(t instanceof Mn)return t;if(e.isAxiosError(t)){const e=t.response?.status??500,n=t.response?.data?.Message??t.message,a=t.response?.data?.Data??void 0;return new Mn(e,`${o}: ${n}`,a)}return new Mn(500,`${o}: ${t instanceof Error?t.message:String(t)}`)}}class zn{constructor(e){this.http=e}async getUserAssets(e,t=20,o=0){try{if(!e||"string"!=typeof e)throw new Mn(400,"Invalid wallet address");const n=Math.max(1,Math.floor(o/t)+1),a={};a.address=e,a.page=n,a.limit=t;const i=await this.http.get("/user/assets",a);if(!i||"object"!=typeof i)throw new Mn(500,"Invalid response format: not an object");const r=i.data;if(!r||"object"!=typeof r)throw new Mn(500,"Invalid response format: missing data wrapper");const s=r.token;if(!Array.isArray(s))throw new Mn(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 Mn(500,"Invalid asset in response: asset must be an object");const t=e;if("string"!=typeof t.symbol||"string"!=typeof t.name)throw new Mn(500,"Invalid asset in response: missing symbol or name",t);const o="number"==typeof t.decimals?t.decimals:"string"==typeof t.decimals?parseInt(t.decimals,10):void 0;if("number"!=typeof o||isNaN(o))throw new Mn(500,"Invalid asset in response: decimals must be a number",t);const n={tokenId:t.compositeKey||`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:o,balance:t.quantity||"0"};t.image&&(n.imageUrl=t.image),t.verify&&(n.verified=t.verify),c.push(n)}const l={tokens:c,count: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 Mn)return e;if(e instanceof Error&&e instanceof Error&&"response"in e){const o=e,n=o.response?.status??500,a=o.response?.data?.message??o.response?.data?.Message??o.message,i=o.response?.data?.Data??o.response?.data?.data??void 0;return o.response,new Mn(n,`${t}: ${a}`,i)}return new Mn(500,`${t}: ${e instanceof Error?e.message:String(e)}`)}}const Vn=10;class Wn extends vo{constructor(e,t,o){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new nn,this.webSocketService=t,this.dexQuoteService=o,this.getWalletAddress=e.getWalletAddress,this.galaChainBaseUrl=e.galaChainBaseUrl,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.privateKey=e.privateKey,!(e.gatewayBaseUrl&&e.bundlerBaseUrl&&e.dexBackendBaseUrl&&e.dexBackendHttp))throw new Error("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.");try{this.gatewayClient=new Kn({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new zn(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{gatewayUrl:e.gatewayBaseUrl,dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new Error("Failed to initialize GSwapService HTTP clients")}}setPricingConcurrency(e){if(e<1)throw new Error("Pricing concurrency must be at least 1");e>100&&this.logger.warn("Pricing concurrency > 100 may cause performance issues",{concurrency:e}),this.pricingConcurrency=e,this.logger.debug("Updated pricing concurrency",{concurrency:this.pricingConcurrency})}async getSwapQuoteExactInput(e){try{if(new a(e.amount).isLessThanOrEqualTo(0))throw new F("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new F("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),o=this.tokenConverter.toLaunchpadFormat(e.toToken),n=[3e3,500,1e4];let i;for(const r of n)try{const n=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:o,fee:r,gatewayBaseUrl:this.gatewayBaseUrl}),i=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:n,fromToken:t,toToken:o,amount:e.amount}),s=new a(i.currentSqrtPrice),c=new a(i.newSqrtPrice),l=s.gt(c)?s.minus(c).dividedBy(s):new a(0),u=new a(i.amount0),d=new a(i.amount1),h=String(i.amount0),p=String(i.amount1),g=u.isNegative(),m=d.isNegative();this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":h,"quoteResult.amount1":p,"amount0BN.isNegative()":g,"amount1BN.isNegative()":m,"amount0BN.toFixed()":u.toFixed(),"amount1BN.toFixed()":d.toFixed(),"amount0BN.s (sign flag)":u.s,"amount1BN.s (sign flag)":d.s});const f=g?m?u:d:u;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:!g,selectedAmount:f.toFixed(),selectedAmountAbs:f.absoluteValue().toFixed()});const y=f.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:y,feeTier:r,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,y),currentSqrtPrice:i.currentSqrtPrice,newSqrtPrice:i.newSqrtPrice}}catch(e){i=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:r,error:e?.message})}throw i||new F("No available fee tiers for quote",{feeTiers:n,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",F,e)}}async getSwapQuoteExactOutput(e){try{if(new a(e.amount).isLessThanOrEqualTo(0))throw new F("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new F("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact output",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),o=this.tokenConverter.toLaunchpadFormat(e.toToken),n=[3e3,500,1e4];let i;for(const r of n)try{const n=await this.dexQuoteService.fetchCompositePoolData({token0:t,token1:o,fee:r,gatewayBaseUrl:this.gatewayBaseUrl}),i=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:n,fromToken:t,toToken:o,amount:e.amount}),s=new a(i.currentSqrtPrice),c=new a(i.newSqrtPrice),l=s.gt(c)?s.minus(c).dividedBy(s):new a(0),u=n.pool.token0,d="string"==typeof u?u.split("|")[0]:u?.tokenName||u,h=o.split("|")[0]===d?i.amount1:i.amount0,p=h.toFixed?.()||String(h);return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:p,estimatedOutput:e.amount,feeTier:r,priceImpact:l.toFixed(),executionPrice:this.calculateExecutionPrice(p,e.amount),currentSqrtPrice:i.currentSqrtPrice,newSqrtPrice:i.newSqrtPrice}}catch(e){i=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:r,error:e?.message})}throw i||new F("No available fee tiers for quote",{feeTiers:n,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",F,e)}}async executeSwap(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");this.logger.debug("Executing swap",{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount});const{gswapToken0:t,gswapToken1:o}=this.convertTokenPair(e.fromToken,e.toToken),n=function(e,t=.01){const o=Xo(e),n=new a(1).minus(t);return o.multipliedBy(n)}(e.estimatedOutput,e.slippageTolerance||.01),i=this.getWalletAddress();if(!i)throw new Error("Wallet address required for swap execution");let r;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});r=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:r,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:t?.message})}const s={fromToken:t,toToken:o,inputAmount:e.inputAmount,minOutput:n.toFixed(),feeTier:e.feeTier,walletAddress:i,slippageTolerance:e.slippageTolerance||.01};void 0!==r&&(s.currentSqrtPrice=r);const c=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:c,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const l=await this.webSocketService.waitForTransaction(c);return{transactionId:l.transactionId,status:l.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance||.01,timestamp:new Date(l.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(c)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",D,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,o=20){try{this.logger.debug("Fetching user assets",{walletAddress:e,page:t,limit:o});const n=await this.dexBackendClient.getUserAssets(e,o,(t-1)*o);return(Array.isArray(n)?n:n?.tokens||[]).map(e=>{const t=e.symbol||"UNKNOWN";try{return{tokenId:qn(`${t}|Unit|none|none`),symbol:t,balance:(o=e.quantity||e.balance||0,void 0!==n?Xo(o).toFixed(n):Xo(o).toFixed()),decimals:e.decimals||18}}catch(o){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:o instanceof Error?o.message:String(o),assetData:{symbol:t,quantity:e.quantity,balance:e.balance,decimals:e.decimals}}),null}var o,n}).filter(e=>null!==e)}catch(n){this.handleGSwapError("Failed to fetch user assets",$,n,{walletAddress:e,page:t,limit:o})}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets (auto-paginated)",{walletAddress:e});const t=await On((t,o)=>this.getUserAssets(e,t,o).then(e=>({items:e,page:t,limit:o,total:e.length,totalPages:1,hasNext:e.length===o,hasPrevious:t>1})),{maxPages:1e4,logger:this.logger,pageSize:20});return this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:t.items.length}),t.items}catch(t){this.handleGSwapError("Failed to fetch all user assets",$,t,{walletAddress:e})}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:o,gswapToken1:n}=this.convertTokenPair(e,t),i=[500,3e3,1e4];let r=new a(0),s=0;for(const c of i)try{const e=await this.gatewayClient.getPoolData({tokenA:o,tokenB:n,feeTier:c});e&&(r=r.plus(new a(e.liquidity||0)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:c})}return{tokenA:e,tokenB:t,liquidity:r.toFixed(),feeTiers:i,swapCount:s}}catch(o){this.logger.warn("Failed to fetch pool info",o);const n=o;return this.logger.debug("Pool error details",{error:new C(`Failed to fetch pool info: ${n?.message||String(o)}`,o,e,t,this.extractGSwapErrorCode(o))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const o=[];for(let n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const o=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;o.has(e)||o.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const n=Array.from(o.values()),a=this.chunkArray(n,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:o.size,chunks:a.length,concurrency:t});const i=new Map;for(let e=0;e<a.length;e++){const t=a[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?i.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return i}normalizePositionResponse(e,t){const o=e=>{if(!e)return"";if("string"==typeof e)return e;if("object"==typeof e){if(e.type&&"none"!==e.type)return e.type;if(e.collection)return e.collection;if(e.symbol)return e.symbol;if(e.tokenSymbol)return e.tokenSymbol;if(e.name)return e.name}return""};return{positionId:e.positionId||e.id||"",ownerAddress:t||e.ownerAddress||e.owner||"",token0:e.token0Symbol||o(e.token0)||o(e.tokenA)||e.tokenSymbol0||"",token1:e.token1Symbol||o(e.token1)||o(e.tokenB)||e.tokenSymbol1||"",feeTier:e.feeTier||e.fee||e.feeAmount||0,tickLower:e.tickLower||e.lowerTick||0,tickUpper:e.tickUpper||e.upperTick||0,liquidity:String(e.liquidity||e.liquidityAmount||"0"),amount0:String(e.amount0||e.amountA||"0"),amount1:String(e.amount1||e.amountB||"0"),feeAmount0:String(e.feeAmount0||e.feesA||"0"),feeAmount1:String(e.feeAmount1||e.feesB||"0"),...e.createdAt&&{createdAt:new Date(e.createdAt)},...e.updatedAt&&{updatedAt:new Date(e.updatedAt)}}}parseTokenFlexible(e){try{return qn(e)}catch(t){if(t instanceof Error&&t.message?.includes("Plain token string"))return this.logger.debug("Using default TokenClassKey for simple token symbol",{token:e}),{collection:"Token",category:"Unit",type:e,additionalKey:"none"};throw t}}async getUserLiquidityPositions(t,o=10,n,a){try{this.logger.debug("Fetching user liquidity positions",{ownerAddress:t,limit:o,bookmark:n});const i=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,r={user:t,limit:o,bookmark:n||""};this.logger.debug("Sending position query request",{endpoint:i,payload:r});const s=await e.post(i,r,{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==s.status||1!==s.data?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:s.status,apiStatus:s.data?.Status}),{items:[]};const c=s.data.Data||{},l=c.positions||[],u=c.nextBookMark,d=l.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(e=>this.normalizePositionResponse(e,t));let h;this.logger.debug("Retrieved liquidity positions",{count:d.length,hasNextBookmark:!!u,nextBookmark:u}),a?.withPrices&&d.length>0&&(h=await this.fetchPositionPrices(d));const p={items:d};return void 0!==u&&(p.nextBookmark=u),void 0!==h&&(p.prices=h),p}catch(e){if(e&&"object"==typeof e&&"response"in e){const o=e;this.logger.error("Position query failed with HTTP error",{status:o.response?.status,statusText:o.response?.statusText,data:o.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:t})}this.handleGSwapError("Failed to fetch user liquidity positions",L,e)}}async getAllSwapUserLiquidityPositions(e,t){try{this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const o=async t=>{const o=await this.getUserLiquidityPositions(e,Vn,t,void 0);return{items:o.items,nextBookmark:o.nextBookmark}},n=await async function(e,t={}){const{maxPages:o=1e4,logger:n,pageSize:a=20}=t,i=[];let r,s=0;for(;s<o;){n&&n.debug(`Auto-pagination (bookmark): fetching page ${s+1} with pageSize ${a}`,{bookmark:r});const t=await e(r,a);let o,c,l;if(Array.isArray(t))o=t,c=void 0,l=!1;else{if(!t||"object"!=typeof t||!("items"in t)){n&&n.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}o=t.items,c=t.nextBookmark,l=!0}if(!Array.isArray(o)){n&&n.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===o.length){n&&n.debug(`Auto-pagination (bookmark): no items returned on page ${s+1}, exiting loop`);break}i.push(...o),s++,n&&n.debug(`Auto-pagination (bookmark): page ${s} returned ${o.length} items`,{hasNextBookmark:!!c,format:l?"BookmarkPaginationResult":"legacy-array"});const u=o.length<a;if(l&&(""===c||void 0===c)){n&&n.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(u){n&&n.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:o.length,pageSize:a,format:l?"BookmarkPaginationResult":"legacy-array"});break}r=c}return s>=o&&n&&n.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${o}, stopping iteration`),n&&n.debug(`Auto-pagination (bookmark): completed with total items: ${i.length}`,{pageCount:s}),{items:i,total:i.length}}(o,{maxPages:1e4,logger:this.logger,pageSize:Vn}),a=n.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:a.length}),t?.withPrices&&a.length>0){return{items:a,prices:await this.fetchPositionPrices(a)}}return a}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",L,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t});const{gswapToken0:o,gswapToken1:n}=this.convertTokenPair(t.token0,t.token1),a=(await this.gatewayClient.getPositions({owner:e,tokenA:o,tokenB:n,feeTier:t.fee})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!a||"object"!=typeof a||!("positionId"in a)&&!("id"in a))throw new Error("Invalid position data returned from API");const i=this.normalizePositionResponse(a,e);return this.logger.debug("Retrieved liquidity position",{positionId:i.positionId}),i}catch(e){this.handleGSwapError("Failed to fetch liquidity position",L,e)}}async getLiquidityPositionById(e,t){try{let o;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t});let n=null;const a=5,i=2e3;for(let e=1;e<=a;e++)try{if(o=(await this.gatewayClient.getPositionById(t)).Data,o&&"object"==typeof o&&("positionId"in o||"id"in o)){this.logger.debug("Successfully fetched position on attempt",{attempt:e,positionId:t});break}if(e<a){this.logger.warn("Position not yet indexed, retrying",{attempt:e,positionId:t,resultType:typeof o}),await new Promise(e=>setTimeout(e,i));continue}n=new Error("Position not found after retries")}catch(o){if(e<a){this.logger.warn("Error fetching position, retrying",{attempt:e,positionId:t,error:o instanceof Error?o.message:o}),await new Promise(e=>setTimeout(e,i));continue}n=o instanceof Error?o:new Error(String(o))}if(!o||"object"!=typeof o||!("positionId"in o)&&!("id"in o))throw this.logger.error("Invalid position data returned from API after retries",{positionId:t,resultType:typeof o,resultKeys:o?Object.keys(o):"null",resultValue:JSON.stringify(o),lastError:n?.message}),n||new Error("Invalid position data returned from API");const r=this.normalizePositionResponse(o,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",L,e)}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t="string"==typeof e.token0?this.parseTokenFlexible(e.token0):e.token0,o={token0:t,token1:"string"==typeof e.token1?this.parseTokenFlexible(e.token1):e.token1,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner},n=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetPositions`;this.logger.debug("Calling position endpoint via compound key",{url:n});const a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(o)});if(!a.ok){if(404===a.status)throw new Error("Position not found (HTTP 404): No position exists for this compound key");if(400===a.status)throw new Error("Invalid parameters (HTTP 400): Check token format, fee (500|3000|10000), and tick ranges");throw new Error(`HTTP ${a.status}: ${a.statusText}`)}const i=await a.json();if(1!==i.Status||!i.Data)throw new Error(`Position not found: ${i.Message||"API returned no position data"}`);const r=this.normalizePositionResponse(i.Data,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:r.positionId,token0:r.token0,token1:r.token1}),r}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",L,e)}}async estimateRemoveLiquidity(e){try{this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1});const{gswapToken0:t,gswapToken1:o}=this.convertTokenPair(e.token0,e.token1),n=await this.gatewayClient.getRemoveLiquidityEstimation({tokenA:t,tokenB:o,fee:e.fee,liquidity:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper});return this.logger.debug("Estimated removal",{result:n}),n}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",L,e)}}async addLiquidityByPrice(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const{gswapToken0:t,gswapToken1:o}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected(),this.logger.debug("Converting price range to ticks",{token0:e.token0,token1:e.token1,minPrice:e.minPrice,maxPrice:e.maxPrice,fee:e.fee});const n=(await this.gatewayClient.getPoolData({tokenA:t,tokenB:o,feeTier:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:n,fee:e.fee});const i=new a(e.minPrice),r=new a(e.maxPrice),s=Math.floor(Yo(i)),c=Math.ceil(Yo(r)),l=Math.floor(s/n)*n,u=Math.ceil(c/n)*n;this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:l,tickUpper:u,tickSpacing:n});const d=this.getWalletAddress();if(!d)throw new Error("GSwapService: No wallet address available - cannot create position");const h="string"==typeof e.token0?qn(e.token0):e.token0,p="string"==typeof e.token1?qn(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${l}-${u}`,walletAddress:d});const g=await this.sendAddLiquidityToBundler({token0:h,token1:p,fee:e.fee,tickLower:l,tickUpper:u,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:d}),m={transactionId:g};if(m.positionId&&g){this.logger.debug("Position ID returned directly from backend",{transactionId:g,positionId:m.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(g);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:g,status:e.status});const t=this.getWalletAddress();if(t&&m.positionId)try{const o=await this.getLiquidityPositionById(t,m.positionId);return{...m,...o,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(g)}}}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(g)}}}}if(g){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:g}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(g);let o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:g,status:t.status});let n=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");const a=(await this.getUserLiquidityPositions(t,10)).items;if(a&&a.length>0){const t=e.token0.split("|")[0].toUpperCase(),i=e.token1.split("|")[0].toUpperCase(),r=[];for(const o of a){if(!o||!o.positionId)continue;const n=o.token0?.toUpperCase(),a=o.token1?.toUpperCase();if(!n||!a)continue;const s=n===t&&a===i||n===i&&a===t,c=o.feeTier===e.fee;s&&c&&r.push(o)}r.length>0&&(n=r[r.length-1],o=n.positionId,this.logger.debug("Found newly created position",{positionId:o,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:a.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:e instanceof Error?e.message:String(e)})}let a=n;if(o)try{a=await this.getLiquidityPositionById(d,o)}catch(e){}return{...m,...a,positionId:o,status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(g)}}}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",L,e)}}async addSwapLiquidityByTicks(e){try{if(!this.privateKey)throw new Error("GSwapService not initialized with signing capability (privateKey required)");const t=this.getWalletAddress();if(!t)throw new Error("GSwapService: No wallet address available - cannot create position");this.logger.debug("Adding liquidity by ticks with direct bundler",{token0:e.token0,token1:e.token1,fee:e.fee,walletAddress:t,tickRange:`${e.tickLower}-${e.tickUpper}`});const o="string"==typeof e.token0?qn(e.token0):e.token0,n="string"==typeof e.token1?qn(e.token1):e.token1;await this.ensureWebSocketConnected();const a=await this.sendAddLiquidityToBundler({token0:o,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min||"0",amount1Min:e.amount1Min||"0",owner:t});this.logger.info("Liquidity transaction submitted to bundler",{transactionId:a});const i=this.webSocketService.waitForTransaction(a),r={transactionId:a};if(r.positionId&&a){this.logger.info("Position ID returned directly from backend",{transactionId:a,positionId:r.positionId});const e=await i;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:a,status:e.status});const t=this.getWalletAddress();if(t&&r.positionId)try{this.logger.debug("Fetching full position details",{positionId:r.positionId});const o=await this.getLiquidityPositionById(t,r.positionId);return this.logger.debug("Fetched full position data",{positionId:o.positionId,liquidity:o.liquidity,amount0:o.amount0,amount1:o.amount1}),{...r,...o,positionId:r.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:r.positionId,error:t instanceof Error?t.message:String(t)}),{...r,positionId:r.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}}if(a){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:a});const o=await i;let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:a,status:o.status});let s=null;const c="string"==typeof e.token0?e.token0:e.token0.type,l="string"==typeof e.token1?e.token1:e.token1.type;this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:l,fee:e.fee});try{const t=this.getWalletAddress();if(!t)throw new Error("No wallet address available");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:Vn});const o=3,a=5e3,i=3e3;let r=[];for(let c=1;c<=o;c++){const l=1===c?a:i;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:o,delayMs:l}),await new Promise(e=>setTimeout(e,l)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:Vn});if(r=(await this.getUserLiquidityPositions(t,Vn)).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(),o=("string"==typeof e.token1?e.token1.split("|")[0]:e.token1.collection).toUpperCase(),a=[];for(const n of r){if(!n||!n.positionId)continue;const i=n.token0?.toUpperCase(),r=n.token1?.toUpperCase();if(!i||!r){this.logger.debug("Skipping position with empty tokens",{positionId:n.positionId});continue}const s=i===t&&r===o||i===o&&r===t,c=n.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:n.positionId,tokens:`${i}/${r}`,tokensMatch:s,fee:n.feeTier,feeMatches:c}),s&&c&&a.push(n)}if(a.length>0){s=a[a.length-1],n=s.positionId,this.logger.info("Found newly created position",{positionId:n,liquidity:s.liquidity,amount0:s.amount0,amount1:s.amount1,fee:s.feeTier}),this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount: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:n||"not found",found:!!n}),this.logger.debug("Matched position data",{positionId:s?.positionId,liquidity:s?.liquidity,amount0:s?.amount0,amount1:s?.amount1,feeAmount0:s?.feeAmount0,feeAmount1:s?.feeAmount1,token0:s?.token0,token1:s?.token1,feeTier:s?.feeTier});let u=s;if(n)try{this.logger.debug("Fetching full position details",{positionId:n}),u=await this.getLiquidityPositionById(t,n),this.logger.debug("Fetched full position data",{positionId:u.positionId,liquidity:u.liquidity,amount0:u.amount0,amount1:u.amount1,feeAmount0:u.feeAmount0,feeAmount1:u.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:n,error:e instanceof Error?e.message:String(e)})}return{...r,...u,positionId:n,status:o.status,transactionId:o.transactionId,timestamp:new Date(o.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),{...r,positionId:void 0}}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",L,e)}}async monitorBundlerTransaction(e,t,o="bundler"){let n;try{n=await t,this.logger.debug(`${o} transaction confirmed on-chain`,{transactionId:e,status:n.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${o} transaction, returning result with transaction ID`,{transactionId:e,error:t instanceof Error?t.message:String(t)}),{transactionId:e,status:"SUBMITTED",timestamp:new Date,wait:async t=>{try{await this.webSocketService.waitForTransaction(e)}catch{this.logger.debug("Explicit wait also timed out",{transactionId:e})}}}}return{transactionId:n.transactionId,status:n.status,timestamp:new Date(n.timestamp),wait:async t=>{await this.webSocketService.waitForTransaction(e)}}}async removeLiquidity(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});try{const t=parseFloat(e.liquidity);if(isNaN(t))throw new Error(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${e.positionId||"unknown"}`);if(0===t)throw new Error(`Cannot remove zero liquidity from position. This would waste gas fees without any effect. Position ID: ${e.positionId||"unknown"}`)}catch(e){if(e instanceof Error&&e.message.includes("Cannot remove zero liquidity"))throw e;if(e instanceof Error&&e.message.includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?qn(e.token0):e.token0,o="string"==typeof e.token1?qn(e.token1):e.token1;await this.ensureWebSocketConnected();const n=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,o,e.fee,e.amount0Min||"0",e.amount1Min||"0",e.positionId||"");this.logger.debug("Liquidity removal submitted to bundler",{transactionId:n});const a=this.webSocketService.waitForTransaction(n);return this.monitorBundlerTransaction(n,a,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",L,e)}}async collectPositionFees(e){try{if(!this.privateKey)throw new Error("Private key not available for bundler-direct operations");this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0.type,token1:"string"==typeof e.token1?e.token1:e.token1.type,tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?qn(e.token0):e.token0,o="string"==typeof e.token1?qn(e.token1):e.token1;await this.ensureWebSocketConnected();const n=await this.sendCollectPositionFeesToBundler(t,o,e.fee,e.amount0Requested||"0",e.amount1Requested||"0",e.tickLower,e.tickUpper,e.positionId||"");this.logger.debug("Fee collection submitted to bundler",{transactionId:n});const a=this.webSocketService.waitForTransaction(n);return this.monitorBundlerTransaction(n,a,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",L,e)}}async getPoolData(e,t,o){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:o});const{gswapToken0:n,gswapToken1:i}=this.convertTokenPair(e,t),r=await this.gatewayClient.getPoolData({tokenA:n,tokenB:i,feeTier:o}),s=this.calculatePriceFromSqrtPriceX96(new a(r.sqrtPriceX96));return{tokenA:e,tokenB:t,feeTier:o,liquidity:r.liquidity.toString(),sqrtPriceX96:r.sqrtPriceX96.toString(),tick:r.tick,feeGrowthGlobal0X128:r.feeGrowthGlobal0X128.toString(),feeGrowthGlobal1X128:r.feeGrowthGlobal1X128.toString(),currentPrice:s.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",C,e)}}async calculateDexPoolSpotPrice(e,t,o){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:o});const n=await this.getPoolData(e,t,o),a=Xo(n.currentPrice);return{tokenA:e,tokenB:t,feeTier:o,price:a.toFixed(),invertedPrice:Jo(a,!0),tick:n.tick,liquidity:n.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",C,e)}}async calculateOptimalPositionSize(e,t,o,n,r,s,c){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:n,desiredAmount1:r});const l=(await this.getPoolData(e,t,o)).tick,u=i.tickToSqrtPrice(s),d=i.tickToSqrtPrice(l),h=i.tickToSqrtPrice(c),p=i.getLiquidityForAmounts(new a(n),new a(r),u,d,h),g=i.getAmountsForLiquidity(p,d,u,h),m=g[0],f=g[1],y=new a(n),w=new a(r);return{amount0:m.toFixed(),amount1:f.toFixed(),liquidity:p.toFixed(),ratio:m.dividedBy(f).toFixed(),utilizationPercent:{amount0:m.dividedBy(y).multipliedBy(100).toFixed(2),amount1:f.dividedBy(w).multipliedBy(100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",L,e)}}async validatePositionParameters(e,t,o,n,i,r,s){const c=[],l=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:n,tickUpper:i});const u=[500,3e3,1e4];u.includes(o)||c.push(`Invalid fee tier: ${o}. Must be one of: ${u.join(", ")}`);const d=this.getTickSpacing(o);let h;n%d!==0&&c.push(`tickLower must be multiple of ${d}`),i%d!==0&&c.push(`tickUpper must be multiple of ${d}`),n>=i&&c.push(`tickLower (${n}) must be less than tickUpper (${i})`);try{h=await this.getPoolData(e,t,o)}catch{return c.push(`Pool not found for ${e}/${t} at fee tier ${o}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}const p=new a(r),g=new a(s);if(p.isNaN()||g.isNaN())c.push("Amounts must be valid numbers");else try{en(p,g)}catch(e){c.push(`Liquidity amounts must be non-negative: ${e.message}`)}const m=h.tick;(m<n||m>i)&&l.push("Position is out of current price range - will not earn fees until price moves into range");new a(h.liquidity).lt("1000000")&&l.push("Low pool liquidity - consider higher slippage tolerance");const f=0===c.length?35e4:0;return{valid:0===c.length,errors:c,warnings:l,gasEstimate:f,tickSpacing:d,currentTick:m,poolLiquidity:h.liquidity}}catch(e){const t=e;return c.includes(t?.message||"")||c.push(`Validation failed: ${t?.message||String(e)}`),{valid:!1,errors:c,warnings:l,gasEstimate:0}}}async calculateTicksForPrice(e,t,o,n,i){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:o,maxPrice:n});const r=this.getTickSpacing(i),s=new a(o),c=new a(n);if(s.gte(c))throw new Error("minPrice must be less than maxPrice");const l=Math.floor(Yo(s)),u=Math.ceil(Yo(c)),d=Math.floor(l/r)*r,h=Math.ceil(u/r)*r,p=Math.pow(1.0001,d),g=Math.pow(1.0001,h),m=new a(p),f=new a(g);return{tokenA:e,tokenB:t,feeTier:i,tickLower:d,tickUpper:h,tickSpacing:r,requestedMinPrice:o,requestedMaxPrice:n,actualMinPrice:m.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:m.minus(s).dividedBy(s).multipliedBy(100).toFixed(4),maxPriceDeviation:f.minus(c).dividedBy(c).multipliedBy(100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",L,e)}}async calculatePriceForTicks(e,t,o,n){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:o,tickUpper:n});const i=Math.pow(1.0001,o),r=Math.pow(1.0001,n);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const c=new a(i),l=new a(r);return{tokenA:e,tokenB:t,tickLower:o,tickUpper:n,minPrice:c.toFixed(8),maxPrice:l.toFixed(8),currentPrice:s,priceRange:`${c.toFixed(4)} - ${l.toFixed(4)}`,tickSpread:n-o}}catch(e){this.handleGSwapError("Failed to calculate price for ticks",L,e)}}calculateExecutionPrice(e,t){try{const o=new a(e),n=new a(t);return o.isZero()?"0":n.dividedBy(o).toFixed()}catch{return"0"}}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw new Error(`Invalid fee tier: ${e}`)}}calculatePriceFromSqrtPriceX96(e){try{const t=new a(2).pow(96);return e.dividedBy(t).pow(2)}catch{return new a(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return new a(0)}}async getPoolSlot0(t,o,n){try{this.logger.debug("Fetching pool slot0 data",{token0:t,token1:o,fee:n});const a="string"==typeof t?qn(t):t,i="string"==typeof o?qn(o):o,r=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetSlot0`,s=await e.post(r,{token0:a,token1:i,fee:n},{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(200!==s.status||1!==s.data?.Status)throw this.logger.warn("Unexpected GetSlot0 API response",{httpStatus:s.status,apiStatus:s.data?.Status}),new C("GetSlot0 API returned unexpected status",{httpStatus:s.status,apiStatus:s.data?.Status});const c=s.data.Data||{},l={sqrtPrice:c.sqrtPrice||"0",tick:c.tick||0,liquidity:c.liquidity||"0",grossPoolLiquidity:c.grossPoolLiquidity||"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:l.sqrtPrice,tick:l.tick,liquidity:l.liquidity}),l}catch(e){this.handleGSwapError("Failed to fetch pool slot0 data",C,e,{token0:t,token1:o,fee:n})}}async getPositionCurrentPrice(e){try{this.logger.debug("Fetching position current price",{token0:e.token0,token1:e.token1,feeTier:e.feeTier});const t=await this.getPoolSlot0(e.token0,e.token1,e.feeTier),o=new a(t.sqrtPrice),n={price:this.calculatePriceFromSqrtPriceDecimal(o).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:n.price,tick:n.tick}),n}catch(t){this.handleGSwapError("Failed to fetch position current price",C,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,o){try{const n=Zo(t),a=Zo(o);return i.liquidity0(e,n,a)}catch{return new a(0)}}calculateLiquidityFromAmount1(e,t,o){try{const n=Zo(t),a=Zo(o);return i.liquidity1(e,n,a)}catch{return new a(0)}}calculateAmount0FromLiquidity(e,t,o){try{const n=Zo(t),a=Zo(o);return i.getAmount0Delta(n,a,e)}catch{return new a(0)}}calculateAmount1FromLiquidity(e,t,o){try{const n=Zo(t),a=Zo(o);return i.getAmount1Delta(n,a,e)}catch{return new a(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(o){if(!this.privateKey)throw new Error("GSwapService: AddLiquidity requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:o.token0.type,token1:o.token1.type,fee:o.fee,tickRange:`${o.tickLower}-${o.tickUpper}`});const n=`galaswap - operation - ${s.v4()}-${Date.now()}-${o.owner}`,a={token0:o.token0,token1:o.token1,fee:o.fee,owner:o.owner,tickLower:o.tickLower,tickUpper:o.tickUpper,amount0Desired:o.amount0Desired,amount1Desired:o.amount1Desired,amount0Min:o.amount0Min,amount1Min:o.amount1Min,positionId:"",uniqueKey:n},i=new t.ethers.Wallet(this.privateKey),r={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},c={name:"ethereum",chainId:1},l=this.calculatePersonalSignPrefix(a),u={...a,prefix:l},d=await i.signTypedData(c,r,u),h={...u,signature:d,types:r,domain:c};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:h.signature?.substring(0,20)+"...",prefix:h.prefix,tickLower:a.tickLower,tickUpper:a.tickUpper});const p=this.buildLiquidityStringsInstructions(o.token0,o.token1,o.fee,o.owner),g=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),m=await g.post("/bundle",{method:"AddLiquidity",signedDto:h,stringsInstructions:p}),f=m.data?.data||m.data?.transactionId||m.data?.id;if(!f)throw this.logger.error("Bundler response structure",{status:m.status,data:m.data,dataType:typeof m.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(m.data)}`);return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:f}),f}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(o,n,a,i,r,c,l,u,d){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const h=new t.ethers.Wallet(this.privateKey),p=await h.getAddress(),g=`galaswap - operation - ${s.v4()}-${Date.now()}-${p}`,m={tickLower:o,tickUpper:n,amount:a,token0:i,token1:r,fee:c,amount0Min:l,amount1Min:u,positionId:d,uniqueKey:g},f={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},y={name:"ethereum",chainId:1},w=this.calculatePersonalSignPrefix(m),k={...m,prefix:w},v=await h.signTypedData(y,f,k),T={...k,signature:v,types:f,domain:y},S=this.buildLiquidityStringsInstructions(i,r,c,p);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:o,tickUpper:n,amount:a,fee:c,positionId:d,transactionId:g});const A=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),b=await A.post("/bundle",{method:"RemoveLiquidity",signedDto:T,stringsInstructions:S}),E=b.data?.data||b.data?.transactionId||b.data?.id;if(!E)throw this.logger.error("Bundler response structure",{status:b.status,data:b.data,dataType:typeof b.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(b.data)}`);return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:E}),E}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(o,n,a,i,r,c,l,u){try{if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const d=new t.ethers.Wallet(this.privateKey),h=await d.getAddress(),p=`galaswap - operation - ${s.v4()}-${Date.now()}-${h}`,g={token0:o,token1:n,fee:a,amount0Requested:i,amount1Requested:r,tickLower:c,tickUpper:l,positionId:u,uniqueKey:p},m={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(g),w={...g,prefix:y},k=await d.signTypedData(f,m,w),v={...w,signature:k,types:m,domain:f},T=this.buildLiquidityStringsInstructions(o,n,a,h);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:a,amount0Requested:i,amount1Requested:r,tickLower:c,tickUpper:l,positionId:u,transactionId:p});const S=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),A=await S.post("/bundle",{method:"CollectPositionFees",signedDto:v,stringsInstructions:T}),b=A.data?.data||A.data?.transactionId||A.data?.id;if(!b)throw this.logger.error("Bundler response structure",{status:A.status,data:A.data,dataType:typeof A.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(A.data)}`);return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:b}),b}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(o){if(!this.privateKey)throw new Error("GSwapService: Swap requires wallet (full-access mode)");if(!this.bundlerBaseUrl)throw new Error("GSwapService: Bundler URL not configured");const n=[500,3e3,1e4];if(!n.includes(o.feeTier))throw new Error(`GSwapService: Invalid fee tier ${o.feeTier}. Must be one of: ${n.join(", ")} (basis points)`);try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof o.fromToken?o.fromToken:o.fromToken.type,toToken:"string"==typeof o.toToken?o.toToken:o.toToken.type,inputAmount:o.inputAmount,minOutput:o.minOutput,feeTier:o.feeTier});let n=o.fromToken,i=o.toToken;"string"==typeof n&&(n=qn(n)),"string"==typeof i&&(i=qn(i));const r=`${n.collection}|${n.category}|${n.type}|${n.additionalKey}`,c=`${i.collection}|${i.category}|${i.type}|${i.additionalKey}`,l=r<c?[n,i,r,c]:[i,n,c,r],[u,d,h,p]=l,g="string"==typeof o.fromToken?qn(o.fromToken):o.fromToken,m=`${g.collection}|${g.category}|${g.type}|${g.additionalKey}`,f=m===h,y=`galaswap - operation - ${s.v4()}-${Date.now()}-${o.walletAddress}`;let w;if(!o.currentSqrtPrice)throw new Error("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation");const k=new a(o.currentSqrtPrice);w=f?k.multipliedBy(.01).toString():k.multipliedBy(100).toString(),this.logger.debug("Using relative price bounds for sqrtPriceLimit",{currentSqrtPrice:o.currentSqrtPrice,zeroForOne:f,sqrtPriceLimit:w,direction:f?"token0→token1 (downward)":"token1→token0 (upward)",reason:"amountOutMinimum provides slippage protection, sqrtPriceLimit sets wide boundaries"});const v={token0:u,token1:d,fee:o.feeTier,amount:new a(o.inputAmount).toFixed(),zeroForOne:f,sqrtPriceLimit:w,recipient:o.walletAddress,amountOutMinimum:new a(o.minOutput).multipliedBy(-1).toFixed(),uniqueKey:y};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:h,orderedToken1String:p,fromTokenStr:m,zeroForOne:f?`TRUE (${h} → ${p})`:`FALSE (${p} → ${h})`,inputAmount:o.inputAmount,expectedOutput:o.minOutput,slippageTolerance:100*(o.slippageTolerance||.01)+"%",currentSqrtPrice:o.currentSqrtPrice,swapDto:{amount:v.amount,zeroForOne:v.zeroForOne,sqrtPriceLimit:v.sqrtPriceLimit,amountOutMinimum:v.amountOutMinimum}});const T=new t.ethers.Wallet(this.privateKey),S={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},A={name:"ethereum",chainId:1},b=this.calculatePersonalSignPrefix(v),E={...v,prefix:b},I=await T.signTypedData(A,S,E),N={...E,signature:I,types:S,domain:A};this.logger.debug("Swap DTO signed",{signature:N.signature?.substring(0,20)+"...",prefix:N.prefix,zeroForOne:v.zeroForOne});const P=this.buildLiquidityStringsInstructions(u,d,o.feeTier,o.walletAddress),x=e.create({baseURL:this.bundlerBaseUrl,timeout:3e4}),F=await x.post("/bundle",{method:"Swap",signedDto:N,stringsInstructions:P}),D=F.data?.data||F.data?.transactionId||F.data?.id;if(!D)throw this.logger.error("Bundler response structure",{status:F.status,data:F.data,dataType:typeof F.data}),new Error(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(F.data)}`);return this.logger.debug("Swap transaction sent to bundler",{transactionId:D,inputAmount:o.inputAmount,minOutput:o.minOutput}),D}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,o,n){const a=`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`,i=`$${t.collection}$${t.category}$${t.type}$${t.additionalKey}`,r=`$pool${a}${i}$${o}`;return[r,`$userPosition${n}`,`$tokenBalance${a}${n}`,`$tokenBalance${i}${n}`,`$tokenBalance${a}${r}`,`$tokenBalance${i}${r}`]}handleGSwapError(e,t,o,n){this.logger.error(e,o);const a=this.extractGSwapErrorCode(o),i=o,r=[`${e}: ${i?.message||String(o)}`,o];throw n&&("GSwapSwapError"===t.name&&n.transactionHash&&r.push(n.transactionHash),"GSwapPoolError"===t.name&&(n.tokenA&&r.push(n.tokenA),n.tokenB&&r.push(n.tokenB)),"GSwapAssetError"===t.name&&n.walletAddress&&r.push(n.walletAddress)),a&&r.push(a),new t(...r)}extractGSwapErrorCode(e){if(e&&"object"==typeof e){const t=e;if(t.constructor&&"GSwapSDKError"===t.constructor.name)return t.code;if("code"in t&&"string"==typeof t.code)return t.code}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}}class jn{}jn.BASE_PRICE=1650667151e-14,jn.PRICE_SCALING_FACTOR=1166069e-12,jn.TRADING_FEE_FACTOR=.001,jn.GAS_FEE="1",jn.MIN_UNBONDING_FEE_FACTOR=0,jn.MAX_UNBONDING_FEE_FACTOR=.5,jn.NET_UNBONDING_FEE_FACTOR=.5,jn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class Hn extends vo{constructor(e=!1){super(e),this.cache=new Map}getLRUKey(){const e=this.cache.keys().next().value;return void 0!==e?e:null}normalizeTokenName(e){return e.trim().toLowerCase().replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}updateCacheEntry(e,t){const o=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=Hn.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...o||{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const o=this.normalizeTokenName(e);this.updateCacheEntry(o,t)}set(e,t){const o=this.normalizeTokenName(e);this.updateCacheEntry(o,t)}get(e){const t=this.normalizeTokenName(e);return this.cache.get(t)||null}getMaxSupply(e){const t=this.normalizeTokenName(e),o=this.cache.get(t);return o?.maxSupply||jn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeTokenName(e);return this.cache.has(t)}clear(e){if(e){const t=this.normalizeTokenName(e);this.cache.delete(t)}else this.cache.clear()}dump(){const e={};return this.cache.forEach((t,o)=>{e[o]=t}),e}stats(){let e=Date.now(),t=0;return this.cache.forEach((o,n)=>{o.lastUpdated<e&&(e=o.lastUpdated);let a=0;a+=2*n.length,void 0!==o.reverseBondingCurveMinFeeFactor&&(a+=8),void 0!==o.reverseBondingCurveMaxFeeFactor&&(a+=8),void 0!==o.reverseBondingCurveNetFeeFactor&&(a+=8),a+=8,o.vaultAddress&&(a+=2*o.vaultAddress.length),o.maxSupply&&(a+=2*o.maxSupply.length),o.symbol&&(a+=2*o.symbol.length),a+=32,t+=a}),{totalTokens:this.cache.size,cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.get(t)||null}setByTokenId(e,t){const o=`token:${e.toLowerCase().trim()}`;this.updateCacheEntry(o,t)}hasByTokenId(e){const t=`token:${e.toLowerCase().trim()}`;return this.cache.has(t)}}Hn.MAX_CACHE_SIZE=1e4;class Qn extends ko{constructor(e,t,o=void 0,n=5,a=!1){super(e,a),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=o,this.pricingConcurrency=n}setGSwapService(e){this.gswapService=e}setPricingConcurrency(e){this.pricingConcurrency=Math.max(1,Math.min(e,20))}async enrichPoolsWithPricing(e){if(!this.gswapService)return this.logger.warn("GSwap service not available, skipping pricing enrichment"),e;if(0===e.length)return e;this.logger.debug("Starting pricing enrichment",{poolCount:e.length,concurrency:this.pricingConcurrency});const t=[];for(let o=0;o<e.length;o++){const n=e[o];t.push({poolIndex:o,token:n.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:n.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${n.token0}`,{error:e.message})})}),t.push({poolIndex:o,token:n.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:n.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${n.token1}`,{error:e.message})})})}const o=new Map;for(let t=0;t<e.length;t++)o.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const n=t.slice(e,e+this.pricingConcurrency),a=await Promise.allSettled(n.map(e=>e.task));for(let e=0;e<n.length;e++){const t=n[e],i=a[e],r=o.get(t.poolIndex)||{};"fulfilled"===i.status&&i.value&&(t.isToken0?r.token0Price=i.value:r.token1Price=i.value),o.set(t.poolIndex,r)}}const n=e.map((e,t)=>{const n=o.get(t)||{},a={...e};return void 0!==n.token0Price&&(a.token0Price=n.token0Price),void 0!==n.token1Price&&(a.token1Price=n.token1Price),a}),a=n.filter(e=>e.token0Price&&e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:a,failed:e.length-a}),n}async fetchDexPools(e={}){const{search:t,sortBy:o="tvl",sortOrder:n="desc",page:a=wo.DEFAULT_PAGE,limit:i=wo.DEFAULT_LIMIT,withPrices:r=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:o,sortOrder:n,page:a,limit:i,withPrices:r});const s=new URLSearchParams({page:a.toString(),limit:Math.min(i,20).toString(),sortBy:o,sortOrder:n});t&&s.append("search",t);const c=`${this.dexBackendBaseUrl}/explore/pools?${s}`;try{const e=await this.http.get(c);if(!e||!e.data)throw new Error("No response from DEX pool service");let t=e.data.pools;const o=e.data.count,n=Math.min(i,20),s=Math.ceil(o/n);return r&&(t=await this.enrichPoolsWithPricing(t)),this.logger.debug("DEX pools fetched successfully",{poolCount:t.length,total:o,totalPages:s,withPrices:r}),{pools:t,page:a,limit:n,total:o,totalPages:s,hasNext:a<s,hasPrevious:a>1}}catch(e){throw this.logger.error("Failed to fetch DEX pools",{error:e,url:c}),e}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=await On((t,o)=>this.fetchDexPools({...e,page:t,limit:o}).then(e=>({items:e.pools,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:20});return this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.items.length,totalCount:t.total,withPrices:e.withPrices}),_n(t.items,t.total,"pools")}}function Xn(e){try{if(!e||"string"!=typeof e)throw new Error("Token must be a non-empty string");const t=e.split("|");if(t.length<4)throw new Error(`Invalid pipe-delimited token format. Expected at least 4 parts separated by |, got ${t.length}`);const[o,n,a,...i]=t;if(!o||!n||!a)throw new Error("Collection, category, and type must be non-empty");const r=i.join("|");if(!r)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:n,type:a,additionalKey:r}}catch(t){throw new I(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${t instanceof Error?t.message:String(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}class Zn extends ko{constructor(e,t,o=!1,n=3e4){super(e,o),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=n}validateFetchCompositePoolDataInput(e,t,o){if(!e||"string"!=typeof e)throw new B("token0 must be a non-empty string",{token0:e});if(!t||"string"!=typeof t)throw new B("token1 must be a non-empty string",{token1:t});const n=e.split("|"),a=t.split("|");if(4!==n.length)throw new B("token0 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token0:e});if(4!==a.length)throw new B("token1 format must be: collection|category|type|additionalKey (4 pipe-separated parts)",{token1:t});const i=[500,3e3,1e4];if(!Number.isInteger(o)||!i.includes(o))throw new B(`fee must be one of: ${i.join(", ")} (got ${o})`,{fee:o})}validateQuoteAmount(e){if(!e||"string"!=typeof e)throw new B("amount must be a non-empty string",{amount:e});const t=new a(e);try{tn(t,"amount","for quote calculation")}catch(t){throw new B(t.message,{amount:e})}}convertTokenClassKey(e){const t=new r.TokenClassKey;return t.collection=e.collection,t.category=e.category,t.type=e.type,t.additionalKey=e.additionalKey,t}setCompositePoolFetchConcurrency(e){this.compositePoolFetchConcurrency=Math.max(1,Math.min(e,20)),this.logger.debug(`Composite pool fetch concurrency set to ${this.compositePoolFetchConcurrency}`)}async fetchCompositePoolData(e){const{token0:t,token1:o,fee:n,gatewayBaseUrl:s}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:o,fee:n}),this.validateFetchCompositePoolDataInput(t,o,n);try{const e=Xn(t),c=Xn(o),l=this.convertTokenClassKey(e),u=this.convertTokenClassKey(c),d=new i.GetCompositePoolDto(l,u,n),h=`${s||this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,p=await this.http.post(h,d);if(!p||1!==p.Status)throw new U(`Pool not found: ${t}/${o} with fee ${n}`);const g=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 i.Pool(e.pool.token0,e.pool.token1,e.pool.token0ClassKey,e.pool.token1ClassKey,e.pool.fee,new a(e.pool.sqrtPrice),e.pool.protocolFees);t.bitmap=e.pool.bitmap,t.grossPoolLiquidity=new a(e.pool.grossPoolLiquidity),t.liquidity=new a(e.pool.liquidity),t.feeGrowthGlobal0=new a(e.pool.feeGrowthGlobal0),t.feeGrowthGlobal1=new a(e.pool.feeGrowthGlobal1),t.protocolFeesToken0=new a(e.pool.protocolFeesToken0),t.protocolFeesToken1=new a(e.pool.protocolFeesToken1),t.tickSpacing=e.pool.tickSpacing,t.maxLiquidityPerTick=new a(e.pool.maxLiquidityPerTick);const o={};Object.keys(e.tickDataMap).forEach(t=>{const n=e.tickDataMap[t],r=new i.TickData(n.poolHash,n.tick);r.initialised=n.initialised,r.liquidityNet=new a(n.liquidityNet),r.liquidityGross=new a(n.liquidityGross),r.feeGrowthOutside0=new a(n.feeGrowthOutside0),r.feeGrowthOutside1=new a(n.feeGrowthOutside1),o[t]=r});const n={...e.token0Balance},s=new r.TokenBalance(n);s.quantity=new a(e.token0Balance.quantity);const c={...e.token1Balance},l=new r.TokenBalance(c);return l.quantity=new a(e.token1Balance.quantity),new i.CompositePoolDto(t,o,s,l,e.token0Decimals,e.token1Decimals)}(p.Data),p.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:o,fee:n,liquidity:g.pool.liquidity.toString()}),g}catch(e){if(e instanceof U)throw e;throw this.logger.error("Failed to fetch composite pool data",e),new B(`Failed to fetch composite pool data: ${e.message}`,{token0:t,token1:o,fee:n})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:o,toToken:n,amount:r}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:o,toToken:n,amount:r}),this.validateQuoteAmount(r),!t)throw new B("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=o===t.pool.token0,s=Xn(o),c=Xn(n),l=this.convertTokenClassKey(s),u=this.convertTokenClassKey(c),d=new i.QuoteExactAmountDto(l,u,t.pool.fee,new a(r),e,t.compositePoolDto),h=await i.quoteExactAmount(void 0,d);return this.logger.debug("Local quote calculated",{amount0:h.amount0,amount1:h.amount1}),{amount0:h.amount0.toString(),amount1:h.amount1.toString(),currentSqrtPrice:h.currentSqrtPrice.toString(),newSqrtPrice:h.newSqrtPrice.toString()}}catch(e){throw this.logger.error("Local quote calculation failed",e),new B(`Local quote calculation failed: ${e.message}`,{fromToken:o,toToken:n,amount:r})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:o,toToken:n,amount:r}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:o,toToken:n,amount:r}),this.validateQuoteAmount(r),!t)throw new B("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=o===t.pool.token0,s=Xn(o),c=Xn(n),l=this.convertTokenClassKey(s),u=this.convertTokenClassKey(c),d=new i.QuoteExactAmountDto(l,u,t.pool.fee,new a(r),e,void 0),h=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,p=await this.http.post(h,d);if(!p||1!==p.Status)throw new B("External quote failed: "+(p?.Message||"Unknown error"));const g=p.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 B(`External quote calculation failed: ${e.message}`,{fromToken:o,toToken:n,amount:r})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}function Yn(e){const t=function(e){const t=Nt(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 Jn="/api/asset/launchpad-contract/CallNativeTokenIn",ea="/api/asset/launchpad-contract/CallNativeTokenOut",ta="/api/asset/launchpad-contract/CallMemeTokenIn",oa="/api/asset/launchpad-contract/CallMemeTokenOut";class na extends o.ChainCallDTO{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,e.websiteUrl&&(this.websiteUrl=e.websiteUrl),e.telegramUrl&&(this.telegramUrl=e.telegramUrl),e.twitterUrl&&(this.twitterUrl=e.twitterUrl),this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration)}}function aa(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 ia={NATIVE:"native",EXACT:"exact"},ra={LOCAL:"local",EXTERNAL:"external"};class sa{static calculateBuyWithExact(e,t){const o=parseFloat(e),n=parseFloat(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:s,GAS_FEE:c}=jn,l=this.roundUp(i*(Math.exp((n+o)*r)-Math.exp(n*r))/r,8),u=new a(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateBuyWithNative(e,t){const o=parseFloat(e),n=parseFloat(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:s,GAS_FEE:c}=jn,l=Math.log(o*r/i+Math.exp(n*r))/r-n,u=new a(l).multipliedBy(s).toFixed();return{amount:l.toString(),reverseBondingCurveFee:"0",transactionFee:u,gasFee:c}}static calculateSellWithExact(e,t,o,n,i){const r=parseFloat(e),s=parseFloat(t),c=parseFloat(o),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=jn,p=l*(Math.exp(s*u)-Math.exp((s-r)*u))/u,g=new a(p),m=n+s/c*(i-n),f=g.multipliedBy(m).toFixed(8,a.ROUND_UP),y=g.multipliedBy(d).toFixed();return{amount:p.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static calculateSellWithNative(e,t,o,n,i){const r=parseFloat(e),s=parseFloat(t),c=parseFloat(o),{BASE_PRICE:l,PRICE_SCALING_FACTOR:u,TRADING_FEE_FACTOR:d,GAS_FEE:h}=jn,p=s-Math.log(Math.exp(s*u)-r*u/l)/u,g=new a(r),m=n+s/c*(i-n),f=g.multipliedBy(m).toFixed(8,a.ROUND_UP),y=g.multipliedBy(d).toFixed();return{amount:p.toString(),reverseBondingCurveFee:f,transactionFee:y,gasFee:h}}static roundUp(e,t){const o=Math.pow(10,t);return Math.ceil(e*o)/o}}class ca{constructor(e,t,o,n,a,i,r="local"){this.http=e,this.tokenResolver=t,this.logger=o,this.bundleHttp=n,this.galaChainHttp=a,this.dexApiHttp=i,this.defaultCalculateAmountMode=r,this.metadataCache=new Hn}addIfDefined(e,t,o){return void 0!==o&&(e[t]=o),e}async uploadImageByTokenName(e){const{tokenName:t,options:o}=e;Wt(t);const n=`${t}.png`;Ko(o.file,n,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&o.file instanceof File)e.append("image",o.file);else{if(!Buffer.isBuffer(o.file))throw R("file","a File object (browser) or Buffer (Node.js)");{const n=`${o.tokenName||t}.png`,a=new Blob([o.file],{type:"image/png"});e.append("image",a,n)}}const n=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(o.tokenName||t)}`,data:e,headers:{}});if(!0===n.error||200!==n.status||!n.data?.imageUrl)throw q(n.message||"Image upload failed - no URL returned",n.status);return n.data.imageUrl}catch(e){if(e instanceof Error&&e.message.includes("FormData"))throw M("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){jt(e),e.tokenName&&Wt(e.tokenName);const t={page:e.page.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search);const o=S(t),n=await this.http.get("/launchpad/fetch-pool",o);if(!0===n.error||200!==n.status||!n.data)throw q(n.message||"Failed to fetch pools",n.status);let a=[];const i=(await import("bignumber.js")).default;if(n.data.tokens)if(Array.isArray(n.data.tokens))a=n.data.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",o=e.reverseBondingCurveMaxFeePortion??"0",n=!new i(t).isZero()||!new i(o).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}});else{const e=n.data.tokens,t=e.reverseBondingCurveMinFeePortion??"0",o=e.reverseBondingCurveMaxFeePortion??"0",r=!new i(t).isZero()||!new i(o).isZero();a=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:r,createdAt:e.created_at||e.createdAt||""}]}else n.data.pools&&Array.isArray(n.data.pools)&&(a=n.data.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",o=e.reverseBondingCurveMaxFeePortion??"0",n=!new i(t).isZero()||!new i(o).isZero();return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:n,createdAt:e.created_at||e.createdAt||""}}));const{extractMetadataFromPoolData:r,isValidPoolForCaching:s}=await Promise.resolve().then(function(){return ba});a.forEach(e=>{if(!s(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=r(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=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:a,page:l,limit:u,total:c,totalPages:d,hasNext:l<d,hasPrevious:l>1}}async _getAmount(e){if(Qt(e),!this.galaChainHttp)throw M("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:o}=((e,t,o,n)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:Jn,body:{vaultAddress:o,tokenQuantity:n,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:ea,body:{vaultAddress:o,tokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:ta,body:{vaultAddress:o,nativeTokenQuantity:n,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:oa,body:{vaultAddress:o,nativeTokenQuantity:n,IsPreMint:!1}};throw R("type-method","one of: NATIVE-IN, NATIVE-OUT, MEME-IN, MEME-OUT")})(e.type,e.method,e.vaultAddress,e.amount);try{const e=await this.galaChainHttp.post(t,o);if(!aa(e))throw q("Malformed response data from GalaChain gateway");if(1!==e.Status)throw q(`GalaChain calculation failed with status ${e.Status}`,e.Status);const{calculatedQuantity:n,extraFees:a}=e.Data;return{amount:n,reverseBondingCurveFee:a.reverseBondingCurve,transactionFee:a.transactionFees,gasFee:"1"}}catch(n){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:o,error:n instanceof Error?n.message:n}),n}}async checkPool(e){Ht(e),e.tokenName&&Wt(e.tokenName);const t=S(e),o=await this.http.get("/launchpad/check-pool",t);if(!0===o.error||200!==o.status)throw q(o.message||"Failed to check pool",o.status);const n=o.data;return e.symbol?n?.isSymbolExist??!1:e.tokenName?n?.isNameExist??!1:n?.exists??!1}async fetchVolumeData(e){if(!Eo(e))throw new I("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:o,to:n,resolution:a}=e;if(Wt(t),!o||!n||!a)throw new I("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:o,to:n,resolution:a};Xt(i);const r=S(i),s=await this.http.get("/launchpad/get-graph-data",r);if(!0===s.error||200!==s.status||!s.data)throw q(s.message||"Failed to fetch graph data",s.status);return{dataPoints:s.data}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const o={page:e.page||1,limit:e.limit||10};return e.search&&(o.search=e.search),e.tokenName&&(o.tokenName=e.tokenName),t&&(o.type=t),this.fetchPoolsFromAPI(o)}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async calculateBuyAmount(e){if(!e||"object"!=typeof e)throw new I("Invalid options provided. Expected an options object.","options","INVALID_OPTIONS");const{tokenName:t,amount:o,type:n,currentSupply:a}=e,i=e.mode??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw new I(`Invalid calculation mode "${i}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new I("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==ia.NATIVE&&n!==ia.EXACT)throw new I('Type must be either "native" or "exact"',"type","INVALID_TYPE");return"external"===i?this.calculateBuyAmountExternal({tokenName:t,amount:o,type:n}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:o,type:n},"currentSupply",a))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:o,type:n}=e,a=await this.tokenResolver.resolveTokenToVault(t);if(!a)throw new I(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===ia.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:a,amount:o}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:a,amount:o})}async calculateSellAmount(e){const{tokenName:t,amount:o,type:n,currentSupply:a,maxSupply:i,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:s}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw new I(`Invalid calculation mode "${c}". Must be "local" or "external".`,"mode","INVALID_CALCULATION_MODE");if(!t||"string"!=typeof t)throw new I("Token name is required and must be a string","tokenName","INVALID_TOKEN_NAME");if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==ia.EXACT&&n!==ia.NATIVE)throw new I('Type must be either "exact" or "native"',"type","INVALID_TYPE");if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:o,type:n});{const e={tokenName:t,amount:o,type:n,...void 0!==a&&{currentSupply:a},...void 0!==i&&{maxSupply:i},...void 0!==r&&{reverseBondingCurveMaxFeeFactor:r},...void 0!==s&&{reverseBondingCurveMinFeeFactor:s}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:o,type:n}=e,a=await this.tokenResolver.resolveTokenToVault(t);if(!a)throw new I(`Token "${t}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND");return n===ia.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:a,amount:o}):this._getAmount({type:"MEME",method:"IN",vaultAddress:a,amount:o})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:o,type:n,currentSupply:a}=e;if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==ia.NATIVE&&n!==ia.EXACT)throw new I('Type must be either "native" or "exact"',"type","INVALID_TYPE");void 0!==a&&Yt(a,"currentSupply");const i=!a;if(i&&!t)throw new I("Token name is required when currentSupply is not provided","tokenName","MISSING_TOKEN_NAME");t&&Wt(t);let r=a;if(i){r=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return n===ia.EXACT?sa.calculateBuyWithExact(o,r):sa.calculateBuyWithNative(o,r)}async calculateSellAmountLocal(e){const{tokenName:t,amount:o,type:n,currentSupply:a,maxSupply:i,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:s}=e;if(!o||"string"!=typeof o)throw new I("Amount is required and must be a string","amount","INVALID_AMOUNT");if(n!==ia.EXACT&&n!==ia.NATIVE)throw new I('Type must be either "exact" or "native"',"type","INVALID_TYPE");void 0!==a&&Yt(a,"currentSupply");const c=!a||!i||void 0===r||void 0===s;if(c&&!t)throw new I("Token name is required when currentSupply, maxSupply, or fee factors are not provided","tokenName","MISSING_TOKEN_NAME");t&&Wt(t);let l=a,u=i,d=r,h=s;if(c&&t){const e=this.metadataCache.get(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,l||(l=await this.fetchCurrentSupply(t));if(void 0===d||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);d=d??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return n===ia.EXACT?sa.calculateSellWithExact(o,l,u,h,d):sa.calculateSellWithNative(o,l,u,h,d)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&bo(t)&&So(t,"currentSupply")}(e))throw new Error("Invalid CalculateBuyAmountForGraduationOptions provided");const{tokenName:o,calculateAmountMode:n,currentSupply:a}=t;Wt(o);const i=await this.tokenResolver.resolveTokenToVault(o);if(!i)throw new I(E(o),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw M("GalaChain HTTP client not configured");const r=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:i});if(1!==r.Status)throw q(`Failed to fetch pool details: Status ${r.Status}`,r.Status);const s=r.Data,c=(await import("bignumber.js")).default,l=a??new c(s.maxSupply).minus(s.sellingTokenQuantity).toFixed(),u=s.sellingTokenQuantity;if("0"===u)throw new I(`Token ${o} is already graduated (no tokens remaining in pool)`,"tokenName","ALREADY_GRADUATED");const d={tokenName:o,amount:u,type:"exact",currentSupply:l,...void 0!==n&&{mode:n}};return await this.calculateBuyAmount(d)}async launchToken(e){if(!this.bundleHttp)throw M("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Yn(e);const t=e.preBuyQuantity||"0";if(isNaN(Number(t))||Number(t)<0)throw new I("Pre-buy quantity must be a valid non-negative number string","preBuyQuantity","INVALID_PRE_BUY_QUANTITY");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:o}=e.reverseBondingCurveConfiguration,n=Number(t),a=Number(o);if(isNaN(n)||isNaN(a)||n<=0||a<=0||n>=a)throw new I("Reverse bonding curve configuration must have valid min/max fee portions with min < max","reverseBondingCurveConfiguration","INVALID_BONDING_CURVE_CONFIG")}let n="";if(e.tokenImage)if(e.tokenImage instanceof File||Buffer.isBuffer(e.tokenImage)){const t=await this.uploadImageByTokenName({tokenName:e.tokenName,options:{file:e.tokenImage,tokenName:e.tokenName}});if(!t)throw q("Image upload failed: No URL returned");n=t}else"string"==typeof e.tokenImage&&(n=e.tokenImage);const a=`galaswap - operation - ${s.v4()}-${Date.now()}-${this.http.getAddress()}`,i={tokenName:e.tokenName.trim(),tokenSymbol:e.tokenSymbol.trim().toUpperCase(),tokenDescription:e.tokenDescription.trim(),tokenImage:n.trim(),preBuyQuantity:t.toString(),tokenCategory:e.tokenCategory||"Unit",tokenCollection:e.tokenCollection||"Token",uniqueKey:a};e.websiteUrl?.trim()&&(i.websiteUrl=e.websiteUrl.trim()),e.telegramUrl?.trim()&&(i.telegramUrl=e.telegramUrl.trim()),e.twitterUrl?.trim()&&(i.twitterUrl=e.twitterUrl.trim()),e.reverseBondingCurveConfiguration&&(i.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration.minFeePortion.toString(),maxFeePortion:e.reverseBondingCurveConfiguration.maxFeePortion.toString()});const r=new na(i),c=await this.http.signWithGalaChain("CreateSale",r,o.SigningType.SIGN_TYPED_DATA),{signature:l,types:u,domain:d,prefix:h}=c,p={tokenName:r.tokenName,tokenSymbol:r.tokenSymbol,tokenDescription:r.tokenDescription,tokenImage:r.tokenImage,preBuyQuantity:r.preBuyQuantity,...r.websiteUrl&&{websiteUrl:r.websiteUrl},...r.telegramUrl&&{telegramUrl:r.telegramUrl},...r.twitterUrl&&{twitterUrl:r.twitterUrl},tokenCategory:r.tokenCategory,tokenCollection:r.tokenCollection,uniqueKey:r.uniqueKey,signature:l,types:u,domain:d,...h&&{prefix:h},...r.reverseBondingCurveConfiguration&&{reverseBondingCurveConfiguration:r.reverseBondingCurveConfiguration}},g=`${e.tokenName.trim()}$Unit$none$none`,m="GALA$Unit$none$none";let f;if(parseFloat(t)>0){const e=`$service$${g}$launchpad`;f=[e,`$token$${g}$${e}`,`$tokenBalance$${g}$${e}`,`$tokenBalance$${g}$${e}`,`$tokenBalance$${m}$${e}`,`$tokenBalance$${m}$${e}`]}else{const e=`$service$${g}$launchpad`;f=[e,`$token$${g}$${e}`,`$tokenBalance$${g}$${e}`]}const y={signedDto:p,stringsInstructions:f,method:"CreateSale"},w=await this.bundleHttp.post("/bundle",y);if(w.error||!w.data)throw q(w.message||"Token launch failed");return w.data}async fetchTokenDistribution(e){if(!e)throw _("tokenName","Token name");Wt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new I(E(e),"tokenName","VAULT_NOT_FOUND");this.metadataCache.set(e,{vaultAddress:t});const o=encodeURIComponent(t),n=await this.http.get(`/holders/${o}`);if(!0===n.error||200!==n.status||!n.data)throw q(n.message||"Failed to fetch token distribution",n.status);const i=n.data;if(!Array.isArray(i))throw q("Invalid API response: expected array of holders",n.status);for(const e of i){if(!e.owner||"string"!=typeof e.owner)throw q("Invalid holder data: missing or invalid owner field",n.status);if(!e.quantity||"string"!=typeof e.quantity)throw q("Invalid holder data: missing or invalid quantity field",n.status);const t=parseFloat(e.quantity);if(isNaN(t)||!isFinite(t))throw q(`Invalid holder quantity: "${e.quantity}"`,n.status)}const r=i.reduce((e,t)=>e.plus(t.quantity),new a(0));return{holders:i.map(e=>{const t=new a(e.quantity),o=r.isZero()?0:t.dividedBy(r).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:o}}),totalSupply:r.toFixed(),totalHolders:i.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(!e)throw _("tokenName","Token name");Wt(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error||!t.data)throw q(t.message||"Failed to fetch token badges");return{volumeBadges:t.data.volumeBadge||[],engagementBadges:t.data.engagementBadge||[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:o,badgeName:n}=e;try{const e=await this.fetchTokenBadges(t);if(!e)return!1;const a=("volume"===o?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===n);return a?.isActive||!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.nativeTokenQuantity&&(void 0===t.vaultAddress||"string"==typeof t.vaultAddress)}(e))throw new I("Invalid pre-mint calculation data","data","INVALID_PRE_MINT_DATA");if(!this.galaChainHttp)throw M("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},o=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!aa(o))throw q("Malformed response data from GalaChain gateway");if(1!==o.Status)throw q(`GalaChain calculation failed with status ${o.Status}`,o.Status);const{calculatedQuantity:n,extraFees:a}=o.Data;return{amount:n,reverseBondingCurveFee:a.reverseBondingCurve,transactionFee:a.transactionFees,gasFee:"1"}}catch(e){if(e instanceof Error){const t=new Error(`Pre-mint calculation failed: ${e.message}`);throw e.stack&&(t.stack=e.stack),t}throw new Error(`Pre-mint calculation failed: ${String(e)}`)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new I(E(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw M("GalaChain HTTP client not configured");const o=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==o.Status)throw q(`Failed to fetch pool details: Status ${o.Status}`,o.Status);const n=o.Data,a=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),i=n.sellingTokenQuantity,r=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:r,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}),{currentSupply:a,remainingTokens:i,maxSupply:r,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}}async fetchCurrentSupply(e){Wt(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(!t)throw new I(E(e),"tokenName","VAULT_NOT_FOUND");if(!this.galaChainHttp)throw M("GalaChain HTTP client not configured");const o=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==o.Status)throw q(`Failed to fetch pool details: Status ${o.Status}`,o.Status);const n=o.Data,a=new(0,(await import("bignumber.js")).default)(n.maxSupply).minus(n.sellingTokenQuantity).toFixed(),i=n.maxSupply;return this.metadataCache.set(e,{maxSupply:i}),a}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Zt(e)}validateTokenName(e){return Wt(e)}validatePagination(e){return jt(e)}async fetchTokenPrice(e){if(!this.dexApiHttp)throw M("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(!e||Array.isArray(e)&&0===e.length)throw _("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),o=[];return e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{e.currentPrices&&e.symbol&&o.push({symbol:e.symbol,price:e.currentPrices.usd})}),o}catch(e){throw q(`Failed to fetch token prices: ${e instanceof Error?e.message:e}`,void 0,e instanceof Error?e:void 0)}}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return To(t,"tokenName")&&bo(t)&&So(t,"currentSupply")}(e))throw new Error("Invalid FetchLaunchpadTokenSpotPriceOptions provided");const{tokenName:o,calculateAmountMode:n,currentSupply:a}=t;if(!o||"string"!=typeof o)throw _("tokenName","Token name (string)");try{const e={tokenName:o,amount:"1",type:"native",...void 0!==n&&{mode:n},...void 0!==a&&{currentSupply:a}},t=await this.calculateBuyAmount(e),i=(await this.fetchTokenPrice("GALA"))[0];if(!i)throw q("GALA price not available");const r=Number(t.amount);if(r<=0)throw new I(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const s=i.price/r;return{symbol:o.toUpperCase(),price:s}}catch(e){if(e instanceof Error)throw new Error(`Failed to calculate launchpad token spot price for ${o}: ${e.message}`);throw new Error(`Failed to calculate launchpad token spot price for ${o}: ${String(e)}`)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.stats()}clearCache(e){this.metadataCache.clear(e)}}const la={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 ua(e){return la[e]}class da extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class ha extends Error{constructor(e,t,o){super(`Transaction ${e} failed with status: ${t}${o?` - ${o}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function pa(e,t){if(!e)throw new da(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new da(`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 da(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function ga(e,t,o,n){pa(e,t);const a=e,i=a.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new da(`Invalid trade data received for transaction ${t}`);const r={transactionId:t,type:o,method:"native"===n.type?"native":"exact",inputAmount:i.inputQuantity||n.amount,outputAmount:i.outputQuantity||n.expectedAmount||"0",totalFees:i.totalFees||"0",tokenName:n.tokenName,vaultAddress:i.vaultAddress||"",timestamp:Date.now()};return void 0!==a.blockHash&&(r.blockHash=a.blockHash),void 0!==a.gasUsed&&(r.gasUsed=a.gasUsed),void 0!==n.slippageToleranceFactor&&(r.slippageTolerance=n.slippageToleranceFactor),r}const ma="4.0.0";class fa{constructor(t){this.wallet=t.wallet;let o=null,n="STAGE";t.env?(n=t.env,o=ua(t.env)):t.baseUrl?.includes("prod")?(n="PROD",o=ua("PROD")):(n="STAGE",o=ua("STAGE")),this.environment=n,this.config={baseUrl:o.launchpadBaseUrl,galaChainBaseUrl:o.galaChainBaseUrl,bundleBaseUrl:o.bundleBaseUrl,webSocketUrl:o.webSocketUrl,dexApiBaseUrl:o.dexApiBaseUrl,dexBackendBaseUrl:o.dexBackendBaseUrl,launchpadFrontendUrl:o.launchpadFrontendUrl,timeout:3e4,debug:!1,...t},this.logger=new T({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===t.slippageToleranceFactor?fa.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(t.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===t.maxAcceptableReverseBondingCurveFeeSlippageFactor?fa.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(t.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=t.calculateAmountMode||fa.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=t.pricingConcurrency||5,this.auth=new v({wallet:t.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.http=new A(this.auth,this.config),this.galaChainHttp=new A(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new A(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new A(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new A(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 Hn(t.debug||!1),this.launchpadService=new Wo(this.http),this.tokenResolverService=new Un(this.launchpadService.poolService),this.launchpadAPI=new ca(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new yn(this.galaChainHttp,t.wallet,this.tokenResolverService,t.debug||!1,this.galaChainPublicAxios),this.dexService=new wn(this.dexBackendHttp,this.cache,this.galaChainService,t.debug||!1),this.bundleService=new Dn(this.bundleHttp,this.tokenResolverService,this.config.debug||!1,t.wallet,t.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Bn({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new Rn(this.dexBackendHttp,this.config.debug||!1,this.tokenResolverService),this.dexQuoteService=new Zn(this.galaChainHttp,this.config.galaChainBaseUrl,t.debug||!1,t.dexQuoteNetworkTimeout||3e4),this.gswapService=new Wn({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 Qn(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,t.debug||!1)}createOverrideSdk(e){if(!e||"string"!=typeof e)throw M("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw M('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const o=new t.Wallet(e),n={...this.config,wallet:o};return new fa(n)}getAddress(){return this.validateWallet(),this.auth.getAddress()}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw new I("Wallet is required for this operation",void 0,"WALLET_REQUIRED");return this.wallet}setWallet(e){if(!e||"object"!=typeof e||!("address"in e))throw new I("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}getWallet(){return this.wallet}hasWallet(){return void 0!==this.wallet}getConfig(){const{wallet:e,...t}=this.config;return{...t,environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode}}getVersion(){return ma}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(!t)throw M("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e||{});return await this.warmCacheFromPools(t.pools),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.pools),t}async fetchDexPools(e={}){return this.dexPoolService.fetchDexPools(e)}async fetchAllDexPools(e={}){return this.dexPoolService.fetchAllDexPools(e)}async fetchCompositePoolData(e){return this.dexQuoteService.fetchCompositePoolData(e)}async calculateDexPoolQuoteExactAmountLocal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountLocal(e)}async calculateDexPoolQuoteExactAmountExternal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountExternal(e)}async calculateDexPoolQuoteExactAmount(e,t="local"){return this.dexQuoteService.calculateDexPoolQuoteExactAmount(e,t)}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:o,currentSupply:n,calculateAmountMode:a}=e;if(t&&!o){const e={tokenName:t};return n&&(e.currentSupply=n),a&&(e.calculateAmountMode=a),this.fetchLaunchpadTokenSpotPrice(e)}if(o&&!t)try{return await this.dexService.fetchTokenPrice({tokenId:o})}catch(e){const t=function(e){if(Uo(e)&&e.response)return e.response.status}(e);if(400===t||404===t){this.logger.debug(`DEX spot price not available (HTTP ${t}) for tokenId, attempting launchpad fallback`);try{const t=(await this.fetchTokenDetails(o)).name.trim().toLowerCase();if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`);const i={tokenName:t};return n&&(i.currentSupply=n),a&&(i.calculateAmountMode=a),this.fetchLaunchpadTokenSpotPrice(i)}catch(t){throw this.logger.error(`Launchpad fallback failed: ${Bo(t)}`),e}}throw e}if(!t&&!o)throw _("tokenName or tokenId","Either tokenName (for launchpad tokens) or tokenId (for DEX tokens) is required");throw new I("tokenName and tokenId are mutually exclusive - provide only one","params","INVALID_PARAMS")}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchLaunchpadTokenSpotPrice(e){const t="string"==typeof e?{tokenName:e}:e;return this.dexService.fetchLaunchpadTokenSpotPrice(t.tokenName,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(!t)throw new Error(E(e));const o=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return o.currentSupply=n.currentSupply,o.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,o.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,o.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,o.tokenName=e,o}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o=t(e)||this.getAddress();return this.galaChainService.fetchGalaBalance({owner:o,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o=t(e.address);if(e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return pn}),n=t(e.tokenId),{collection:a,category:i,type:r,additionalKey:s}=n;return this.galaChainService.fetchTokenBalance({owner:o,collection:a,category:i,additionalKey:s,type:r,instance:"0"})}if(e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,page:1,limit:1,...o&&{address:o}})).tokens[0];return t?{quantity:t.quantity,collection:t.collection||"Token",category:"Unit",tokenId:`${t.collection||"Token"}|Unit|${t.symbol}|none`,symbol:t.symbol,name:t.name}:null}throw _("tokenId or tokenName","Either tokenId or tokenName")}async fetchComments(e){return this.launchpadService.fetchComments(e)}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:o,maxAcceptableReverseBondingCurveFeeSlippageFactor:n,privateKey:a,calculateAmountMode:i,currentSupply:r}=e;let s=t;void 0===i&&void 0===r||(s={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==r&&{currentSupply:r}});const c=await this.calculateBuyAmountForGraduation(s),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==o&&(l.slippageToleranceFactor=o),void 0!==n&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=n),void 0!==a&&(l.privateKey=a),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.buy(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,o=t?.transactionId;if(!o)throw G("No transaction ID returned from buy operation");return this.waitForConfirmation(o,t=>ga(t,o,"buy",e))}async sell(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.sell(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,o=t?.transactionId;if(!o)throw G("No transaction ID returned from sell operation");return this.waitForConfirmation(o,t=>ga(t,o,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async postComment(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.postComment(n)}return this.validateWallet(),this.launchpadService.postComment(e)}async launchToken(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.launchToken(n)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,o=>{pa(o,t);const n=o?.data||{};if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(n))throw new da(`Invalid launch data received for transaction ${t}`);const a={transactionId:t,vaultAddress:n.vaultAddress||"",tokenStringKey:n.tokenStringKey||"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:n.creatorAddress||this.getAddress(),timestamp:Date.now(),...o.blockHash&&{blockHash:o.blockHash},...o.gasUsed&&{gasUsed:o.gasUsed}};return"string"==typeof e.tokenImage&&(a.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(a.preBuyQuantity=e.preBuyQuantity),a.vaultAddress&&this.tokenResolverService.set(e.tokenName,a.vaultAddress),a})}async uploadTokenImage(e){if(e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:o,...n}=e;return t.uploadTokenImage(n)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o=t(e)||this.getAddress();return this.launchpadService.fetchProfile(o)}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,address:t(e.address)};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.updateProfile(n)}return this.validateWallet(),this.launchpadService.updateProfile(o)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,address:t(e.address)||this.getAddress()};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.uploadProfileImage(n)}return this.validateWallet(),this.launchpadService.uploadProfileImage(o)}async retrieveGalaFromFaucet(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={walletAddress:t(e)||this.getAddress(),amount:"5"};return this.launchpadService.transferFaucets(o)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o=t(e?.address)||this.getAddress(),n={page:e?.page||1,limit:e?.limit||10,address:o};return e?.tokenName&&(n.tokenName=e.tokenName),e?.search&&(n.search=e.search),this.launchpadService.fetchTokensHeld(n)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={type:"DEFI",address:t(e?.address)||this.getAddress(),page:e?.page||1,limit:e?.limit||10};return e?.tokenName&&(o.tokenName=e.tokenName),e?.search&&(o.search=e.search),this.launchpadService.fetchTokenList(o)}async fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,recipientAddress:t(e.recipientAddress)};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.transferGala(n)}return this.validateWallet(),this.galaChainService.transferGala(o)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Jt}),o={...e,to:t(e.to)};if(o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.transferToken(n)}return this.validateWallet(),this.galaChainService.transferToken(o)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async 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 M("baseUrl is required in configuration","baseUrl");if(!this.config.webSocketUrl)throw M("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw M(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw M(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw M(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw M(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw M(`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: ${fa.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),fa.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: ${fa.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),fa.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const o=await this.websocketService.waitForTransaction(e);if("completed"!==o.status)throw new ha(e,o.status,o.message);let n;try{n=t(o)}catch(t){if(t instanceof da)throw t;throw new da(`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 ha||t instanceof da)throw t;throw new da(`WebSocket confirmation failed for transaction ${e}`,t instanceof Error?t:new Error(String(t)))}}async warmCacheFromPools(e){if(!e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:o}=await Promise.resolve().then(function(){return ba});e.forEach(e=>{if(!o(e))return;const n=t(e,this.logger);n&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,n)})}async getSwapQuoteExactInput(e,t,o){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:o})}async getSwapQuoteExactOutput(e,t,o){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:o})}async executeSwap(e,t,o,n,a,i=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:o,estimatedOutput:n,feeTier:a,slippageTolerance:i})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,o){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:o})}async getSwapUserLiquidityPositions(e,t,o,n){let a,i;"string"==typeof o?(a=o,i=n):"object"==typeof o?i=o:n&&(i=n);return await this.gswapService.getUserLiquidityPositions(e,t,a,i)}async getAllSwapUserLiquidityPositions(e,t){const o=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(o))return o;if(o&&"items"in o)return o.items}return o}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t){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 o=this.websocketService.getSocket();return o?(o.on(e,t),()=>{o.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onDexPoolCreation(e,t){const o=1e3,n=Math.max(t?.intervalMs??3e4,o);t?.intervalMs&&t.intervalMs<o&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const a=t?.minTVL,i=t?.tokens,r=new Map;let s=!0,c=null;let l=0;const u=async()=>{if(s){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.pools.forEach(t=>{const o=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!r.has(o)){if((e=>{if(r.set(e,!0),r.size>1e3){const e=r.keys().next().value;void 0!==e&&r.delete(e)}})(o),a){if((t.token0Tvl+t.token1Tvl)/2<a)return}if(i&&i.length>0){if(!(i.includes(t.token0)||i.includes(t.token1)))return}e(t)}})}catch(e){l++;const t=e instanceof Error?e.message:String(e);l>=5?this.logger.error(`Polling for new DEX pools failed ${l} consecutive times. Last error: ${t}. Continuing to retry...`):l>1?this.logger.warn(`Error polling for new DEX pools (attempt ${l}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(s){const e=Math.min(Math.max(l-1,0),2),t=n*Math.pow(2,e);c=setTimeout(u,t)}}};return u(),()=>{s=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const o=1e3,n=Math.max(t?.intervalMs??3e4,o);t?.intervalMs&&t.intervalMs<o&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const a=t?.creatorAddress,i=new Map;let r=!0,s=null;let c=0;const l=async()=>{if(r){try{const t=await this.fetchPools({type:"recent",limit:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.pools.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),a&&t.creatorAddress!==a||e(t))})}catch(e){c++;const t=e instanceof Error?e.message:String(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(r){const e=Math.min(Math.max(c-1,0),2),t=n*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 T({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:o}=require("./services/WebSocketService");o.cleanupAll(e),t.debug("Global cleanup completed")}}fa.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,fa.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,fa.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=jn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,fa.DEFAULT_CALCULATE_AMOUNT_MODE=ra.LOCAL;class ya{static generateWallet(){try{const e=t.Wallet.createRandom();if(!e.mnemonic?.phrase)throw new Error("Failed to generate wallet with mnemonic phrase");const o=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:o,mnemonic:e.mnemonic.phrase,wallet:new t.Wallet(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,o="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),n=new t.Wallet(o),a=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:a,mnemonic:"test test test test test test test test test test test junk",wallet:n}}throw e}}static fromPrivateKey(e){const o=new t.Wallet(e),n=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:n,mnemonic:"",wallet:o}}static fromMnemonic(e,o=0){try{const n=t.Mnemonic.fromPhrase(e),a=t.HDNodeWallet.fromMnemonic(n,`m/44'/60'/0'/0/${o}`),i=new t.Wallet(a.privateKey),r=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:r,mnemonic:e,wallet:i}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${o}-${e}`,a="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),i=new t.Wallet(a),r=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:r,mnemonic:e,wallet:i}}throw n}}static toGalaAddress(e){const t=e.replace(/^0x/i,"");if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid Ethereum address format: ${e}`);return`eth|${t}`}static toEthereumAddress(e){if(!e.startsWith("eth|"))throw new Error(`Invalid Gala address format: ${e}. Must start with 'eth|'`);const t=e.slice(4);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new Error(`Invalid address in Gala format: ${e}`);return`0x${t}`}static isValidEthereumAddress(e){try{const t=e.replace(/^0x/i,"");return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){try{if(!e.startsWith("eth|"))return!1;const t=e.slice(4);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static generateMultipleWallets(e=1){if(e<1||e>100)throw new Error("Count must be between 1 and 100");const t=[];if("undefined"!=typeof process&&"test"===process.env.NODE_ENV)for(let o=0;o<e;o++){const e=`test-multi-${o}-${Date.now()}-${++this.testCounter}`,n="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(n))}else for(let o=0;o<e;o++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const o=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${e.mnemonic||"Not available"}`];return t?o.splice(3,0,`🔑 Private Key: ${e.privateKey}`):o.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),o.push("═".repeat(50)),o.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),o.push("This is your backup to recover the wallet."),o.join("\n")}}function wa(e){if(void 0===e)return ya.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 ya.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 ya.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?"...":""}"`)}ya.testCounter=0;class ka{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,new a(e)),this.CACHE.get(t)}static clearCache(){this.CACHE.clear()}static getCacheStats(){return{size:this.CACHE.size,entries:Array.from(this.CACHE.keys())}}static trimCache(e=1e3){if(this.CACHE.size>e){const t=this.CACHE.size-e,o=Array.from(this.CACHE.keys());for(let e=0;e<t;e++)this.CACHE.delete(o[e])}}}ka.CACHE=new Map,ka.ZERO=new a(0),ka.ONE=new a(1),ka.FEE_PIPS=new a(1e6),ka.MIN_SQRT_RATIO=new a("4295128739"),ka.MAX_SQRT_RATIO=new a("1461446703485210103287273052203988822378723970342");const va={maxIterations:100,enableBigNumberCache:!0,roundingMode:a.ROUND_DOWN,debugLogging:!1};class Ta{static calculateSwapDelta(e,t,o={}){const n=Date.now(),i={...va,...o};try{const o=this.initializeSwapState(e,t,i);i.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:o.sqrtPrice.toString(),liquidity:o.liquidity.toString(),tick:o.tick,zeroForOne:t.zeroForOne});const r=this.computeSwapLoop(o,e,t,i);i.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:r.stepCount,ticksCrossed:r.ticksCrossed.length,priceHitLimit:r.priceHitLimit});const s=this.createUpdatedPool(e.pool,r.state,t,i),c=this.calculateFinalAmounts(o,r.state,t);let l;if(t.actualSqrtPrice){const e=new a(s.sqrtPrice),o=new a(t.actualSqrtPrice);l=e.minus(o).abs().div(o).times(100).toNumber()}const u=Date.now()-n;i.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:u,amount0:c.amount0.toString(),amount1:c.amount1.toString(),driftPercentage:l}),u>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:u,stepCount:r.stepCount,ticksCrossed:r.ticksCrossed.length}),r.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:r.stepCount}),r.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:r.stepCount,ticksCrossed:r.ticksCrossed.length});return{updatedPool:s,updatedTicks:r.updatedTicks,amount0:c.amount0,amount1:c.amount1,feeAmount0:c.feeAmount0,feeAmount1:c.feeAmount1,ticksCrossed:r.ticksCrossed,metadata:{calculationTimeMs:u,swapSteps:r.stepCount,priceHitLimit:r.priceHitLimit,...void 0!==l&&{driftPercentage:l}}}}catch(e){throw this.logger.error("Swap delta calculation failed",e),new Error(`Swap delta calculation failed: ${e.message}`)}}static initializeSwapState(e,t,o){const{pool:n}=e;if(!n.sqrtPrice||!n.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const r=o.enableBigNumberCache?ka.getCached.bind(ka):e=>new a(e),s="string"==typeof n.sqrtPrice?n.sqrtPrice:new a(n.sqrtPrice).toFixed(0),c="string"==typeof n.liquidity?n.liquidity:new a(n.liquidity).toFixed(0),l=r(s),u=r(c),d=n.tick??0,h=i.sqrtPriceToTick(new a(s)),p=Math.abs(h-d);p>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:d,calculatedTick:h,drift:p,threshold:100});const g=r(t.amountSpecified);tn(g,"amountSpecified","for swap operation");const m="string"==typeof n.feeGrowthGlobal1?n.feeGrowthGlobal1:new a(n.feeGrowthGlobal1).toFixed(0),f="string"==typeof n.feeGrowthGlobal0?n.feeGrowthGlobal0:new a(n.feeGrowthGlobal0).toFixed(0),y=t.zeroForOne?r(m):r(f);return{sqrtPrice:l,liquidity:u,tick:d,amountSpecifiedRemaining:g,amountCalculated:ka.ZERO,feeGrowthGlobalX:y,protocolFee:ka.ZERO}}static computeSwapLoop(e,t,o,n){const{pool:r,tickDataMap:s}=t,c=[],l={};let u=0;const d=o.zeroForOne?ka.MIN_SQRT_RATIO:ka.MAX_SQRT_RATIO,h=new a("0.000001");for(;e.amountSpecifiedRemaining.gt(h)&&!e.sqrtPrice.eq(d)&&u<n.maxIterations;){u++;const[t,h]=this.findNextInitializedTick(s,e.tick,r.tickSpacing,o.zeroForOne);let p;if(n.debugLogging&&this.logger.debug(`Swap step ${u}`,{currentTick:e.tick,tickNext:t,initialized:h,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),h&&t>=-887272&&t<=887272){const e=i.tickToSqrtPrice(t);p=e instanceof a?e:new a(String(e))}else p=d;const g=o.zeroForOne?a.max(p,d):a.min(p,d),m=this.executeSwapStep(e.sqrtPrice,g,e.liquidity,e.amountSpecifiedRemaining,r.fee,o.exactInput);if(e.sqrtPrice=m.sqrtPriceNext,o.exactInput){const t=m.amountIn.plus(m.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=ka.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=ka.ZERO)),e.amountCalculated=e.amountCalculated.minus(m.amountOut)}else{m.amountOut.lte(0)?e.amountSpecifiedRemaining=ka.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(m.amountOut),e.amountCalculated=e.amountCalculated.plus(m.amountIn.plus(m.feeAmount))}if(e.liquidity.gt(0)){const t=m.feeAmount.div(e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(p)&&h){const i=s[t.toString()];if(!i)throw new Error(`Missing tick data for initialized tick ${t}`);const r=o.zeroForOne?new a(i.liquidityNet).negated():new a(i.liquidityNet);if(e.liquidity=e.liquidity.plus(r),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);c.push(t),l[t.toString()]=i,n.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:r.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(p))e.tick=o.zeroForOne?t-1:t;else{const t=i.sqrtPriceToTick(new a(e.sqrtPrice.toString()));e.tick=t}}if(u>=n.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${n.maxIterations}). Possible infinite loop or very complex swap.`);const p=e.sqrtPrice.eq(d);return{state:e,ticksCrossed:c,priceHitLimit:p,stepCount:u,updatedTicks:l}}static createUpdatedPool(e,t,o,n){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,o.zeroForOne?i.feeGrowthGlobal1=t.feeGrowthGlobalX.toFixed(0):i.feeGrowthGlobal0=t.feeGrowthGlobalX.toFixed(0),o.zeroForOne){const o=new a(e.protocolFeesToken0);i.protocolFeesToken0=o.plus(t.protocolFee).toFixed(0)}else{const o=new a(e.protocolFeesToken1);i.protocolFeesToken1=o.plus(t.protocolFee).toFixed(0)}return i}static calculateFinalAmounts(e,t,o){let n,i,r,s;if(o.exactInput){const e=new a(o.amountSpecified),c=t.amountCalculated.abs();o.zeroForOne?(n=e.negated(),i=c,r=ka.ZERO,s=ka.ZERO):(n=c,i=e.negated(),r=ka.ZERO,s=ka.ZERO)}else{const e=new a(o.amountSpecified),c=t.amountCalculated.abs();o.zeroForOne?(n=c.negated(),i=e,r=ka.ZERO,s=ka.ZERO):(n=e,i=c.negated(),r=ka.ZERO,s=ka.ZERO)}const c=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return o.zeroForOne?s=c:r=c,{amount0:n,amount1:i,feeAmount0:r,feeAmount1:s}}static findNextInitializedTick(e,t,o,n){const a=Object.keys(e).map(e=>parseInt(e,10)).sort((e,t)=>e-t);if(0===a.length){return[n?-887272:887272,!1]}if(n){const e=a.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=a.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,o,n,r,s){en(o),tn(n,"amountRemaining","for swap step");const c=[500,3e3,1e4];if(!c.includes(r))throw new Error(`Invalid fee tier: ${r}. Must be one of: ${c.join(", ")}`);const l=i.computeSwapStep(e,t,o,n,r,t.lt(e)),u=l[0],d=l[1],h=l[2],p=l[3],g=a.isBigNumber(u)?u:new a(String(u)),m=a.isBigNumber(d)?d:new a(String(d)),f=a.isBigNumber(h)?h:new a(String(h)),y=a.isBigNumber(p)?p:new a(String(p));return{sqrtPriceStart:e,tickNext:i.sqrtPriceToTick(g),sqrtPriceNext:g,initialised:!1,amountIn:m,amountOut:f,feeAmount:y}}}Ta.logger=new T({debug:!1,context:"SwapDeltaCalculator"});class Sa{static fastValidation(e,t,o,n=Sa.DEFAULT_CONFIG){const i=Date.now();let r=!0;try{const s=new a(e.sqrtPrice),c=new a(t.sqrtPrice);o.zeroForOne?c.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:c.toString(),zeroForOne:o.zeroForOne}),r=!1):c.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:c.toString(),zeroForOne:o.zeroForOne}),r=!1);const l=new a(e.liquidity),u=new a(t.liquidity);if(!l.isZero()){const e=u.minus(l).abs().div(l);e.gt(n.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:l.toString(),updatedLiquidity:u.toString(),changePct:e.times(100).toFixed(2)})}const d=new a(e.feeGrowthGlobal0),h=new a(t.feeGrowthGlobal0),p=new a(e.feeGrowthGlobal1),g=new a(t.feeGrowthGlobal1);o.zeroForOne?g.lt(p)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:p.toString(),updatedFeeGrowth1:g.toString()}),r=!1):h.lt(d)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:d.toString(),updatedFeeGrowth0:h.toString()}),r=!1);const m=new a(e.protocolFeesToken0),f=new a(t.protocolFeesToken0),y=new a(e.protocolFeesToken1),w=new a(t.protocolFeesToken1);f.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:m.toString(),updatedProtocolFees0:f.toString()}),r=!1),w.lt(y)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:y.toString(),updatedProtocolFees1:w.toString()}),r=!1);const k=Date.now()-i;return this.logger.debug("Fast validation completed",{passed:r,elapsedMs:k}),r}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,o=Sa.DEFAULT_CONFIG){const n=Date.now(),r=[];let s=0;try{if(t.actualSqrtPrice){const n=new a(e.sqrtPrice),i=new a(t.actualSqrtPrice),c=this.calculateDriftPercentage(n,i);s=c,c>100*o.maxDriftThreshold&&r.push(`Price drift detected: ${c.toFixed(4)}% (threshold: ${(100*o.maxDriftThreshold).toFixed(4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:n.toString(),actualSqrtPrice:i.toString(),driftPct:c.toFixed(4)})}const c=new a(e.sqrtPrice),l=new a(2).pow(96),u=c.dividedBy(l),d=i.sqrtPriceToTick(u),h=e.tick??0,p=Math.abs(d-h);p>o.maxTickDrift&&r.push(`Tick/price mismatch: tick=${h}, calculated=${d}, drift=${p}`);const g=new a(e.feeGrowthGlobal0),m=new a(e.feeGrowthGlobal1),f=new a(e.liquidity);try{en(g,m,f)}catch(e){r.push(e.message)}const y=0===r.length,w=!y||s>100*o.maxDriftThreshold,k=Date.now()-n;return this.logger.debug("Moderate validation completed",{isValid:y,shouldRefetch:w,driftPercentage:s,errorCount:r.length,elapsedMs:k}),this.buildValidationResult(y,s,w,r)}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,o){const n=Date.now(),i=[];let r=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await o(),c=new a(t.pool.sqrtPrice),l=new a(s.pool.sqrtPrice),u=this.calculateDriftPercentage(c,l);r=Math.max(r,u),u>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&i.push(`Price drift: ${u.toFixed(4)}% (cached: ${c.toString()}, fresh: ${l.toString()})`);const d=new a(t.pool.liquidity),h=new a(s.pool.liquidity),p=this.calculateDriftPercentage(d,h);r=Math.max(r,p),p>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&i.push(`Liquidity drift: ${p.toFixed(4)}% (cached: ${d.toString()}, fresh: ${h.toString()})`);const g=Object.keys(t.tickDataMap).length,m=Object.keys(s.tickDataMap).length;if(m>0){const e=Math.abs(m-g)/m;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&i.push(`Tick data incomplete: cached has ${g} ticks, fresh has ${m} ticks (${(100*e).toFixed(2)}% difference)`)}const f=0===i.length,y=!f,w=Date.now()-n;return this.logger.debug("Full validation completed",{poolKey:e,isValid:f,shouldRefetch:y,maxDriftPercentage:r,priceDrift:u,liquidityDrift:p,cachedTickCount:g,freshTickCount:m,errorCount:i.length,elapsedMs:w}),this.buildValidationResult(f,r,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,o,n=[]){let a;if(o&&n.length>0){const e=n.join(" ").toLowerCase();a=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const i={isValid:e,driftPercentage:t,shouldRefetch:o,validationErrors:n};return void 0!==a&&(i.refetchReason=a),i}}Sa.logger=new T({debug:!1,context:"PoolStateValidator"}),Sa.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class Aa{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick||0}`;return h.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){this.logger=new T({debug:t?.debug??!1,context:"PoolStateManager"});const o={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??a.ROUND_DOWN,debug:t?.debug??!1,maxSwapsSinceRefetch:t?.maxSwapsSinceRefetch??50,maxCumulativeDrift:t?.maxCumulativeDrift??5,strictValidation:t?.strictValidation??!1,enablePerformanceWarnings:t?.enablePerformanceWarnings??!0,performanceWarningThreshold:t?.performanceWarningThreshold??100};this.config={...o,...t?.onRefetchNeeded?{onRefetchNeeded:t.onRefetchNeeded}:{}},this.validationConfig=Sa.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:Aa.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},o={maxIterations:this.config.maxIterations,enableBigNumberCache:this.config.enableBigNumberCache,roundingMode:this.config.roundingMode,debugLogging:this.config.debug},n=Ta.calculateSwapDelta(t,e,o);this.lastSwapMetrics={calculationTimeMs:n.metadata.calculationTimeMs,swapSteps:n.metadata.swapSteps,timestamp:Date.now()},this.config.enablePerformanceWarnings&&n.metadata.calculationTimeMs>this.config.performanceWarningThreshold&&this.logger.warn("Slow swap calculation",{calculationTimeMs:n.metadata.calculationTimeMs,swapSteps:n.metadata.swapSteps,threshold:this.config.performanceWarningThreshold});if(!Sa.fastValidation(t.pool,n.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new Error("Swap validation failed");if(e.actualAmount0&&e.actualAmount1&&e.actualSqrtPrice){const t=new a(e.actualAmount0),o=new a(e.actualAmount1),i=n.amount0.minus(t).abs(),r=n.amount1.minus(o).abs(),s=t.isZero()?0:i.div(t.abs()).times(100).toNumber(),c=o.isZero()?0:r.div(o.abs()).times(100).toNumber(),l=Math.max(s,c);l>1&&(this.logger.warn("Drift detected in swap delta",{driftPercentage:l.toFixed(2),swapId:e.transactionId}),this.metadata.cumulativeDrift+=l)}if((this.metadata.swapsSinceRefetch>this.config.maxSwapsSinceRefetch||this.metadata.cumulativeDrift>this.config.maxCumulativeDrift)&&(this.logger.info("Triggering full refetch due to drift accumulation",{swapsSinceRefetch:this.metadata.swapsSinceRefetch,cumulativeDrift:this.metadata.cumulativeDrift.toFixed(2)}),this.config.onRefetchNeeded)){const e=await this.config.onRefetchNeeded(this.pool,this.tickDataMap);this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata.lastFullRefetch=Date.now(),this.metadata.swapsSinceRefetch=0,this.metadata.cumulativeDrift=0,this.metadata.stateHash=Aa.calculatePoolStateHash(this.pool),this.logger.info("Full refetch completed",{sqrtPrice:this.pool.sqrtPrice.toString()})}return this.pool=n.updatedPool,Object.assign(this.tickDataMap,n.updatedTicks),this.metadata.swapsSinceRefetch++,this.metadata.stateHash=Aa.calculatePoolStateHash(this.pool),this.metadata.processedTransactions.push(e.transactionId),this.metadata.processedTransactions.length>1e3&&(this.metadata.processedTransactions=this.metadata.processedTransactions.slice(-1e3)),this.logger.debug("Swap delta applied",{transactionId:e.transactionId,amount0:n.amount0.toString(),amount1:n.amount1.toString(),sqrtPriceNew:this.pool.sqrtPrice.toString()}),n}catch(o){const n=o instanceof Error?o.message:String(o);if(this.logger.error("Failed to apply swap delta",{transactionId:e.transactionId,error:n}),this.config.strictValidation)throw o;return{updatedPool:this.pool,updatedTicks:{},amount0:new a(0),amount1:new a(0),feeAmount0:new a(0),feeAmount1:new a(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:Aa.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}var ba=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const o={};if(e.vaultAddress&&(o.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const n=parseFloat(e.reverseBondingCurveMinFeePortion);isNaN(n)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):o.reverseBondingCurveMinFeeFactor=n}if(void 0!==e.reverseBondingCurveMaxFeePortion){const n=parseFloat(e.reverseBondingCurveMaxFeePortion);isNaN(n)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):o.reverseBondingCurveMaxFeeFactor=n}return void 0!==o.reverseBondingCurveMaxFeeFactor&&void 0!==o.reverseBondingCurveMinFeeFactor&&(o.reverseBondingCurveNetFeeFactor=o.reverseBondingCurveMaxFeeFactor-o.reverseBondingCurveMinFeeFactor),Object.keys(o).length>0?o:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.AgentConfig=class{static async quickSetup(e={}){const t=e.environment||this.detectEnvironment(),o=this.setupWallet(e.privateKey),n={wallet:o.wallet,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{}},a=new fa(n),i={sdk:a,wallet:o,config:n};if(!1!==e.autoValidate){const e=await this.validateSetup(a,o);return{...i,validation:e}}return i}static async readOnlySetup(e={}){const t=e.environment||this.detectEnvironment(),o={wallet:void 0,baseUrl:e.baseUrl||this.getDefaultBaseUrl(t),timeout:e.timeout||this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config||{}};return{sdk:new fa(o),config:o}}static async validateSetup(e,t){const o=[],n=[],a={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(a.connectionHealthy=!0,t&&t.quantity){const e=parseFloat(t.quantity);a.hasBalance=e>0,a.canTrade=e>=.1,a.canCreateTokens=e>=100,0===e?n.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?n.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&n.push("GALA balance too low for token creation (minimum 100 GALA)")}else o.push("Failed to fetch GALA balance: No balance returned")}catch(e){o.push(`Balance check error: ${e instanceof Error?e.message:String(e)}`)}try{const t=await e.fetchPools({type:"recent",page:1,limit:1});t.pools&&0!==t.pools.length||n.push("Pool listing not accessible - some features may be limited")}catch(e){n.push(`Pool access test failed: ${e instanceof Error?e.message:String(e)}`)}return{ready:0===o.length&&a.connectionHealthy,sdk:e,wallet:t||ya.generateWallet(),issues:o,warnings:n,capabilities:a}}static getRecommendedConfig(e,t="general"){const o={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(o,{debug:!1,timeout:3e4});break;case"development":Object.assign(o,{debug:!0,timeout:45e3});break;case"testing":Object.assign(o,{debug:!0,timeout:6e4})}switch(t){case"trading":o.timeout=1.5*(o.timeout||3e4);break;case"creation":o.timeout=2*(o.timeout||3e4);break;case"monitoring":o.timeout=.5*(o.timeout||3e4)}return o}static async multiWalletSetup(e,t="development"){const o={};for(const[n,a]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:a,agentId:`multi-wallet-${n}`,autoValidate:!1});o[n]=e}return o}static detectEnvironment(){const e=process.env.NODE_ENV?.toLowerCase();return"development"===e?"development":"test"===e||"testing"===e?"testing":"production"}static setupWallet(e){if(!e){const e=process.env.PRIVATE_KEY;return e?ya.fromPrivateKey(e):ya.generateWallet()}return"generate"===e?ya.generateWallet():ya.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}},exports.CALCULATION_MODES=ra,exports.COMPOSITE_POOL_FETCH_CONCURRENCY=5,exports.ConfigurationError=P,exports.DexPoolNotFoundError=U,exports.DexQuoteError=B,exports.FileValidationError=Go,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.GSwapAssetError=$,exports.GSwapPoolError=C,exports.GSwapQuoteError=F,exports.GSwapSwapError=D,exports.IMAGE_EXTENSIONS=Be,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LaunchpadSDK=fa,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.NetworkError=N,exports.PAGINATION_DEFAULTS=wo,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PoolStateManager=Aa,exports.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},exports.SDK_VERSION=ma,exports.TRADING_TYPES=ia,exports.TokenMetadataService=class extends vo{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}async resolveTokenMetadata(e){const t=this.getCacheKey(e),o=this.cache[t];if(o&&!this.isCacheExpired(o.timestamp))return this.logger.debug(`Using cached metadata for token: ${t}`),o.data;const n=this.extractMetadata(e);return this.cache[t]={data:n,timestamp:Date.now()},n}async getTokenSymbol(e){return(await this.resolveTokenMetadata(e)).symbol}async getTokenDecimals(e){return(await this.resolveTokenMetadata(e)).decimals}clearCache(e){e?(delete this.cache[e],this.logger.debug(`Cleared cache for token: ${e}`)):(this.cache={},this.logger.debug("Cleared all token metadata cache"))}getCacheStats(){const e=Object.keys(this.cache);return{size:e.length,entries:e}}getCacheKey(e){if("string"==typeof e)return e.toLowerCase();return`${e.type||e.symbol||"unknown"}|${e.additionalKey||"none"}`.toLowerCase()}extractMetadata(e){let t,o,n="Token",a="Unit",i="none";if("string"==typeof e)if(e.includes("|")){const r=e.split("|");"Token"===r[0]&&r[2]?(n=r[0],a=r[1]||"Unit",t=r[2],i=r[3]||"none",o=t):(t=r[0],o=t,a=r[1]||"Unit",i=r[3]||"none")}else t=e,o=e;else t=e.type||"unknown",o=e.symbol||e.type||"unknown",n=e.collection||"Token",a=e.category||"Unit",i=e.additionalKey||"none";const r=this.getDecimalsForToken(o);return{symbol:o.toUpperCase(),decimals:r,collection:n,category:a,type:t.toUpperCase(),additionalKey:i,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return Date.now()-e>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}},exports.TransactionError=x,exports.TransactionFailedError=ha,exports.ValidationError=I,exports.WebSocketError=da,exports.WebSocketTimeoutError=class extends da{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.addressFormatSchema=ee,exports.amountMethodSchema=Ce,exports.amountTypeSchema=De,exports.browserFileSchema=Oe,exports.bufferFileSchema=_e,exports.buyTokensDataSchema=rt,exports.calculatePreMintDataSchema=pt,exports.checkPoolOptionsSchema=Fe,exports.commentMessageSchema=ye,exports.commentPaginationSchema=Ve,exports.createLaunchpadSDK=function(e){e||(e={});const{wallet:o,env:n,config:a={},...i}=e,r={...i,...a},{wallet:s,env:c,config:l,...u}=r;let d;if(o)if("string"==typeof o){d=wa(o).wallet}else{if(!(o instanceof t.Wallet))throw new Error("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.");d=o}else{d=wa().wallet}const h={wallet:d,...n&&{env:n},debug:!1,timeout:3e4,...u};return new fa(h)},exports.createLimitSchema=ue,exports.createPaginatedResultSchema=function(e){return n.z.object({data:n.z.array(e),page:n.z.number().int().min(1),limit:n.z.number().int().min(1),total:n.z.number().int().min(0),totalPages:n.z.number().int().min(0),hasNext:n.z.boolean(),hasPrevious:n.z.boolean()})},exports.createPoolStateManager=function(e,t){return new Aa(e,t)},exports.createTradeDataSchema=it,exports.createWallet=wa,exports.ethereumAddressSchema=te,exports.faucetAmountSchema=re,exports.fetchGalaBalanceOptionsSchema=Je,exports.fetchPoolDetailsDataSchema=gt,exports.fetchTokenBalanceOptionsSchema=ot,exports.fileSizeSchema=ge,exports.fileUploadSchema=Ue,exports.filenameSchema=me,exports.filterByFeeTier=function(e,t){return e.filter(e=>e.feeTier===t)},exports.filterByLiquidity=function(e){return e.filter(e=>new a(e.liquidity).isGreaterThan(0))},exports.filterByMinLiquidity=function(e,t){const o=new a(t);return e.filter(e=>new a(e.liquidity).isGreaterThanOrEqualTo(o))},exports.filterByPoolKey=function(e,t,o,n){const a=t.toUpperCase(),i=o.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),o=e.token1.toUpperCase();return(t===a&&o===i||t===i&&o===a)&&e.feeTier===n})},exports.filterByToken=function(e,t){const o=t.toUpperCase();return e.filter(e=>e.token0.toUpperCase()===o||e.token1.toUpperCase()===o)},exports.filterByTokenPair=function(e,t,o){const n=t.toUpperCase(),a=o.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),o=e.token1.toUpperCase();return t===n&&o===a||t===a&&o===n})},exports.flexibleAddressSchema=oe,exports.flexibleFileSchema=Re,exports.formatGalaForDTO=vn,exports.formatLaunchpadTokenForDTO=Tn,exports.fullNameSchema=J,exports.getAmountOptionsSchema=ht,exports.getEnv=function(e,t){return process.env[e]??t},exports.getEnvOrThrow=function(e,t){const o=process.env[e];if(!o){throw new Error(t?`${e} not set in root or local .env (${t})`:`${e} not set in root or local .env`)}return o},exports.getTradeOptionsSchema=ct,exports.graduateTokenOptionsSchema=Le,exports.graphDataOptionsSchema=$e,exports.groupByFeeTier=function(e){const t=new Map;return e.forEach(e=>{t.has(e.feeTier)||t.set(e.feeTier,[]),t.get(e.feeTier).push(e)}),t},exports.groupByPoolKey=function(e){const t=new Map;return e.forEach(e=>{const o=`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`;t.has(o)||t.set(o,[]),t.get(o).push(e)}),t},exports.groupByTokenPair=function(e){const t=new Map;return e.forEach(e=>{const o=`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`;t.has(o)||t.set(o,[]),t.get(o).push(e)}),t},exports.imageExtensionSchema=qe,exports.imageFilenameSchema=Me,exports.imageMimeTypeSchema=fe,exports.imageUploadOptionsSchema=Pe,exports.isoDateStringSchema=we,exports.launchTokenDataSchema=Ne,exports.loadEnvWithFallback=function(){const e=f.join(process.cwd(),"..","..",".env");y.existsSync(e)&&w.config({path:e});const t=f.join(process.cwd(),".env");y.existsSync(t)&&w.config({path:t})},exports.nonNegativeDecimalStringSchema=ie,exports.optionalUrlSchema=ce,exports.pageNumberSchema=le,exports.paginationResultMetaSchema=Qe,exports.poolFetchTypeSchema=xe,exports.poolPaginationSchema=We,exports.positiveDecimalStringSchema=ae,exports.privateKeySchema=ve,exports.requireNonNegative=en,exports.requirePositive=function(...e){e.forEach((e,t)=>{if(e.isNaN())throw new Error(`Value at index ${t} must be a valid number, got: NaN`);if(!e.isFinite())throw new Error(`Value at index ${t} must be finite, got: ${e.toString()}`);if(e.isLessThanOrEqualTo(0))throw new Error(`Value at index ${t} must be positive, got: ${e.toString()}`)})},exports.requirePositiveWithContext=tn,exports.reverseBondingCurveConfigSchema=Ie,exports.reverseBondingCurveConfigurationSchema=mt,exports.searchQuerySchema=Y,exports.sellTokensDataSchema=st,exports.sortByLiquidity=function(e,t="desc"){return[...e].sort((e,o)=>{const n=new a(e.liquidity),i=new a(o.liquidity);return"desc"===t?i.minus(n).toNumber():n.minus(i).toNumber()})},exports.standardLimitSchema=de,exports.standardPaginationSchema=Ge,exports.timestampSchema=ke,exports.tokenCategorySchema=be,exports.tokenCollectionSchema=Ee,exports.tokenDescriptionSchema=X,exports.tokenListOptionsSchema=Ze,exports.tokenNameSchema=H,exports.tokenSymbolSchema=Q,exports.tokenUrlsSchema=Ae,exports.tradeCalculationMethodSchema=dt,exports.tradeCalculationTypeSchema=ut,exports.tradeLimitSchema=pe,exports.tradeListParamsSchema=lt,exports.tradePaginationSchema=ze,exports.tradePaginationWithFiltersSchema=He,exports.tradeTypeBackendSchema=at,exports.tradeTypeSchema=nt,exports.transactionIdSchema=Te,exports.transferFaucetsDataSchema=Ye,exports.uniqueKeySchema=Se,exports.updateProfileDataSchema=et,exports.uploadProfileImageOptionsSchema=tt,exports.urlSchema=se,exports.userLimitSchema=he,exports.userPaginationSchema=Ke,exports.userTokenNameSchema=Z,exports.userTokenTypeSchema=Xe,exports.userTokensPaginationSchema=je,exports.validateAddress=vt,exports.validateAmountString=St,exports.validateBuyTokensData=_t,exports.validateCalculatePreMintData=Kt,exports.validateCheckPoolOptions=Ft,exports.validateCreateTradeData=Ot,exports.validateFaucetAmount=At,exports.validateFetchGalaBalanceOptions=$t,exports.validateFetchPoolDetailsData=zt,exports.validateFetchTokenBalanceOptions=Ut,exports.validateFullName=bt,exports.validateGetAmountOptions=Gt,exports.validateGetTradeOptions=qt,exports.validateImageUploadOptions=xt,exports.validateLaunchTokenData=Nt,exports.validateSearchQuery=Et,exports.validateSellTokensData=Rt,exports.validateTokenDescription=kt,exports.validateTokenListOptions=Dt,exports.validateTokenName=yt,exports.validateTokenSymbol=wt,exports.validateTokenUrls=Pt,exports.validateTradeListParams=Mt,exports.validateTransferFaucetsData=Ct,exports.validateUpdateProfileData=Lt,exports.validateUploadProfileImageOptions=Bt,exports.validateUserTokenName=It,exports.validateVaultAddress=Tt,exports.vaultAddressSchema=ne;