@gala-chain/launchpad-sdk 9.0.0-rc.0 → 9.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +500 -10
- package/EXAMPLES.md +1 -1
- package/MIGRATING-TO-9.0.md +43 -1
- package/README.md +1 -1
- package/dist/LaunchpadSDK.d.ts +414 -219
- package/dist/LaunchpadSDK.d.ts.map +1 -1
- package/dist/api/LaunchpadAPI.d.ts +2 -140
- package/dist/api/LaunchpadAPI.d.ts.map +1 -1
- package/dist/auth/SessionAuthService.d.ts +32 -2
- package/dist/auth/SessionAuthService.d.ts.map +1 -1
- package/dist/auth/session.d.ts +59 -0
- package/dist/auth/session.d.ts.map +1 -0
- package/dist/auth/types.d.ts +6 -1
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/constants/endpoints.d.ts +19 -1
- package/dist/constants/endpoints.d.ts.map +1 -1
- package/dist/constants/enums.d.ts +19 -0
- package/dist/constants/enums.d.ts.map +1 -1
- package/dist/constants/version.generated.d.ts +1 -1
- package/dist/errors/LaunchpadSDKError.d.ts +18 -0
- package/dist/errors/LaunchpadSDKError.d.ts.map +1 -1
- package/dist/index.browser.d.ts +36 -27
- package/dist/index.browser.d.ts.map +1 -1
- package/dist/index.browser.esm.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/launchpad/bundle-submission.d.ts +57 -2
- package/dist/launchpad/bundle-submission.d.ts.map +1 -1
- package/dist/launchpad/create-sale-validation.d.ts +19 -0
- package/dist/launchpad/create-sale-validation.d.ts.map +1 -0
- package/dist/launchpad/transport.d.ts +31 -1
- package/dist/launchpad/transport.d.ts.map +1 -1
- package/dist/launchpad/writes.d.ts +37 -11
- package/dist/launchpad/writes.d.ts.map +1 -1
- package/dist/native.cjs +1 -1
- package/dist/native.d.ts +1 -1
- package/dist/native.d.ts.map +1 -1
- package/dist/native.esm.js +1 -1
- package/dist/schemas/launchpad.d.ts +3 -2
- package/dist/schemas/launchpad.d.ts.map +1 -1
- package/dist/schemas/primitives.d.ts +12 -2
- package/dist/schemas/primitives.d.ts.map +1 -1
- package/dist/schemas/user.d.ts +3 -3
- package/dist/schemas/validators.d.ts +3 -3
- package/dist/services/ApiKeyService.d.ts +1 -1
- package/dist/services/BanService.d.ts +1 -1
- package/dist/services/ChartService.d.ts.map +1 -1
- package/dist/services/ContentReactionService.d.ts +6 -18
- package/dist/services/ContentReactionService.d.ts.map +1 -1
- package/dist/services/EventsQueryService.d.ts +47 -0
- package/dist/services/EventsQueryService.d.ts.map +1 -0
- package/dist/services/GalaChainLockService.d.ts.map +1 -1
- package/dist/services/GalaChainTransferService.d.ts.map +1 -1
- package/dist/services/HealthService.d.ts +33 -0
- package/dist/services/HealthService.d.ts.map +1 -0
- package/dist/services/ImageService.d.ts +3 -3
- package/dist/services/ImageService.d.ts.map +1 -1
- package/dist/services/LaunchpadPriceService.d.ts.map +1 -1
- package/dist/services/LaunchpadService.d.ts +34 -42
- package/dist/services/LaunchpadService.d.ts.map +1 -1
- package/dist/services/MessagesService.d.ts +12 -44
- package/dist/services/MessagesService.d.ts.map +1 -1
- package/dist/services/ModeratorService.d.ts +2 -2
- package/dist/services/ModeratorService.d.ts.map +1 -1
- package/dist/services/OverseerService.d.ts +3 -3
- package/dist/services/OverseerService.d.ts.map +1 -1
- package/dist/services/PlatformStatsService.d.ts +1 -2
- package/dist/services/PlatformStatsService.d.ts.map +1 -1
- package/dist/services/PoolService.d.ts +31 -65
- package/dist/services/PoolService.d.ts.map +1 -1
- package/dist/services/RestrictedNamesService.d.ts +1 -1
- package/dist/services/RestrictedNamesService.d.ts.map +1 -1
- package/dist/services/StreamChatService.d.ts +8 -19
- package/dist/services/StreamChatService.d.ts.map +1 -1
- package/dist/services/StreamTokenServiceBase.d.ts +2 -1
- package/dist/services/StreamTokenServiceBase.d.ts.map +1 -1
- package/dist/services/StreamWebSocketService.d.ts +423 -451
- package/dist/services/StreamWebSocketService.d.ts.map +1 -1
- package/dist/services/StreamingService.d.ts +14 -15
- package/dist/services/StreamingService.d.ts.map +1 -1
- package/dist/services/TokenBanService.d.ts +1 -1
- package/dist/services/TradeService.d.ts +13 -9
- package/dist/services/TradeService.d.ts.map +1 -1
- package/dist/services/TradingQuotesService.d.ts.map +1 -1
- package/dist/services/UserService.d.ts +64 -20
- package/dist/services/UserService.d.ts.map +1 -1
- package/dist/services/realtime/event-catalog.d.ts +456 -0
- package/dist/services/realtime/event-catalog.d.ts.map +1 -0
- package/dist/services/shared/pagination-helpers.d.ts +22 -5
- package/dist/services/shared/pagination-helpers.d.ts.map +1 -1
- package/dist/services/shared/service-validators.d.ts.map +1 -1
- package/dist/signing/signers.d.ts +57 -1
- package/dist/signing/signers.d.ts.map +1 -1
- package/dist/types/api-key.dto.d.ts +1 -1
- package/dist/types/ban.dto.d.ts +21 -16
- package/dist/types/ban.dto.d.ts.map +1 -1
- package/dist/types/chat-messages.dto.d.ts +10 -72
- package/dist/types/chat-messages.dto.d.ts.map +1 -1
- package/dist/types/comments.dto.d.ts +8 -78
- package/dist/types/comments.dto.d.ts.map +1 -1
- package/dist/types/common.d.ts +40 -62
- package/dist/types/common.d.ts.map +1 -1
- package/dist/types/constraints.d.ts +47 -23
- package/dist/types/constraints.d.ts.map +1 -1
- package/dist/types/content-flag.dto.d.ts +5 -1
- package/dist/types/content-flag.dto.d.ts.map +1 -1
- package/dist/types/content-reactions.dto.d.ts +0 -4
- package/dist/types/content-reactions.dto.d.ts.map +1 -1
- package/dist/types/engagement-stats.dto.d.ts +16 -27
- package/dist/types/engagement-stats.dto.d.ts.map +1 -1
- package/dist/types/events.dto.d.ts +89 -0
- package/dist/types/events.dto.d.ts.map +1 -1
- package/dist/types/global-feed.dto.d.ts +23 -164
- package/dist/types/global-feed.dto.d.ts.map +1 -1
- package/dist/types/health.dto.d.ts +32 -0
- package/dist/types/health.dto.d.ts.map +1 -0
- package/dist/types/launchpad.dto.d.ts +99 -66
- package/dist/types/launchpad.dto.d.ts.map +1 -1
- package/dist/types/messages.dto.d.ts +168 -118
- package/dist/types/messages.dto.d.ts.map +1 -1
- package/dist/types/moderator.dto.d.ts +1 -1
- package/dist/types/options.dto.d.ts +1 -3
- package/dist/types/options.dto.d.ts.map +1 -1
- package/dist/types/overseer.dto.d.ts +2 -1
- package/dist/types/overseer.dto.d.ts.map +1 -1
- package/dist/types/platform-stats.dto.d.ts +3 -3
- package/dist/types/realtime-events.dto.d.ts +340 -0
- package/dist/types/realtime-events.dto.d.ts.map +1 -0
- package/dist/types/restricted-names.dto.d.ts +2 -2
- package/dist/types/restricted-names.dto.d.ts.map +1 -1
- package/dist/types/stream-chat.dto.d.ts +15 -14
- package/dist/types/stream-chat.dto.d.ts.map +1 -1
- package/dist/types/streaming.dto.d.ts +73 -104
- package/dist/types/streaming.dto.d.ts.map +1 -1
- package/dist/types/token-ban.dto.d.ts.map +1 -1
- package/dist/types/token-config.dto.d.ts +34 -19
- package/dist/types/token-config.dto.d.ts.map +1 -1
- package/dist/types/trades-query.dto.d.ts +8 -24
- package/dist/types/trades-query.dto.d.ts.map +1 -1
- package/dist/types/user.dto.d.ts +126 -50
- package/dist/types/user.dto.d.ts.map +1 -1
- package/dist/types/websocket-events.dto.d.ts +5 -5
- package/dist/types/websocket-events.dto.d.ts.map +1 -1
- package/dist/utils/address-formatter.d.ts +15 -0
- package/dist/utils/address-formatter.d.ts.map +1 -1
- package/dist/utils/auto-pagination.d.ts +1 -1
- package/dist/utils/auto-pagination.d.ts.map +1 -1
- package/dist/utils/error-factories.d.ts +8 -7
- package/dist/utils/error-factories.d.ts.map +1 -1
- package/dist/utils/errors.d.ts +54 -11
- package/dist/utils/errors.d.ts.map +1 -1
- package/dist/utils/http.d.ts +24 -3
- package/dist/utils/http.d.ts.map +1 -1
- package/dist/utils/message-validators.d.ts.map +1 -1
- package/dist/utils/pagination-helpers.d.ts +17 -0
- package/dist/utils/pagination-helpers.d.ts.map +1 -1
- package/dist/utils/pagination-validation.d.ts +2 -2
- package/dist/utils/response-handlers.d.ts.map +1 -1
- package/dist/utils/service-validators.d.ts +6 -6
- package/dist/utils/service-validators.d.ts.map +1 -1
- package/dist/utils/validation-helpers.d.ts +18 -59
- package/dist/utils/validation-helpers.d.ts.map +1 -1
- package/dist/utils/validation.d.ts +4 -1
- package/dist/utils/validation.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/services/StreamingEventService.d.ts +0 -441
- package/dist/services/StreamingEventService.d.ts.map +0 -1
- package/dist/types/comment.dto.d.ts +0 -176
- package/dist/types/comment.dto.d.ts.map +0 -1
- package/dist/types/streaming-events.dto.d.ts +0 -605
- package/dist/types/streaming-events.dto.d.ts.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("ethers"),t=require("@gala-chain/gala-core-sdk"),n=require("zod"),r=require("@gala-chain/gala-core-sdk/providers"),s=require("@gala-chain/api"),a=require("uuid"),o=require("socket.io-client"),i=require("bignumber.js"),c=require("axios");function l(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}const d={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},u="/v1/users/referrals/url",h="/v1/users/referrals",g="/v1/users/referrals/summary",m="/v1/tokens/:tokenName/start-stream",p="/v1/tokens/:tokenName/stop-stream",f="/v1/tokens/:tokenName/stream/disable",E="/v1/tokens/:tokenName/stream/enable",A="/v1/tokens/:tokenName/reset-key",v="/v1/tokens/:tokenName/recordings",S="/v1/tokens/:tokenName/recordings/:assetId/download",T="/v1/tokens/:tokenName/recordings/:assetId",y="/v1/tokens/:tokenName/simulcasts",k="/v1/tokens/:tokenName/simulcasts",b="/v1/tokens/:tokenName/simulcasts/:targetId",N="/v1/config",w="/v1/config",C="/v1/config",_="/v1/tokens/:tokenName/role",I="/v1/roles",D="/v1/permissions",R="/v1/tokens/:tokenName/credentials",O="/auth/login",x="/auth/logout",M="/auth/refresh",L="/auth/session",U="/v1/tokens/:tokenName/bans",F="/v1/tokens/:tokenName/bans",P="/v1/tokens/:tokenName/bans/:userAddress",B="/v1/tokens/:tokenName/bans/:userAddress",$="/v1/tokens/:tokenName/active-users",G="/v1/user-bans",K="/v1/user-bans",H="/v1/user-bans/:userAddress",W="/v1/user-bans/:userAddress",V={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},z="/v1/moderator-invites",j="/v1/moderator-invites/claim",q="/v1/moderated-tokens",X="/v1/moderator-invites",Q="/v1/moderator-invites/:id",Y="/v1/moderator-invites/:id/role",J="/v1/moderator-invites/:id",Z="/v1/moderator-invites/code/:code",ee={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},te="/v1/overseer-invites",ne="/v1/overseer-invites",re="/v1/overseer-invites/code/:code",se="/v1/overseer-invites/claim",ae="/v1/overseer-invites/:id",oe="/v1/overseers",ie="/v1/overseers",ce="/v1/overseers/:address",le="/v1/overseers/me",de="/v1/overseer-summary",ue="/v1/overseer-summary/bans",he="/v1/overseer-summary/token-bans",ge="/v1/overseer-summary/invites",me="/v1/overseer-summary/flags",pe="/v1/overseer-summary/users",fe="/v1/users",Ee="/v1/users/:address/summary",Ae="/v1/cache/flush/address/:address",ve="/v1/cache/flush/token/:tokenName",Se="/v1/cache/flush/all",Te="/v1/cache/flush/wallet-aliases/:address",ye="/v1/cache/flush/wallet-aliases",ke="/v1/token-bans",be="/v1/token-bans",Ne="/v1/token-bans/:tokenName",we="/v1/token-bans/:tokenName",Ce="/v1/reactions",_e="/v1/reactions",Ie="/v1/trades",De={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},Re="/v1/restricted-token-names",Oe="/v1/restricted-token-names",xe="/live/:tokenName/chat",Me="/live/:tokenName/chat",Le="/live/:tokenName/chat",Ue="/live/:tokenName/chat/slow-mode",Fe={GET_SETTINGS:"/v1/ai-moderation/settings",UPDATE_SETTINGS:"/v1/ai-moderation/settings",GET_MODERATION:"/v1/ai-moderation/flags/:flagId",TRIGGER_MODERATION:"/v1/ai-moderation/flags/:flagId/analyze",GET_STATUS:"/v1/ai-moderation/status"},Pe="/v1/stats",Be="/v1/trading/fee",$e="/v1/trading/sale-details",Ge="/v1/trading/quote",Ke="/v1/trading/premint-quote",He={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},We="/v1/notifications/register",Ve="/v1/notifications/unregister",ze="/v1/notifications/preferences",je="/v1/notifications/preferences",qe="/v1/config/client-flags",Xe={NATIVE:"native",EXACT:"exact"},Qe={LOCAL:"local",EXTERNAL:"external"},Ye={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class Je extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class Ze extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class et extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class tt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function nt(e){return e instanceof Error}function rt(e){return nt(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 st(e){return nt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function at(e){if(function(e){return"object"==typeof e&&null!==e&&"code"in e&&("string"==typeof e.code||"number"==typeof e.code)}(e))return e.code}function ot(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function it(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function ct(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}function lt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function dt(e,t){return new Je(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function ut(e,t){const n=lt(e,t);return new Je(`${n} is required`,e,"REQUIRED")}function ht(e,t,n){const r=lt(e,n);return new Je(`${r} must be ${t}`,e,"INVALID_FORMAT")}function gt(e,t,n){return new Ze(e,t,n)}function mt(e,t){return new et(e,t)}function pt(e,t,n){return new tt(e,t,n)}function ft(e,t,n,r,s){const a=lt(e,s);return new Je(`${a} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function Et(e,t,n,r){const s=lt(e,r);return new Je(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function At(e,t,n,r){const s=lt(e,r);return new Je(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function vt(e,t,n,r){const s=lt(e,r),a=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new Je(`${s} must be ${t}${a}`,e,"INVALID_TYPE")}function St(e,t,n){const r=lt(e,n);return new Je(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Tt(e,t,n,r){const s=lt(e,r);return new Je(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function yt(e,t){if(e.length<2)return ut(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new Je(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function kt(e,t,n,r){const s=lt(e,r);return new Je(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function bt(e,t){const n=lt(e,t);return new Je(`${n} cannot be empty`,e,"EMPTY_STRING")}function Nt(e){return null!=e&&"object"==typeof e&&"data"in e}function wt(e,t,n=!1){const r=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(r||s){const n=e?.statusCode??e.status??void 0;throw gt(e?.message??t,n)}}function Ct(e){if(Nt(e))return e.data}function _t(e,t="No data found in response"){if(!Nt(e))throw gt(t);const n=e.data;if(null==n)throw gt(t);return n}async function It(e,t={}){return Ot(e,t,e=>{if(void 0===e.data)throw new Je(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function Dt(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:s=!1}=t;s&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return s&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function Rt(e,t={}){return Ot(e,t,e=>e)}async function Ot(e,t,n){const{errorContext:r="Operation failed",logger:s,debugLogEnabled:a=!1}=t;a&&s&&s.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new Je(`${r}: No response from server`,"response","NO_RESPONSE");return wt(t,r,!0),a&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{error:e}),e}}const xt={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function Mt(e){return e.trim().toLowerCase()}function Lt(e){return e.trim().toUpperCase()}var Ut;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Ut||(Ut={}));class Ft{constructor(e){this.levelPriority={[Ut.DEBUG]:0,[Ut.INFO]:1,[Ut.WARN]:2,[Ut.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Ut.DEBUG:Ut.INFO)}debug(e,t){this.log(Ut.DEBUG,e,t)}info(e,t){this.log(Ut.INFO,e,t)}warn(e,t){this.log(Ut.WARN,e,t)}error(e,t){this.log(Ut.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Ut.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?nt(n)?s(`${r} ${t}`,n.message,st(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case Ut.DEBUG:return console.debug;case Ut.INFO:return console.info;case Ut.WARN:return console.warn;case Ut.ERROR:return console.error;default:return console.log}}child(e){return new Ft({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Ut.DEBUG]>=this.levelPriority[this.minLevel]}}function Pt(e){return null==e||""===e}function Bt(e){return null==e}const $t=new Ft({debug:!1,context:"DateUtils"});function Gt(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?($t.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return $t.warn(`Date parsing error for "${e}":`,t),new Date}}function Kt(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}const Ht={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},Wt={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},Vt={MIN_LENGTH:1,MAX_LENGTH:50},zt=100,jt=20,qt={MAX_LIMIT:50,DEFAULT_OFFSET:0,DEFAULT_LIMIT:20},Xt={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},Qt={MAX_LENGTH:100},Yt={COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},Jt={CHAT_MESSAGE:{PATTERN:/^chat-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i},CONTENT_REACTION:{MAX_LENGTH:64,PATTERN:/^(msg-\d{13}-[a-f0-9]{32}|chat-\d{13}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/}},Zt=60,en=31536e3,tn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},nn={PATTERN:/^[a-fA-F0-9]{64}$/},rn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},sn=50,an=1,on=100,cn={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function ln(e,t=0){if(Pt(e))return t;if("number"==typeof e)return isNaN(e)||!isFinite(e)?t:e;const n=parseFloat(e);return isNaN(n)||!isFinite(n)?t:n}function dn(e,t,n){if(Bt(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const r=parseInt(String(e),10);return isNaN(r)?t:r}function un(e,t=0){if(Bt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return ln(String(e).replace("%","").trim(),t)}function hn(e,t=18){const n=ln(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function gn(e){return hn(e,8)}function mn(e){return hn(e,18)}function pn(e,t,n,r){if("number"!=typeof e)throw vt(r,"a number",e,r);if(e<t||e>n)throw ft(r,t,n,e)}function fn(e,t,n){if("string"!=typeof e)throw vt(n,"a string",e,n);if(e.length>t)throw At(n,t,e.length)}function En(e,t){if("number"!=typeof e)throw vt(t,"a number",e,t);if(!Number.isInteger(e))throw vt(t,"an integer",e,t);if(e<=0)throw Et(t,1,e,t)}function An(e,t,n=!1){if("string"!=typeof e)throw vt(t,"a string",e,t);if(!n&&0===e.trim().length)throw ut(t,`${t} (non-empty string)`)}function vn(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new Je(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new Je(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new Je(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new Je(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new Je(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}const Sn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},Tn=function(e){return"string"==typeof e&&e.trim().length>0},yn=Pt,kn=Bt;function bn(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new Je("cursor must be a string","cursor",Ye.INVALID_TYPE);const a=r??t,o=void 0!==r?"pageSize":"limit";if(void 0!==a&&(En(a,o),a>n))throw new Je(`${o} must be at most ${n}`,o,Ye.TOO_LARGE)}function Nn(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function wn(e){return Object.values(e)}function Cn(e,t="tokenName",n=Ht){if(!Tn(e))throw ut(t);const r=e.trim();if(0===r.length)throw ut(t);if(r.length<n.MIN_LENGTH)throw ft(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw ft(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new Je(`${t} must contain only alphanumeric characters`,t,Ye.INVALID_FORMAT)}function _n(e,t="tokenName",n=Ht){if(null==e)throw ut(t,t);if("string"!=typeof e)throw vt(t,"a string",e);const r=e.trim();if(0===r.length)throw ut(t,t);if(!n.PATTERN.test(r))throw new Je(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,Ye.INVALID_FORMAT)}function In(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:s=!1,optional:a=!1,validator:o}of e){const e=n[t];if((!a||void 0!==e)&&(!s||null!==e)){if(typeof e!==r)return!1;if(o&&!o(e))return!1}}return!0}}const Dn={requiredString:e=>t=>kn(t)?`${e} is required`:"string"!=typeof t?`${e} must be a string`:0===t.trim().length?`${e} cannot be empty`:void 0,maxLength:(e,t)=>n=>{if(!yn(n))return"string"!=typeof n?`${e} must be a string`:n.length>t?`${e} must be at most ${t} characters`:void 0},positiveInteger:e=>t=>{if(!kn(t))return"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`},requiredPositiveInteger:e=>t=>kn(t)?`${e} is required`:"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`,enumValue:(e,t)=>n=>{if(!kn(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>kn(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!kn(t))return"string"!=typeof t?`${e} must be a string`:Kt(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(kn(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return Sn.ETH_ADDRESS.test(n)||Sn.BACKEND_ADDRESS.test(n)||Sn.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function Rn(e){return""===e||0===e.trim().length}function On(e,t,n){if(!kn(e)){if("string"!=typeof e)throw vt(t,"a string",e,t);if(e.length>n)throw new Je(`${t} must be at most ${n} characters`,t,Ye.TOO_LARGE)}}function xn(e,t){kn(e)||function(e,t){const n=e instanceof Date?e:"string"==typeof e||"number"==typeof e?new Date(e):void 0;if(void 0===n)throw vt(t,"a date",e,t);if(isNaN(n.getTime()))throw new Je(`${t} must be a valid date`,t,Ye.INVALID_FORMAT)}(e,t)}function Mn(e,t,n){try{En(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new Je(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function Ln(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new Je(`${n} must be one of: ${r.join(", ")}`,n,Ye.INVALID_FORMAT)}(e,t,n)}class Un{constructor(e,t=!1,n){this.http=e,this.logger=new Ft({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new et("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=st(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Mn(e,t,n)}}class Fn{constructor(e=!1,t){this.logger=t||new Ft({debug:e,context:this.constructor.name})}}class Pn extends Fn{constructor(e=!1){super(e),this.cache=new Map}get(e){const t=this.normalizeKey(e);return this.cache.get(t)}set(e,t){const n=this.normalizeKey(e);this.cache.set(n,t)}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(){this.cache.clear(),this.logger.debug("Cleared cache")}dump(){return new Map(this.cache)}size(){return this.cache.size}isEmpty(){return 0===this.cache.size}buildBaseStats(){return{totalItems:this.cache.size}}}class Bn extends Pn{constructor(e=!1){super(e)}normalizeKey(e){return Mt(e).replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}getLRUKey(){return this.cache.keys().next().value??null}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=Bn.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n??{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}getByName(e){const t=this.normalizeKey(e);return this.cache.get(t)}getMaxSupply(e){const t=this.normalizeKey(e),n=this.cache.get(t);return n?.maxSupply??xt.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${Mt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${Mt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${Mt(e)}`;return this.cache.has(t)}}Bn.MAX_CACHE_SIZE=1e4;const $n={ETHEREUM:Sn.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Sn.BACKEND_ADDRESS,CLIENT:Sn.CLIENT_ADDRESS};class Gn{toBackendFormat(t){if(!Tn(t))throw new Je("Address is required and must be a string","address","REQUIRED");let n=t;if(t.startsWith("eth|")){if(n=t.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new Je(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${t}"`,"address","INVALID_FORMAT");return t}if(n=Hn(t),!/^[a-fA-F0-9]{40}$/.test(n))throw new Je(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${t}"`,"address","INVALID_FORMAT");return`eth|${e.getAddress(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!Tn(e))throw new Je("Backend address is required and must be a string","address","REQUIRED");const t=e.match(/^eth\|(0x)?([0-9a-fA-F]{40})$/i);if(!t)throw new Je(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],r=void 0!==n&&""!==n?6:4;return`0x${e.substring(r)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!$n.CLIENT.test(e))throw new Je(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!$n.BACKEND.test(e))throw new Je(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Tn(e)&&(!!$n.ETHEREUM.test(e)||(!!$n.ETHEREUM_NO_PREFIX.test(e)||(!!$n.BACKEND.test(e)||!!$n.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new Je(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Tn(e)?$n.ETHEREUM.test(e)||$n.ETHEREUM_NO_PREFIX.test(e)?"ethereum":$n.BACKEND.test(e)?"backend":$n.CLIENT.test(e)?"client":null:null}normalize(e){if(void 0!==e&&""!==e)return e.toLowerCase()}extractHex(e){if(e.startsWith("eth|"))return e.substring(4).toLowerCase();if(e.startsWith("0x"))return Hn(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new Je(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Kn=new Gn;function Hn(e){return e.startsWith("0x")?e.slice(2):e}function Wn(e){return Kn.toBackendFormat(e)}function Vn(e){return Kn.toEthereumFormat(e)}function zn(e){return Kn.normalizeInput(e)}function jn(e){return Kn.isValid(e)}function qn(e,t="address"){Kn.assertValid(e,t)}function Xn(e){const t="string"==typeof e?e:e.address;return Kn.toBackendFormat(t)}var Qn=Object.freeze({__proto__:null,AddressFormatter:Gn,assertValidWalletAddress:qn,fromBackendAddressFormat:Vn,isValidAddress:jn,normalizeAddressInput:zn,stripHexPrefix:Hn,toBackendAddressFormat:Wn,toBackendAddressFromEthers:Xn});const Yn=n.z.string({message:"Token name is required"}).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"),Jn=n.z.string({message:"Token symbol is required"}).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"),Zn=n.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),er=n.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),tr=n.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),nr=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"),rr=n.z.string().regex(Sn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),sr=n.z.string().regex(Sn.ETH_ADDRESS,"Invalid Ethereum address format"),ar=n.z.string().refine(e=>Sn.BACKEND_ADDRESS.test(e)||Sn.ETH_ADDRESS.test(e)||Sn.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new Gn).normalizeInput(e)??e),or=n.z.string().refine(e=>Sn.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),ir=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>ln(e,0)>0,"Amount must be greater than zero"),cr=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>ln(e,0)>=0,"Amount must be zero or greater"),lr=n.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),dr=n.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),ur=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 hr(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 gr=hr(100),mr=hr(20),pr=hr(20),fr=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"),Er=n.z.string().max(255,"Filename must be at most 255 characters"),Ar=n.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),vr=n.z.string().datetime("Must be a valid ISO 8601 date string"),Sr=n.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Tr=n.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),yr=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"),kr=n.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),br=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Nr=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),name:Er,size:fr,type:Ar}),wr=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"),Cr=n.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),_r=n.z.union([wr,Cr]),Ir=n.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Dr=Er.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return br.includes(t)},`Filename must end with one of: ${br.join(", ")}`),Rr=n.z.object({websiteUrl:dr,telegramUrl:dr,twitterUrl:dr,instagramUrl:dr,facebookUrl:dr,redditUrl:dr,tiktokUrl:dr}).refine(e=>void 0!==e.websiteUrl||void 0!==e.telegramUrl||void 0!==e.twitterUrl||void 0!==e.instagramUrl||void 0!==e.facebookUrl||void 0!==e.redditUrl||void 0!==e.tiktokUrl,"At least one social URL (website, telegram, twitter, instagram, facebook, reddit, or tiktok) is required"),Or=n.z.string().min(1,"Token category must not be empty").default("Unit"),xr=n.z.string().min(1,"Token collection must not be empty").default("Token"),Mr=n.z.object({minFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>ln(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>ln(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>ln(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>ln(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>ln(e.maxFeePortion,0)>=ln(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Lr=n.z.object({tokenName:Yn,tokenSymbol:Jn,tokenDescription:Zn,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:cr.default("0"),websiteUrl:dr,telegramUrl:dr,twitterUrl:dr,instagramUrl:dr,facebookUrl:dr,redditUrl:dr,tiktokUrl:dr,tokenCategory:Or,tokenCollection:xr,reverseBondingCurveConfiguration:Mr.optional(),saleStartTime:n.z.number().int().positive().optional(),privateKey:Tr.optional()}),Ur=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),tokenName:Yn}),Fr=n.z.enum(["RECENT","POPULAR"]),Pr=n.z.object({tokenName:Yn.optional(),symbol:Jn.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),Br=n.z.enum(["NATIVE","MEME"]),$r=n.z.enum(["IN","OUT"]),Gr=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:Yn}),Kr=n.z.object({tokenName:Yn,slippageToleranceFactor:n.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:n.z.number().min(0).max(1).optional(),privateKey:Tr.optional()}),Hr=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(100).default(10)}),Wr=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),Vr=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),zr=Hr.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()}),jr=Wr.extend({tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),qr=Vr.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")}),Xr={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()},Qr=n.z.object(Xr);const Yr=n.z.enum(["buy","sell"]),Jr=n.z.enum(["BUY","SELL"]),Zr=n.z.object({tradeType:Yr,tokenAmount:ir,vaultAddress:or,userAddress:ar,slippageTolerance:ir.optional(),deadline:n.z.number().int().positive().optional()}),es=n.z.object({tokenSymbol:Jn,nativeTokenQuantity:ir,expectedToken:ir,maxAcceptableReverseBondingCurveFee:cr.default("0").optional()}),ts=n.z.object({tokenSymbol:Jn,tokenQuantity:ir,expectedNativeToken:ir,maxAcceptableReverseBondingCurveFee:cr.default("0").optional()}),ns=Vr.extend({tokenName:er.optional()}),rs=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()}),ss=n.z.enum(["NATIVE","MEME"]),as=n.z.enum(["IN","OUT"]),os=n.z.object({type:ss,method:as,vaultAddress:or,amount:ir}),is=n.z.object({nativeTokenQuantity:ir}),cs=n.z.object({vaultAddress:or}),ls=n.z.object({minFeePortion:ir,maxFeePortion:ir}),ds=n.z.enum(["both","held","created"]),us=Wr.extend({type:ds.optional(),address:ar.optional(),search:tr.optional(),tokenName:er.optional()}),hs=n.z.object({address:ar.optional(),refresh:n.z.boolean().optional()}),gs=n.z.object({profileImage:n.z.string(),fullName:nr,address:ar,privateKey:Tr.optional()}),ms=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),address:ar.optional(),privateKey:Tr.optional()}),ps=n.z.object({address:ar,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:er.optional(),withExpired:n.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function fs(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.issues.map(e=>e.message)}}}const Es=fs(Yn),As=fs(Jn),vs=fs(Zn),Ss=fs(ar),Ts=fs(or),ys=fs(ir),ks=fs(nr),bs=fs(tr),Ns=fs(er),ws=fs(Lr),Cs=fs(Rr),_s=fs(Ur),Is=fs(Pr),Ds=fs(us),Rs=fs(hs),Os=fs(gs),xs=fs(ms),Ms=fs(ps),Ls=fs(Zr),Us=fs(es),Fs=fs(ts),Ps=fs(ns),Bs=fs(rs),$s=fs(os),Gs=fs(is),Ks=fs(cs);function Hs(e){const t=ws(e);return t.success?[]:t.errors??["Unknown validation error"]}function Ws(e){const t=Hs(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Vs(e,t){return"string"==typeof e[t]}function zs(e,t){return void 0===e[t]||"string"==typeof e[t]}function js(e,t){return void 0===e[t]||"number"==typeof e[t]}function qs(e,t){switch(t){case"string":return"string"==typeof e;case"number":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return null!==e&&"object"==typeof e&&!Array.isArray(e);case"array":return Array.isArray(e);case"optional-string":return void 0===e||"string"==typeof e;case"optional-number":return void 0===e||"number"==typeof e;case"optional-boolean":return void 0===e||"boolean"==typeof e;case"optional-object":return void 0===e||null!==e&&"object"==typeof e&&!Array.isArray(e);case"optional-array":return void 0===e||Array.isArray(e);default:return!1}}function Xs(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,r]of Object.entries(e)){if(!qs(n[t],r))return!1}return!0}}Nn({BUY:"buy",SELL:"sell"});const Qs=Xs({nativeTokenQuantity:"string"});function Ys(e){if(kn(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))kn(r)||(Tn(r)?t[n]=r:"number"==typeof r||"boolean"==typeof r?t[n]=r.toString():Array.isArray(r)?t[n]=r.join(","):t[n]="object"==typeof r?JSON.stringify(r):String(r));return t}var Js=Object.freeze({__proto__:null,adaptQueryParams:Ys});function Zs(e,t="0"){return function(e,t="0"){if(Pt(e))return new i(t);if(i.isBigNumber(e))return e.isNaN()?new i(t):e;try{const n=new i(e);return n.isNaN()||!n.isFinite()?new i(t):n}catch{return new i(t)}}(e,t)}function ea(e,t){return void 0!==t?Zs(e).toFixed(t):Zs(e).toFixed()}function ta(e){const t=Zs(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function na(e){return Zs(e).isZero()}function ra(e,t){return Zs(e).isLessThan(Zs(t))}function sa(...e){e.forEach(e=>{if(e.isNaN())throw St("value","NaN");if(!e.isFinite())throw At("value","finite");if(e.isLessThanOrEqualTo(0))throw Et("value","0",e.toString())})}function aa(e,t,n){if(e.isNaN())throw St(t,"NaN");if(!e.isFinite())throw At(t,"finite");if(e.isLessThanOrEqualTo(0))throw Et(t,"0",e.toString())}function oa(e,t,n="0"){const r=Zs(t);return na(r)?Zs(n):Zs(e).dividedBy(r)}const ia={calculateBuyWithExact(e,t){const n=ln(e),r=ln(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:a,TRADING_FEE_FACTOR:o,GAS_FEE:i}=xt,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((r+n)*a)-Math.exp(r*a))/a,8),l=ea(Zs(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:i}},calculateBuyWithNative(e,t){const n=ln(e),r=ln(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:a,TRADING_FEE_FACTOR:o,GAS_FEE:i}=xt,c=Math.log(n*a/s+Math.exp(r*a))/a-r,l=ea(Zs(c).multipliedBy(o));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:i}},calculateSellWithExact(e,t,n,r,s){const a=ln(e),o=ln(t),i=ln(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=xt,h=c*(Math.exp(o*l)-Math.exp((o-a)*l))/l,g=Zs(h),m=r+o/i*(s-r),p=ea(g.multipliedBy(m),8),f=ea(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}},calculateSellWithNative(e,t,n,r,s){const a=ln(e),o=ln(t),i=ln(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=xt;if(a>=c*(Math.exp(o*l)-1)/l){const e=Zs(a),t=r+o/i*(s-r),n=ea(e.multipliedBy(t),8),c=ea(e.multipliedBy(d));return{amount:o.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=o-Math.log(Math.exp(o*l)-a*l/c)/l,g=Zs(a),m=r+o/i*(s-r),p=ea(g.multipliedBy(m),8),f=ea(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}}};class ca extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function la(e,t,n){if(null==e)throw new ca("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=wr.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new ca(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new ca("Filename is required when uploading Buffer objects",t,n);const r=Cr.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new ca(e,t,n)}try{fn(t,255,"filename")}catch(e){throw new ca(e.message,t,n)}const s=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!s.includes(n))throw new ca(`Invalid file type "${n}" is not allowed. Allowed types: ${s.join(", ")}`,t,n);const a=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),o=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!o.includes(a))throw new ca(`File extension "${a}" is not allowed. Allowed extensions: ${o.join(", ")}`,t,n);const i=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(a);if(i!==n&&"application/octet-stream"!==i)throw new ca(`File extension "${a}" does not match MIME type "${n}"`,t,n);return}throw new ca("File must be a File object (browser) or Buffer (Node.js)",t,n)}function da(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ua(e,t){if(!function(e){if(!da(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return da(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw gt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:xt.GAS_FEE}}class ha{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:a=ha.MAX_DECIMAL_PLACES,fieldName:o="amount"}=t;if(!Tn(e))throw new Je(`${o} cannot be empty or whitespace-only. Provide a valid numeric string.`,o,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Je(`${o} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,o,"INVALID_NUMERIC_STRING");const i=ln(e,NaN);if(isNaN(i))throw new Je(`${o} must be a valid numeric string. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!isFinite(i))throw new Je(`${o} must be a finite number. Cannot be Infinity or -Infinity.`,o,"INVALID_NUMERIC_STRING");if(i<0)throw new Je(`${o} must be non-negative. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");if(!n&&0===i)throw new Je(`${o} must be greater than zero. Received: "${e}"`,o,"INVALID_NUMERIC_STRING");const c=Zs(e),l=c.decimalPlaces()??0;if(l>a)throw new Je(`${o} cannot exceed ${a} decimal places. Received: ${l} decimal places`,o,"PRECISION_EXCEEDED");if(void 0!==r&&ra(c,r))throw new Je(`${o} must be at least ${r}. Received: "${e}"`,o,"BELOW_MINIMUM");if(void 0!==s&&(d=s,Zs(c).isGreaterThan(Zs(d))))throw new Je(`${o} cannot exceed ${s}. Received: "${e}"`,o,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Zs(e,t)}isValid(e,t={}){try{return null==e||""===e?!1!==t.allowZero:(this.validate(e,t),!0)}catch{return!1}}formatAmount(e,t){return ea(e,t)}clampAmount(e,t,n){const r=Zs(e),s=Zs(t),a=Zs(n);return function(e,t,n){const r=Zs(e),s=Zs(t),a=Zs(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(a)}(r,s,a)?ea(r):ra(r,s)?ea(s):ea(a)}}function ga(e,t){throw new Je(e.join("; "),t,"VALIDATION_ERROR")}function ma(e){const t=Es(e);!t.success&&t.errors&&ga(t.errors,"tokenName")}function pa(e){const t=Gr.safeParse(e);var n;t.success||ga((n=t.error.issues,Array.isArray(n)?n.map(e=>null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:String(e)).filter(e=>""!==e):[]),"options")}function fa(e,t,n=!0){Ea.validate(e,{fieldName:t,allowZero:n})}ha.MAX_DECIMAL_PLACES=18,ha.MIN_POSITIVE="0.00000000000000001";const Ea=new ha;function Aa(e,t,n=ea){if(!Array.isArray(e))throw gt("Invalid API response: expected array of holders",t);for(const n of e){if(!va(n))throw gt("Invalid holder data: missing or invalid owner field",t);if(!Sa(n))throw gt("Invalid holder data: missing or invalid quantity field",t);const e=ln(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw gt(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),Zs(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:oa(Zs(e.quantity),s,Zs(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}function va(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Sa(e){return"string"==typeof e.quantity&&""!==e.quantity}class Ta{constructor(e,t,n,r="local",s){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=r,this.launchpadWrites=s,this.metadataCache=new Bn}createSale(e){if(void 0===this.launchpadWrites)throw new Error("Launchpad write transport is not configured.");return this.launchpadWrites.createSale(e)}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;ma(t);const r=`${t}.png`;la(n.file,r,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&n.file instanceof File)e.append("image",n.file);else{if(!Buffer.isBuffer(n.file))throw ht("file","a File object (browser) or Buffer (Node.js)");{const r=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,s=new Blob([n.file],{type:"image/png"});e.append("image",s,r)}}const r=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t)}`,data:e,headers:{}});if(!0===r.error||200!==r.status)throw gt(void 0!==r.message&&""!==r.message?r.message:"Image upload failed - no URL returned",r.status);const s=Ct(r);if(!s?.imageUrl)throw gt("Image upload failed - no URL returned",r.status);return s.imageUrl}catch(e){if(nt(e)&&e.message.includes("FormData"))throw mt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){void 0!==e.pageSize&&bn(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&ma(e.tokenName);const t={pageSize:String(e.pageSize??10)};void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search),void 0!==e.hasUpcomingShows&&(t.hasUpcomingShows=e.hasUpcomingShows.toString()),void 0!==e.language&&(t.language=e.language),void 0!==e.recentlyStreamed&&(t.recentlyStreamed=e.recentlyStreamed.toString());const n=Ys(t),r=await this.http.get(d.FETCH_POOLS,n);if(!0===r.error||200!==r.status)throw gt(void 0!==r.message&&""!==r.message?r.message:"Failed to fetch pools",r.status);const s=Ct(r);if(null==s)throw gt("Failed to fetch pools - no data returned",r.status);let a=[];if(s.tokens)if(Array.isArray(s.tokens))a=s.tokens.map(e=>this.normalizePoolData(e));else{const e=s.tokens;a=[this.normalizePoolData(e)]}else s.pools&&Array.isArray(s.pools)&&(a=s.pools.map(e=>this.normalizePoolData(e)));const{extractMetadataFromPoolData:o,isValidPoolForCaching:i}=await Promise.resolve().then(function(){return Zd});a.forEach(e=>{if(!i(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=o(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=s.count??s.total??0,l={hasNextPage:s.hasNextPage??!1};return void 0!==s.hasPrevPage&&(l.hasPrevPage=s.hasPrevPage),void 0!==s.nextCursor&&(l.nextCursor=s.nextCursor),void 0!==s.prevCursor&&(l.prevCursor=s.prevCursor),c>0&&(l.totalCount=c),{items:a,pageInfo:l}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={pageSize:e.pageSize??10};return void 0!==e.cursor&&(n.cursor=e.cursor),void 0!==e.search&&""!==e.search&&(n.search=e.search),void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),null!=t&&(n.type=t),void 0!==e.hasUpcomingShows&&(n.hasUpcomingShows=e.hasUpcomingShows),void 0!==e.language&&""!==e.language&&(n.language=e.language),void 0!==e.recentlyStreamed&&(n.recentlyStreamed=e.recentlyStreamed),this.fetchPoolsFromAPI(n)}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw ht("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[Xe.NATIVE,Xe.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return ua(await It(()=>this.http.get(Ge,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:a,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[Xe.EXACT,Xe.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==s&&{currentSupply:s},...void 0!==a&&{maxSupply:a},...void 0!==o&&{reverseBondingCurveMaxFeeFactor:o},...void 0!==i&&{reverseBondingCurveMinFeeFactor:i}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s}=e;if(!Tn(n))throw ut("amount","Amount");if(r!==Xe.NATIVE&&r!==Xe.EXACT)throw vt("type",'"native" or "exact"',r);void 0!==s&&fa(s,"currentSupply");const a=null==s||""===s;if(a&&(null==t||""===t))throw ut("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&ma(t);let o=s;if(a){o=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===Xe.EXACT?ia.calculateBuyWithExact(n,o):ia.calculateBuyWithNative(n,o)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:a,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i}=e;if(!Tn(n))throw ut("amount","Amount");if(r!==Xe.EXACT&&r!==Xe.NATIVE)throw vt("type",'"exact" or "native"',r);void 0!==s&&fa(s,"currentSupply");const c=null==s||""===s||null==a||""===a||void 0===o||void 0===i;if(c&&(null==t||""===t))throw ut("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&ma(t);let l=s,d=a,u=o,h=i;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===Xe.EXACT?ia.calculateSellWithExact(n,l,d,h,u):ia.calculateSellWithNative(n,l,d,h,u)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Vs(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&zs(t,"currentSupply")}(e))throw vt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;ma(n);const a=await this.fetchSaleDetails(n),o=s??ea(Zs(a.maxSupply).minus(a.sellingTokenQuantity)),i=a.sellingTokenQuantity;if("0"===i)throw ut("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:i,type:"exact",currentSupply:o,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(c),remainingTokens:i}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw mt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Ws(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=ln(t);if(0===n&&"0"!==t)throw St("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw St("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;vn(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async fetchTokenDistribution(e){if(null==e||""===e)throw ut("tokenName","Token name");ma(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw gt(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=Ct(t);if(null==n)throw gt("Failed to fetch token distribution - no data returned",t.status);return Aa(n,t.status)}async calculateInitialBuyAmount(e){if(!Qs(e))throw ht("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return ua(await It(()=>this.http.get(Ke,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=ea(Zs(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let a=.5,o=.1;const i=t.reverseBondingCurveConfiguration;null!=i?.maxFeePortion&&(a=un(i.maxFeePortion,.5)),null!=i?.minFeePortion&&(o=un(i.minFeePortion,.1)),void 0===i&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=a-o;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){ma(e);const t=await this.fetchSaleDetails(e),n=ea(Zs(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}async fetchPoolDetails(e){ma(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...r}=t,s=n?.minFeePortion??"0",a=n?.maxFeePortion??"0";return{...r,reverseBondingCurveMinFeePortion:s,reverseBondingCurveMaxFeePortion:a,hasReverseBondingCurveFee:!na(s)||!na(a),isGraduated:"Finished"===t.saleStatus}}normalizePoolData(e){const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0";return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:!na(t)||!na(n),createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}}async fetchSaleDetails(e){return It(()=>this.http.get($e,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,r,s,a){const o=r??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw vt("mode",'"local" or "external"',o);if(!Tn(e))throw ut("tokenName","Token name");if(!Tn(t))throw ut("amount","Amount");if("string"!=typeof n||!s.includes(n))throw vt("type",a,n);return o}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new Je("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new Je("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Wn(e)}validateTokenName(e){return ma(e)}validatePagination(e){void 0!==e.pageSize&&bn(0,void 0,100,e.pageSize)}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const ya={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class ka{constructor(){this.data=new Map}async get(e){return this.data.get(e)??null}async set(e,t){this.data.set(e,t)}async remove(e){this.data.delete(e)}}var ba;exports.AuthErrorType=void 0,(ba=exports.AuthErrorType||(exports.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",ba.SIGNATURE_FAILED="SIGNATURE_FAILED",ba.INVALID_ADDRESS="INVALID_ADDRESS",ba.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class Na extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class wa{constructor(e,t=ya.REFRESH_THRESHOLD_MS){this.tokenState=null,this.STORAGE_KEYS={ACCESS_TOKEN:"lpad_access_token",ACCESS_EXPIRES:"lpad_access_expires",REFRESH_TOKEN:"lpad_refresh_token",REFRESH_EXPIRES:"lpad_refresh_expires"},this.storage=e??new ka,this.refreshThresholdMs=t}setToken(e,t){if(!Tn(e))throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,r){if(this.setToken(e,t),n){const e=Date.now()+1e3*(r??7776e3);if(!this.tokenState)throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${ya.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[ya.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),a=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&a){const e=Number(a);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}async function Ca(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const r=ot(e)?e.response?.status:void 0;return gt(`${t}: ${rt(e)}`,r,nt(e)?e:void 0)}(e,t,n))}}class _a{constructor(e,t,n,r=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new Ft({debug:r,context:"SessionAuthService"})}async login(){if(this.loginPromise)return this.logger.debug("Login already in progress, reusing existing promise"),this.loginPromise;if(!this.signatureAuth.hasWallet())throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return Ca(async()=>{const e=Date.now(),t=`${ya.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=this.signatureAuth.getAddress();qn(r,"address");const s={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const a=await this.http.post(O,s),o=this.extractLoginData(a);return await this.jwtAuth.setTokens(o.accessToken,o.expiresIn,o.refreshToken,o.refreshExpiresIn),this.logger.debug("Login successful",{address:o.address,expiresIn:o.expiresIn,hasRefreshToken:!!o.refreshToken}),o},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Na)throw e;throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${rt(e)}`,nt(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(!this.jwtAuth.hasToken())throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performRefresh(){return Ca(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.jwtAuth.getRefreshToken();if(e){this.logger.debug("Using refresh token flow");const t=await this.http.post(M,{refreshToken:e}),n=this.extractLoginData(t);return await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),this.logger.debug("Token refreshed successfully via refresh token",{address:n.address,expiresIn:n.expiresIn,hasNewRefreshToken:!!n.refreshToken}),n}this.logger.debug("Using legacy access token refresh");const t=await this.http.post(M,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof Na)throw e;throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${rt(e)}`,nt(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(x,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${rt(e)}`)}else t&&this.logger.debug("Skipping server-side revocation: no valid local token available");await this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Ca(async()=>{const e=await this.http.get(L,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Na)throw e;throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${rt(e)}`,nt(e)?e:void 0)})}getAccessToken(){return this.jwtAuth.getToken()}isAuthenticated(){return this.jwtAuth.isValid()}shouldRefresh(e){return this.jwtAuth.shouldRefresh(e)}async ensureValidToken(e){if(!this.jwtAuth.hasToken())throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${rt(e)} - attempting re-login`)}}else this.logger.debug("Token expired - no refresh token available, attempting re-login");return(await this.login()).accessToken}if(this.jwtAuth.shouldRefresh(e)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(e){if(e.error)throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,""!==rt(e)?rt(e):"Authentication failed");const t=_t(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:a,refreshExpiresIn:o}=t;if(!Tn(n))throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:s,...void 0!==a&&{refreshToken:a},...void 0!==o&&{refreshExpiresIn:o}}}extractSessionData(e){if(e.error)throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,""!==rt(e)?rt(e):"Failed to get session");return _t(e,"No data in session response")}}class Ia{constructor(e){if(this.wallet=e.wallet,e.walletProvider?this.walletProvider=e.walletProvider:e.wallet,this.messagePrefix=e.messagePrefix??"Create a GalaChain Wallet",void 0!==e.messagePrefix)try{An(e.messagePrefix,"messagePrefix",!1)}catch{throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=r.PrivateKeyProvider.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Wn(this.wallet.address)}catch(e){if(e instanceof Na)throw e;if(e instanceof Je&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Na(exports.AuthErrorType.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Na(exports.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=r.PrivateKeyProvider.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Wn(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(t){this.walletProvider=t,this.wallet=void 0;const n=void 0!==t&&r.isPrivateKeyProvider(t)?e.computeAddress(t.exportPrivateKey()):void 0;this.cachedAddress=n,this.cachedGalaAddress=void 0===n?void 0:Wn(n)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=await this.walletProvider.getGalaAddress())}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof Na)throw e;throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",nt(e)?e:new Error(rt(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getGalaAddress()}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null===this.wallet.privateKey||void 0===this.wallet.privateKey)throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&r.isPrivateKeyProvider(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.")}async getPrivateKeyAsync(){if(await this.validateWalletAsync(),!this.walletProvider.getPrivateKey)throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",nt(e)?e:void 0)}}formatAddress(e){try{return Wn(e)}catch{throw new Na(exports.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Na)throw e;throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,rt(e),nt(e)?e:new Error(rt(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(r);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof Na)throw e;throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",nt(e)?e:new Error(rt(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof Na)throw e;throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",nt(e)?e:new Error(rt(e)))}}async generateCustomSignature(e){if(!Tn(e))throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getGalaAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Na)throw e;throw new Na(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",nt(e)?e:new Error(rt(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Na(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Da={prod:{...t.GALA_CHAIN_ENVIRONMENTS.prod,bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},stage:{...t.GALA_CHAIN_ENVIRONMENTS.stage,bundleBaseUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadBaseUrl:"https://lpad-backend.stage.defi.ovh.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",webSocketUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function Ra(e){return Da[e]}var Oa,xa;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Oa||(Oa={})),exports.SDKTransactionStatus=void 0,(xa=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",xa.PROCESSING="processing",xa.COMPLETED="completed",xa.FAILED="failed",xa.TIMEOUT="timeout";const Ma={[Oa.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[Oa.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[Oa.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[Oa.FAILED]:exports.SDKTransactionStatus.FAILED,[Oa.ERROR]:exports.SDKTransactionStatus.FAILED,[Oa.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[Oa.PENDING]:exports.SDKTransactionStatus.PENDING},La="9.0.0-rc.0",Ua={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Fa(e,t=1,n=Ua.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Pa(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Ba(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const r=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(r),n}function $a(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=Pa(n))}return e}const Ga="x-api-key";class Ka extends Un{constructor(e,t,n,r=!1,s){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=s??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Tn(e))throw ut("tokenName","Token name");const n=Mt(e);if(!t.PATTERN.test(n))throw ht("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Tn(e))throw ut(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw vt(t,"string",typeof e,n);if(e.length>r)throw At(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,s,a,o){!function(e,t,n,r,s){if(null!=e){if("number"!=typeof e)throw vt(t,"number",typeof e,n);if(e<r||e>s)throw ft(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Kt(e))throw ht(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Mn(e,t,n)}validateStatusFilter(e,t,n="status"){Ln(e,t,n)}buildPaginationParams(e,t){return Ba(e,t)}addOptionalFilterParams(e,t,n){return $a(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,r]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(r.toLowerCase()));return n}(e,t)}buildEndpointWithId(e,t){return e.replace(":id",encodeURIComponent(t))}validateAndBuildTokenEndpoint(e,t,n){return this.validateTokenName(e,t),this.buildEndpoint(n,{tokenName:e})}getAdminHeaders(){if(void 0===this.adminApiKey||""===this.adminApiKey)throw new et("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[Ga]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new et("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return void 0!==this.adminApiKey&&""!==this.adminApiKey}getDualAuthHeaders(){return void 0!==this.adminApiKey&&""!==this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}getMultiAuthHeaders(){return void 0!==this.userApiKey&&""!==this.userApiKey?{[Ga]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return wt(e,"Backend request failed",!0),_t(e,"No data in backend response")}extractDataOrNull(e){return wt(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(r,{},this.getAdminHeaders()),a=this.extractData(s);return{enabled:a.enabled,tokenName:a.tokenName??Mt(e)}}}class Ha extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(Fe.GET_SETTINGS,{},this.getDualAuthHeaders())).settings}}async updateSettings(e){const t={};void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.mode&&(t.mode=e.mode),void 0!==e.provider&&(t.provider=e.provider);return{settings:(await this.http.post(Fe.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Fe.GET_MODERATION.replace(":flagId",String(e.flagId));return{moderation:(await this.http.get(t,{},this.getDualAuthHeaders())).analysis}}async triggerModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Fe.TRIGGER_MODERATION.replace(":flagId",String(e.flagId)),n=await this.http.post(t,{},this.getDualAuthHeaders());return{queued:n.queued,message:n.message.length>0?n.message:"Moderation queued successfully"}}async getStatus(){return{status:(await this.http.get(Fe.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const Wa={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},Va=wn(Wa),za={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},ja=Object.values(za);function qa(e){return Va.includes(e)}function Xa(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):qa(e.role)||t.push(`Invalid role. Must be one of: ${Va.join(", ")}`),Ya(e,t),t}function Qa(e){const t=[];return["role","description","delegateAllTokens","tokenNames","expiresAt","tokenPermissions"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||qa(e.role)||t.push(`Invalid role. Must be one of: ${Va.join(", ")}`),Ya(e,t,!0),t}function Ya(e,t,n=!1){const r=t.length;if(ct(t,()=>{On(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;ct(t,()=>{if(!Array.isArray(e.tokenNames))throw vt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw vt("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n?.includes("array")?t[e]="tokenNames must be an array":n?.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt&&(!n||null!==e.expiresAt)){const n=t.length;ct(t,()=>{xn(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function Ja(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>zt))throw vt("pageSize",`number between 1 and ${zt}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw vt("cursor","non-empty string",typeof e.cursor)}const Za={[Wa.MODERATOR]:1,[Wa.TECHNICAL_PRODUCER]:1,[Wa.MANAGER]:2,[Wa.OWNER]:3};class eo extends Un{constructor(e,t,n=!1){super(e,n,t)}extractData(e){let t;t="error"in e?e.error:"success"in e&&!e.success;const n={status:200,error:t,data:e.data};return void 0!==e.message&&(n.message=e.message),wt(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=Xa(e);if(t.length>0)throw new Je(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(V.CREATE,n,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){Ja(e),this.logger.debug("Listing API keys",e);const t=Ba(e,zt),n=await this.http.get(V.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=V.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=Qa(t);if(n.length>0)throw new Je(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const s=V.UPDATE.replace(":id",String(e)),a=await this.http.patch(s,r,this.getJwtHeaders()),o=this.extractData(a);return this.logger.debug("Updated API key",{id:o.id,keyPrefix:o.keyPrefix}),o}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=V.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Va]}}const to={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},no=Nn(to),ro=In([{field:"id",type:"number"},{field:"userAddress",type:"string"},{field:"bannedBy",type:"string"},{field:"createdAt",type:"string"},{field:"isPermanent",type:"boolean"},{field:"tokenName",type:"string",nullable:!0},{field:"reason",type:"string",nullable:!0},{field:"expiresAt",type:"string",nullable:!0}]),so=In([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),ao=In([{field:"userAddress",type:"string"}]),oo=In([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function io(e){return null==e||""===e||"string"==typeof e&&(!Rn(e)&&e.length<=Yt.BAN_REASON.MAX_LENGTH)}function co(e){return!!kn(e)||"number"==typeof e&&(e>=Zt&&e<=en)}function lo(e){if(!Tn(e.userAddress))throw ut("userAddress");if(!io(e.reason))throw new Je(`reason must be at most ${Yt.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!co(e.durationSeconds))throw new Je(`durationSeconds must be between ${Zt} and ${en} seconds`,"durationSeconds","OUT_OF_RANGE")}class uo extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){Cn(e.tokenName,"tokenName",Ht),lo(e)}(e);const t=this.buildEndpoint(U,{tokenName:e.tokenName}),n=ho(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:Mt(e.tokenName)}}async removeBan(e){!function(e){if(Cn(e.tokenName,"tokenName",Ht),!Tn(e.userAddress))throw ut("userAddress")}(e);const t=this.buildEndpoint(B,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,tokenName:Mt(e.tokenName),userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){Cn(e.tokenName,"tokenName",Ht),bn(0,void 0,zt,e.pageSize)}(e);const t=this.buildEndpoint(F,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,zt);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(Cn(e.tokenName,"tokenName",Ht),!Tn(e.userAddress))throw ut("userAddress")}(e);const t=this.buildEndpoint(P,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Mt(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(Cn(e.tokenName,"tokenName",Ht),void 0!==e.type&&!no(e.type))throw new Je(`type must be one of: ${Object.values(to).join(", ")}`,"type",Ye.INVALID_VALUE)}(e);const t=this.buildEndpoint($,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){lo(e)}(e);const t=ho(e),n=await this.http.post(G,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Tn(e.userAddress))throw ut("userAddress")}(e);const t=this.buildEndpoint(W,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){bn(0,void 0,zt,e.pageSize)}(t);const n=this.buildPaginationParams(t,zt);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const r=await this.http.get(K,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!Tn(e.userAddress))throw ut("userAddress")}(e);const t=this.buildEndpoint(H,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},userAddress:e.userAddress.toLowerCase()}}}function ho(e){const t={userAddress:e.userAddress};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function go(e){return{maxAcceptableReverseBondingCurveFee:gn(e.maxAcceptableReverseBondingCurveFee)}}class mo extends s.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=gn(t),this.expectedToken=mn(n),this.extraFees=go(r)}}class po extends s.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=mn(t),this.expectedNativeToken=gn(n),this.extraFees=go(r)}}class fo extends s.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=mn(t),this.expectedNativeToken=gn(n),this.extraFees=go(r)}}class Eo extends s.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=gn(t),this.expectedToken=mn(n),this.extraFees=go(r)}}const Ao={BuyNativeDto:mo,BuyExactDto:po,SellExactDto:fo,SellNativeDto:Eo};function vo(e,t,n){let r;pn(t,0,1,"slippageToleranceFactor");try{r=function(e,t){if(Bt(e)||""===e)throw ut(t);if(i.isBigNumber(e)){if(e.isNaN())throw St(t,"NaN");return e}try{const n=new i(e);if(n.isNaN())throw St(t,e);if(!n.isFinite())throw St(t,e);return n}catch(n){if(n instanceof Je)throw n;throw St(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=r.multipliedBy(t);let a;switch(n){case"buy-native":case"sell-exact":a=r.minus(s);break;case"buy-exact":case"sell-native":a=r.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return Zs(a).isLessThan(0)&&(a=Zs(0)),ea(a)}function So(e,t){if(!Tn(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);return n}function To(e,t,n,r){const s=e?.split?.(t)??[],a=void 0!==n?` (${n})`:"";return new Je(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${a}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${rt(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function yo(e,t,n){try{const n=So(e,t),r=n[n.length-1],s=n[n.length-2],a=n[n.length-3],o=n.slice(0,n.length-3).join(t);if(void 0===o||void 0===a||void 0===s||void 0===r||""===r||""===o||""===a||""===s)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:o,category:a,type:s,additionalKey:r}}catch(r){throw To(e,t,n,r)}}function ko(e){return function(e,t,n){try{const n=So(e,t),[r,s,a,...o]=n;if(""===r||""===s||""===a)throw new Error("Collection, category, and type must be non-empty");const i=o.join(t);if(void 0===r||void 0===s||void 0===a||""===i)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:s,type:a,additionalKey:i}}catch(r){throw To(e,t,n,r)}}(e,"|","pipe-delimited token")}const bo={name:"GalaChain"},No={name:"ethereum",chainId:1};function wo(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function Co(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=_o(r));return t}function _o(e){return Array.isArray(e)?e.map(_o):"object"==typeof e&&null!==e?Co(e):e}function Io(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class Do extends t.PrivateKeySigner{constructor(t){super(t),this.typedDataWallet=new e.Wallet(t),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,n){const r=Co(n),s=t.generateEIP712Types(e,r);return Io(r,await this.typedDataWallet.signTypedData(bo,s,r),s,bo)}}class Ro extends t.GalaWalletSigner{async signTypedData(e,n){const r=Co(n),s=t.generateEIP712Types(e,r),a={domain:No,types:s,message:r,Primary_type:e},o=function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();return Io(r,wo(await o.request({method:"eth_signTypedData",params:[JSON.stringify(a),await this.typedDataAccount(o)]})),s,No)}async typedDataAccount(t){if(e.isAddress(this.walletAddress))return this.walletAddress;const n=await t.request({method:"eth_accounts"}),r=Array.isArray(n)?n[0]:void 0,s="string"==typeof r?r.replace(/^eth\|/,"0x"):"";if(!e.isAddress(s))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return s}}class Oo extends t.BrowserWalletSigner{constructor(e,t,n){super(e,t,n),this.typedDataProvider=e}async signTypedData(n,r){const s=Co(r),a=this.typedDataProvider,o=await a.getNetwork(),i={name:o.name,chainId:Number(o.chainId)},c=t.generateEIP712Types(n,s),l=await a.getSigner(),d=e.getAddress(await l.getAddress());if(e.isAddress(this.walletAddress)&&d!==e.getAddress(this.walletAddress))throw new Error(`Wallet account ${d} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`);return Io(s,wo(await l.signTypedData(i,c,s)),c,i)}}function xo(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const r=n.split("$"),s=r[r.length-1],a=r.slice(0,-1),o=a.slice(0,-3).join("$"),[i,c,l]=a.slice(-3);if("launchpad"!==s||a.length<4||""===o||void 0===i||void 0===c||void 0===l||""===i||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:o,category:i,type:c,additionalKey:l}}function Mo(e){const{collection:t,category:n,type:r}=xo(e),s=`${t}$${n}$${r}$none`,a="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${a}$${e}`,`$tokenBalance$${a}$${e}`]}function Lo(e){const t=`${e.tokenName}$Unit$none$none`,n=`$service$${t}$launchpad`;return Number(e.preBuyQuantity??"0")>0?[n,`$token$${t}$${n}`,`$tokenBalance$${t}$${n}`,`$tokenBalance$${t}$${n}`,`$tokenBalance$GALA$Unit$none$none$${n}`,`$tokenBalance$GALA$Unit$none$none$${n}`]:[n,`token$${t}$${n}`,`tokenBalance$${t}$${n}`]}function Uo(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Fo(e){if("string"==typeof e){if(!Tn(n=e)||!n.includes("|"))throw new Je(`Invalid tokenId string format: "${e}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const t=e.split("|");if(t.length>=5){const e=ko(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...ko(e),instance:"0"}}var n;if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!t.isTokenClassKey(e))throw new Je("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!t.isTokenClassKey(e))throw new Je("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new Je(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Po(e){return function(e){try{if(!Tn(e))throw new Error("Vault address must be a non-empty string");const t=e.split("|")[1];if(""===t||void 0===t)throw new Error("Missing token part after service prefix");const n=t.split("$");return yo((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new Je(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${rt(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Bo(e){return{...Po(e),instance:"0"}}function $o(e){const t=Po(e);if("Token"!==t.collection)throw new Je(`Cannot extract a token symbol from vault address "${e}": collection "${t.collection}" is not the launchpad "Token" collection, and a symbol cannot be derived from a class key.`,"vaultAddress","SYMBOL_NOT_DERIVABLE_FROM_KEY");return t.type}var Go,Ko,Ho,Wo,Vo=Object.freeze({__proto__:null,extractTokenSymbolFromVault:$o,normalizeToTokenInstanceKey:Fo,parseVaultAddressToTokenClassKey:Po,parseVaultAddressToTokenInstance:Bo});class zo extends Fn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=Mo(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=rt(e);throw new Je(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}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(!Tn(e))throw ut("vaultAddress","Vault address");try{const t=$o(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof Je)throw ht("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Tn(e))throw ut("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw ht("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw ht("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Tn(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],r=t[2];return void 0===n||void 0===r?null:{tokenSymbol:n,creatorAddress:r.toLowerCase()}}(e);if(!t)throw ht("vaultAddress","valid vault address format (service|Token$Unit$SYMBOL$eth:address$launchpad)");const n=t.tokenSymbol;if(""===n||!/^[A-Za-z]{1,10}$/.test(n))throw ht("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return yo(e,"$","dollar-delimited token")}catch(e){if(e instanceof Je)throw ht("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function jo(e){return"object"==typeof e&&null!==e?e:void 0}class qo extends Un{constructor(e,t,n=!1,r,s,a=.05,o=.01,i){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=s,this.defaultSlippageToleranceFactor=a,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=o,this.sellFeeCeiling=i,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=jo(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new Do(t):function(e){const t=jo(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new Oo(this._walletProvider,this.userAddress)),this.tokenKeyService=new zo(n)}}async submitTransaction(e){try{this.validateBundleData(e),this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)});const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});let n=null;try{n=await Dt(()=>this.http.post(this.bundleEndpoint,t),{errorContext:"Bundle transaction submission failed",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==n?{success:!1,error:"No response from bundle API"}:(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:Nt(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof Je)return{success:!1,error:rt(e)};throw e}}validateBundleData(e){if(null==e)throw ut("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw ut("signedDto","Signed DTO");if(!Tn(e.method))throw ut("method","Method name");if(!Array.isArray(e.stringsInstructions))throw ht("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Je("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw ht("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Tn(e))throw new Je(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new Je(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT");var n}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){const t=Ct(e);if(null!=t&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",t),{success:!0,data:t};const n=("string"==typeof e.error?e.error:e.message)??"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",n),{success:!1,error:n}}formatErrorMessage(e){if("string"==typeof e)return e;if(ot(e)&&null!==e.response&&void 0!==e.response){const t=Ct(e.response);if(null!=t&&"object"==typeof t){const e=t;if(null!==e.error&&void 0!==e.error)return"string"==typeof e.error?e.error:JSON.stringify(e.error);if(null!==e.message&&void 0!==e.message)return"string"==typeof e.message?e.message:JSON.stringify(e.message)}}return rt(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Tn(e))throw ut("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Dt(()=>this.http.get(`${this.bundleEndpoint}?id=${e}`),{errorContext:"Failed to get bundler transaction result",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from bundler transaction query"}:(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t})}catch(e){if(e instanceof Je)return{success:!1,error:rt(e)};throw e}}async cancelTransaction(e){try{if(!Tn(e))throw ut("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Dt(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from transaction cancellation"}:(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t})}catch(e){if(e instanceof Je)return{success:!1,error:rt(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Dt(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:a,effectiveMaxFee:o,vaultAddress:i}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==s||""===s)throw new Je("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=vo(s,a,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:a,adjustedMinTokens:e});const t=new Ao.BuyNativeDto(i,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyWithNative",i)}{if(null==s||""===s)throw new Je("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=vo(s,a,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:a,adjustedMaxGalaCost:e});const t=new Ao.BuyExactDto(i,n,e,{maxAcceptableReverseBondingCurveFee:o});return await this.executeBundleTransaction(t,"BuyExactToken",i)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:a,effectiveMaxFee:o,vaultAddress:i}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,i):o;if("exact"===r){if(null==s||""===s)throw new Je("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=vo(s,a,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:a,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Ao.SellExactDto(i,n,e,t);return await this.executeBundleTransaction(r,"SellExactToken",i)}{if(null==s||""===s)throw new Je("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=vo(s,a,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:a,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Ao.SellNativeDto(i,n,e,t);return await this.executeBundleTransaction(r,"SellWithNative",i)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:s,effectiveMaxFee:a}=this.calculateEffectiveSlippage(t,n,r),o=await this.resolveTokenNameToVault(e);if(null==o)throw dt(e);return{effectiveSlippageFactor:s,effectiveMaxFee:a,vaultAddress:o}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw mt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let a=e??"0";return null!=e&&(a=vo(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:a})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:s,effectiveMaxFee:a}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw mt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw ut("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${a.v4().replace(/-/gu,"").substring(0,26)}`;const r=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),o={stringsInstructions:s,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(r)});const i=await this.submitTransaction(o);if(i.success){const e=Ct(i);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const c=i.error;throw new tt("string"==typeof c?c:"Bundle transaction failed",void 0,"BUNDLE_FAILED")}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}class Xo extends Un{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(qe),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}exports.ContentType=void 0,(Go=exports.ContentType||(exports.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",Go.COMMENT="COMMENT",Go.STREAM="STREAM",Go.RECORDING="RECORDING",exports.FlagReason=void 0,(Ko=exports.FlagReason||(exports.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",Ko.SPAM="SPAM",Ko.HARASSMENT="HARASSMENT",Ko.SCAM="SCAM",Ko.OTHER="OTHER",exports.FlagStatus=void 0,(Ho=exports.FlagStatus||(exports.FlagStatus={})).PENDING="PENDING",Ho.DISMISSED="DISMISSED",Ho.ACTIONED="ACTIONED",exports.FlagAction=void 0,(Wo=exports.FlagAction||(exports.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",Wo.BAN_USER="BAN_USER",Wo.DELETE_AND_BAN="DELETE_AND_BAN";const Qo={[exports.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[exports.FlagReason.SPAM]:"Spam",[exports.FlagReason.HARASSMENT]:"Harassment",[exports.FlagReason.SCAM]:"Scam",[exports.FlagReason.OTHER]:"Other"},Yo={[exports.FlagStatus.PENDING]:"Pending",[exports.FlagStatus.DISMISSED]:"Dismissed",[exports.FlagStatus.ACTIONED]:"Actioned"},Jo={[exports.FlagAction.DELETE_CONTENT]:"Delete Content",[exports.FlagAction.BAN_USER]:"Ban User",[exports.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},Zo={[exports.ContentType.CHAT_MESSAGE]:"Chat Message",[exports.ContentType.COMMENT]:"Comment",[exports.ContentType.STREAM]:"Stream",[exports.ContentType.RECORDING]:"Recording"},ei=Nn(exports.ContentType),ti=Nn(exports.FlagReason),ni=Nn(exports.FlagStatus),ri=Nn(exports.FlagAction),si=In([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:ei},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:ni}]),ai={TOKEN_NAME:Wt,CONTENT_ID:Yt.CONTENT_ID,DETAILS:Yt.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:zt}};function oi(e,t="tokenName"){Cn(e,t,ai.TOKEN_NAME)}function ii(e){if(void 0!==e.contentType&&!ei(e.contentType))throw ht("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!ni(e.status))throw ht("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!ti(e.reason))throw ht("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!Tn(e.reporterAddress))throw vt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&qn(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Tn(e.reportedUserAddress))throw vt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&qn(e.reportedUserAddress,"reportedUserAddress"),bn(0,void 0,ai.PAGINATION.MAX_LIMIT,e.pageSize)}class ci extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(oi(e.tokenName),void 0===e.contentType)throw ut("contentType","Content type");if(!ei(e.contentType))throw ht("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(!Tn(e.contentId))throw ut("contentId","Content ID");if(e.contentId.length>ai.CONTENT_ID.MAX_LENGTH)throw At("contentId",ai.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Tn(e.reportedUserAddress))throw ut("reportedUserAddress","Reported user address");if(qn(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==exports.ContentType.STREAM&&e.contentType!==exports.ContentType.RECORDING||void 0!==e.reason&&null!==e.reason))throw ut("reason","Reason");if(void 0!==e.reason&&!ti(e.reason))throw ht("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`,"Reason");if(void 0!==e.details&&!Tn(e.details))throw vt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>ai.DETAILS.MAX_LENGTH)throw At("details",ai.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};null!==e.reason&&void 0!==e.reason&&(t.reason=e.reason),null!==e.details&&void 0!==e.details&&(t.details=e.details);const n=await this.http.post(ee.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){oi(e.tokenName),ii(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&oi(e.tokenName),ii(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw ut("flagId","Flag ID");try{En(e.flagId,"flagId")}catch{throw ht("flagId","a positive integer","Flag ID")}}(e);const t=ee.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw ut("flagId","Flag ID");try{En(e.flagId,"flagId")}catch{throw ht("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw ut("action","Action");if(!ri(e.action))throw ht("action",`one of: ${Object.values(exports.FlagAction).join(", ")}`,"Action")}(e);const t=ee.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async fetchFlagList(e){const t=Ba(e,zt);$a(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(ee.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const li=["heart","fire","laugh","wow","thumbs_up"];class di extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateReactionTokenName(e){this.validateTokenName(e,Wt)}validateMessageId(e){if(!Tn(e))throw ut("messageId","Message ID");if(fn(e,Jt.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Jt.CONTENT_REACTION.PATTERN.test(e))throw ht("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Tn(e))throw ut("reactionType","Reaction type");if(!li.includes(e))throw ht("reactionType",`one of: ${li.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Ce,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=Mt(e.tokenName));const r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:a,...o}=s;return{data:o,created:a}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${_e}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}const ui="Token name is required and must be a string";const hi="GALA|Unit|none|none";class gi extends Fn{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Tn(e))throw new Je(ui,"tokenName",Ye.REQUIRED);let r;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(r=Uo(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${rt(t)}`)}if(void 0!==r)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(r);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),r=await this.fetchMarketUsdPrice(hi),s=ln(n.amount,0)/1e18;if(s<=0)throw new Je(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");return{symbol:Lt(e),price:r.price/s}}catch(t){throw gt(`Failed to calculate launchpad token spot price for ${e}: ${rt(t)}`)}}async resolveAuthoritativeSymbol(e){if(e===hi)return"GALA";const t=this.cache?.getByTokenId(e);if(null!=t?.symbol&&""!==t.symbol)return t.symbol;let n;this.logger.debug(`Symbol cache miss for ${e}, reading the token class`);try{if(void 0===this.fetchTokenDetails)throw gt("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw gt(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${rt(t)}`)}if(""===n)throw gt(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!Tn(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}(e);if(this.logger.debug(`Fetching swap backend price for token: ${t}`),void 0===this.dexBackendHttp)throw gt("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),r=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),s=null!==r&&"object"==typeof r?r:{},a=Object.keys(s).find(e=>e.toUpperCase()===n.toUpperCase()),o=void 0!==a?s[a]:1===Object.keys(s).length?Object.values(s)[0]:void 0,i=o?.price;if("number"!=typeof i||!Number.isFinite(i))throw new Je(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${i}`),{symbol:n,price:i}}catch(e){if(e instanceof Je)throw e;throw gt(`Failed to fetch DEX spot price: ${rt(e)}`)}}}const mi={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1};class pi{constructor(e,t={}){this.eventBuffer=[],this.flushTimer=null,this.isShuttingDown=!1,this.totalQueued=0,this.totalFlushed=0,this.totalDropped=0,this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.eventBuffer.length>0&&this.flushWithBeacon()},this.handleBeforeUnload=()=>{this.eventBuffer.length>0&&this.flushWithBeacon()},this.httpClient=e,this.logger=new Ft({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??mi.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??mi.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??mi.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??mi.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??mi.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??mi.DEBUG},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const r={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:n.userAddress},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}function fi(e){let t;return{requestor:async(n,r)=>{const s="string"==typeof r?.body?JSON.parse(r.body):void 0,{data:a,status:o,headers:i}=await e(n,s);t=a;const c=void 0===a?"":JSON.stringify(a),l="number"==typeof o?o:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(a),text:()=>Promise.resolve(c),headers:i??{}}},answer:()=>t}}const Ei=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class Ai extends Un{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,n=!1){try{const{requestor:r}=fi(async(e,t)=>({data:await this.http.post(e,t)})),s=new t.GatewayReads({gatewayBaseUrl:"",httpRequestor:r,requestTimeoutMs:1/0}),{owner:a,collection:o,category:i,type:c,additionalKey:l}=e,d=await s.fetchTokenBalance({owner:a,tokenClassKey:{collection:o,category:i,type:c,additionalKey:l},includeExpiredHolds:n});return void 0===d?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,r={quantity:e.quantity,collection:t,category:n,tokenId:Uo(e.tokenClassKey)};return e.inUseHolds.length>0&&(r.inUseHolds=[...e.inUseHolds],r.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(r.lockedHolds=[...e.lockedHolds],r.lockedQuantity=e.lockedQuantity),void 0===r.lockedQuantity&&void 0===r.inUseQuantity||(r.availableQuantity=e.availableQuantity),r}(d)}catch(e){if(t.isGalaError(e)&&Ei.has(e.code))return null;throw gt(`Failed to fetch token balance from GalaChain: ${rt(e)}`,void 0,nt(e)?e:void 0)}}}function vi(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Tn(t.amount)&&(void 0!==t.tokenId||Tn(t.tokenName))&&(void 0===t.lockAuthority||"string"==typeof t.lockAuthority)&&(void 0===t.expires||"number"==typeof t.expires)&&(void 0===t.name||"string"==typeof t.name)}function Si(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Tn(t.amount)&&(void 0!==t.tokenId||Tn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function Ti(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(vi)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function yi(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Si)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var ki,bi;exports.LockErrorType=void 0,(ki=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",ki.INVALID_AMOUNT="INVALID_AMOUNT",ki.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",ki.SIGNATURE_FAILED="SIGNATURE_FAILED",ki.NETWORK_ERROR="NETWORK_ERROR",ki.WALLET_REQUIRED="WALLET_REQUIRED",ki.VALIDATION_ERROR="VALIDATION_ERROR",ki.LOCK_NOT_FOUND="LOCK_NOT_FOUND",ki.LOCK_EXPIRED="LOCK_EXPIRED",ki.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",ki.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",ki.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class Ni extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="LockError"}}!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"}(bi||(bi={}));class wi extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function Ci(e){const t=e?.tokens?.[0];if(void 0===t)return;const n={};return void 0!==t.tokenName&&(n.tokenName=t.tokenName),void 0!==t.amount&&(n.amount=t.amount),Object.keys(n).length>0?n:void 0}async function _i(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=Bo(s);return n.debug(r,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new Je(`Token "${e}" is not a launchpad token (no vault address found), and a token class key cannot be derived from a name. Pass an explicit tokenId (collection|category|type|additionalKey) for standard GalaChain tokens.`,"tokenName","TOKEN_CLASS_KEY_NOT_DERIVABLE")}class Ii extends Un{constructor(e,t,n,r=!1,s){super(e,r),this.wallet=t,this.tokenResolver=n,this.writer=s,this.nativeSigner=t?new Do(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:Wn(this.wallet.address)}:this.writer}}function Di(e,t){const{collection:n,category:r,type:s,additionalKey:a,instance:o}=e;return{tokenClassKey:{collection:n,category:r,type:s,additionalKey:a},instance:o,quantity:t}}const Ri=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function Oi(e,{signer:n,walletAddress:r}){const{requestor:s,answer:a}=fi((t,n)=>e.postWithMeta(t,n));return{writes:new t.GatewayWrites({gatewayBaseUrl:"",signer:n,walletAddress:r,httpRequestor:s,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:a}}async function xi(e,n,r){let s;try{s=await n(e.writes)}catch(n){throw function(e){return t.isGalaError(e)&&Ri.has(e.code)}(n)&&r(e.answer(),void 0),n}return r(e.answer(),s)}function Mi(e){return void 0===e||""===e?{}:{uniqueKey:e}}const Li=100,Ui=100;class Fi extends Ii{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Ni("Wallet required for token lock operations",exports.LockErrorType.WALLET_REQUIRED);return Ca(async()=>{const n=Oi(this.http,t),r=n.writes.walletAddress,s=[],a=[];let o=r;const i=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==i?.lockAuthority&&(o=Wn(i.lockAuthority));const c=e.tokens.find(e=>void 0!==e.expires),l=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);a.push(Di(e,t.amount)),s.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount,lockAuthority:void 0!==t.lockAuthority?Wn(t.lockAuthority):o})}return xi(n,t=>t.lockTokens({tokens:a,lockAuthority:o,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...Mi(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token lock failed"),this.extractLockResult(e,t,s)))},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){this.validateUnlockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Ni("Wallet required for token unlock operations",exports.LockErrorType.WALLET_REQUIRED);return Ca(async()=>{const n=[],r=[],s=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);r.push(Di(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return xi(Oi(this.http,t),t=>t.unlockTokens({tokens:r,...void 0!==s?.name&&{name:s.name},...Mi(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token unlock failed"),this.extractUnlockResult(e,t,n)))},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}assertLockAnswer(e,t){try{it(e,t)}catch(t){const n=function(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}(e);throw new Ni(`${rt(t)}${n}`,exports.LockErrorType.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new Ni("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{_n(e.tokenName,"tokenName")}catch{throw new Ni("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{sa(Zs(e.amount))}catch{throw new Ni(ht(t,"a positive number",n).message,exports.LockErrorType.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!Ti(e))throw new Ni("Invalid lock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>Li)throw new Ni(`Batch size exceeds maximum limit of ${Li} tokens per lock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!jn(t.lockAuthority))throw new Ni("Invalid lock authority address format",exports.LockErrorType.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{En(t.expires,"expires")}catch{throw new Ni(ht("expires","a positive integer (epoch milliseconds)","Expires").message,exports.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!yi(e))throw new Ni("Invalid unlock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>Ui)throw new Ni(`Batch size exceeds maximum limit of ${Ui} tokens per unlock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},locked:n}}extractUnlockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},unlocked:n}}handleLockError(e,n,r){if(e instanceof Ni)return e;if(t.isGalaError(e)&&"pre_send"===e.phase)return new Ni(`${n}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?exports.LockErrorType.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?exports.LockErrorType.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?exports.LockErrorType.INVALID_AMOUNT:exports.LockErrorType.VALIDATION_ERROR,Ci(r));var s;let a=n,o=exports.LockErrorType.NETWORK_ERROR;if(ot(e)){const t=e.response?.data;if("object"==typeof t&&null!==t){const e=t.Message;"string"==typeof e&&e.length>0&&(a=`${n}: ${e}`);const r="string"==typeof e?e.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?o=exports.LockErrorType.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?o=exports.LockErrorType.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?o=exports.LockErrorType.TOKEN_NOT_FOUND:r.includes("authority")?o=exports.LockErrorType.NOT_LOCK_AUTHORITY:r.includes("expired")&&(o=exports.LockErrorType.LOCK_EXPIRED)}}else nt(e)&&(a=`${n}: ${rt(e)}`);return new Ni(a,o,Ci(r))}async resolveTokenInstance(e){return Ca(async()=>_i(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof wi)throw new Ni(rt(t),exports.LockErrorType.TOKEN_NOT_FOUND);throw new Ni(`Failed to resolve token '${e}': ${rt(t)}`,exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Fo(e.tokenId);return this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),t}if(void 0!==e.tokenName)return this.resolveTokenInstance(e.tokenName);throw new Ni("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND)}}const Pi=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function Bi(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class $i extends Un{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Fo(e):e,{collection:n,category:r,type:s,additionalKey:a}=t,o={collection:n,category:r,type:s,additionalKey:a},i="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(o),e=>{if(it(e,i),void 0===Bi(e)?.[0])throw gt(`Token not found on GalaChain: ${Uo(o)}`,404)},()=>gt(`Token not found on GalaChain: ${Uo(o)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw ut("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(it(e,"Failed to fetch token classes with supply from GalaChain"),0===(Bi(e)?.length??0))throw gt("No token supply data found for requested token classes",404)},void 0)}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}async readPublic(e,n,r){if(!this.publicAxios)throw ut("publicAxios","Public Axios instance");const s=this.publicAxios,{requestor:a,answer:o}=fi(async(e,t)=>{const n=await s.post(e,t);return{data:n.data,status:n.status}});try{return await e(new t.GatewayReads({gatewayBaseUrl:"",httpRequestor:a,requestTimeoutMs:1/0}))}catch(e){if(t.isGalaError(e)&&Pi.has(e.code)&&(n(o()),"TOKEN_CLASS_NOT_FOUND"===e.code&&void 0!==r))throw r();throw e}}handleTokenServiceError(e,t,n){if(e instanceof Je)throw e;if(ot(e)&&404===e.response?.status)throw gt(t,404,nt(e)?e:void 0);if(nt(e)&&"Error"===e.name&&rt(e).includes("status indicates failure"))throw gt(rt(e),400,nt(e)?e:void 0);const r=rt(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw gt(`${n}: ${r}`,void 0,nt(e)?e:void 0)}}function Gi(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Tn(t.amount)&&(void 0!==t.tokenId||Tn(t.tokenName))}function Ki(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Gi)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var Hi;exports.BurnErrorType=void 0,(Hi=exports.BurnErrorType||(exports.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",Hi.INVALID_AMOUNT="INVALID_AMOUNT",Hi.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Hi.SIGNATURE_FAILED="SIGNATURE_FAILED",Hi.NETWORK_ERROR="NETWORK_ERROR",Hi.WALLET_REQUIRED="WALLET_REQUIRED",Hi.VALIDATION_ERROR="VALIDATION_ERROR";class Wi extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Vi={validateAmount(e){const t=Zs(e);try{aa(t,"amount")}catch(t){throw new wi(t.message,bi.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!kn(e)&&Tn(e)){if(e.length>tn.MAX_LENGTH)throw new Je(`Unique key too long. Maximum length: ${tn.MAX_LENGTH}`);if(!tn.PATTERN.test(e))throw new wi('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',bi.INVALID_AMOUNT,{uniqueKey:e})}}},zi="gala-transfer-successful",ji="token-transfer-successful",qi="token-locked-successfully",Xi="token-unlocked-successfully",Qi="transfer-successful-no-id",Yi=50;class Ji extends Ii{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new wi("Wallet required for GALA transfer operations",bi.WALLET_REQUIRED);try{const n=Wn(e.recipientAddress),r=Oi(this.http,t);return await xi(r,t=>t.transferGala({to:n,quantity:e.amount,...Mi(e.uniqueKey)}),(e,t)=>this.extractTransferResult(e,t,"gala"))}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){this.validateTransferTokenData(e);const t=this.writeIdentity();if(void 0===t)throw new wi("Wallet required for token transfer operations",bi.WALLET_REQUIRED);try{const n=Wn(e.to),r=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new wi("Must provide either tokenId or tokenName for token identification",bi.TOKEN_NOT_FOUND)),s=Oi(this.http,t);return await xi(s,t=>t.transferToken({to:n,...Di(r,e.amount),...Mi(e.uniqueKey)}),(e,t)=>this.extractTransferResult(e,t,"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}':`,{collection:t.collection,category:t.category,type:t.type}),t}catch(t){if(t instanceof wi)throw t;throw new wi(`Failed to resolve token class key for '${e}': ${rt(t)}`,bi.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Wi("Wallet required for token burn operations",exports.BurnErrorType.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new Wi("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND));n.push(Di(e,t.amount))}const r=Oi(this.http,t);return await xi(r,t=>t.burnTokens({tokens:n,...Mi(e.uniqueKey)}),(e,t)=>this.burnResultOf(e,t))}catch(t){throw this.handleBurnError(t,"Token burn failed",e)}}validateTransferGalaData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Tn(t.recipientAddress)&&Tn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Je("Invalid GALA transfer data: missing required fields");if(!jn(e.recipientAddress))throw new wi("Invalid recipient address format",bi.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Vi.validateAmount(e.amount),Vi.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Tn(t.to)&&Tn(t.amount)&&(void 0!==t.tokenId||Tn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Je("Invalid token transfer data: missing required fields");if(!jn(e.to))throw new wi("Invalid recipient address format",bi.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new wi("Must provide either tokenId or tokenName for token identification",bi.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{_n(e.tokenName,"tokenName")}catch{throw new wi("Invalid token name format",bi.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}Vi.validateAmount(e.amount),Vi.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!Ki(e))throw new Wi("Invalid burn data: missing required fields",exports.BurnErrorType.VALIDATION_ERROR);if(e.tokens.length>Yi)throw new Wi(`Batch size exceeds maximum limit of ${Yi} tokens per burn operation`,exports.BurnErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!(null!==t.tokenId&&void 0!==t.tokenId||null!==t.tokenName&&void 0!==t.tokenName))throw new Wi("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);const e=Zs(t.amount);try{sa(e)}catch{throw new Wi("Burn amount must be a positive number",exports.BurnErrorType.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=Fo(e);return this.logger.debug("[DEBUG] Using provided tokenId:",e),t}if(null!=t)return this.resolveTokenInstance(t);throw n()}async resolveTokenInstance(e){try{return await _i(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof wi)throw t;throw new wi(`Failed to resolve token '${e}': ${rt(t)}`,bi.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new wi("No response from GalaChain transfer service",bi.NETWORK_ERROR);const r=t?.blockNumber,s="object"==typeof e&&"Status"in e;s&&it(e,"Extract transaction ID");const a=s&&"Data"in e,o=t?.transactionId;if(void 0!==o)return{transactionId:o,...void 0!==r?{blockNumber:r}:{}};if(a){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==r?{blockNumber:r}:{}}}}let e=Qi;if(t.Data.length>0)switch(n){case"gala":e=zi;break;case"token":e=ji;break;case"lock":e=qi;break;case"unlock":e=Xi}return{transactionId:e,...void 0!==r?{blockNumber:r}:{}}}}throw new wi("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",bi.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new Wi("No response from GalaChain burn service",exports.BurnErrorType.NETWORK_ERROR);try{it(e,"Token burn operation")}catch(e){throw new Ze(rt(e),500)}return this.extractBurnResult(e,t)}extractBurnResult(e,t){const n=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const t of e.Data)n.push({collection:t.collection??"",category:t.category??"",type:t.type??"",additionalKey:t.additionalKey??"",instance:t.instance??"0",quantity:t.quantity??"0",burnedBy:t.burnedBy??""});const r=Array.isArray(e.Data)?e.Data[0]:void 0,s=t?.transactionId??r?.transactionId??r?.txnId??r?.TxnId??r?.id??void 0,a=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==a&&{blockNumber:a},burned:n}}handleTransferError(e,n,r){if(e instanceof wi)return e;if(e instanceof Je)return new wi(rt(e),bi.INVALID_AMOUNT);if(t.isGalaError(e)&&"pre_send"===e.phase)return new wi(e.message,"SIGNING_FAILED"===(s=e.code)?bi.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===s?bi.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===s?bi.TOKEN_NOT_FOUND:bi.INVALID_AMOUNT);var s;if(ot(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t){const e=n?.message;return new wi(("string"==typeof e?e:void 0)??"Invalid transfer request",bi.INVALID_AMOUNT)}if(403===t)return new wi("Insufficient balance for transfer",bi.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in r&&(e.tokenName=r.tokenName),new wi("Token not found",bi.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===at(e)||"ETIMEDOUT"===at(e)))return new wi("Transfer request timed out",bi.NETWORK_ERROR);const a=""!==rt(e)?rt(e):n;return new wi(a,bi.NETWORK_ERROR)}handleBurnError(e,n,r){if(e instanceof Wi)return e;if(t.isGalaError(e)&&"pre_send"===e.phase)return new Wi(`${n}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?exports.BurnErrorType.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?exports.BurnErrorType.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?exports.BurnErrorType.INVALID_AMOUNT:exports.BurnErrorType.VALIDATION_ERROR,Ci(r));var s;let a=n,o=exports.BurnErrorType.NETWORK_ERROR;if(ot(e)){const t=e.response?.data;if("object"==typeof t){const e=t.Message;if("string"==typeof e&&e.length>0){a=`${n}: ${e}`;const t=e.toLowerCase();t.includes("insufficient")||t.includes("balance")?o=exports.BurnErrorType.INSUFFICIENT_BALANCE:(t.includes("not found")||t.includes("token"))&&(o=exports.BurnErrorType.TOKEN_NOT_FOUND)}}}else nt(e)&&(a=`${n}: ${rt(e)}`);return new Wi(a,o,Ci(r))}}class Zi extends Un{constructor(e,t,n,r=!1,s,a){super(e,r),this.balanceService=new Ai(e,r),this.tokenService=new $i(e,r,s),this.lockService=new Fi(e,t,n,r,a),this.transferService=new Ji(e,t,n,r,a)}async fetchGalaBalance(e){return this.balanceService.fetchGalaBalance(e)}async fetchTokenBalance(e,t=!1){return this.balanceService.fetchTokenBalance(e,t)}async fetchTokenClassFromChain(e){return this.tokenService.fetchTokenClassFromChain(e)}async fetchTokenDetails(e){try{return t.tokenDetailsOf(await this.fetchTokenClassFromChain(e))}catch(t){if(nt(t)&&("NetworkError"===t.name||rt(t).includes("Token not found")))throw t;throw gt(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:Uo(e)}: ${rt(t)}`,500)}}async fetchTokenClassesWithSupply(e){return this.tokenService.fetchTokenClassesWithSupply(e)}async transferGala(e){return this.transferService.transferGala(e)}async transferToken(e){return this.transferService.transferToken(e)}async resolveTokenClassKey(e){return this.transferService.resolveTokenClassKey(e)}async lockTokens(e){return this.lockService.lockTokens(e)}async unlockTokens(e){return this.lockService.unlockTokens(e)}async burnTokens(e){return this.transferService.burnTokens(e)}}function ec(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw ht("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});r.append(t,s,n)}}return r}class tc extends Un{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;ma(t);const r=`${t}.png`;la(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=ec(n.file,"image",e),s=await It(()=>this.http.request({method:"POST",url:`${d.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof et)throw e;if(nt(e)&&rt(e).includes("FormData"))throw mt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function nc(e,t){if(void 0!==e){if(!Tn(e))throw vt("tokenName","string");if(e.length>Vt.MAX_LENGTH)throw new Je(`tokenName must be at most ${Vt.MAX_LENGTH} characters`,"tokenName",Ye.TOO_LONG)}if(void 0!==t){if(!Tn(t))throw vt("userAddress","string");if(t.length>Qt.MAX_LENGTH)throw new Je(`userAddress must be at most ${Qt.MAX_LENGTH} characters`,"userAddress",Ye.TOO_LONG)}}const rc={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},sc={PAGINATION:{MAX_LIMIT:qt.MAX_LIMIT},CONTENT:{CHAT_MAX_LENGTH:Yt.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:Yt.COMMENTS_V1.MAX_LENGTH}};function ac(e){if(!!(void 0===e.messagesEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl))throw new Je("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",Ye.REQUIRED);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw vt("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw vt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw vt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw vt("streamLanguage","string");const t=["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"];for(const n of t){const t=e[n];if(null!=t&&"string"!=typeof t)throw vt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw vt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new Je("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",Ye.INVALID_FORMAT)}}function oc(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class ic extends Un{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!kn(e.search)&&{search:e.search},...!kn(e.tokenName)&&{tokenName:e.tokenName},...!kn(e.type)&&{type:e.type},...!kn(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!kn(e.language)&&{language:e.language},...!kn(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!kn(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!kn(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,r={pageSize:String(t)};void 0!==n&&(r.cursor=n),kn(e.type)||(r.type=e.type),kn(e.tokenName)||(r.tokenName=e.tokenName),kn(e.search)||(r.search=e.search),kn(e.hasUpcomingShows)||(r.hasUpcomingShows=e.hasUpcomingShows.toString()),kn(e.language)||(r.language=e.language),kn(e.recentlyStreamed)||(r.recentlyStreamed=e.recentlyStreamed.toString()),kn(e.hasRecordings)||(r.hasRecordings=e.hasRecordings.toString()),kn(e.streamStatus)||(r.streamStatus=e.streamStatus);const s=Ys(r),a=Ct(await Rt(()=>this.http.get(d.FETCH_POOLS,s),{errorContext:"Failed to fetch pools"})),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 n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else null!==e.pools&&void 0!==e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at??e.createdAt??""})));return t}(a),i={hasNextPage:a.hasNextPage??a.pageInfo?.hasNextPage??!1},c=a.count??a.total;void 0!==c&&(i.totalCount=c);const l=a.nextCursor??a.pageInfo?.endCursor;null!=l&&(i.nextCursor=l);const u=a.prevCursor??a.pageInfo?.startCursor;null!=u&&(i.prevCursor=u);const h=a.hasPrevPage??a.pageInfo?.hasPreviousPage;return void 0!==h&&(i.hasPrevPage=h),{items:o,pageInfo:i}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??Ua.DEFAULT_LIMIT;Tn(e?.tokenName)&&ma(e.tokenName);const r=void 0!==e?.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,s=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,a={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:r,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:s}),pageSize:n,...void 0!==t&&{cursor:t}},o=await this.fetchSinglePage(a);return{items:o.items,pageInfo:o.pageInfo}}async fetchAllPools(e){const t=[];let n;const r=Ua.BACKEND_MAX_PAGE_SIZE;for(;;){const s={...e,pageSize:r,...void 0!==n&&{cursor:n}},a=await this.fetchPools(s);if(t.push(...a.items),0===a.items.length)break;if(!a.pageInfo.hasNextPage)break;n=a.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=Is(e);!t.success&&t.errors&&ga(t.errors,"options")}(e),Tn(e.tokenName)&&ma(e.tokenName);try{const t=await this.http.post(d.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===Tn(e.symbol)){return!n.symbolAvailable}if(!0===Tn(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,r="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||r.includes("404")||r.includes("Pool not found"))return!1;const s="number"==typeof n.statusCode?n.statusCode:null;if(404===s)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||r.includes("400")||r.includes("Missing required pool identifier"))return!1;if(400===s&&r.includes("Missing required pool identifier"))return!1;throw e}}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(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Vs(t,"tokenName")&&js(t,"from")&&js(t,"to")&&js(t,"resolution")}(e))throw new Je("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:s}=e;if(ma(t),null==n||null==r||null==s)throw new Je("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const a={tokenName:t,from:n,to:r,resolution:s};pa(a);const o=Ys(a);return{dataPoints:await It(()=>this.http.get(d.CHART,o),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw ut("tokenName","Token name");let t;ma(e);try{t=await Rt(()=>this.http.get(`${d.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(ot(t)&&500===t.response?.status)throw gt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return Aa(Ct(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw ut("tokenName","Token name");if(""===t||null==t)throw ut("userAddress","User address");return ma(e),It(()=>this.http.get(`${d.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async resolveTokenNameToVault(e){const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0]?.vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");ma(e);try{const t=d.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=Ct(await this.http.get(t));if(null!=n?.tokens){const t=Array.isArray(n.tokens)?n.tokens[0]:n.tokens;if(null==t)throw new Error(`Token not found: ${e}`);return t}throw new Error(`Invalid response format when fetching token: ${e}`)}catch(t){const n=String(t);if(n.includes("404")||n.includes("not found"))throw new Error(`Token not found: ${e}`);throw t}}async validateToken(e){if(!(null!==e.tokenName&&void 0!==e.tokenName||null!==e.symbol&&void 0!==e.symbol))throw new Error("At least one of tokenName or symbol is required");if(null!==e.tokenName&&void 0!==e.tokenName&&("string"!=typeof e.tokenName||""===e.tokenName.trim()))throw new Error("tokenName must be a non-empty string");if(null!==e.symbol&&void 0!==e.symbol&&("string"!=typeof e.symbol||""===e.symbol.trim()))throw new Error("symbol must be a non-empty string");null!==e.tokenName&&void 0!==e.tokenName&&ma(e.tokenName);try{const t=await this.http.post(d.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!Tn(e))throw ut("tokenName","Token name");ma(e);const t=d.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=Ct(await this.http.get(t));if(!e?.stats)throw new Error("Invalid response: missing stats data");return{success:!0,data:e.stats}}catch(t){throw this.logger.warn(`Failed to fetch token stats for ${e}: ${String(t)}`),t}}async updateTokenConfig(e,t){if(""===e||null==e)throw ut("tokenName","Token name");ma(e),ac(t);const n=d.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.messagesEnabled&&(r.messagesEnabled=t.messagesEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}async getTokenConfig(e){if(!Tn(e))throw ut("tokenName","Token name");ma(e);const t=d.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=Ct(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const cc={PAGINATION:qt,TOKEN_NAME:Vt,USER_ADDRESS:Qt};function lc(e){if(void 0!==e.tokenName){if(!Tn(e.tokenName))throw vt("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>cc.TOKEN_NAME.MAX_LENGTH)throw At("tokenName",cc.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!Tn(e.userAddress))throw vt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>cc.USER_ADDRESS.MAX_LENGTH)throw At("userAddress",cc.USER_ADDRESS.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw vt("search","a string",typeof e.search);if(e.search.length>256)throw At("search",256,e.search.length)}if(bn(0,void 0,cc.PAGINATION.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw ht("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Tn(e.startDate))throw vt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw ht("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Tn(e.endDate))throw vt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw ht("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{pn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw ht("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{pn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw ht("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw vt(n,"numeric values",void 0,n);if(r>s)throw new Je(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,Ye.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class dc extends Un{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Vs(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&zs(t,"userAddress")&&js(t,"offset")&&js(t,"pageSize")&&js(t,"page")&&js(t,"limit")}(e))throw new Je("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=Ua.DEFAULT_LIMIT}=e;if(!Tn(t))throw ut("tokenName","Token name");const s={pageSize:String(Math.min(r,jt))};void 0!==n&&(s.cursor=n);const a={...s};a.tokenName=t;const o=await this.http.get(d.GET_TRADES,a);if(null==o)throw new Je("No response from trade service","response","NO_RESPONSE");const i=Ct(o),c=oc(i,"trades"),l=i?.pageInfo;return{items:c,pageInfo:l??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=Mt(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=e.userAddress),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?Fa(e.pageSize,1,cc.PAGINATION.MAX_LIMIT):cc.PAGINATION.MAX_LIMIT;return void 0!==e.cursor&&(t.cursor=e.cursor),t.pageSize=String(n),null!==e.txnType&&void 0!==e.txnType&&e.txnType.length>0&&(t.txnType=e.txnType),null!==e.startDate&&void 0!==e.startDate&&e.startDate.length>0&&(t.startDate=e.startDate),null!==e.endDate&&void 0!==e.endDate&&e.endDate.length>0&&(t.endDate=e.endDate),void 0!==e.minAmount&&(t.minAmount=String(e.minAmount)),void 0!==e.maxAmount&&(t.maxAmount=String(e.maxAmount)),t}async getTrades(e){lc(e);const t=this.buildTradesQueryParams(e);return It(()=>this.http.get(Ie,t),{errorContext:"Failed to fetch trades"})}}function uc(e){return!!Tn(e)&&Xt.PATTERN.test(e)}function hc(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const r=e.trim();return r.length<n?null:r}function gc(e){if(""===e||"string"!=typeof e)return!1;const t=e.startsWith("0x")?e.slice(2):e;return/^[0-9a-fA-F]{40}$/.test(t)}function mc(e){return e.startsWith("0x")?e.slice(2):e}Nn({BOTH:"both",HELD:"held",CREATED:"created"});class pc extends Un{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!uc(t))throw ht("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,r=n?d.GET_CURRENT_USER:d.GET_PROFILE.replace(":address",t),s=await this.http.get(r,void 0,n?this.getJwtHeaders():void 0);if(null==s)throw new Je("No response from user service","response","NO_RESPONSE");return s}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Tn(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await It(()=>this.http.put(d.UPDATE_PROFILE,n,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(null==t||""===t)throw new Je("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=ec(e.file,"image",n),s=await It(()=>this.http.request({method:"POST",url:`${d.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Je||e instanceof et)throw e;throw new Je(`Profile image upload failed: ${rt(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new Je("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},r="created"===e.type;r&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(d.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:r?"launches":"token",errorMessage:"Failed to fetch token list"});return r&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new Je("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new Je("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(d.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:s,status:a}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new Je("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const o=e?.address??this.http.getAddress();if(null==o||""===o)throw new Je("Wallet address not available - wallet not configured","address","NO_WALLET");const i={type:"created",address:o,pageSize:n??Ua.DEFAULT_LIMIT};return void 0!==t&&(i.cursor=t),void 0!==r&&(i.search=r),void 0!==s&&void 0===r&&(i.search=s),void 0!==s&&(i.tokenName=s),void 0!==a&&(i.status=a),this.fetchTokenList(i)}async getManagedTokens(e={}){const t=Ba({pageSize:e.pageSize??Ua.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},jt);return It(()=>this.http.get(d.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=Ba({pageSize:t.pageSize??Ua.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},jt);$a(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const a=t.address??this.http.getAddress();if(e.includes(":address")){if(0===a.length)throw ut("address","User address");s=e.replace(":address",a),delete r.address}const o=Ct(await Rt(()=>this.http.get(s,r),{errorContext:n.errorMessage})),i=oc(o,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",r="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",o=e.metadata,i={...e};return delete i.metadata,{...i,id:"string"==typeof e.id?e.id:t,name:r,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:a,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==o&&"object"==typeof o?{metadata:o}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),c={hasNextPage:o.hasNextPage??!1},l=o.pageInfo,d=o.count??o.total??l?.totalCount;void 0!==l&&(c.hasNextPage=l.hasNextPage??!1,void 0!==l.hasPreviousPage&&(c.hasPrevPage=l.hasPreviousPage),null!==l.endCursor&&void 0!==l.endCursor&&(c.nextCursor=l.endCursor),null!==l.startCursor&&void 0!==l.startCursor&&(c.prevCursor=l.startCursor)),void 0!==d&&(c.totalCount=d),void 0!==o.nextCursor&&(c.nextCursor=o.nextCursor),void 0!==o.prevCursor&&(c.prevCursor=o.prevCursor),void 0!==o.hasPrevPage&&(c.hasPrevPage=o.hasPrevPage);const u={tokens:i,pageInfo:c};return void 0!==d&&(u.total=d),u}validateGetTokenListOptions(e){const t=e.pageSize??Ua.DEFAULT_LIMIT;if(t<1||t>jt)throw new Je(`pageSize must be between 1 and ${jt}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!uc(e.address))throw ht("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=hc(e.search);if(null!==n&&!(Tn(r=n)&&r.length>=an&&r.length<=on))throw ft("search",an,on,n.length,"Search query");var r;const s=hc(e.tokenName);if(null!==s&&!(Tn(a=s)&&a.length>=Vt.MIN_LENGTH&&a.length<=Vt.MAX_LENGTH))throw ft("tokenName",Vt.MIN_LENGTH,Vt.MAX_LENGTH,s.length,"Token name");var a}validateUpdateProfileData(e){if(!uc(e.address))throw ht("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(Tn(t)&&t.length>=cn.FULL_NAME.MIN_LENGTH&&t.length<=cn.FULL_NAME.MAX_LENGTH&&cn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw ft("fullName",cn.FULL_NAME.MIN_LENGTH,cn.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!uc(e.address))throw ht("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class fc{constructor(e,t,n=!1){this.http=e,this.poolService=new ic(e,t,n),this.tradeService=new dc(e,n),this.userService=new pc(e,t,n),this.imageService=new tc(e,t,n)}setJwtAuth(e){this.poolService.setJwtAuth(e),this.userService.setJwtAuth(e),this.imageService.setJwtAuth(e)}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 checkPoolExists(e,t){const n={};return void 0!==e&&(n.tokenName=e),void 0!==t&&(n.symbol=t),this.poolService.checkPool(n)}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 fetchUserHolderContext(e,t){return this.poolService.fetchUserHolderContext(e,t)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async getTrades(e){return this.tradeService.getTrades(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 getManagedTokens(e={}){return this.userService.getManagedTokens(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return ma(e)}async fetchToken(e){return this.poolService.fetchToken(e)}async validateToken(e){return this.poolService.validateToken(e)}async fetchTokenStats(e){return this.poolService.fetchTokenStats(e)}async updateTokenConfig(e,t){return this.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.poolService.getTokenConfig(e)}}class Ec extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!Tn(e))throw ut("content","Message content");if(0===e.trim().length)throw ut("content","Message content");fn(e,t===rc.CHAT_MESSAGE?Yt.CHAT_MESSAGES_V1.MAX_LENGTH:Yt.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Tn(e))throw ut("id","Message ID");if(e.length<10||e.length>64)throw ht("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==rc.CHAT_MESSAGE&&e!==rc.COMMENT)throw new Je(`type must be one of: ${Object.values(rc).join(", ")}`,"type","INVALID_VALUE")}async fetchMessages(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName;t&&this.validateMessageType(e.type),n&&this.validateTokenName(e.tokenName,Wt);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Ua.DEFAULT_LIMIT;const s=Ba(r,qt.MAX_LIMIT),a={};void 0!==s.pageSize&&(a.pageSize=s.pageSize),void 0!==s.cursor&&(a.cursor=s.cursor),t&&(a.type=e.type.toUpperCase()),n&&(a.tokenName=Mt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(a.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(a.search=e.search);const o=await this.http.get(De.GET_MESSAGES,a),i=this.extractData(o);return{messages:i.messages,pageInfo:i.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,Wt),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:Mt(e.tokenName),content:e.content.trim()},n=await this.http.post(De.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content);const n=this.buildEndpointWithId(De.UPDATE_MESSAGE,e),r={content:t.content.trim()},s=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(De.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Wt);const t=await this.http.get(De.GET_PINNED,{tokenName:Mt(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=De.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=De.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){const e=await this.http.get(De.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const Ac={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},vc=wn(Ac),Sc={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},Tc=wn(Sc),yc={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},kc=wn(yc);function bc(e){return vc.includes(e)}function Nc(e){return kc.includes(e)}function wc(e){return nn.PATTERN.test(e)}const Cc=In([{field:"id",type:"number"},{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"role",type:"string"},{field:"inviteCode",type:"string"},{field:"inviteUrl",type:"string"},{field:"status",type:"string"},{field:"createdAt",type:"string"}]),_c=In([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),Ic=In([{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"tokenSymbol",type:"string",nullable:!0},{field:"role",type:"string"},{field:"status",type:"string"},{field:"invitedBy",type:"string"}]);function Dc(e){return Tc.includes(e)}class Rc extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!Tn(e))throw ut("role","Role");if(!bc(e))throw ht("role",`one of: ${vc.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Tn(e))throw ut("inviteCode","Invite code");if(!wc(e))throw ht("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!Dc(e))throw new Je(`Invalid invite scope. Must be one of: ${Tc.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??Sc.TOKEN;if(t===Sc.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new Je("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,Ht)}else if(t===Sc.ALL_OWNER_TOKENS&&e.tokenName)throw new Je("Token name should not be provided for ALL_OWNER_TOKENS scope invites","tokenName","INVALID_VALUE");this.validateRole(e.role),this.validateOptionalString(e.description,"description","Description",Yt.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=z,r={inviteScope:t,role:e.role};t===Sc.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=Mt(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const s=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,Ht),this.validateStatusFilter(e.status,yc);const t=X,n={...this.buildPaginationParams(e,qt.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=Mt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Q,{id:String(e)});wt(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(Y,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new Je("At least one of role or description must be provided","options","REQUIRED");void 0!==e.role&&this.validateRole(e.role),void 0!==e.description&&this.validateOptionalString(e.description,"description","Description",Yt.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(J,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=j,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=q,n=this.buildPaginationParams(e??{},qt.MAX_LIMIT),r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Z,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const Oc={COLLECTION_CLAIM_FEE:"10000",TOKEN_CLASS_CREATE_FEE:"1000",DESCRIPTIONS:{COLLECTION_CLAIM:"10,000 GALA to claim a collection name",TOKEN_CLASS_CREATE:"1,000 GALA to create a token class",MINT:"Dynamic fee estimated via DryRun endpoint"}};function xc(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Mc(){return Date.now()+6e4}function Lc(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Uc(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Fc(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class Pc extends Un{constructor(e){super(e)}getCollectionClaimFee(){return Oc.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return Oc.TOKEN_CLASS_CREATE_FEE}async estimateMintFee(e){try{if(this.logger.debug("Estimating mint fee",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for mint fee estimation");if(!Fc(e.ownerAddress))throw new Error(`Invalid owner address format: ${e.ownerAddress}`);const t="0";return this.logger.debug("Estimated mint fee:",t),t}catch(e){throw this.logger.error("Failed to estimate mint fee",e),e}}estimateNftOperationFees(e){let t="0";const n={};if(e.claimCollection){const e=Oc.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=Oc.TOKEN_CLASS_CREATE_FEE,s=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(s))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!Lc(e.collectionName))throw new Error(`Invalid collection name format. Must be alphanumeric, 3-50 characters: ${e.collectionName}`);if(!await this.isCollectionAvailable(e.collectionName))throw new Error(`Collection name already claimed: ${e.collectionName}`);const t={collectionName:e.collectionName,expiresAt:Mc(),uniqueKey:xc("auth")};this.logger.debug("Built claim DTO",t);return{transactionId:`claim-${Date.now()}`,collection:e.collectionName,authorizedUser:"",status:"pending"}}catch(e){throw this.logger.error("Failed to claim collection",e),e}}async fetchUserCollections(e){try{if(this.logger.debug("Fetching user collections for",e),!Fc(e))throw new Error(`Invalid wallet address format: ${e}`);const t=e.toLowerCase(),n=(await this.allAuthorizations()).filter(e=>e.authorizedUsers.some(e=>e.toLowerCase()===t)).map(t=>({authorizedUser:e,collection:t.collection}));return this.logger.debug(`Found ${n.length} collections for user`),n}catch(e){throw this.logger.error("Failed to fetch user collections",e),e}}async isCollectionAvailable(e){try{if(this.logger.debug("Checking collection availability",e),!Lc(e))throw new Error(`Invalid collection name format: ${e}`);const t=!(await this.allAuthorizations()).some(t=>t.collection===e);return this.logger.debug(`Collection ${e} available:`,t),t}catch(e){throw this.logger.error("Failed to check collection availability",e),e}}async createTokenClass(e){try{if(this.logger.debug("Creating NFT token class",e),null===e.collection||void 0===e.collection||0===e.collection.length||null===e.type||void 0===e.type||0===e.type.length||null===e.category||void 0===e.category||0===e.category.length)throw new Error("Missing required parameters: collection, type, category");if(!Lc(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);if(void 0!==e.symbol&&(""===(t=e.symbol)||"string"!=typeof t||!/^[a-zA-Z]{1,8}$/.test(t)))throw new Error(`Invalid token symbol: ${e.symbol}`);const n={collection:e.collection,type:e.type,category:e.category,name:e.name,description:e.description,image:e.image,symbol:e.symbol,rarity:e.rarity,maxSupply:void 0!==e.maxSupply?Uc(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Uc(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Mc(),uniqueKey:xc("create")};this.logger.debug("Built token class DTO",n);return{transactionId:`create-${Date.now()}`,tokenClass:{collection:e.collection,type:e.type,category:e.category,additionalKey:e.additionalKey??""},status:"pending"}}catch(e){throw this.logger.error("Failed to create token class",e),e}var t}async fetchTokenClasses(e){try{if(this.logger.debug("Fetching token classes",e),!Lc(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);const t=(await this.reads().fetchAllTokenClasses({collection:e.collection,category:e.category,type:e.type},{pageSize:1e3})).map(e=>({collection:e.collection,type:e.type,category:e.category,additionalKey:e.additionalKey,totalSupply:e.totalSupply,maxSupply:e.maxSupply,isNonFungible:e.isNonFungible,name:e.name,description:e.description,image:e.image,symbol:e.symbol,...void 0===e.rarity?{}:{rarity:e.rarity}}));return this.logger.debug(`Found ${t.length} token classes`),t}catch(e){throw this.logger.error("Failed to fetch token classes",e),e}}async mintNft(e){try{if(this.logger.debug("Minting NFT",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for minting");const t=parseInt(e.quantity,10);if(t<=0)throw new Error("Quantity must be greater than 0");if(!Fc(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const r={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:Mc(),uniqueKey:xc("mint")};this.logger.debug("Built mint DTO",r);const s=`mint-${Date.now()}`,a=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:a,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!Fc(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:e,collection:t})).map(e=>({owner:e.owner,collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instanceIds:[...e.instanceIds],totalOwned:e.instanceIds.length}));return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}reads(){const{requestor:e}=fi(async(e,t)=>({data:await this.http.post(e,t)}));return new t.GatewayReads({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class Bc extends Un{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(We,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:Ve,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(ze,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(je,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class $c extends Un{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(d.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(d.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Je("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=d.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Je("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=d.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Je("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=d.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:r.title}),{oembed:r}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Je("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=d.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function Gc(e){if(!Tn(e))throw ut("address","Address")}const Kc={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Hc={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Wc=Nn(Kc),Vc=Nn(Hc);function zc(e){try{On(e.description,"description",255)}catch(e){if(e instanceof Je){throw e.message.includes("255")?new Error("description must be at most 255 characters"):new Error("description must be a string")}throw e}if(void 0!==e.expiresAt){if(!Tn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{xn(e.expiresAt,"expiresAt")}catch(e){if(e instanceof Je)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Kt(e.expiresAt)){if(Gt(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function jc(e){if(void 0!==e.status&&!Wc(e.status))throw Tt("status",e.status,Object.values(Kc),"status");bn(0,void 0,50,e.pageSize,e.cursor)}function qc(e){if(void 0!==e.status&&!Vc(e.status))throw Tt("status",e.status,Object.values(Hc),"status");bn(0,void 0,50,e.pageSize,e.cursor)}function Xc(e){if(!Tn(e))throw new Error("Invite code must be a non-empty string");fn(e,100,"code")}function Qc(e){if(!Tn(e))throw new Error("Address must be a non-empty string");try{qn(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Yc(e){try{En(e,"id")}catch(e){if(e instanceof Je)throw new Error("Invite ID must be a positive integer");throw e}}function Jc(e){if(null==e||"object"!=typeof e)throw new Je("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new Je("Search must be a string");if(0===e.search.length)throw new Je("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new Je("Sort field must be a string");if(0===e.sortBy.length)throw new Je("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new Je('Sort order must be "asc" or "desc"')}function Zc(e){if(null==e||"object"!=typeof e)throw new Je("Options are required");if(!Tn(e.userAddress))throw new Je("userAddress is required and must be a non-empty string");try{qn(e.userAddress,"userAddress")}catch{throw new Je("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new Je("description must be a string");if(e.description.length>255)throw new Je("description must be at most 255 characters")}}class el extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!Tn(e))throw ut("inviteCode","Invite code");Xc(e)}validateWalletAddressFormat(e){if(!Tn(e))throw ut("address","Address");Qc(e)}async createInvite(e={}){zc(e),this.validateOptionalString(e.description,"description","Description",Yt.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=te,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){jc(e),this.validateStatusFilter(e.status,Kc);const t=ne,n={...this.buildPaginationParams(e,qt.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(re,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){Yc(e);const t=this.buildEndpoint(ae,{id:String(e)});wt(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=se,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){qc(e),this.validateStatusFilter(e.status,Hc);const t=oe,n={...this.buildPaginationParams(e,qt.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.overseers,pageInfo:s.pageInfo}}async createOverseerDirect(e){Zc(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",Yt.DESCRIPTION.MAX_LENGTH);const t=ie,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(ce,{address:e});wt(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=le,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=de,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=he,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=ge,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=pe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&Jc(t);const n=fe,r=this.buildPaginationParams(t,qt.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const s=await this.http.get(n,r,this.getDualAuthHeaders()),a=this.extractData(s);return{items:a.users,pageInfo:a.pageInfo}}async getOverseerUserSummary(e){if(!Tn(e))throw ut("address","User address");Qc(e);const t=this.buildEndpoint(Ee,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Gc(e);const t=this.buildEndpoint(Ae,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Tn(e))throw ut("tokenName","Token name")}(e);const t=this.buildEndpoint(ve,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new Je("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Se,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Gc(e);const t=this.buildEndpoint(Te,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=ye,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function tl(e){const t=[];return 0===Object.keys(e).length&&t.push("At least one field (streamingEnabled, chatEnabled, commentsEnabled, webhooksEnabled, aiModerationEnabled) must be provided"),void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled&&t.push("streamingEnabled must be a boolean"),void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled&&t.push("chatEnabled must be a boolean"),void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled&&t.push("commentsEnabled must be a boolean"),void 0!==e.webhooksEnabled&&"boolean"!=typeof e.webhooksEnabled&&t.push("webhooksEnabled must be a boolean"),void 0!==e.aiModerationEnabled&&"boolean"!=typeof e.aiModerationEnabled&&t.push("aiModerationEnabled must be a boolean"),t}class nl extends Un{constructor(e,t,n=!1){super(e,n,t)}extractData(e){const t={status:200,error:"error"in e?e.error:"success"in e?!e.success:!("data"in e),data:e.data};return void 0!==e.message&&(t.message=e.message),wt(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(N);return this.extractData(e)}async updatePlatformConfig(e){const t=tl(e);if(t.length>0)throw new Je(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(w,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(I);return this.extractData(e)}}class rl extends Un{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Platform stats operation failed";throw new Error(t)}return e.data}async getStats(){this.logger.debug("Fetching platform stats");const e=await this.http.get(Pe),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class sl extends Ka{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Re)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!Tn(e.content))throw new Je("Content is required");return{success:!0,data:(await this.http.put(Oe,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class al extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw ut("tokenName","Token name");return this.validateTokenName(e,Ht),Ca(async()=>{const t=this.buildEndpoint(xe,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResult(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw ut("tokenName","Token name");return this.validateTokenName(e,Ht),Ca(async()=>{const t=this.buildEndpoint(Le,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResult(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw ut("tokenName","Token name");return this.validateTokenName(e,Ht),Ca(async()=>{const t=this.buildEndpoint(Me,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResult(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResult(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??Mt(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw ut("tokenName","Token name");if(this.validateTokenName(e,Ht),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Ca(async()=>{const n=this.buildEndpoint(Ue,{tokenName:e}),r=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(r)},`Failed to set slow mode for token: ${e}`,this.logger)}}class ol extends Fn{constructor(e=!1){super(e),this.eventRegistry=this.createEmptyRegistry()}setSocket(e){this.logger.debug("📡 [Events] Socket attached to StreamingEventService")}clearSocket(){this.logger.debug("📡 [Events] Socket cleared from StreamingEventService")}createEmptyRegistry(){return{stream_status:new Set,user_banned:new Set,user_unbanned:new Set,ban_enforcement:new Set,content_flagged:new Set,flag_resolved:new Set,stream_chat_message:new Set,stream_chat_updated:new Set,stream_chat_deleted:new Set,stream_chat_pinned:new Set,stream_chat_unpinned:new Set,chat_status_changed:new Set,viewer_count:new Set,recording_status:new Set,simulcast_status:new Set,download_ready:new Set,recordings_count_updated:new Set,user_typing:new Set,stream_reaction:new Set,content_reaction_added:new Set,content_reaction_removed:new Set,stream_countdown_updated:new Set,stream_language_updated:new Set,stream_control_status_changed:new Set,connection:new Set,authenticated:new Set,token_subscribed:new Set,token_unsubscribed:new Set,room_subscribed:new Set,room_left:new Set}}registerCallback(e,t){const n=this.eventRegistry[e];return n.add(t),()=>{n.delete(t)}}async emitEvent(e,t){const n=this.eventRegistry[e];if(0!==n.size)for(const r of n)try{const e=r(t);e instanceof Promise&&await e}catch(t){this.logger.error(`Error in ${e} callback:`,t instanceof Error?t.message:String(t))}}onStreamStatusChanged(e){return this.registerCallback("stream_status",e)}onUserBanned(e){return this.registerCallback("user_banned",e)}onUserUnbanned(e){return this.registerCallback("user_unbanned",e)}onBanEnforcement(e){return this.registerCallback("ban_enforcement",e)}onContentFlagged(e){return this.registerCallback("content_flagged",e)}onFlagResolved(e){return this.registerCallback("flag_resolved",e)}onStreamChatMessage(e){return this.registerCallback("stream_chat_message",e)}onStreamChatUpdated(e){return this.registerCallback("stream_chat_updated",e)}onStreamChatDeleted(e){return this.registerCallback("stream_chat_deleted",e)}onStreamChatPinned(e){return this.registerCallback("stream_chat_pinned",e)}onStreamChatUnpinned(e){return this.registerCallback("stream_chat_unpinned",e)}onChatStatusChanged(e){return this.registerCallback("chat_status_changed",e)}onViewerCountChanged(e){return this.registerCallback("viewer_count",e)}onRecordingStatusChanged(e){return this.registerCallback("recording_status",e)}onSimulcastStatusChanged(e){return this.registerCallback("simulcast_status",e)}onDownloadReady(e){return this.registerCallback("download_ready",e)}onRecordingsCountUpdated(e){return this.registerCallback("recordings_count_updated",e)}onUserTyping(e){return this.registerCallback("user_typing",e)}onStreamReaction(e){return this.registerCallback("stream_reaction",e)}onContentReactionAdded(e){return this.registerCallback("content_reaction_added",e)}onContentReactionRemoved(e){return this.registerCallback("content_reaction_removed",e)}onStreamCountdownUpdated(e){return this.registerCallback("stream_countdown_updated",e)}onStreamLanguageUpdated(e){return this.registerCallback("stream_language_updated",e)}onStreamControlStatusChanged(e){return this.registerCallback("stream_control_status_changed",e)}onConnection(e){return this.registerCallback("connection",e)}onAuthenticated(e){return this.registerCallback("authenticated",e)}onTokenSubscribed(e){return this.registerCallback("token_subscribed",e)}onTokenUnsubscribed(e){return this.registerCallback("token_unsubscribed",e)}onRoomSubscribed(e){return this.registerCallback("room_subscribed",e)}onRoomLeft(e){return this.registerCallback("room_left",e)}async emitStreamStatusChanged(e){await this.emitEvent("stream_status",e)}async emitUserBanned(e){await this.emitEvent("user_banned",e)}async emitUserUnbanned(e){await this.emitEvent("user_unbanned",e)}async emitBanEnforcement(e){await this.emitEvent("ban_enforcement",e)}async emitContentFlagged(e){await this.emitEvent("content_flagged",e)}async emitFlagResolved(e){await this.emitEvent("flag_resolved",e)}async emitStreamChatMessage(e){await this.emitEvent("stream_chat_message",e)}async emitStreamChatUpdated(e){await this.emitEvent("stream_chat_updated",e)}async emitStreamChatDeleted(e){await this.emitEvent("stream_chat_deleted",e)}async emitStreamChatPinned(e){await this.emitEvent("stream_chat_pinned",e)}async emitStreamChatUnpinned(e){await this.emitEvent("stream_chat_unpinned",e)}async emitChatStatusChanged(e){await this.emitEvent("chat_status_changed",e)}async emitViewerCountChanged(e){await this.emitEvent("viewer_count",e)}async emitRecordingStatusChanged(e){await this.emitEvent("recording_status",e)}async emitSimulcastStatusChanged(e){await this.emitEvent("simulcast_status",e)}async emitDownloadReady(e){await this.emitEvent("download_ready",e)}async emitRecordingsCountUpdated(e){await this.emitEvent("recordings_count_updated",e)}async emitUserTyping(e){await this.emitEvent("user_typing",e)}async emitStreamReaction(e){await this.emitEvent("stream_reaction",e)}async emitContentReactionAdded(e){await this.emitEvent("content_reaction_added",e)}async emitContentReactionRemoved(e){await this.emitEvent("content_reaction_removed",e)}async emitStreamCountdownUpdated(e){await this.emitEvent("stream_countdown_updated",e)}async emitStreamLanguageUpdated(e){await this.emitEvent("stream_language_updated",e)}async emitStreamControlStatusChanged(e){await this.emitEvent("stream_control_status_changed",e)}async emitConnection(e){await this.emitEvent("connection",e)}async emitAuthenticated(e){await this.emitEvent("authenticated",e)}async emitTokenSubscribed(e){await this.emitEvent("token_subscribed",e)}async emitTokenUnsubscribed(e){await this.emitEvent("token_unsubscribed",e)}async emitRoomSubscribed(e){await this.emitEvent("room_subscribed",e)}async emitRoomLeft(e){await this.emitEvent("room_left",e)}}const il={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},cl={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},ll={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},dl=Nn(il),ul=Nn(cl),hl=Nn(ll);const gl={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},ml={OWNER:"OWNER",MODERATOR:"MODERATOR"};Nn(gl),Nn(ml);const pl={...gl,OVERSEER:"OVERSEER"},fl=Nn(pl);function El(e,t="tokenName"){Cn(e,t,Ht)}function Al(e){if(El(e.tokenName),!Tn(e.language))throw ut("language");if(t=e.language,!Tn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new Je('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",Ye.INVALID_FORMAT);var t}class vl extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,Ht);const t=this.buildEndpoint(m,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Ht);const t=this.buildEndpoint(p,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,f,Ht)}async enableStream(e){return this.toggleFeature(e,E,Ht)}async resetStreamKey(e){this.validateTokenName(e,Ht);const t=this.buildEndpoint(A,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Ht);const t=this.buildEndpoint(R,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){El(e.tokenName),bn(0,void 0,sn,e.pageSize)}(e);const t=this.buildEndpoint(v,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,sn),r=e.offset;"number"==typeof r&&(n.offset=String(r));const s=await this.http.get(t,n),a=this.extractData(s),o=e,i=a.pageSize??a.limit??e.pageSize??("number"==typeof o.limit?o.limit:20),c="number"==typeof o.offset?o.offset:0,l=Math.floor(c/i)+1;return{recordings:a.recordings,tokenName:Mt(e.tokenName),page:a.page??l,limit:i,total:a.total,hasNext:a.recordings.length===i}}async getRecordingDownload(e,t){this.validateTokenName(e,Ht),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(S,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,Ht),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(T,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Ht);const t=this.buildEndpoint(y,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(El(e.tokenName),!Tn(e.platform))throw ut("platform");if(!hl(e.platform))throw new Je("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",Ye.INVALID_VALUE);if(!Tn(e.rtmpUrl))throw ut("rtmpUrl");if(!rn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new Je("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",Ye.INVALID_FORMAT);if(!Tn(e.streamKey))throw ut("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new Je("name must be a string","name",Ye.INVALID_TYPE)}(e);const t=this.buildEndpoint(k,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,rtmpUrl:e.rtmpUrl,streamKey:e.streamKey,name:e.name},this.getJwtHeaders());return this.extractData(n)}async removeSimulcastTarget(e,t){this.validateTokenName(e,Ht),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(b,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(N);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(w,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(C,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(El(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Tn(e.nextLiveStreamAt)))throw new Je("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",Ye.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new Je("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",Ye.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,Ht);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Al(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){El(e.tokenName)}(e);const t=this.buildEndpoint(_,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(I);return this.extractData(e)}async getTokenAccess(e){!function(e){El(e.tokenName)}(e);const t=await this.http.get(D,{tokenName:Mt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}class Sl{constructor(e={}){this.attempts=0,this.config={maxAttempts:e.maxAttempts??5,baseDelayMs:e.baseDelayMs??2e3,useExponentialBackoff:e.useExponentialBackoff??!1,maxDelayMs:e.maxDelayMs??3e4,backoffMultiplier:e.backoffMultiplier??2},this.currentDelayMs=this.config.baseDelayMs}shouldRetry(){return this.attempts<this.config.maxAttempts}getNextDelay(){return this.currentDelayMs}recordAttempt(){this.attempts++,this.config.useExponentialBackoff&&(this.currentDelayMs=Math.min(this.currentDelayMs*this.config.backoffMultiplier,this.config.maxDelayMs))}reset(){this.attempts=0,this.currentDelayMs=this.config.baseDelayMs}getAttempts(){return this.attempts}getMaxAttempts(){return this.config.maxAttempts}isExhausted(){return this.attempts>=this.config.maxAttempts}getState(){return{attempts:this.attempts,maxAttempts:this.config.maxAttempts,canRetry:this.shouldRetry(),nextDelayMs:this.currentDelayMs,exhausted:this.isExhausted()}}getStatusString(){return`${this.attempts}/${this.config.maxAttempts} attempts`}}const Tl={SUBSCRIBE:"subscribe_token",UNSUBSCRIBE:"unsubscribe_token",AUTHENTICATE:"authenticate",SEND_CHAT:"send_stream_chat",SEND_REACTION:"SEND_STREAM_REACTION",TYPING_START:"typing_start",TYPING_STOP:"typing_stop",STREAM_STATUS:"STREAM_STATUS",RECORDING_STATUS:"RECORDING_STATUS",RECORDINGS_COUNT_UPDATED:"RECORDINGS_COUNT_UPDATED",SIMULCAST_STATUS:"SIMULCAST_STATUS",DOWNLOAD_READY:"DOWNLOAD_READY",STREAM_COUNTDOWN_UPDATED:"STREAM_COUNTDOWN_UPDATED",STREAM_LANGUAGE_UPDATED:"STREAM_LANGUAGE_UPDATED",VIEWER_COUNT:"VIEWER_COUNT",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",STREAM_GLOBAL_STATUS:"STREAM_GLOBAL_STATUS",ENGAGEMENT_STATS_UPDATED:"ENGAGEMENT_STATS_UPDATED",CHAT_MESSAGE:"STREAM_CHAT_MESSAGE",CHAT_SENT:"STREAM_CHAT_SENT",CHAT_UPDATED:"STREAM_CHAT_UPDATED",CHAT_DELETED:"STREAM_CHAT_DELETED",CHAT_ERROR:"stream_chat_error",CHAT_STATUS:"CHAT_STATUS_CHANGED",CHAT_GLOBAL_STATUS:"STREAM_CHAT_GLOBAL_STATUS",CHAT_AUTHENTICATED:"authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",STREAM_CONTROL_STATUS_CHANGED:"STREAM_CONTROL_STATUS_CHANGED",REACTION:"STREAM_REACTION",CONTENT_REACTION_ADDED:"CONTENT_REACTION_ADDED",CONTENT_REACTION_REMOVED:"CONTENT_REACTION_REMOVED",REACTION_ERROR:"stream_reaction_error",USER_TYPING:"USER_TYPING",CHAT_PINNED:"STREAM_CHAT_PINNED",CHAT_UNPINNED:"STREAM_CHAT_UNPINNED",COMMENT_CREATED:"COMMENT_CREATED",COMMENT_UPDATED:"COMMENT_UPDATED",COMMENT_DELETED:"COMMENT_DELETED",USER_BANNED:"USER_BANNED",USER_UNBANNED:"USER_UNBANNED",BAN_ENFORCEMENT:"BAN_ENFORCEMENT",TOKEN_BANNED:"TOKEN_BANNED",TOKEN_UNBANNED:"TOKEN_UNBANNED",CONTENT_FLAGGED:"CONTENT_FLAGGED",FLAG_RESOLVED:"FLAG_RESOLVED",MODERATOR_INVITE_CREATED:"MODERATOR_INVITE_CREATED",MODERATOR_ADDED:"MODERATOR_ADDED",MODERATOR_REMOVED:"MODERATOR_REMOVED",MODERATOR_ROLE_UPDATED:"MODERATOR_ROLE_UPDATED",OVERSEER_ADDED:"OVERSEER_ADDED",OVERSEER_REMOVED:"OVERSEER_REMOVED",TRADE_EXECUTED:"TRADE_EXECUTED",BALANCE_UPDATED:"BALANCE_UPDATED",STATS_UPDATED:"STATS_UPDATED",POOL_METADATA_UPDATED:"POOL_METADATA_UPDATED",POOL_SOCIAL_LINKS_UPDATED:"POOL_SOCIAL_LINKS_UPDATED",POOL_BADGE_ASSIGNED:"POOL_BADGE_ASSIGNED",HOLDER_COUNT_UPDATED:"HOLDER_COUNT_UPDATED",USER_PROFILE_UPDATED:"USER_PROFILE_UPDATED",API_KEY_CREATED:"API_KEY_CREATED",API_KEY_UPDATED:"API_KEY_UPDATED",API_KEY_REVOKED:"API_KEY_REVOKED",TOKEN_CONFIG_UPDATED:"TOKEN_CONFIG_UPDATED",SITE_CONFIG_CHANGED:"SITE_CONFIG_CHANGED",COMMENTS_GLOBAL_STATUS:"COMMENTS_GLOBAL_STATUS",WEBHOOKS_GLOBAL_STATUS:"WEBHOOKS_GLOBAL_STATUS",SUBSCRIBE_GLOBAL_FEED:"subscribe_global_feed",UNSUBSCRIBE_GLOBAL_FEED:"unsubscribe_global_feed",GLOBAL_FEED_SUBSCRIBED:"global_feed_subscribed",GLOBAL_FEED_UNSUBSCRIBED:"global_feed_unsubscribed"};class yl extends Fn{constructor(e,t=!1){if(super(t),this.socket=null,this.isAuthenticated=!1,this.subscribedRooms=new Map,this.roomCallbacks=new Map,this.pendingSubscriptions=new Map,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=100,this.BUFFER_CLEANUP_MS=3e4,this.globalCallbacks={},this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks={},this.pendingGlobalFeedSubscription=null,""===e.url)throw new et("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,authToken:e.authToken??"",reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,subscriptionTimeout:e.subscriptionTimeout??1e4},this.reconnectionManager=new Sl({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof o.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:",rt(e)),!1}}getRoomName(e){return`token:${Mt(e)}`}bufferEvent(e,t,n){const r=`${e}:${t}`;let s=this.eventBuffer.get(r);s||(s=[],this.eventBuffer.set(r,s)),s.length>=this.MAX_BUFFER_SIZE&&(s.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${r} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),s.push(n);const a=this.eventBufferTimeouts.get(r);a&&clearTimeout(a);const o=setTimeout(()=>{this.eventBuffer.delete(r),this.eventBufferTimeouts.delete(r),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${r}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(r,o)}processBufferedEvents(e,t){const n=Mt(e),r=[{key:`${Tl.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${Tl.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${Tl.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${Tl.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${Tl.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${Tl.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${Tl.STREAM_COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${Tl.STREAM_LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated},{key:`${Tl.TOKEN_BANNED}:${n}`,callback:t.onTokenBanned},{key:`${Tl.TOKEN_UNBANNED}:${n}`,callback:t.onTokenUnbanned},{key:`${Tl.MODERATOR_INVITE_CREATED}:${n}`,callback:t.onModeratorInviteCreated},{key:`${Tl.MODERATOR_ADDED}:${n}`,callback:t.onModeratorAdded},{key:`${Tl.MODERATOR_REMOVED}:${n}`,callback:t.onModeratorRemoved},{key:`${Tl.MODERATOR_ROLE_UPDATED}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${Tl.TRADE_EXECUTED}:${n}`,callback:t.onTradeExecuted},{key:`${Tl.BALANCE_UPDATED}:${n}`,callback:t.onBalanceUpdated},{key:`${Tl.POOL_METADATA_UPDATED}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${Tl.POOL_SOCIAL_LINKS_UPDATED}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${Tl.POOL_BADGE_ASSIGNED}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${Tl.HOLDER_COUNT_UPDATED}:${n}`,callback:t.onHolderCountUpdated},{key:`${Tl.COMMENT_CREATED}:${n}`,callback:t.onCommentCreated}];for(const{key:e,callback:t}of r){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const r of n)try{t(r)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const r=this.eventBufferTimeouts.get(e);r&&(clearTimeout(r),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(Tl.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(Tl.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onStreamStatus&&t.onStreamStatus(e),this.globalCallbacks.onStreamStatus&&this.globalCallbacks.onStreamStatus(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onStreamStatus&&this.globalFeedCallbacks.onStreamStatus(e)}),this.socket.on(Tl.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=Mt(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const r=this.roomCallbacks.get(t);r?.onStreamSubscribed&&r.onStreamSubscribed(e)}),this.socket.on(Tl.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(Mt(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(Tl.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(Tl.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onViewerCount&&t.onViewerCount(e),this.globalCallbacks.onViewerCount&&this.globalCallbacks.onViewerCount(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onViewerCount&&this.globalFeedCallbacks.onViewerCount(e)}),this.socket.on(Tl.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Tl.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(Tl.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(Tl.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(Tl.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(Tl.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(Tl.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(Tl.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(Tl.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(Tl.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(Tl.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(Tl.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(Tl.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(Mt(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(Tl.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(Tl.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(Tl.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(Tl.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(Tl.STREAM_COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(Tl.STREAM_COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(Mt(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(Tl.STREAM_LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(Tl.STREAM_LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(Tl.TOKEN_BANNED,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(Tl.TOKEN_BANNED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(Tl.TOKEN_UNBANNED,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(Tl.TOKEN_UNBANNED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(Tl.USER_BANNED,e=>{this.logger.debug(`📡 [User Banned] ${e.tokenName}: ${e.userAddress}`),this.streamingEventService?.emitUserBanned(e)}),this.socket.on(Tl.USER_UNBANNED,e=>{this.logger.debug(`📡 [User Unbanned] ${e.tokenName}: ${e.userAddress}`),this.streamingEventService?.emitUserUnbanned(e)}),this.socket.on(Tl.BAN_ENFORCEMENT,e=>{this.logger.debug(`📡 [Ban Enforcement] ${e.tokenName}: ${e.action}`),this.streamingEventService?.emitBanEnforcement(e)}),this.socket.on(Tl.MODERATOR_INVITE_CREATED,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(Tl.MODERATOR_INVITE_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(Tl.MODERATOR_ADDED,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Tl.MODERATOR_ADDED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(Tl.MODERATOR_REMOVED,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Tl.MODERATOR_REMOVED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(Tl.MODERATOR_ROLE_UPDATED,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Tl.MODERATOR_ROLE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(Tl.OVERSEER_ADDED,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(Tl.OVERSEER_REMOVED,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(Tl.TRADE_EXECUTED,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(Tl.TRADE_EXECUTED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(Tl.BALANCE_UPDATED,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(Tl.BALANCE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(Tl.POOL_METADATA_UPDATED,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(Tl.POOL_METADATA_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(Tl.POOL_SOCIAL_LINKS_UPDATED,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(Tl.POOL_SOCIAL_LINKS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(Tl.POOL_BADGE_ASSIGNED,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(Tl.POOL_BADGE_ASSIGNED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(Tl.HOLDER_COUNT_UPDATED,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(Tl.HOLDER_COUNT_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(Tl.COMMENT_CREATED,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(Tl.COMMENT_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(Tl.USER_PROFILE_UPDATED,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(Tl.API_KEY_CREATED,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(Tl.API_KEY_UPDATED,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(Tl.API_KEY_REVOKED,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(Tl.TOKEN_CONFIG_UPDATED,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(Tl.TOKEN_CONFIG_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(Tl.STATS_UPDATED,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(Tl.STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onStatsUpdated&&t.onStatsUpdated(e),this.globalCallbacks.onStatsUpdated&&this.globalCallbacks.onStatsUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onStatsUpdated&&this.globalFeedCallbacks.onStatsUpdated(e)}),this.socket.on(Tl.ENGAGEMENT_STATS_UPDATED,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(Tl.ENGAGEMENT_STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Mt(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(Tl.GLOBAL_FEED_SUBSCRIBED,e=>{if(this.logger.debug("📡 [Global Feed Subscribed]"),this.isGlobalFeedSubscribed=!0,this.pendingGlobalFeedSubscription){const{resolve:t,timeoutId:n}=this.pendingGlobalFeedSubscription;clearTimeout(n),this.pendingGlobalFeedSubscription=null,t(e)}this.globalFeedCallbacks.onGlobalFeedSubscribed&&this.globalFeedCallbacks.onGlobalFeedSubscribed(e)}),this.socket.on(Tl.GLOBAL_FEED_UNSUBSCRIBED,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(Tl.SITE_CONFIG_CHANGED,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(Tl.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Tl.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(Tl.COMMENTS_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(Tl.WEBHOOKS_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Webhooks Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onWebhooksGlobalStatus&&this.globalFeedCallbacks.onWebhooksGlobalStatus(e)}))}resubscribeAll(){const e=Array.from(this.subscribedRooms.keys());this.logger.debug(`📡 Re-subscribing to ${e.length} rooms after reconnect`);for(const t of e)try{this.roomCallbacks.get(t)&&this.socket?.emit(Tl.SUBSCRIBE,{tokenName:t})}catch(e){this.logger.error(`Failed to re-subscribe to ${t}:`,e)}if(this.isGlobalFeedSubscribed)try{this.logger.debug("📡 Re-subscribing to global feed after reconnect"),this.socket?.emit(Tl.SUBSCRIBE_GLOBAL_FEED)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}setStreamingEventService(e){this.streamingEventService=e}async connect(){return new Promise((e,t)=>{Ca(async()=>{if(!this.isSocketIOAvailable)throw new et('Socket.IO not available. Install "socket.io-client" package.');this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const n={};return""!==this.config.authToken&&(n.token=this.config.authToken),this.socket=o.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,auth:n}),this.socket.on("connect",()=>{this.logger.debug(`✅ Stream WebSocket connected: ${String(this.socket?.id)}`),this.reconnectionManager.reset(),this.setupGlobalListeners(),this.subscribedRooms.size>0&&this.resubscribeAll(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.isAuthenticated=!1}),this.socket.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)}),this.socket.io.on("reconnect",e=>{this.logger.debug(`🔄 Stream WebSocket reconnected after ${e} attempts`),this.reconnectionManager.reset(),""!==this.config.authToken&&this.authenticate(this.config.authToken)}),this.socket.io.on("reconnect_attempt",()=>{this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${this.reconnectionManager.getStatusString()}`)}),this.socket.io.on("reconnect_failed",()=>{this.logger.error("❌ Stream WebSocket max reconnection attempts reached")}),Promise.resolve(void 0)},"Stream WebSocket connection setup",this.logger,e=>{const n=e instanceof Error?e:new Error(String(e));throw t(n),n})})}authenticate(e){if(!this.socket?.connected)throw new Je("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw ut("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(Tl.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw ut("tokenName","Token name");if(!this.socket?.connected)throw new Je("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=Mt(e);return this.subscribedRooms.has(n)?(this.logger.debug(`📡 Already subscribed to ${n}, updating callbacks`),this.roomCallbacks.set(n,t),this.processBufferedEvents(n,t),{tokenName:n,room:this.getRoomName(e)}):new Promise((r,s)=>{const a=setTimeout(()=>{this.pendingSubscriptions.delete(n),s(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:r,reject:s,timeoutId:a}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(Tl.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=Mt(e);if(!this.subscribedRooms.has(t))return void this.logger.debug(`📡 Not subscribed to ${t}, skipping unsubscribe`);this.logger.debug(`📡 Unsubscribing from stream: ${t}`),this.socket?.connected&&this.socket.emit(Tl.UNSUBSCRIBE,{tokenName:t}),this.subscribedRooms.delete(t),this.roomCallbacks.delete(t);const n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t));for(const e of this.eventBuffer.keys())if(e.endsWith(`:${t}`)){this.eventBuffer.delete(e);const t=this.eventBufferTimeouts.get(e);t&&(clearTimeout(t),this.eventBufferTimeouts.delete(e))}}sendChatMessage(e,t){if(""===e)throw ut("tokenName","Token name");if(""===t)throw ut("content","Message content");if(!this.socket?.connected)throw new Je("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Je("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=Mt(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(Tl.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw ut("tokenName","Token name");if(""===t)throw ut("emoji");if(!this.socket?.connected)throw new Je("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Je("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=Mt(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(Tl.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Tl.TYPING_START,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,Tl.TYPING_STOP,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw ut("tokenName","Token name");if(!this.socket?.connected)throw new Je("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Je("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=Mt(e);this.logger.debug(`📡 Sending ${n} to ${r}`),this.socket.emit(t,{tokenName:r})}subscribeTokenBanned(e,t){const n=Mt(e),r={onTokenBanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenBanned,this.roomCallbacks.set(n,t)}}}subscribeTokenUnbanned(e,t){const n=Mt(e),r={onTokenUnbanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenUnbanned,this.roomCallbacks.set(n,t)}}}subscribeModeratorInviteCreated(e,t){const n=Mt(e),r={onModeratorInviteCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorInviteCreated,this.roomCallbacks.set(n,t)}}}subscribeModeratorAdded(e,t){const n=Mt(e),r={onModeratorAdded:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorAdded,this.roomCallbacks.set(n,t)}}}subscribeModeratorRemoved(e,t){const n=Mt(e),r={onModeratorRemoved:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRemoved,this.roomCallbacks.set(n,t)}}}subscribeModeratorRoleUpdated(e,t){const n=Mt(e),r={onModeratorRoleUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRoleUpdated,this.roomCallbacks.set(n,t)}}}subscribeOverseerAdded(e){return this.globalCallbacks.onOverseerAdded=e,()=>{delete this.globalCallbacks.onOverseerAdded}}subscribeOverseerRemoved(e){return this.globalCallbacks.onOverseerRemoved=e,()=>{delete this.globalCallbacks.onOverseerRemoved}}subscribeTradeExecuted(e,t){const n=Mt(e),r={onTradeExecuted:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTradeExecuted,this.roomCallbacks.set(n,t)}}}subscribePoolMetadataUpdated(e,t){const n=Mt(e),r={onPoolMetadataUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolMetadataUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolSocialLinksUpdated(e,t){const n=Mt(e),r={onPoolSocialLinksUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolSocialLinksUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolBadgeAssigned(e,t){const n=Mt(e),r={onPoolBadgeAssigned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolBadgeAssigned,this.roomCallbacks.set(n,t)}}}subscribeHolderCountUpdated(e,t){const n=Mt(e),r={onHolderCountUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onHolderCountUpdated,this.roomCallbacks.set(n,t)}}}subscribeCommentCreated(e,t){const n=Mt(e),r={onCommentCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onCommentCreated,this.roomCallbacks.set(n,t)}}}subscribeUserProfileUpdated(e){return this.globalCallbacks.onUserProfileUpdated=e,()=>{delete this.globalCallbacks.onUserProfileUpdated}}subscribeApiKeyCreated(e){return this.globalCallbacks.onApiKeyCreated=e,()=>{delete this.globalCallbacks.onApiKeyCreated}}subscribeApiKeyUpdated(e){return this.globalCallbacks.onApiKeyUpdated=e,()=>{delete this.globalCallbacks.onApiKeyUpdated}}subscribeApiKeyRevoked(e){return this.globalCallbacks.onApiKeyRevoked=e,()=>{delete this.globalCallbacks.onApiKeyRevoked}}subscribeStatsUpdated(e){return this.globalCallbacks.onStatsUpdated=e,()=>{delete this.globalCallbacks.onStatsUpdated}}subscribeEngagementStatsUpdated(e){return this.globalCallbacks.onEngagementStatsUpdated=e,()=>{delete this.globalCallbacks.onEngagementStatsUpdated}}setGlobalCallbacks(e){this.globalCallbacks=e}getSubscribedTokens(){return Array.from(this.subscribedRooms.keys())}isConnected(){return this.socket?.connected??!1}isAuthenticatedForChat(){return this.isAuthenticated}async subscribeToGlobalFeed(e){if(!this.socket?.connected)throw new Je("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");return this.isGlobalFeedSubscribed?(this.logger.debug("📡 Already subscribed to global feed, updating callbacks"),e&&(this.globalFeedCallbacks=e),{room:"global:feed"}):new Promise((t,n)=>{const r=setTimeout(()=>{this.pendingGlobalFeedSubscription=null,n(new Error(`Global feed subscription timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingGlobalFeedSubscription={resolve:t,reject:n,timeoutId:r},e&&(this.globalFeedCallbacks=e),this.logger.debug("📡 Subscribing to global feed"),this.socket.emit(Tl.SUBSCRIBE_GLOBAL_FEED)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(Tl.UNSUBSCRIBE_GLOBAL_FEED),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks={},this.pendingGlobalFeedSubscription&&(clearTimeout(this.pendingGlobalFeedSubscription.timeoutId),this.pendingGlobalFeedSubscription=null)):this.logger.debug("📡 Not subscribed to global feed, skipping unsubscribe")}isSubscribedToGlobalFeed(){return this.isGlobalFeedSubscribed}setGlobalFeedCallbacks(e){this.globalFeedCallbacks=e,this.logger.debug("📡 Updated global feed callbacks")}getSocket(){return this.socket}disconnect(){if(this.socket){this.logger.debug("🔌 Disconnecting from Stream WebSocket");try{for(const[e,t]of this.pendingSubscriptions){try{clearTimeout(t.timeoutId),t.reject(new Error("WebSocket disconnected"))}catch(t){this.logger.error(`Error cleaning up pending subscription for ${e}:`,t)}this.pendingSubscriptions.delete(e)}}catch(e){this.logger.error("Error clearing pending subscriptions:",e)}try{this.subscribedRooms.clear(),this.roomCallbacks.clear()}catch(e){this.logger.error("Error clearing room tracking:",e)}try{for(const e of this.eventBufferTimeouts.values())clearTimeout(e);this.eventBuffer.clear(),this.eventBufferTimeouts.clear()}catch(e){this.logger.error("Error clearing event buffers:",e)}this.globalCallbacks={};try{this.globalFeedCallbacks={},this.isGlobalFeedSubscribed=!1,this.pendingGlobalFeedSubscription&&(clearTimeout(this.pendingGlobalFeedSubscription.timeoutId),this.pendingGlobalFeedSubscription.reject(new Error("WebSocket disconnected")),this.pendingGlobalFeedSubscription=null)}catch(e){this.logger.error("Error clearing global feed state:",e)}try{this.socket.disconnect()}catch(e){this.logger.error("Error disconnecting socket:",e)}this.socket=null,this.isAuthenticated=!1,this.logger.debug("✅ Stream WebSocket disconnected and cleaned up")}}}function kl(e){return null==e||""===e||"string"==typeof e&&(!Rn(e)&&e.length<=Yt.BAN_REASON.MAX_LENGTH)}function bl(e){if(Cn(e.tokenName,"tokenName",Ht),!kl(e.reason))throw new Je(`reason must be at most ${Yt.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function Nl(e){Cn(e.tokenName,"tokenName",Ht)}function wl(e){bn(0,void 0,zt,e.pageSize)}function Cl(e){Cn(e.tokenName,"tokenName",Ht)}class _l extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){bl(e);const t=ke,n={tokenName:Mt(e.tokenName)};if(void 0!==e.reason)try{An(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:Mt(e.tokenName)}}async unbanToken(e){Nl(e);const t=this.buildEndpoint(we,{tokenName:e.tokenName});return wt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:Mt(e.tokenName)}}async listTokenBans(e={}){wl(e);const t=be,n=this.buildPaginationParams(e,zt);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getTokenBan(e){Cl(e);const t=this.buildEndpoint(Ne,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Mt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class Il extends Fn{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map,this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}async resolveTokenToVault(e){if(!Tn(e))throw ut("tokenName","Token name");const t=Mt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null!==r&&""!==r){const e=this.parseVaultAddressToTokenClassKey(r);this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:e,cachedAt:Date.now()})}return r}async resolveTokenClassKey(e){if(!Tn(e))throw ut("tokenName","Token name");const t=Mt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw dt(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(Mt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=Il.MAX_CACHE_SIZE&&!this.cache.has(e)&&this.evictOldestEntry(),this.cache.set(e,t),this.updateAccessOrder(e)}updateAccessOrder(e){this.accessOrder.delete(e),this.accessOrder.add(e)}evictOldestEntry(){const e=this.accessOrder.values().next().value;void 0!==e&&""!==e&&(this.cache.delete(e),this.accessOrder.delete(e))}set(e,t){const n=Mt(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:Il.MAX_CACHE_SIZE,hits:this.cacheHits,misses:this.cacheMisses,hitRate:t>0?this.cacheHits/t:0,oldestEntry:e.length>0?Math.min(...e):null,newestEntry:e.length>0?Math.max(...e):null}}getCachedTokenClassKey(e){const t=this.getCacheEntry(Mt(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=Mt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Po(e)}catch(e){if(e instanceof Je)throw ht("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}Il.MAX_CACHE_SIZE=1e4;class Dl extends Un{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return It(()=>this.http.get(Be),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return It(()=>this.http.get($e,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return ua(await It(()=>this.http.get(Ge,{tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return ua(await It(()=>this.http.get(Ke,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class Rl extends Ka{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,Wt);const n={action:"trade_executed",tokenName:e,payload:t};await this.emitEvent(n)}async emitBalanceUpdated(e,t,n){this.validateRequiredString(e,"userAddress","User Address"),this.validateTokenName(t,Wt);const r={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Wt);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Wt);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Wt);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Wt);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Wt);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Wt);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,Wt);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Wt);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Wt);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Wt);const r={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:e,payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=e.userAddress),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const r=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(r)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new et("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.includes(e)),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,Wt);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const r=await this.getConnectedClients(n);return{clients:r.clients,count:r.summary.totalConnected,authenticatedCount:r.summary.authenticatedCount}}async getOnlineOverseers(){const e=await this.getConnectedClients({isOverseer:!0});return{clients:e.clients,count:e.summary.totalConnected}}async emitRecordingStatus(e,t){this.validateTokenName(e,Wt);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Wt);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Wt);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class Ol{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const r=n??this.defaultTtlMs,s={value:t};r>0&&(s.expiresAt=Date.now()+r),this.cache.set(e,s)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}class xl extends Fn{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.hasOnAnyListener=!1,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.reconnectionManager=new Sl({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Ol(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),xl.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof o.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)=>{Ca(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",rt(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=o.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.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=nt(e)?e:new Error(rt(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const r=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),s={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,s=r?.data,a=r?.status??r?.Status??s?.status??s?.Status;let o=r?.message??r?.Message??s?.message??s?.Message??r?.error??s?.error;Tn(o)||(o=a===Oa.FAILED||a===Oa.ERROR?"Transaction failed - check transaction details":a===Oa.COMPLETED||a===Oa.PROCESSED||a===Oa.SUCCESS?"Transaction completed successfully":null!=a?`Transaction status: ${String(a)}`:"Unknown transaction status");const i=r?.blockHash??s?.blockHash,c=r?.gasUsed??s?.gasUsed,l=r?.Data??s?.Data,d={transactionId:e,status:this.mapSocketStatus(a),message:"string"==typeof o?o:"Transaction update received",timestamp:Date.now(),...null!=i?{blockHash:i}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(a)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(o)}"`),n(d),d.status===exports.SDKTransactionStatus.COMPLETED||d.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} (${d.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Ma[t]??exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):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.logger.debug("🧹 Cleared event buffer"),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")),xl.instances.delete(this)}static cleanupAll(e=!1){for(const e of xl.instances)e.disconnect();xl.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}xl.instances=new Set;class Ml extends Un{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Weekly challenge operation failed";throw new Error(t)}return e.data}async getLeaderboard(e={}){const{limit:t=10}=e;if(t<1||t>50)throw new Je("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(He.GET_LEADERBOARD,n),s=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new Je("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=He.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),s=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}class Ll extends Error{constructor(e,t,n={}){super(e),this.name="LaunchpadSDKError",this.code=t,this.status=n.status,this.chainMessage=n.chainMessage,this.details=n.details}}class Ul{constructor(e){this.bundleId=e.bundleId,this.uniqueKey=e.uniqueKey,this.method=e.method,this.waitForResult=e.wait}wait(e){return this.waitForResult(e)}}class Fl{constructor(e){this.bundleBaseUrl=Vl(e.bundleBaseUrl),this.launchpadBaseUrl=Vl(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>o.io(e,{transports:["websocket"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof Ll)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new Ll(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),r=`${this.bundleBaseUrl}/bundle`,s=await this.requestor(r,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),a=await Hl(s);if(!s.ok)throw Bl(s.status,a,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!Wl(e))throw new Ll("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(Wl(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Ll("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(a),i=Kl(e.dto,"uniqueKey");return new Ul({bundleId:o,uniqueKey:i,method:e.method,wait:t=>this.waitForResult(e,o,t)})}async waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,a=Date.now();let o,i,c=!1,l=new Promise(()=>{});try{o=this.socketFactory(this.bundleBaseUrl),l=new Promise((e,n)=>{i=t=>{const r=function(e){if(!Wl(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(t);void 0===r||c||(c=!0,"FAILED"===r.status?n(Pl(r.data)):e(r))},o?.on(t,i)})}catch{o=void 0}const d=this.pollConfirmation(e,t,a,r,s);try{return await Promise.race([l,d])}finally{c=!0,void 0!==o&&(void 0!==i&&o.off(t,i),o.disconnect())}}async pollConfirmation(e,t,n,r,s){const a="CreateSale"===e.method,o=a?function(e,t){const n=Kl(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`;for(;Date.now()-n<=r;){const e=await this.requestor(o,{method:"GET"}),t=await Hl(e);if(a){if(e.ok)return{status:"PROCESSED",data:Gl(t)};if(404!==e.status&&202!==e.status)throw Bl(e.status,t,o)}else{if(!e.ok)throw Bl(e.status,t,o);const n=Wl(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw Pl(t)}const i=r-(Date.now()-n);if(i<=0)break;await zl(Math.min(Math.max(0,s),i))}throw new Ll(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function Pl(e){const t=$l(e)??"Launchpad bundle failed on chain.";return new Ll(t,"BUNDLE_FAILED",{chainMessage:t})}function Bl(e,t,n){const r=$l(t)??`Bundle request failed with HTTP ${e}`;return new Ll(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function $l(e){if("string"==typeof e&&""!==e)return e;if(Wl(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(Wl(n)){const e=$l(n);if(void 0!==e)return e}}}function Gl(e){return Wl(e)?e.data??e.Data??e:e}function Kl(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Ll(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function Hl(e){try{return await e.json()}catch{return e.text()}}function Wl(e){return"object"==typeof e&&null!==e}function Vl(e){return e.replace(/\/$/u,"")}function zl(e){return new Promise(t=>setTimeout(t,e))}function jl(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new Je(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new Je(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new i(e).multipliedBy(new i(1).plus(new i(String(t)))).decimalPlaces(8,i.ROUND_UP).toFixed()}function ql(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=xo(t).type,r=await e.findTokenNameByVault(t,n);if(void 0===r)throw new Je(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return r}(e,t.vaultAddress);return jl((await e.getTradeQuote("SellExactToken"===t.method?{tokenName:n,amount:t.quantity,type:"MEME",method:"IN"}:{tokenName:n,amount:t.quantity,type:"NATIVE",method:"OUT"})).reverseBondingCurveFee,t.feeSlippageFactor??e.defaultFeeSlippageFactor())}}const Xl={minFeePortion:"0.1",maxFeePortion:"0.5"};class Ql{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress,this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){!function(e){const t=ws(e);!t.success&&t.errors&&ga(t.errors,"data")}(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:e.preBuyQuantity??"0",websiteUrl:e.websiteUrl??"",telegramUrl:e.telegramUrl??"",twitterUrl:e.twitterUrl??"",instagramUrl:e.instagramUrl??"",facebookUrl:e.facebookUrl??"",redditUrl:e.redditUrl??"",tiktokUrl:e.tiktokUrl??"",tokenCategory:e.tokenCategory??"Unit",tokenCollection:e.tokenCollection??"Token",uniqueKey:e.uniqueKey??Yl(t)},r=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:r?.minFeePortion??Xl.minFeePortion,maxFeePortion:r?.maxFeePortion??Xl.maxFeePortion},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Lo(e)})}buyWithNative(e){return this.submitTrade("BuyWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}buyExactToken(e){return this.submitTrade("BuyExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}sellWithNative(e){return this.submitTrade("SellWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}sellExactToken(e){return this.submitTrade("SellExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}async submitTrade(e,t,n){const r={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??await this.defaultExtraFees(e,t),uniqueKey:t.uniqueKey??Yl(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:Mo(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new Je("A sell needs a reverse bonding curve fee ceiling and no quote source is configured: pass extraFees.maxAcceptableReverseBondingCurveFee.","extraFees","FEE_CEILING_REQUIRED");return{maxAcceptableReverseBondingCurveFee:await this.sellFeeCeiling({method:e,vaultAddress:t.vaultAddress,quantity:t.quantity,...void 0===t.tokenName?{}:{tokenName:t.tokenName}})}}}function Yl(e){return`galaswap-operation-${a.v4()}-${Date.now()}-${e}`}function Jl(e,t=3e4){return c.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Zl=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function ed(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>ed(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=Zl.has(e.toLowerCase())?"[REDACTED]":ed(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=Zl.has(r.toLowerCase())?"[REDACTED]":ed(s,t+1);return n}return e}class td{constructor(e,t={},n={signRequests:!0}){this.auth=e,this.signRequests=n.signRequests,this.debug=t.debug??!1,this.logger=new Ft({debug:this.debug,context:"HttpClient"});const r=t.baseUrl??Ra("stage").launchpadBaseUrl,s=t.timeout??6e4;this.axios=Jl(r,s),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return Ca(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Ys(e.params)},...void 0!==e.headers&&{headers:e.headers},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};e.data instanceof FormData&&(void 0!==t.headers&&"Content-Type"in t.headers&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload")),e.headers&&this.logger.debug("Custom headers provided:",Object.keys(t.headers??{}));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":ed(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:ed(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const r=await this.axios.request(t),s=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(r.headers);return this.logger.debug("Response:",{status:r.status,data:ed(r.data),transactionId:s["x-transaction-id"],blockNumber:s["x-block-number"]}),{data:r.data,headers:s,status:r.status}},`HTTP ${e.method} ${e.url}`,this.logger)}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return Ca(async()=>{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()}},"Failed to generate custom signature for message",this.logger)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.signRequests&&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("Skipping signature header (no wallet, or signRequests is off)");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e instanceof Error?e:new Error(String(e)))),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,r={message:n?.message??rt(e),...n&&Boolean(n.error)&&{error:n.error},statusCode:t.response.status,...n&&Boolean(n.details)&&{details:n.details},...n&&Boolean(n.timestamp)&&{timestamp:n.timestamp},...n&&Boolean(n.path)&&{path:n.path}};t.launchpadError=r,this.logger.error("Backend error:",r)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(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")}}class nd extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class rd extends Error{constructor(e,t,n){super(`Transaction ${e} failed with status: ${t}${void 0!==n?` - ${n}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function sd(e,t){if(kn(e))throw new nd(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new nd(`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 nd(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function ad(e,t,n,r){sd(e,t);const s=e,a=s.data??{};if(!function(e){if(kn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(a))throw new nd(`Invalid trade data received for transaction ${t}`);const o={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:a.inputQuantity??r.amount,outputAmount:a.outputQuantity??r.expectedAmount??"0",totalFees:a.totalFees??"0",tokenName:r.tokenName,vaultAddress:a.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(o.blockHash=s.blockHash),void 0!==s.gasUsed&&(o.gasUsed=s.gasUsed),void 0!==r.slippageToleranceFactor&&(o.slippageTolerance=r.slippageToleranceFactor),o}function od(t){return void 0!==t&&r.isPrivateKeyProvider(t)?new e.Wallet(t.exportPrivateKey()):void 0}const id={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function cd(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const ld=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function dd(e,t,n){if(void 0===e||void 0===t)return;const r=ld.exec(e)?.[1],s=ld.exec(t)?.[1];if(void 0!==r&&void 0!==s&&r.toLowerCase()!==s.toLowerCase())throw mt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}let ud;class hd{constructor(e){let t,n;this.walletGeneration=0,this._tokenRoomRefCounts=new Map,this._tokenRoomListeners=new Map,this._tokenRoomUnsubscribers=new Map,e.walletProvider?(t=e.walletProvider,n=od(e.walletProvider)):e.wallet&&(n=e.wallet,t=r.PrivateKeyProvider.fromWallet(e.wallet)),this.wallet=n;const s=e.env??"prod",a=Ra(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??a.launchpadBaseUrl,gatewayBaseUrl:a.gatewayBaseUrl,bundleBaseUrl:a.bundleBaseUrl,webSocketUrl:a.webSocketUrl,dexApiBaseUrl:a.dexApiBaseUrl,dexBackendBaseUrl:a.dexBackendBaseUrl,launchpadFrontendUrl:a.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const o=e.signer??(void 0!==n?new Do(n.privateKey):void 0),i=void 0!==n?`eth|${n.address.slice(2)}`:cd(o);dd(i,e.walletAddress,"walletAddress"),dd(i,e.galaChainAddress,"galaChainAddress");const c=e.walletAddress??e.galaChainAddress??(void 0!==n?`eth|${n.address.slice(2)}`:cd(o)),l=o??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},d=c??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==c?{signer:e.signer,walletAddress:c}:void 0;const u=new Fl({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:l,walletAddress:d,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}}),h=ql({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});if(this.sellFeeCeiling=h,this.launchpad=new Ql({transport:u,walletAddress:d,sellFeeCeiling:h}),this.logger=new Ft({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?hd.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?hd.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??hd.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===n?c:void 0),this.auth=new Ia({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new wa,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new td(this.auth,this.config),this.sessionAuth=new _a(this.http,this.auth,this.jwtAuth,e.debug??!1);const g={signRequests:!1};this.galaChainHttp=new td(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},g),this.bundleHttp=new td(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},g),this.dexApiHttp=new td(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},g),this.dexBackendHttp=new td(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},g),this.galaChainPublicAxios=Jl(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Bn(e.debug??!1),this.launchpadService=new fc(this.http,this.jwtAuth),this.tokenResolverService=new Il(this.launchpadService.poolService),this.launchpadAPI=new Ta(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new Zi(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new gi(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new xl({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new Pc(this.galaChainHttp),this.tradingQuotesService=new Dl(this.http,e.debug??!1)}createOverrideSdk(t){if(!Tn(t))throw mt("Invalid privateKey: must be a non-empty string","privateKey");if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw mt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new e.Wallet(t),r={...this.config,wallet:n};return new hd(r)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw ut("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw ut("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new Je("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e),this.onWalletChanged()}onWalletChanged(){this.walletGeneration+=1,this.galaChainAddressOverride=void 0,this.signerWalletAddress=void 0,this.rebuildTokenWrites(),this.bundleService=this.createBundleService(),this._bridgeService=void 0,this._wrapService=void 0,this._galaConnectClient=void 0}createBundleService(){return new qo(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,this.wallet,this.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor,this.sellFeeCeiling)}rebuildTokenWrites(){this.tokenWriter=void 0,this.galaChainService=new Zi(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?od(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:r,streamAdminApiKey:s,userApiKey:a,accessToken:o,headers:i,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==a&&{userApiKey:"[REDACTED]"},...void 0!==o&&{accessToken:"[REDACTED]"},...void 0!==i&&{headers:Object.fromEntries(Object.keys(i).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:xt.GAS_FEE}}getVersion(){return La}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw mt("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.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=await this.fetchTokenDistribution(e),r=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===r)return null;const s=n.holders[r];return void 0===s?null:{rank:r+1,balance:s.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,a=Math.min(t?.limit??100,1e3),o=new Map;return n.holders.forEach((e,t)=>{o.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:o.get(e.address)??0})).slice(0,a)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const t="object"==typeof e&&null!==e?e:{};if(void 0!==t.tokenId)throw new Je("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",Ye.INVALID_PARAMETERS);const n=t.tokenName;return this.priceService.fetchLaunchpadTokenSpotPrice("string"==typeof n?n:"",e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.galaChainService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.launchpadAPI.fetchPoolDetails(e),n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return t.currentSupply=n.currentSupply,t.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,t.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,t.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,t.tokenName=e,t}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 Qn}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none"})}async coreBridge(){const e=this.walletGeneration,t=await(ud??(ud=Promise.resolve().then(function(){return l(require("@gala-chain/gala-core-sdk/bridge"))}).then(e=>{if("object"!=typeof(t=e)||null===t||"function"!=typeof t.BridgeService)throw new Error("the module has no BridgeService export");var t;return e}).catch(e=>{throw ud=void 0,mt(`The bridge and wrap methods use @gala-chain/gala-core-sdk/bridge, which needs its optional peers ethers, @solana/web3.js and @solana/spl-token installed: ${rt(e)}`,"bridge")})),ud);if(e!==this.walletGeneration)throw mt("The wallet changed while this bridge or wrap call was starting; nothing was sent. Call it again.","wallet");return t}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new e.BridgeService({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(e),environment:this.environment,...void 0!==this.config.ethereumRpcUrl&&""!==this.config.ethereumRpcUrl?{ethereumRpcUrl:this.config.ethereumRpcUrl}:{},...void 0!==this.config.solanaRpcUrl&&""!==this.config.solanaRpcUrl?{solanaRpcUrl:this.config.solanaRpcUrl}:{}})}return this._bridgeService}getBridgeableTokenService(e){return this._bridgeableTokenService??(this._bridgeableTokenService=new e.BridgeableTokenService(this.dexApiHttp)),this._bridgeableTokenService}getWrappableTokenService(e){return this._wrappableTokenService??(this._wrappableTokenService=new e.WrappableTokenService(this.dexApiHttp)),this._wrappableTokenService}getGalaConnectClient(e){if(void 0===this._galaConnectClient){const t=this.getAddress();if(void 0===this.config.dexApiBaseUrl||""===this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new e.GalaConnectClient({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:t})}return this._galaConnectClient}getWrapService(e){if(!this._wrapService){const t=this.getWallet();this._wrapService=new e.WrapService({galaConnectClient:this.getGalaConnectClient(e),wrappableTokenService:this.getWrappableTokenService(e),...void 0!==t&&{walletAddress:this.getAddress(),signer:new Do(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new vl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new al(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new uo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new _l(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new Ha(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new Ml(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new $c(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new rl(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new Bc(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new Xo(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new eo(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Rc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new ci(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new el(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Rl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new di(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}toLegacyPinnedMessage(e){return{messageId:e.id,content:e.content,userAddress:e.userAddress,pinnedBy:""!==e.pinnedBy?e.pinnedBy:e.userAddress,pinnedAt:""!==e.pinnedAt?e.pinnedAt:e.createdAt}}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}async resolveReferralAddress(e){if(void 0===e||""===e)return this.getAddress();if(e.startsWith("client|"))return e;const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn}),n=t(e);if(void 0===n)throw new Je(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new Ec(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new sl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new nl(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new pi(this.http,this.config.events)),this._eventsBatcherService}getStreamWebSocketService(){if(null===this._streamWebSocketService||void 0===this._streamWebSocketService){if(void 0===this.config.streamWebSocketUrl||""===this.config.streamWebSocketUrl)throw new Error('Stream WebSocket URL is required for real-time streaming features.\n\nConfigure SDK:\n const sdk = createLaunchpadSDK({\n wallet: yourWallet,\n streamWebSocketUrl: getEnvironmentConfig("stage").launchpadBaseUrl\n });\n\nFor MCP Server, set STREAM_WEBSOCKET_URL environment variable.\nSee SDK documentation for streaming configuration details.');this._streamWebSocketService=new yl({url:this.config.streamWebSocketUrl},this.config.debug??!1),this._streamWebSocketService.setStreamingEventService(this.getStreamingEventService())}return this._streamWebSocketService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new ol(this.config.debug??!1)),this._streamingEventService}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService(await this.coreBridge()).requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService(await this.coreBridge()).fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService(await this.coreBridge()).fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService(await this.coreBridge()).getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService(await this.coreBridge()).getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService(await this.coreBridge()).isTokenWrappable(e)}async wrapToken(e){return this.getWrapService(await this.coreBridge()).wrapToken(e)}async unwrapToken(e){return this.getWrapService(await this.coreBridge()).unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateUnwrapFee(e,t)}async login(){return this.sessionAuth.login()}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===n.message?null:this.toLegacyPinnedMessage(n.message)}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);const r=await n.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===r.message?null:this.toLegacyPinnedMessage(r.message)}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.id),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.id}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async getPoolRealtimeState(e){const[t,n,r,s]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{recentTradesError:String(r.reason)},price:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{priceError:String(s.reason)}}}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.setGlobalCallbacks(e)}async authenticateStreamWebSocket(){const e=this.getStreamWebSocketService(),t=await this.ensureValidToken();e.authenticate(t)}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamingEventService().onStreamStatusChanged(e)}onUserBanned(e){return this.getStreamingEventService().onUserBanned(e)}onUserUnbanned(e){return this.getStreamingEventService().onUserUnbanned(e)}onBanEnforcement(e){return this.getStreamingEventService().onBanEnforcement(e)}watchBanEnforcement(e,t={}){const n=(e,n,r,s)=>(void 0===t.actionType||t.actionType===e)&&((void 0===t.userAddress||t.userAddress===n)&&((void 0===t.tokenName||t.tokenName===r)&&!!(void 0===t.reason||null!==s&&s.includes(t.reason)))),r=this.onUserBanned(t=>{n("BANNED",t.userAddress,t.tokenName,t.reason)&&e({actionType:"BANNED",userAddress:t.userAddress,tokenName:t.tokenName,reason:t.reason})}),s=this.onUserUnbanned(t=>{n("UNBANNED",t.userAddress,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:t.userAddress,tokenName:t.tokenName,reason:null,timestamp:t.timestamp})}),a=this.onBanEnforcement(t=>{n("ENFORCEMENT",t.userAddress,t.tokenName,t.reason)&&e({actionType:"ENFORCEMENT",userAddress:t.userAddress,tokenName:t.tokenName,reason:t.reason,timestamp:t.timestamp})});return()=>{r(),s(),a()}}watchTokenRoomEvent(e,t,n,r){const s=r.tokenName;if(void 0===s||""===s)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);const a=s.toLowerCase(),o=`${e}:${a}`,i=n;let c=this._tokenRoomListeners.get(o);const l=void 0===c;void 0===c&&(c=new Set,this._tokenRoomListeners.set(o,c)),c.add(i),this._tokenRoomRefCounts.set(a,(this._tokenRoomRefCounts.get(a)??0)+1);const d=this.getStreamWebSocketService(),u=(async()=>{d.isConnected()||await this.connectStreamWebSocket(),await d.subscribeToStream(a),l&&this._tokenRoomUnsubscribers.set(o,t.call(d,a,e=>{for(const t of c)t(e)}))})();let h=!1;return()=>{if(h)return;h=!0,c.delete(i);const e=(this._tokenRoomRefCounts.get(a)??1)-1,t=e<=0;t?this._tokenRoomRefCounts.delete(a):this._tokenRoomRefCounts.set(a,e),u.then(()=>{if(0===c.size){this._tokenRoomListeners.delete(o);const e=this._tokenRoomUnsubscribers.get(o);this._tokenRoomUnsubscribers.delete(o),e?.()}t&&!this._tokenRoomRefCounts.has(a)&&d.unsubscribeFromStream(a)})}}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{void 0!==t.authorAddress&&t.authorAddress!==n.userAddress||void 0!==t.minLength&&n.content.length<t.minLength||e(n)},t)}watchHolderCountUpdated(e,t={}){return this.watchTokenRoomEvent("watchHolderCountUpdated",(e,t)=>this.getStreamWebSocketService().subscribeHolderCountUpdated(e,t),n=>{void 0!==t.minThreshold&&Math.abs(n.change??0)<t.minThreshold||e(n)},t)}watchModeratorAdded(e,t={}){return this.watchTokenRoomEvent("watchModeratorAdded",(e,t)=>this.getStreamWebSocketService().subscribeModeratorAdded(e,t),e,t)}watchPoolMetadataUpdated(e,t={}){return this.watchTokenRoomEvent("watchPoolMetadataUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolMetadataUpdated(e,t),e,t)}watchTradeExecuted(e,t={}){return this.watchTokenRoomEvent("watchTradeExecuted",(e,t)=>this.getStreamWebSocketService().subscribeTradeExecuted(e,t),n=>{void 0!==t.tradeType&&t.tradeType!==n.tradeType||void 0!==t.userAddress&&t.userAddress!==n.userAddress||void 0!==t.minAmount&&Number(n.inputAmount)<t.minAmount||e(n)},t)}watchTokenBanned(e,t={}){return this.watchTokenRoomEvent("watchTokenBanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenBanned(e,t),e,t)}watchModeratorChanged(e,t={}){const n=(e,n)=>(void 0===t.eventType||t.eventType===e)&&(void 0===t.moderatorAddress||t.moderatorAddress===n),r=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),s=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),a=this.watchTokenRoomEvent("watchModeratorRoleUpdated",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRoleUpdated(e,t),t=>{n("ROLE_UPDATED",t.userAddress)&&e({actionType:"ROLE_UPDATED",tokenName:t.tokenName,moderatorAddress:t.userAddress,oldRole:t.oldRole,newRole:t.newRole})},t);return()=>{r(),s(),a()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,r=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),s=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),a=this.watchTokenRoomEvent("watchPoolBadgeAssigned",(e,t)=>this.getStreamWebSocketService().subscribePoolBadgeAssigned(e,t),t=>{n("BADGE_ASSIGNED")&&e({updateType:"BADGE_ASSIGNED",tokenName:t.tokenName,details:t})},t);return()=>{r(),s(),a()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,r=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),s=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{r(),s()}}onContentFlagged(e){return this.getStreamingEventService().onContentFlagged(e)}onFlagResolved(e){return this.getStreamingEventService().onFlagResolved(e)}onStreamChatMessage(e){return this.getStreamingEventService().onStreamChatMessage(e)}onStreamChatUpdated(e){return this.getStreamingEventService().onStreamChatUpdated(e)}onStreamChatDeleted(e){return this.getStreamingEventService().onStreamChatDeleted(e)}onStreamChatPinned(e){return this.getStreamingEventService().onStreamChatPinned(e)}onStreamChatUnpinned(e){return this.getStreamingEventService().onStreamChatUnpinned(e)}onChatStatusChanged(e){return this.getStreamingEventService().onChatStatusChanged(e)}onViewerCountChanged(e){return this.getStreamingEventService().onViewerCountChanged(e)}onRecordingStatusChanged(e){return this.getStreamingEventService().onRecordingStatusChanged(e)}onSimulcastStatusChanged(e){return this.getStreamingEventService().onSimulcastStatusChanged(e)}onDownloadReady(e){return this.getStreamingEventService().onDownloadReady(e)}onRecordingsCountUpdated(e){return this.getStreamingEventService().onRecordingsCountUpdated(e)}onUserTyping(e){return this.getStreamingEventService().onUserTyping(e)}onStreamReaction(e){return this.getStreamingEventService().onStreamReaction(e)}onContentReactionAdded(e){return this.getStreamingEventService().onContentReactionAdded(e)}onContentReactionRemoved(e){return this.getStreamingEventService().onContentReactionRemoved(e)}onStreamCountdownUpdated(e){return this.getStreamingEventService().onStreamCountdownUpdated(e)}onStreamLanguageUpdated(e){return this.getStreamingEventService().onStreamLanguageUpdated(e)}onStreamControlStatusChanged(e){return this.getStreamingEventService().onStreamControlStatusChanged(e)}onConnection(e){return this.getStreamingEventService().onConnection(e)}onAuthenticated(e){return this.getStreamingEventService().onAuthenticated(e)}onTokenSubscribed(e){return this.getStreamingEventService().onTokenSubscribed(e)}onTokenUnsubscribed(e){return this.getStreamingEventService().onTokenUnsubscribed(e)}onRoomSubscribed(e){return this.getStreamingEventService().onRoomSubscribed(e)}onRoomLeft(e){return this.getStreamingEventService().onRoomLeft(e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEngagementStatsUpdated(e)}async estimateBridgeFee(e){return this.getBridgeService(await this.coreBridge()).estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService(await this.coreBridge()).bridgeOut(e)}async bridgeIn(e){return this.getBridgeService(await this.coreBridge()).bridgeIn(e)}async getBridgeStatus(e){return this.getBridgeService(await this.coreBridge()).getBridgeStatus(e)}async getSupportedBridgeTokens(){const e=this.getBridgeService(await this.coreBridge()),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Vo}),r=t(e.tokenId),{collection:s,category:a,type:o,additionalKey:i}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:a,additionalKey:i,type:o},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Lt(e.tokenName),r=id[t];if(void 0!==r)return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:"Unit",additionalKey:"none",type:"none"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,pageSize:1,...void 0!==n?{address:n}:{}})).tokens[0];if(void 0===t)return null;const r=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:r.collection,category:r.category,tokenId:Uo(r)}}throw ut("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:s,calculateAmountMode:a,currentSupply:o}=e;let i=t;void 0===a&&void 0===o||(i={tokenName:t,...void 0!==a&&{calculateAmountMode:a},...void 0!==o&&{currentSupply:o}});const c=await this.calculateBuyAmountForGraduation(i),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw pt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>ad(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw pt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>ad(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.launchToken(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{sd(n,t);const r=n.data??{};if(!function(e){if(kn(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)}(r))throw new nd(`Invalid launch data received for transaction ${t}`);const s={transactionId:t,vaultAddress:r.vaultAddress??"",tokenStringKey:r.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:r.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(s.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(s.preBuyQuantity=e.preBuyQuantity),""!==s.vaultAddress&&this.tokenResolverService.set(e.tokenName,s.vaultAddress),s})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(u,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},a=await this.dexApiHttp.get(h,s,{"x-wallet-address":t});if(!Array.isArray(a))throw new Ze("Unexpected API response: expected array, got "+typeof a);return{referrals:a,page:n,limit:r,hasMore:a.length===r}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:a=1,startPage:o=1}=t,i=[];let c=o;const l=o+n-1;let d=!0,u=0;if(a<=1)for(;d&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(i.push(...t.items),u=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${a}`);d&&c<=l;){const t=[];for(let e=0;e<a&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,a=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===a||404===a)return r&&r.debug(`Auto-pagination: page ${t} returned ${a} (end of pagination)`,{statusCode:a}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),o=await Promise.all(n);for(const e of o){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(i.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${i.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${i.length}, total count: ${u}`),{items:i,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=await this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(g,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Ze(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.updateProfile(r)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.uploadProfileImage(r)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn}),n=t(e?.address)??this.getAddress(),r={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(r.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn}),n={type:"created",address:t(e?.address)??this.getAddress(),pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(n.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(n.search=e.search),void 0!==e?.status&&(n.status=e.status),this.launchpadService.fetchTokenList(n)}async getManagedTokens(e){return this.launchpadService.getManagedTokens(e??{})}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferGala(r)}return this.assertTokenWriter(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferToken(r)}return this.assertTokenWriter(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async convertTokenNameToTokenClassKey(e){return this.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(void 0!==e.lockAuthority&&""!==e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Qn});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.assertTokenWriter(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.assertTokenWriter(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let r=0;r<10;r+=1){const r=await this.launchpadAPI.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),s=r.items.find(t=>t.vaultAddress===e);if(void 0!==s)return s.tokenName;if(!r.pageInfo.hasNextPage||void 0===r.pageInfo.nextCursor)return;n=r.pageInfo.nextCursor}}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{pn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw mt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw mt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw mt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw mt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw mt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw mt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw mt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=ln("string"==typeof e||"number"==typeof e?e:String(e),hd.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${hd.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),hd.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=ln("string"==typeof e||"number"==typeof e?e:String(e),hd.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${String(e)}, using default: ${hd.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),hd.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if(n.status!==exports.SDKTransactionStatus.COMPLETED)throw new rd(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof nd)throw t;throw new nd(`Failed to transform WebSocket response for transaction ${e}`,nt(t)?t:new Error(rt(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof rd||t instanceof nd)throw t;throw new nd(`WebSocket confirmation failed for transaction ${e}`,nt(t)?t:new Error(rt(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Zd});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,a=new Map;let o=!0,i=null;let c=0;const l=async()=>{if(o){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{a.has(t.tokenName)||((e=>{if(a.set(e,!0),a.size>1e3){const e=a.keys().next().value;void 0!==e&&a.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=rt(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(o){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);i=setTimeout(()=>{l()},t)}}};return l(),()=>{o=!1,i&&clearTimeout(i),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw mt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const s=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n=(e,t="")=>{const n=r[e];return"string"==typeof n&&""!==n?n:t},s={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===r.isFinalized};this.matchesCreatorFilter(s,t?.creatorFilter)&&e(s)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${rt(e)}`)}};let a=this.websocketService.getSocket();if(a)a.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${rt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const o=()=>{if(a=this.websocketService.getSocket(),!a&&e<hd.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),hd.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=hd.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${hd.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*hd.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}a&&(a.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};o()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.disconnect(),this._streamWebSocketService=void 0),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new Ft({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),xl.cleanupAll(e),t.debug("Global cleanup completed")}}function gd(n){const r=t.createWallet(n);return{...r,wallet:new e.Wallet(r.privateKey)}}function md(){const e=globalThis;return e.process?.env??{}}hd.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,hd.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,hd.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=xt.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,hd.DEFAULT_CALCULATE_AMOUNT_MODE=Qe.LOCAL,hd.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,hd.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;function pd(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function fd(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Ed(e){if(null==e||"object"!=typeof e)return 0;const t=e;if("number"==typeof t.status)return t.status;if("number"==typeof t.statusCode)return t.statusCode;if("number"==typeof t.code)return t.code;const n=t.response;return n&&"number"==typeof n.status?n.status:0}function Ad(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function vd(e){if(void 0!==e&&e.length>0&&!/^[a-z0-9]+$/.test(e.toLowerCase()))throw new Error(`Invalid asset extension format: "${e}". Must contain only alphanumeric characters.`)}function Sd(e,t){return`${e.replace(/\/$/,"")}${t}`}const Td=new Map;const yd={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},kd=Xs({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),bd=Xs({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});Ht.MIN_LENGTH,Ht.MAX_LENGTH,Ht.PATTERN;Nn({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function Nd(e){return"global"===e||"token"===e}function wd(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.tokenName&&"string"==typeof t.createdAt}function Cd(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}const _d=Nn({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function Id(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}var Dd,Rd,Od,xd,Md,Ld;exports.AnalysisStatus=void 0,(Dd=exports.AnalysisStatus||(exports.AnalysisStatus={})).PENDING="PENDING",Dd.PROCESSING="PROCESSING",Dd.COMPLETED="COMPLETED",Dd.FAILED="FAILED",exports.AnalysisType=void 0,(Rd=exports.AnalysisType||(exports.AnalysisType={})).TEXT="TEXT",Rd.IMAGE="IMAGE",Rd.VIDEO="VIDEO",exports.AIRecommendation=void 0,(Od=exports.AIRecommendation||(exports.AIRecommendation={})).NO_ACTION="NO_ACTION",Od.REVIEW_REQUIRED="REVIEW_REQUIRED",Od.DELETE_CONTENT="DELETE_CONTENT",Od.BAN_USER="BAN_USER",Od.DELETE_AND_BAN="DELETE_AND_BAN",exports.AnalysisCategory=void 0,(xd=exports.AnalysisCategory||(exports.AnalysisCategory={})).VIOLENCE="VIOLENCE",xd.HATE_SPEECH="HATE_SPEECH",xd.SEXUAL_CONTENT="SEXUAL_CONTENT",xd.HARASSMENT="HARASSMENT",xd.SPAM="SPAM",xd.SCAM="SCAM",xd.SELF_HARM="SELF_HARM",xd.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",xd.MISINFORMATION="MISINFORMATION",xd.COPYRIGHT="COPYRIGHT",xd.SAFE="SAFE",exports.AnalysisTier=void 0,(Md=exports.AnalysisTier||(exports.AnalysisTier={})).QUICK="QUICK",Md.DETAILED="DETAILED",exports.AIModerationMode=void 0,(Ld=exports.AIModerationMode||(exports.AIModerationMode={})).DISABLED="DISABLED",Ld.ADVISORY="ADVISORY";const Ud={[exports.AnalysisStatus.PENDING]:"Pending",[exports.AnalysisStatus.PROCESSING]:"Processing",[exports.AnalysisStatus.COMPLETED]:"Completed",[exports.AnalysisStatus.FAILED]:"Failed"},Fd={[exports.AIRecommendation.NO_ACTION]:"No Action Needed",[exports.AIRecommendation.REVIEW_REQUIRED]:"Human Review Required",[exports.AIRecommendation.DELETE_CONTENT]:"Delete Content",[exports.AIRecommendation.BAN_USER]:"Ban User",[exports.AIRecommendation.DELETE_AND_BAN]:"Delete & Ban"},Pd={[exports.AnalysisCategory.VIOLENCE]:"Violence",[exports.AnalysisCategory.HATE_SPEECH]:"Hate Speech",[exports.AnalysisCategory.SEXUAL_CONTENT]:"Sexual Content",[exports.AnalysisCategory.HARASSMENT]:"Harassment",[exports.AnalysisCategory.SPAM]:"Spam",[exports.AnalysisCategory.SCAM]:"Scam",[exports.AnalysisCategory.SELF_HARM]:"Self Harm",[exports.AnalysisCategory.ILLEGAL_ACTIVITY]:"Illegal Activity",[exports.AnalysisCategory.MISINFORMATION]:"Misinformation",[exports.AnalysisCategory.COPYRIGHT]:"Copyright",[exports.AnalysisCategory.SAFE]:"Safe"},Bd={[exports.AnalysisTier.QUICK]:"Quick Scan",[exports.AnalysisTier.DETAILED]:"Detailed Scan"},$d={[exports.AnalysisType.TEXT]:"Text",[exports.AnalysisType.IMAGE]:"Image",[exports.AnalysisType.VIDEO]:"Video"},Gd={[exports.AIModerationMode.DISABLED]:"Disabled",[exports.AIModerationMode.ADVISORY]:"Advisory"},Kd=Nn(exports.AnalysisStatus),Hd=Nn(exports.AnalysisType),Wd=Nn(exports.AIRecommendation),Vd=Nn(exports.AnalysisCategory),zd=Nn(exports.AnalysisTier),jd=Nn(exports.AIModerationMode),qd=In([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:Kd},{field:"analysisType",type:"string",validator:Hd},{field:"provider",type:"string"}]),Xd=In([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:jd},{field:"provider",type:"string"}]);function Qd(e){return null!==e.analysisTier}function Yd(e){if(!Tn(e))throw ut("content");if(0===e.trim().length)throw bt("content","Content");if(e.length>Yt.COMMENTS_V1.MAX_LENGTH)throw kt("content",Yt.COMMENTS_V1.MAX_LENGTH,e.length)}function Jd(e){if(!Tn(e))throw ut("content");if(0===e.trim().length)throw new Je("content cannot be empty","content",Ye.REQUIRED);if(e.length>Yt.CHAT_MESSAGES_V1.MAX_LENGTH)throw new Je(`content must be at most ${Yt.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",Ye.TOO_LONG)}var Zd=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=ln(e.reverseBondingCurveMinFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=r}if(void 0!==e.reverseBondingCurveMaxFeePortion){const r=ln(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.ACTIVE_USER_TYPE=to,exports.AI_MODE_LABELS=Gd,exports.AI_RECOMMENDATION_LABELS=Fd,exports.ALL_PERMISSIONS=ja,exports.ANALYSIS_CATEGORY_LABELS=Pd,exports.ANALYSIS_STATUS_LABELS=Ud,exports.ANALYSIS_TIER_LABELS=Bd,exports.ANALYSIS_TYPE_LABELS=$d,exports.API_KEY_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.API_KEY_ROLE=Wa,exports.API_KEY_ROLES=Va,exports.API_KEY_ROLE_HIERARCHY=Za,exports.AddressFormatter=Gn,exports.AgentConfig=class{constructor(){this.utilityInstance=!0,this.utilityInstance}static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=this.buildSdkConfig(e,t,n),s=new hd(r),a={sdk:s,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(s,n);return{...a,validation:e}}return a}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new hd(n);return Promise.resolve({sdk:r,config:n})}static async validateSetup(e,t){const n=[],r=[],s={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(s.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=ln(t.quantity,0);s.hasBalance=e>0,s.canTrade=e>=.1,s.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${rt(e)}`)}try{const t=await e.fetchPools({type:"recent",pageSize:1});null!==t.items&&void 0!==t.items&&0!==t.items.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${rt(e)}`)}return{ready:0===n.length&&s.connectionHealthy,sdk:e,wallet:t??gd(),issues:n,warnings:r,capabilities:s}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"prod":Object.assign(n,{debug:!1,timeout:3e4});break;case"stage":Object.assign(n,{debug:!0,timeout:45e3})}switch(t){case"trading":n.timeout=1.5*(n.timeout??3e4);break;case"creation":n.timeout=2*(n.timeout??3e4);break;case"monitoring":n.timeout=.5*(n.timeout??3e4);break;case"general":break;default:throw new Error(`Unexpected useCase: ${String(t)}`)}return n}static async multiWalletSetup(e,t="stage"){const n={};for(const[r,s]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:s,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){return"stage"===(md().LAUNCHPAD_ENV??md().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=md().PRIVATE_KEY;return void 0!==e&&""!==e?gd(e):gd()}return"generate"===e?gd():gd(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??md().WALLET_ADDRESS;return{wallet:n?.wallet,baseUrl:e.baseUrl??this.getDefaultBaseUrl(t),timeout:e.timeout??this.getDefaultTimeout(t),debug:e.debug??"prod"!==t,...this.getEnvironmentDefaults(t),...e.config??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{},env:t}}static getDefaultBaseUrl(e){return Ra(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=Ra(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}},exports.AuthError=Na,exports.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},exports.BrowserWalletSigner=Oo,exports.BundleSubmission=Ul,exports.BundlerTransport=Fl,exports.BurnError=Wi,exports.CALCULATION_MODES=Qe,exports.CONTENT_REACTION_TYPES=li,exports.CONTENT_TYPE_LABELS=Zo,exports.ChartService=class extends Un{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw ut("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw ut("tokenName","Token name");if(null==n)throw ut("from","Start timestamp");if(null==r)throw ut("to","End timestamp");if(null==s)throw ut("resolution","Data resolution interval");ma(t);const a=173e6;if("number"!=typeof n||n<a)throw new Je("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<a)throw new Je("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new Je("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:o}=await Promise.resolve().then(function(){return Js}),i=o({tokenName:t,from:n,to:r,resolution:s}),c=await Rt(()=>this.http.get(d.CHART,i),{errorContext:"Failed to fetch chart data"}),l=Ct(c);if(null==l||"object"!=typeof l)throw gt("Invalid API response: missing or invalid data",c.status??500);const u=l,h=u.data;if(!Array.isArray(h))throw gt("Invalid API response: expected data array",c.status??500);const g={dataPoints:h.map(e=>{if("object"!=typeof e||null===e)throw gt("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,s=t.closePrice??t.value,a=t.lowPrice??t.value,o=t.highPrice??t.value,i=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(s),lowPrice:String(a),highPrice:String(o),volume:String(i)}})};return"boolean"==typeof u.isPreviousData&&(g.isPreviousData=u.isPreviousData),g}},exports.ConfigurationError=et,exports.DEFAULT_EVENTS_CONFIG=mi,exports.DEFAULT_PRICING_CONCURRENCY=5,exports.DEFAULT_REVERSE_BONDING_CURVE_CONFIGURATION=Xl,exports.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,exports.ENVIRONMENT_URLS=Da,exports.ERROR_CODES=Ye,exports.EVENT_TYPES={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"},exports.EXTENDED_STREAM_ROLE=pl,exports.EventBufferWithAutoCleanup=class{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}},exports.EventsBatcherService=pi,exports.FLAG_ACTION_LABELS=Jo,exports.FLAG_DETAILS_MAX_LENGTH=500,exports.FLAG_REASON_LABELS=Qo,exports.FLAG_STATUS_LABELS=Yo,exports.FileValidationError=ca,exports.GALA_DECIMALS=8,exports.GalaWalletSigner=Ro,exports.GlobalAndRoomCallbackDispatcher=class{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${rt(e)}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${rt(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}},exports.HOLDER_DELTA_TYPES=yd,exports.IMAGE_EXTENSIONS=br,exports.INVITE_STATUS=yc,exports.INVITE_STATUSES=kc,exports.JWT_CONSTANTS=ya,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LaunchpadSDK=hd,exports.LaunchpadSDKError=Ll,exports.LaunchpadWrites=Ql,exports.ListenerCleanupManager=class{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const n=this.listeners[t];if(void 0===n)continue;const{id:r,cleanup:s}=n;try{await s()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}},exports.LockError=Ni,exports.MAX_BURN_BATCH_SIZE=50,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.MAX_LOCK_BATCH_SIZE=100,exports.MAX_UNLOCK_BATCH_SIZE=100,exports.MESSAGES_CONSTRAINTS=sc,exports.MESSAGE_TYPES=rc,exports.MODERATOR_ROLE=Ac,exports.MODERATOR_ROLES=vc,exports.NFT_FEES=Oc,exports.NetworkError=Ze,exports.NftCollectionService=Pc,exports.OEmbedService=$c,exports.OVERSEER_INVITE_STATUS=Kc,exports.OVERSEER_STATUS=Hc,exports.PAGINATION_DEFAULTS=Ua,exports.PERMISSION=za,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PayloadWalkerWithDeduplication=class{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,s=0)=>{if(s>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const a=this.extractor(e);if(null!==a){const e=this.dedupeKeyFn(a);this.seen.has(e)||(this.seen.add(e),t.push(a))}for(const t of Object.values(e))r(t,s+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}},exports.PendingSubscriptionTracker=class{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}},exports.PlatformStatsService=rl,exports.PrivateKeySigner=Do,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.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},exports.RECORDING_STATUS=cl,exports.ROLE_SOURCE=ml,exports.RoomSubscriptionManager=class{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}},exports.SDK_VERSION=La,exports.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},exports.SIMULCAST_PLATFORM=ll,exports.SIMULCAST_STATUS={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},exports.STREAM_EVENTS=Tl,exports.STREAM_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.STREAM_ROLE=gl,exports.STREAM_STATUS=il,exports.SelectiveEventForwarding=class{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}},exports.StreamWebSocketService=yl,exports.StreamingEventService=ol,exports.TIME_CONSTANTS={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6},exports.TRADES_QUERY_CONSTRAINTS=cc,exports.TRADING_TYPES=Xe,exports.TokenRestrictedError=class extends Je{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}},exports.TradingQuotesService=Dl,exports.TransactionError=tt,exports.TransactionFailedError=rd,exports.TypingIndicatorDebouncer=class{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const s=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,s)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}},exports.ValidationError=Je,exports.WebSocketError=nd,exports.WebSocketTimeoutError=class extends nd{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.WeeklyChallengeService=Ml,exports.addCursorToPagination=function(e,t){return void 0===t?e:{...e,cursor:t}},exports.addressFormatSchema=rr,exports.aggregateMultipleApiSources=async function(e,t,n){const r=n?.logger,s=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const a=e.map(async(t,n)=>{try{const a=await s(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),a}catch(s){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${rt(s)}`)}}),o=(await Promise.allSettled(a)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${o.filter(e=>void 0!==e).length} successful results`),t(o)},exports.amountMethodSchema=$r,exports.amountTypeSchema=Br,exports.assertValidWalletAddress=qn,exports.bidirectionalTokenMatch=function(e,t,n,r){return e===n&&t===r||e===r&&t===n},exports.browserFileSchema=wr,exports.bufferFileSchema=Cr,exports.buildConcurrentBatchRequests=async function(e,t,n,r){const s=r?.logger,a=[];a.length=e.length;let o=0,i=0;s?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return a[c]=r,o++,s?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw i++,s?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${rt(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&s?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){s?.error(`Batch processing error at index ${r}: ${rt(e)}`)}}return s?.debug(`Batch complete: ${o} succeeded, ${i} failed`),a},exports.buildQueryParametersWithValidation=function(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(yn(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>fd(e)).join(","):fd(r);const s=encodeURIComponent(n),a=encodeURIComponent(e);t.push(`${s}=${a}`)}return t.length>0?`?${t.join("&")}`:""},exports.buildSafePaginationOptions=pd,exports.buyTokensDataSchema=es,exports.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new i(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const s=n-t;return new i(t).plus(new i(s).multipliedBy(r))},exports.calculatePreMintDataSchema=is,exports.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Zs(e).multipliedBy(t).integerValue(i.ROUND_DOWN)},exports.calculateTotalPages=function(e,t){if("number"!=typeof e||!Number.isInteger(e))throw vt("total","a non-negative integer",e);if(e<0)throw ft("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw vt("limit","a non-negative integer",t);if(t<0)throw ft("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)},exports.capitalize=lt,exports.caseInsensitiveTokenComparison=function(e,t){return e.toLowerCase()===t.toLowerCase()},exports.checkPoolOptionsSchema=Pr,exports.commonValidators=Dn,exports.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},exports.conditionalTrimAndValidateString=hc,exports.createLaunchpadSDK=function(n){kn(n)&&(n={});const{wallet:r,env:s,config:a={},...o}=n,i={...{...o,...a}};delete i.wallet,delete i.env,delete i.config;const c=!kn(i.signer)||!kn(i.walletProvider);let l;if(kn(r))l=c?void 0:new e.Wallet(t.createWallet().privateKey);else if("string"==typeof r)l=new e.Wallet(t.createWallet(r).privateKey);else{if(!(r instanceof e.Wallet))throw mt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");l=r}const d={...void 0!==l?{wallet:l}:{},...void 0!==s?{env:s}:{},debug:!1,timeout:3e4,...i};return new hd(d)},exports.createLimitSchema=hr,exports.createOptionsValidator=function(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:s,type:a,validator:o}=t,i=r[e];if(s){if(kn(i)){n.push(`${e} is required`);continue}if("string"===a){if("string"!=typeof i){n.push(`${e} must be a string`);continue}if(0===i.trim().length){n.push(`${e} is required`);continue}}}if(!kn(i))if(void 0===a||typeof i===a){if(void 0!==o){const e=o(i,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${a}`)}return n}},exports.createPaginatedResultSchema=function(e){return n.z.object({data:n.z.array(e),...Xr})},exports.createPaginationQuery=function(e,t=Ua.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw vt("offset","a non-negative integer",e);return En(t,"limit"),{offset:e,limit:t}},exports.createTradeDataSchema=Zr,exports.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Zs(e),r=new i(10).pow(t);return n.multipliedBy(r).integerValue(i.ROUND_UP).dividedBy(r)},exports.deduplicateByKey=function(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const s=t(e);r.set(s,n)}),n){const n=new Set;return e.filter(e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)})}return e.filter((e,n)=>{const s=t(e);return r.get(s)===n})},exports.errorMessageCaseNormalization=function(e){return e.toLowerCase()},exports.ethereumAddressSchema=sr,exports.extractFieldWithFallbackPath=function(e,t,n=null){if(null==e||"object"!=typeof e)return n;const r=e;for(const e of t){const t=e.split(".");let n=r;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(Tn(n))return n;if(null!=n&&""!==n)return n}return n},exports.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=dn(fd(n.page??n.Page??n.current??1),t.page),s=dn(fd(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),a=n.data,o=a?.meta;let i;i="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof o?.totalItems?o.totalItems:"number"==typeof a?.count?a.count:dn(fd(n.totalCount??n.total??-1),t.totalCount);let c=t.hasMore;return"boolean"==typeof n.hasMore?c=n.hasMore:"boolean"==typeof n.has_more?c=n.has_more:"boolean"==typeof o?.hasMore&&(c=o.hasMore),{page:r,pageSize:s,totalCount:i,hasMore:c}},exports.feeCeilingFromQuotedFee=jl,exports.fetchGalaBalanceOptionsSchema=hs,exports.fetchPoolDetailsDataSchema=cs,exports.fetchTokenBalanceOptionsSchema=ps,exports.fileSizeSchema=fr,exports.fileUploadSchema=Nr,exports.filenameSchema=Er,exports.flexibleAddressSchema=ar,exports.flexibleFileSchema=_r,exports.formatGalaForDTO=gn,exports.formatLaunchpadTokenForDTO=mn,exports.fromBackendAddressFormat=Vn,exports.fullNameSchema=nr,exports.generateBuySellStringsInstructions=Mo,exports.generateCreateSaleStringsInstructions=Lo,exports.getAmountOptionsSchema=os,exports.getEnvironmentConfig=Ra,exports.getIntervalRegistryStats=function(){const e=Array.from(Td.entries()).map(([e,t])=>({id:e,...t}));return{size:Td.size,entries:e}},exports.getLaunchTokenDataValidationErrors=Hs,exports.getNftFeeAsNumber=function(e){return parseFloat(Oc[e])},exports.getRecordingAnimatedUrl=function(e,t,n,r="gif"){const s=Ad(e),a=t.trim();if(0===a.length)throw new Error("Recording ID cannot be empty");return vd(r),Sd(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(a)}/assets/animated.${r.toLowerCase()}`)},exports.getRecordingAssetUrl=function(e,t,n,r,s){const a=Ad(e),o=t.trim(),i=n.trim().toLowerCase();if(0===o.length)throw new Error("Recording ID cannot be empty");if(0===i.length)throw new Error("Asset type cannot be empty");vd(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return Sd(r,`/v1/tokens/${encodeURIComponent(a)}/recordings/${encodeURIComponent(o)}/assets/${encodeURIComponent(i)}${c}`)},exports.getRecordingPosterUrl=function(e,t,n){const r=Ad(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Sd(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)},exports.getRecordingStoryboardUrl=function(e,t,n,r="vtt"){const s=Ad(e),a=t.trim();if(0===a.length)throw new Error("Recording ID cannot be empty");return vd(r),Sd(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(a)}/assets/storyboard.${r.toLowerCase()}`)},exports.getRecordingStreamUrl=function(e,t,n){const r=Ad(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Sd(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)},exports.getRecordingThumbnailUrl=function(e,t,n,r="jpg"){const s=Ad(e),a=t.trim();if(0===a.length)throw new Error("Recording ID cannot be empty");return vd(r),Sd(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(a)}/assets/thumbnail.${r.toLowerCase()}`)},exports.getTieredModerationSavings=function(e,t){if(!Qd(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))},exports.getTokenAnimatedUrl=function(e,t,n="gif"){const r=Ad(e);return vd(n),Sd(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)},exports.getTokenAssetUrl=function(e,t,n,r){const s=Ad(e),a=t.trim().toLowerCase();if(0===a.length)throw new Error("Asset type cannot be empty");vd(r);const o=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return Sd(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(a)}${o}`)},exports.getTokenImageUrl=function(e,t){const n=Ad(e);return Sd(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)},exports.getTokenLiveStreamUrl=function(e,t){const n=Ad(e);return Sd(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)},exports.getTokenPosterUrl=function(e,t){const n=Ad(e);return Sd(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)},exports.getTokenStoryboardUrl=function(e,t,n="vtt"){const r=Ad(e);return vd(n),Sd(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)},exports.getTokenThumbnailUrl=function(e,t,n="jpg"){const r=Ad(e);return vd(n),Sd(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)},exports.getTradeOptionsSchema=ns,exports.graduateTokenOptionsSchema=Kr,exports.graphDataOptionsSchema=Gr,exports.groupByKey=function(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n},exports.hasMorePages=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw vt("offset","a non-negative integer",e);if(e<0)throw ft("offset",0,1/0,e);return e+t<n},exports.hexStringExtractionAndNormalization=function(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(void 0!==e&&gc(e))return mc(e)}return null}return gc(e)?mc(e):null},exports.imageExtensionSchema=Ir,exports.imageFilenameSchema=Dr,exports.imageMimeTypeSchema=Ar,exports.imageUploadOptionsSchema=Ur,exports.isAIModerationData=qd,exports.isAIModerationMode=jd,exports.isAIModerationSettings=Xd,exports.isAIRecommendation=Wd,exports.isActiveUserType=no,exports.isAnalysisCategory=Vd,exports.isAnalysisStatus=Kd,exports.isAnalysisTier=zd,exports.isAnalysisType=Hd,exports.isBanData=ro,exports.isBanEnforcementEvent=oo,exports.isBurnTokenEntry=Gi,exports.isBurnTokensData=Ki,exports.isChatDisabledReason=Nd,exports.isChatMessageItem=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt&&"number"==typeof t.flagCount&&"object"==typeof t.reactions},exports.isChatStatusResponse=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||Nd(t.reason))},exports.isClaimableInvite=function(e){if(e.status!==Kc.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(Gt(e.expiresAt)<=new Date)return!1}return!0},exports.isContentType=ei,exports.isEmptyValue=yn,exports.isExtendedStreamRole=fl,exports.isFlagAction=ri,exports.isFlagData=si,exports.isFlagReason=ti,exports.isFlagStatus=ni,exports.isHolderDelta=kd,exports.isHolderDeltaType=function(e){return"string"==typeof e&&(e===yd.NEW_HOLDER||e===yd.EXITED_HOLDER||e===yd.BALANCE_CHANGED)},exports.isLockTokenEntry=vi,exports.isLockTokensData=Ti,exports.isMessage=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.type&&(t.type===rc.CHAT_MESSAGE||t.type===rc.COMMENT)&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt},exports.isMessageType=function(e){return e===rc.CHAT_MESSAGE||e===rc.COMMENT},exports.isModeratedToken=_c,exports.isModerationTiered=Qd,exports.isModeratorInvite=Cc,exports.isNonEmptyString=Tn,exports.isOverseerInviteStatus=Wc,exports.isOverseerStatus=Vc,exports.isPinnedMessage=Cd,exports.isPublicInviteInfo=Ic,exports.isReactionErrorCode=_d,exports.isRecordingStatus=ul,exports.isSimulcastPlatform=hl,exports.isStreamChatDeletedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt},exports.isStreamChatErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamChatMessage=wd,exports.isStreamChatMessageEvent=function(e){return wd(e)},exports.isStreamChatPinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Cd(t.pinnedMessage)},exports.isStreamChatUnpinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},exports.isStreamReactionErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamReactionEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime},exports.isStreamStatus=dl,exports.isStreamStatusEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&dl(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},exports.isStreamingEvent=function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&["stream_status","user_banned","user_unbanned","ban_enforcement","content_flagged","flag_resolved","stream_chat_message","stream_chat_updated","stream_chat_deleted","stream_chat_pinned","stream_chat_unpinned","chat_status_changed","viewer_count","recording_status","simulcast_status","download_ready","recordings_count_updated","user_typing","stream_reaction","content_reaction_added","content_reaction_removed","stream_countdown_updated","stream_language_updated","stream_control_status_changed","connection","authenticated","token_subscribed","token_unsubscribed","room_subscribed","room_left"].includes(t.type)},exports.isTokenAccessResult=function(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},exports.isTokenBanData=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)},exports.isTypingIndicatorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(Id)},exports.isTypingUser=Id,exports.isUnlockTokenEntry=Si,exports.isUnlockTokensData=yi,exports.isUserBannedEvent=so,exports.isUserHoldingData=bd,exports.isUserUnbannedEvent=ao,exports.isValidAddress=jn,exports.isValidApiKeyRole=qa,exports.isValidBanDuration=co,exports.isValidBanReason=io,exports.isValidChatContent=function(e){return!!Tn(e)&&(e.length>=Yt.CHAT_MESSAGE.MIN_LENGTH&&e.length<=Yt.CHAT_MESSAGE.MAX_LENGTH)},exports.isValidChatTokenName=function(e){return!!Tn(e)&&Ht.PATTERN.test(e)},exports.isValidInviteCode=wc,exports.isValidInviteStatus=Nc,exports.isValidLaunchTokenData=function(e){return ws(e).success},exports.isValidModeratorRole=bc,exports.isValidTokenBanReason=kl,exports.isValidTokenName=function(e,t=Ht){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},exports.isViewerCountEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},exports.isoDateStringSchema=vr,exports.launchTokenDataSchema=Lr,exports.mergeSafePaginationOptions=function(e,t){return pd({...e,...t})},exports.nonNegativeDecimalStringSchema=cr,exports.normalizeAddressInput=zn,exports.normalizeDataWithMapping=function(e,t){return e.map(e=>{const n={};for(const[r,s]of Object.entries(t)){const t=s(e);void 0!==t&&(n[r]=t)}return n})},exports.normalizeErrorMessage=function(e,t){return e.toLowerCase().includes(t.toLowerCase())},exports.normalizeLimit=Fa,exports.normalizeTokenKey=function(e){return e.trim().toUpperCase()},exports.normalizeTokenName=Mt,exports.normalizeTokenSymbol=Lt,exports.optionalUrlSchema=dr,exports.pageNumberSchema=ur,exports.paginationResultMetaSchema=Qr,exports.parseHttpErrorResponse=function(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let s,a=t.errorMessage;"string"==typeof n.message?a=n.message:"string"==typeof n.error?a=n.error:e instanceof Error?a=e.message:"string"==typeof e&&(a=e);const o=n.response;if(o){const e=o.data;if("object"==typeof e&&null!==e){s=e;const t=e;"string"==typeof t.message?a=t.message:"string"==typeof t.error&&(a=t.error)}}const i={statusCode:r,errorMessage:a,raw:e};return null!=s&&(i.errorData=s),i},exports.parseLaunchpadVaultAddress=xo,exports.percentileIndexCalculation=function(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)},exports.poolFetchTypeSchema=Fr,exports.poolPaginationSchema=zr,exports.positiveDecimalStringSchema=ir,exports.priceTickRangeMapping=function(e,t,n=60){const r=Zs(e),s=Zs(t);if(r.isLessThanOrEqualTo(0)||s.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(s))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${s.toString()}`);const a=Math.floor(ta(r)),o=Math.ceil(ta(s)),c=Math.floor(a/n)*n,l=Math.ceil(o/n)*n;return{minTick:c,maxTick:l,actualMinPrice:new i(1.0001).pow(c),actualMaxPrice:new i(1.0001).pow(l)}},exports.privateKeySchema=Tr,exports.registerInterval=function(e,t){const n=e;return Td.set(n,{createdAt:Date.now(),label:t}),n},exports.requireNonNegative=function(...e){e.forEach(e=>{if(e.isNaN())throw St("value","NaN");if(!e.isFinite())throw At("value","finite");if(e.isLessThan(0))throw Et("value","0",e.toString())})},exports.requirePositive=sa,exports.requirePositiveWithContext=aa,exports.retryableHttpRequest=async function(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,s=t?.retryableStatus??[429,503,504];let a,o=0;for(;o<=n;)try{return await e()}catch(e){a=e,o++;const t=Ed(e),i=s.includes(t);if(o>n||!i)throw e;const c=r*Math.pow(2,o-1);await new Promise(e=>setTimeout(e,c))}throw a},exports.reverseBondingCurveConfigSchema=Mr,exports.reverseBondingCurveConfigurationSchema=ls,exports.roleHasSufficientPermission=function(e,t){return e===Wa.MANAGER?t!==Wa.OWNER:e===Wa.OWNER||e===t},exports.roundTickBoundaries=function(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}},exports.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},exports.safeDivideWithMinimum=function(e,t,n,r="0"){const s=Zs(t);if(na(s))return Zs(r);const a=Zs(e).dividedBy(s);if(null!=n){const e=Zs(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(a.isLessThan(e))return e}return a},exports.searchQuerySchema=tr,exports.sellTokensDataSchema=ts,exports.standardLimitSchema=gr,exports.standardPaginationSchema=Hr,exports.timestampSchema=Sr,exports.toBackendAddressFormat=Wn,exports.toBackendAddressFromEthers=Xn,exports.tokenCategorySchema=Or,exports.tokenCollectionSchema=xr,exports.tokenDescriptionSchema=Zn,exports.tokenListOptionsSchema=us,exports.tokenNameSchema=Yn,exports.tokenSymbolSchema=Jn,exports.tokenUrlsSchema=Rr,exports.tradeCalculationMethodSchema=as,exports.tradeCalculationTypeSchema=ss,exports.tradeLimitSchema=pr,exports.tradeListParamsSchema=rs,exports.tradePaginationSchema=Vr,exports.tradePaginationWithFiltersSchema=qr,exports.tradeTypeBackendSchema=Jr,exports.tradeTypeSchema=Yr,exports.transactionIdSchema=yr,exports.transformRawApiTokenToDomainModel=function(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(Tn(t.name)?t.name:void 0)??(Tn(t.tokenName)?t.tokenName:void 0)??"";if(!Tn(n))throw new Error("Token name is required and must be a non-empty string");const r=(Tn(t.symbol)?t.symbol:void 0)??(Tn(t.tokenSymbol)?t.tokenSymbol:void 0)??"";if(!Tn(r))throw new Error("Token symbol is required and must be a non-empty string");let s=8;"number"==typeof t.decimals&&t.decimals>=0&&(s=Math.floor(t.decimals));const a={name:n,symbol:r,decimals:s};return Tn(t.address)&&(a.address=t.address),"boolean"==typeof t.verified&&(a.verified=t.verified),a},exports.trimmedLengthValidation=function(e){return null==e||"string"!=typeof e||0===e.trim().length},exports.uniqueKeySchema=kr,exports.unregisterAllIntervals=function(){const e=Td.size;return Td.clear(),e},exports.unregisterInterval=function(e){const t=e;Td.delete(t)},exports.updateProfileDataSchema=gs,exports.uploadProfileImageOptionsSchema=ms,exports.urlSchema=lr,exports.userLimitSchema=mr,exports.userPaginationSchema=Wr,exports.userTokenNameSchema=er,exports.userTokenTypeSchema=ds,exports.userTokensPaginationSchema=jr,exports.validateAddress=Ss,exports.validateAmountString=ys,exports.validateBanTokenOptions=bl,exports.validateBuyTokensData=Us,exports.validateCalculatePreMintData=Gs,exports.validateChatMessageId=function(e){if(!Tn(e))throw ut("id","Message ID");if(!Jt.CHAT_MESSAGE.PATTERN.test(e))throw new Je("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",Ye.INVALID_FORMAT)},exports.validateCheckPoolOptions=Is,exports.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new Je(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},exports.validateCreateApiKeyOptions=Xa,exports.validateCreateChatMessageOptions=function(e){if(!Tn(e.tokenName))throw ut("tokenName");if(e.tokenName.length>Vt.MAX_LENGTH)throw new Je(`tokenName must be at most ${Vt.MAX_LENGTH} characters`,"tokenName",Ye.TOO_LONG);Jd(e.content)},exports.validateCreateCommentOptions=function(e){if(!Tn(e.tokenName))throw ut("tokenName","Token name");const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=Wt;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw ht("tokenName",`${t}-${n} alphanumeric characters`,"Token name");Yd(e.content)},exports.validateCreateMessageOptions=function(e){if(void 0===e.type||null===e.type)throw ut("type");if(e.type!==rc.CHAT_MESSAGE&&e.type!==rc.COMMENT)throw new Je(`type must be one of: ${Object.values(rc).join(", ")}`,"type",Ye.INVALID_VALUE);if(!Tn(e.tokenName))throw ut("tokenName");if(e.tokenName.length>Vt.MAX_LENGTH)throw new Je(`tokenName must be at most ${Vt.MAX_LENGTH} characters`,"tokenName",Ye.TOO_LONG);if(!Tn(e.content))throw ut("content");if(0===e.content.trim().length)throw bt("content","Content");const t=e.type===rc.CHAT_MESSAGE?sc.CONTENT.CHAT_MAX_LENGTH:sc.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw kt("content",t,e.content.length)},exports.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??Sc.TOKEN;return void 0===e.inviteScope||Dc(e.inviteScope)||ct(t,()=>{throw Tt("inviteScope",e.inviteScope,Tc,"Invite scope")}),n===Sc.TOKEN?ct(t,()=>{Cn(e.tokenName??"","tokenName",Ht)}):n===Sc.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),bc(e.role)||ct(t,()=>{throw Tt("role",e.role,vc,"Role")}),void 0!==e.description&&""!==e.description&&ct(t,()=>{fn(e.description,Yt.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||Kt(e.expiresAt)||ct(t,()=>{throw function(e,t="a valid date",n){const r=lt(e,n);return new Je(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},exports.validateCreateOverseerDirectOptions=Zc,exports.validateCreateOverseerInviteOptions=zc,exports.validateCreateTradeData=Ls,exports.validateDecimalRangeStrict=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new Je(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw ft(r,t,n,s,r)},exports.validateFeePortionConstraints=vn,exports.validateFetchGalaBalanceOptions=Rs,exports.validateFetchMessagesOptions=function(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw yt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==rc.CHAT_MESSAGE&&e.type!==rc.COMMENT)throw new Je(`type must be one of: ${Object.values(rc).join(", ")}`,"type",Ye.INVALID_VALUE);nc(e.tokenName,e.userAddress),void 0!==e.pageSize&&bn(0,void 0,qt.MAX_LIMIT,e.pageSize)},exports.validateFetchPoolDetailsData=Ks,exports.validateFetchTokenBalanceOptions=Ms,exports.validateFullName=ks,exports.validateGetAmountOptions=$s,exports.validateGetChatMessagesOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new Je("At least one of tokenName or userAddress is required","options",Ye.REQUIRED);nc(e.tokenName,e.userAddress),void 0!==e.pageSize&&bn(0,void 0,qt.MAX_LIMIT,e.pageSize)},exports.validateGetCommentsOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw yt(["tokenName","userAddress"]);if(void 0!==e.tokenName&&""!==e.tokenName){const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=Wt;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw ht("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}bn(0,void 0,qt.MAX_LIMIT,e.pageSize,e.cursor)},exports.validateGetTokenBanOptions=Cl,exports.validateGetTradeOptions=Ps,exports.validateGetTradesOptions=lc,exports.validateImageUploadOptions=_s,exports.validateInviteCode=function(e){const t=[];return Tn(e)?wc(e)||t.push("Invalid invite code format"):t.push(ut("inviteCode","Invite code").message),t},exports.validateLaunchTokenData=Ws,exports.validateListApiKeysOptions=Ja,exports.validateListModeratorInvitesOptions=function(e){const t=[];return ct(t,()=>{Cn(e.tokenName??"","tokenName",Ht)}),void 0===e.status||Nc(e.status)||ct(t,()=>{throw Tt("status",e.status,kc,"Status")}),ct(t,()=>{bn(0,void 0,zt,e.pageSize)}),t},exports.validateListOverseerInvitesOptions=jc,exports.validateListOverseersOptions=qc,exports.validateListTokenBansOptions=wl,exports.validateListUsersOptions=Jc,exports.validateMessageId=function(e){if(!Tn(e))throw ut("id","Message ID");const t=Jt.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new Je("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",Ye.INVALID_FORMAT)},exports.validateMinMaxRelationship=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,a="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new Je(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(a))throw new Je(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>a)throw new Je(`${n} (${s}) must be less than or equal to ${r} (${a})`,n,"INVALID_RANGE")},exports.validateOptionalTokenName=function(e,t="tokenName",n=Ht){if(null==e)return;if("string"!=typeof e)throw vt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new Je(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,Ye.INVALID_FORMAT)},exports.validateOverseerInviteCode=Xc,exports.validateOverseerInviteId=Yc,exports.validateOverseerWalletAddress=Qc,exports.validatePaginationParams=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw vt("offset","a non-negative integer",e);En(t,"limit")},exports.validateSearchQuery=bs,exports.validateSellTokensData=Fs,exports.validateSortOrderDirection=function(e,t){if("ASC"!==e&&"DESC"!==e)throw new Je(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")},exports.validateTokenDescription=vs,exports.validateTokenListOptions=Ds,exports.validateTokenName=_n,exports.validateTokenSymbol=As,exports.validateTokenUrls=Cs,exports.validateTradeListParams=Bs,exports.validateUnbanTokenOptions=Nl,exports.validateUpdateApiKeyOptions=Qa,exports.validateUpdateChatMessageOptions=function(e){Jd(e.content)},exports.validateUpdateCommentOptions=function(e){Yd(e.content)},exports.validateUpdateMessageOptions=function(e){if(!Tn(e.content))throw ut("content");if(0===e.content.trim().length)throw bt("content","Content");const t=Math.max(sc.CONTENT.CHAT_MAX_LENGTH,sc.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw kt("content",t,e.content.length)},exports.validateUpdatePlatformConfigOptions=tl,exports.validateUpdateProfileData=Os,exports.validateUpdateTokenConfigOptions=ac,exports.validateUploadProfileImageOptions=xs,exports.validateUserTokenName=Ns,exports.validateVaultAddress=Ts,exports.vaultAddressSchema=or,exports.wasModerationEscalated=function(e){return!0===e.escalatedFromQuick};
|
|
1
|
+
"use strict";var e=require("ethers"),t=require("@gala-chain/gala-core-sdk"),n=require("zod"),r=require("@gala-chain/gala-core-sdk/providers"),s=require("@gala-chain/api"),o=require("uuid"),i=require("socket.io-client"),a=require("bignumber.js"),c=require("axios");const l={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",UPLOAD_PROFILE_IMAGE:"/v1/users/me/image",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",GET_GALA_BALANCE:"/v1/users/:address/gala-balance",GET_REFERRAL_CODE:"/v1/connect/users/referrals/code",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},d="/v1/users/referrals/url",u="/v1/users/referrals",h="/v1/users/referrals/summary",g="/v1/tokens/:tokenName/start-stream",p="/v1/tokens/:tokenName/stop-stream",m="/v1/tokens/:tokenName/stream/disable",f="/v1/tokens/:tokenName/stream/enable",E="/v1/tokens/:tokenName/reset-key",A="/v1/tokens/:tokenName/recordings",T="/v1/tokens/:tokenName/recordings/:assetId/download",v="/v1/tokens/:tokenName/recordings/:assetId",S="/v1/tokens/:tokenName/simulcasts",y="/v1/tokens/:tokenName/simulcasts",b="/v1/tokens/:tokenName/simulcasts/:targetId",N="/v1/config",k="/v1/config",w="/v1/config",_="/v1/tokens/:tokenName/role",I="/v1/roles",C="/v1/permissions",D="/v1/tokens/:tokenName/credentials",R="/auth/login",O="/auth/logout",x="/auth/refresh",L="/auth/session",M="/v1/tokens/:tokenName/bans",U="/v1/tokens/:tokenName/bans",F="/v1/tokens/:tokenName/bans/:userAddress",P="/v1/tokens/:tokenName/bans/:userAddress",B="/v1/tokens/:tokenName/active-users",G="/v1/user-bans",$="/v1/user-bans",K="/v1/user-bans/:userAddress",H="/v1/user-bans/:userAddress",W={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},V="/v1/moderator-invites",j="/v1/moderator-invites/claim",q="/v1/moderated-tokens",z="/v1/moderator-invites",Y="/v1/moderator-invites/:id",X="/v1/moderator-invites/:id/role",Q="/v1/moderator-invites/:id",J="/v1/moderator-invites/code/:code",Z={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},ee="/v1/overseer-invites",te="/v1/overseer-invites",ne="/v1/overseer-invites/code/:code",re="/v1/overseer-invites/claim",se="/v1/overseer-invites/:id",oe="/v1/overseers",ie="/v1/overseers",ae="/v1/overseers/:address",ce="/v1/overseers/me",le="/v1/overseer-summary",de="/v1/overseer-summary/bans",ue="/v1/overseer-summary/token-bans",he="/v1/overseer-summary/invites",ge="/v1/overseer-summary/flags",pe="/v1/overseer-summary/users",me="/v1/users",fe="/v1/users/:address/summary",Ee="/v1/cache/flush/address/:address",Ae="/v1/cache/flush/token/:tokenName",Te="/v1/cache/flush/all",ve="/v1/cache/flush/wallet-aliases/:address",Se="/v1/cache/flush/wallet-aliases",ye="/v1/token-bans",be="/v1/token-bans",Ne="/v1/token-bans/:tokenName",ke="/v1/token-bans/:tokenName",we="/v1/reactions",_e="/v1/reactions",Ie="/v1/trades",Ce={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},De="/v1/restricted-token-names",Re="/v1/restricted-token-names",Oe="/live/:tokenName/chat",xe="/live/:tokenName/chat",Le="/live/:tokenName/chat",Me="/live/:tokenName/chat/slow-mode",Ue="/v1/events",Fe="/v1/events/stats",Pe="/health",Be={GET_SETTINGS:"/v1/ai-moderation/settings",UPDATE_SETTINGS:"/v1/ai-moderation/settings",GET_MODERATION:"/v1/ai-moderation/flags/:flagId",TRIGGER_MODERATION:"/v1/ai-moderation/flags/:flagId/analyze",GET_STATUS:"/v1/ai-moderation/status"},Ge="/v1/stats",$e="/v1/trading/fee",Ke="/v1/trading/sale-details",He="/v1/trading/quote",We="/v1/trading/premint-quote",Ve={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},je="/v1/notifications/register",qe="/v1/notifications/unregister",ze="/v1/notifications/preferences",Ye="/v1/notifications/preferences",Xe="/v1/config/client-flags",Qe={NATIVE:"native",EXACT:"exact"},Je=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],Ze=["IDLE","ACTIVE","DISABLED"],et=100,tt={LOCAL:"local",EXTERNAL:"external"},nt={REQUIRED:"REQUIRED",INVALID_TYPE:"INVALID_TYPE",INVALID_VALUE:"INVALID_VALUE",INVALID_FORMAT:"INVALID_FORMAT",TOO_SHORT:"TOO_SHORT",TOO_LONG:"TOO_LONG",TOO_LARGE:"TOO_LARGE",TOO_SMALL:"TOO_SMALL",EMPTY_ARRAY:"EMPTY_ARRAY",ARRAY_TOO_LARGE:"ARRAY_TOO_LARGE",ZERO_VALUE:"ZERO_VALUE",INVALID_TICK_SPACING:"INVALID_TICK_SPACING",INVALID_FEE_TIER:"INVALID_FEE_TIER",INVALID_RANGE:"INVALID_RANGE",INVALID_PARAMETERS:"INVALID_PARAMETERS",NOT_FOUND:"NOT_FOUND",INVALID_DATA:"INVALID_DATA"};class rt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}function st(e){return"object"==typeof e&&null!==e}function ot(e){if(null==e||""===e)return{};if(!st(e)||Array.isArray(e))return{body:e};const t=Reflect.get(e,"message"),n="string"==typeof t?t:Array.isArray(t)&&t.every(e=>"string"==typeof e)?t.join(","):void 0,r=Reflect.get(e,"error"),s=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof r&&""!==r?{serverError:r}:{},...void 0===s?{}:{details:s},body:e}}function it(e){if(e instanceof at)return{...void 0===e.serverMessage?{}:{serverMessage:e.serverMessage},...void 0===e.serverError?{}:{serverError:e.serverError},...void 0===e.details?{}:{details:e.details},...void 0===e.body?{}:{body:e.body}};const t=function(e){if(!st(e))return;const t=Reflect.get(e,"response");return st(t)?t:void 0}(e);return void 0===t?{}:ot(Reflect.get(t,"data"))}class at extends Error{constructor(e,t,n,r=it(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=r.serverMessage,this.serverError=r.serverError,this.details=r.details,this.body=r.body}}class ct extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class lt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function dt(e){return e instanceof Error}function ut(e){return dt(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 ht(e){return dt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function gt(e){if(function(e){return"object"==typeof e&&null!==e&&"code"in e&&("string"==typeof e.code||"number"==typeof e.code)}(e))return e.code}function pt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function mt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function ft(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}function Et(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function At(e,t){return new rt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Tt(e,t){const n=Et(e,t);return new rt(`${n} is required`,e,"REQUIRED")}function vt(e,t,n){const r=Et(e,n);return new rt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function St(e,t,n,r){return new at(e,t,n,r)}function yt(e,t){return new ct(e,t)}function bt(e,t,n){return new lt(e,t,n)}function Nt(e,t,n,r,s){const o=Et(e,s);return new rt(`${o} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function kt(e,t,n,r){const s=Et(e,r);return new rt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function wt(e,t,n,r){const s=Et(e,r);return new rt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function _t(e,t,n,r){const s=Et(e,r),o=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new rt(`${s} must be ${t}${o}`,e,"INVALID_TYPE")}function It(e,t,n){const r=Et(e,n);return new rt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Ct(e,t,n,r){const s=Et(e,r);return new rt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Dt(e,t){if(e.length<2)return Tt(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]??"field"}`}return new rt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function Rt(e,t,n,r){const s=Et(e,r);return new rt(`${s} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function Ot(e,t){const n=Et(e,t);return new rt(`${n} cannot be empty`,e,"EMPTY_STRING")}function xt(e){return null!=e&&"object"==typeof e&&"data"in e}function Lt(e,t,n=!1){const r=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(r||s){const n=e?.statusCode??e.status??void 0;throw St(e?.message??t,n,void 0,r?ot(e):void 0)}}function Mt(e){if(xt(e))return e.data}function Ut(e,t="No data found in response"){if(!xt(e))throw St(t);const n=e.data;if(null==n)throw St(t);return n}async function Ft(e,t={}){return Gt(e,t,e=>{if(void 0===e.data)throw new rt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function Pt(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:s=!1}=t;s&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return s&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function Bt(e,t={}){return Gt(e,t,e=>e)}async function Gt(e,t,n){const{errorContext:r="Operation failed",logger:s,debugLogEnabled:o=!1}=t;o&&s&&s.debug(`${r}: starting operation`);try{const t=await e();if(null==t)throw new rt(`${r}: No response from server`,"response","NO_RESPONSE");return Lt(t,r,!0),o&&s&&s.debug(`${r}: completed successfully`),n(t)}catch(e){throw s&&s.error(r,{error:e}),e}}const $t={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function Kt(e){return e.trim().toLowerCase()}function Ht(e){return e.trim().toUpperCase()}var Wt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Wt||(Wt={}));class Vt{constructor(e){this.levelPriority={[Wt.DEBUG]:0,[Wt.INFO]:1,[Wt.WARN]:2,[Wt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Wt.DEBUG:Wt.INFO)}debug(e,t){this.log(Wt.DEBUG,e,t)}info(e,t){this.log(Wt.INFO,e,t)}warn(e,t){this.log(Wt.WARN,e,t)}error(e,t){this.log(Wt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Wt.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?dt(n)?s(`${r} ${t}`,n.message,ht(n)??""):s(`${r} ${t}`,n):s(`${r} ${t}`)}getConsoleMethod(e){switch(e){case Wt.DEBUG:return console.debug;case Wt.INFO:return console.info;case Wt.WARN:return console.warn;case Wt.ERROR:return console.error;default:return console.log}}child(e){return new Vt({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Wt.DEBUG]>=this.levelPriority[this.minLevel]}}function jt(e){return null==e||""===e}function qt(e){return null==e}const zt=new Vt({debug:!1,context:"DateUtils"});function Yt(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(zt.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return zt.warn(`Date parsing error for "${e}":`,t),new Date}}function Xt(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function Qt(e,t=0){if(jt(e))return t;if("number"==typeof e)return isNaN(e)||!isFinite(e)?t:e;const n=parseFloat(e);return isNaN(n)||!isFinite(n)?t:n}function Jt(e,t,n){if(qt(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const r=parseInt(String(e),10);return isNaN(r)?t:r}function Zt(e,t=0){if(qt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Qt(String(e).replace("%","").trim(),t)}function en(e,t=18){const n=Qt(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function tn(e){return en(e,8)}function nn(e){return en(e,18)}function rn(e,t,n,r){if("number"!=typeof e)throw _t(r,"a number",e,r);if(e<t||e>n)throw Nt(r,t,n,e)}function sn(e,t,n){if("string"!=typeof e)throw _t(n,"a string",e,n);if(e.length>t)throw wt(n,t,e.length)}function on(e,t){if("number"!=typeof e)throw _t(t,"a number",e,t);if(!Number.isInteger(e))throw _t(t,"an integer",e,t);if(e<=0)throw kt(t,1,e,t)}function an(e,t,n=!1){if("string"!=typeof e)throw _t(t,"a string",e,t);if(!n&&0===e.trim().length)throw Tt(t,`${t} (non-empty string)`)}function cn(e,t,n){const r="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new rt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new rt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new rt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new rt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(r>s)throw new rt(`${n} minFee (${r}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}const ln={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},dn=function(e){return"string"==typeof e&&e.trim().length>0},un=jt,hn=qt;function gn(e,t,n=100,r,s){if(void 0!==s&&"string"!=typeof s)throw new rt("cursor must be a string","cursor",nt.INVALID_TYPE);const o=r??t,i=void 0!==r?"pageSize":"limit";if(void 0!==o&&(on(o,i),o>n))throw new rt(`${i} must be at most ${n}`,i,nt.TOO_LARGE)}function pn(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function mn(e){return Object.values(e)}function fn(e,t,n){if(!dn(e))throw Tt(t);const r=e.trim();if(0===r.length)throw Tt(t);if(r.length<n.MIN_LENGTH)throw Nt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw Nt(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new rt(`${t} must be ${n.DESCRIPTION}`,t,nt.INVALID_FORMAT)}function En(e,t,n){if(null==e)throw Tt(t,t);if("string"!=typeof e)throw _t(t,"a string",e);const r=e.trim();if(0===r.length)throw Tt(t,t);if(!n.PATTERN.test(r))throw new rt(`${t} must be ${n.DESCRIPTION}`,t,nt.INVALID_FORMAT)}function An(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:s=!1,optional:o=!1,validator:i}of e){const e=n[t];if((!o||void 0!==e)&&(!s||null!==e)){if(typeof e!==r)return!1;if(i&&!i(e))return!1}}return!0}}const Tn={requiredString:e=>t=>hn(t)?`${e} is required`:"string"!=typeof t?`${e} must be a string`:0===t.trim().length?`${e} cannot be empty`:void 0,maxLength:(e,t)=>n=>{if(!un(n))return"string"!=typeof n?`${e} must be a string`:n.length>t?`${e} must be at most ${t} characters`:void 0},positiveInteger:e=>t=>{if(!hn(t))return"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`},requiredPositiveInteger:e=>t=>hn(t)?`${e} is required`:"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`,enumValue:(e,t)=>n=>{if(!hn(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>hn(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!hn(t))return"string"!=typeof t?`${e} must be a string`:Xt(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(hn(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return ln.ETH_ADDRESS.test(n)||ln.BACKEND_ADDRESS.test(n)||ln.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function vn(e){return""===e||0===e.trim().length}function Sn(e,t,n){if(!hn(e)){if("string"!=typeof e)throw _t(t,"a string",e,t);if(e.length>n)throw new rt(`${t} must be at most ${n} characters`,t,nt.TOO_LARGE)}}function yn(e,t){hn(e)||function(e,t){const n=e instanceof Date?e:"string"==typeof e||"number"==typeof e?new Date(e):void 0;if(void 0===n)throw _t(t,"a date",e,t);if(isNaN(n.getTime()))throw new rt(`${t} must be a valid date`,t,nt.INVALID_FORMAT)}(e,t)}function bn(e,t,n){try{on(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new rt(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function Nn(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new rt(`${n} must be one of: ${r.join(", ")}`,n,nt.INVALID_FORMAT)}(e,t,n)}class kn{constructor(e,t=!1,n){this.http=e,this.logger=new Vt({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new ct("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=ht(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){bn(e,t,n)}}class wn{constructor(e=!1,t){this.logger=t||new Vt({debug:e,context:this.constructor.name})}}class _n extends wn{constructor(e=!1){super(e),this.cache=new Map}get(e){const t=this.normalizeKey(e);return this.cache.get(t)}set(e,t){const n=this.normalizeKey(e);this.cache.set(n,t)}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(){this.cache.clear(),this.logger.debug("Cleared cache")}dump(){return new Map(this.cache)}size(){return this.cache.size}isEmpty(){return 0===this.cache.size}buildBaseStats(){return{totalItems:this.cache.size}}}class In extends _n{constructor(e=!1){super(e)}normalizeKey(e){return Kt(e).replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}getLRUKey(){return this.cache.keys().next().value??null}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=In.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n??{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}getByName(e){const t=this.normalizeKey(e);return this.cache.get(t)}getMaxSupply(e){const t=this.normalizeKey(e),n=this.cache.get(t);return n?.maxSupply??$t.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${Kt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${Kt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${Kt(e)}`;return this.cache.has(t)}}In.MAX_CACHE_SIZE=1e4;const Cn={MIN_LENGTH:1,MAX_LENGTH:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 letters and digits"},Dn={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},Rn={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},On={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},xn={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},Ln=100,Mn=100,Un=50,Fn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},Pn=100,Bn={COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},Gn={CHAT_MESSAGE:{PATTERN:/^chat-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i},CONTENT_REACTION:{MAX_LENGTH:64,PATTERN:/^(msg-\d{13}-[a-f0-9]{32}|chat-\d{13}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/}},$n=60,Kn=31536e3,Hn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Wn={PATTERN:/^[a-fA-F0-9]{64}$/,MAX_LENGTH:64},Vn=1,jn=100,qn={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},zn={ETHEREUM:ln.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:ln.BACKEND_ADDRESS,CLIENT:ln.CLIENT_ADDRESS};class Yn{toBackendFormat(t){if(!dn(t))throw new rt("Address is required and must be a string","address","REQUIRED");let n=t;if(t.startsWith("eth|")){if(n=t.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new rt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${t}"`,"address","INVALID_FORMAT");return t}if(n=Qn(t),!/^[a-fA-F0-9]{40}$/.test(n))throw new rt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${t}"`,"address","INVALID_FORMAT");return`eth|${e.getAddress(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!dn(e))throw new rt("Backend address is required and must be a string","address","REQUIRED");const t=e.match(/^eth\|(0x)?([0-9a-fA-F]{40})$/i);if(!t)throw new rt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],r=void 0!==n&&""!==n?6:4;return`0x${e.substring(r)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!zn.CLIENT.test(e))throw new rt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!zn.BACKEND.test(e))throw new rt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!dn(e)&&(!!zn.ETHEREUM.test(e)||(!!zn.ETHEREUM_NO_PREFIX.test(e)||(!!zn.BACKEND.test(e)||!!zn.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new rt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return dn(e)?zn.ETHEREUM.test(e)||zn.ETHEREUM_NO_PREFIX.test(e)?"ethereum":zn.BACKEND.test(e)?"backend":zn.CLIENT.test(e)?"client":null:null}normalize(e){if(void 0!==e&&""!==e)return e.toLowerCase()}extractHex(e){if(e.startsWith("eth|"))return e.substring(4).toLowerCase();if(e.startsWith("0x"))return Qn(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new rt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Xn=new Yn;function Qn(e){return e.startsWith("0x")?e.slice(2):e}function Jn(e){return Xn.toBackendFormat(e)}function Zn(e){return Xn.toEthereumFormat(e)}function er(e){return Xn.normalizeInput(e)}function tr(e){return Xn.isValid(e)}const nr=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function rr(e){if(!dn(e))return!1;const t=e.toLowerCase().trim();if(t.startsWith("eth|")||t.startsWith("client|")||t.startsWith("service|"))return nr.test(t.replace(/0x/g,""));const n=t.replace(/^0x/,"");return nr.test(/^[0-9a-f]{24}$/.test(n)?`client|${n}`:`eth|${n}`)}function sr(e,t){if(!rr(e))throw new rt(`${t} must be a GalaChain user address (eth|<40 hex>, 0x<40 hex> or client|<24 hex>)`,t,"INVALID_FORMAT")}function or(e,t="address"){Xn.assertValid(e,t)}function ir(e){const t="string"==typeof e?e:e.address;return Xn.toBackendFormat(t)}var ar=Object.freeze({__proto__:null,AddressFormatter:Yn,assertBackendUserAddress:sr,assertValidWalletAddress:or,fromBackendAddressFormat:Zn,isBackendUserAddress:rr,isValidAddress:tr,normalizeAddressInput:er,stripHexPrefix:Qn,toBackendAddressFormat:Jn,toBackendAddressFromEthers:ir});const cr=n.z.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").regex(/^[a-zA-Z0-9]+$/,"Token name can only contain letters and numbers"),lr=cr.max(25,"Token name must be at most 25 characters"),dr=n.z.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),ur=n.z.string({message:"Token symbol is required"}).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"),hr=n.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),gr=n.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),pr=n.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),mr=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"),fr=n.z.string().regex(ln.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),Er=n.z.string().regex(ln.ETH_ADDRESS,"Invalid Ethereum address format"),Ar=n.z.string().refine(e=>ln.BACKEND_ADDRESS.test(e)||ln.ETH_ADDRESS.test(e)||ln.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new Yn).normalizeInput(e)??e),Tr=n.z.string().refine(e=>ln.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),vr=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Qt(e,0)>0,"Amount must be greater than zero"),Sr=n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Qt(e,0)>=0,"Amount must be zero or greater"),yr=n.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),br=n.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Nr=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 kr(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 wr=kr(100),_r=kr(20),Ir=kr(20),Cr=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"),Dr=n.z.string().max(255,"Filename must be at most 255 characters"),Rr=n.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Or=n.z.string().datetime("Must be a valid ISO 8601 date string"),xr=n.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Lr=n.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Mr=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"),Ur=n.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Fr=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Pr=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),name:Dr,size:Cr,type:Rr}),Br=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"),Gr=n.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),$r=n.z.union([Br,Gr]),Kr=n.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Hr=Dr.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Fr.includes(t)},`Filename must end with one of: ${Fr.join(", ")}`),Wr=n.z.object({websiteUrl:br,telegramUrl:br,twitterUrl:br,instagramUrl:br,facebookUrl:br,redditUrl:br,tiktokUrl:br}).refine(e=>void 0!==e.websiteUrl||void 0!==e.telegramUrl||void 0!==e.twitterUrl||void 0!==e.instagramUrl||void 0!==e.facebookUrl||void 0!==e.redditUrl||void 0!==e.tiktokUrl,"At least one social URL (website, telegram, twitter, instagram, facebook, reddit, or tiktok) is required"),Vr=n.z.string().min(1,"Token category must not be empty").default("Unit"),jr=n.z.string().min(1,"Token collection must not be empty").default("Token"),qr=n.z.object({minFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Qt(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Qt(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:n.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Qt(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Qt(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Qt(e.maxFeePortion,0)>=Qt(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),zr=n.z.object({tokenName:cr,tokenSymbol:ur,tokenDescription:hr,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:Sr.default("0"),websiteUrl:br,telegramUrl:br,twitterUrl:br,instagramUrl:br,facebookUrl:br,redditUrl:br,tiktokUrl:br,tokenCategory:Vr,tokenCollection:jr,reverseBondingCurveConfiguration:qr.optional(),saleStartTime:n.z.number().int().positive().optional(),privateKey:Lr.optional()}),Yr=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),tokenName:cr}),Xr=n.z.enum(Je),Qr=n.z.object({tokenName:dr.optional(),symbol:ur.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),Jr=n.z.enum(["NATIVE","MEME"]),Zr=n.z.enum(["IN","OUT"]),es=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:lr}),ts=n.z.object({tokenName:lr,slippageToleranceFactor:n.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:n.z.number().min(0).max(1).optional(),privateKey:Lr.optional()}),ns=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(100).default(10)}),rs=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),ss=n.z.object({offset:n.z.number().int().min(0).default(0),pageSize:n.z.number().int().min(1).max(20).default(10)}),os=ns.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()}),is=rs.extend({tokenName:n.z.string().min(1).max(50).optional(),search:n.z.string().min(1).max(100).optional()}),as=ss.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")}),cs={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()},ls=n.z.object(cs);const ds=n.z.enum(["buy","sell"]),us=n.z.enum(["BUY","SELL"]),hs=n.z.object({tradeType:ds,tokenAmount:vr,vaultAddress:Tr,userAddress:Ar,slippageTolerance:vr.optional(),deadline:n.z.number().int().positive().optional()}),gs=n.z.object({tokenSymbol:ur,nativeTokenQuantity:vr,expectedToken:vr,maxAcceptableReverseBondingCurveFee:Sr.default("0").optional()}),ps=n.z.object({tokenSymbol:ur,tokenQuantity:vr,expectedNativeToken:vr,maxAcceptableReverseBondingCurveFee:Sr.default("0").optional()}),ms=ss.extend({tokenName:gr.optional()}),fs=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()}),Es=n.z.enum(["NATIVE","MEME"]),As=n.z.enum(["IN","OUT"]),Ts=n.z.object({type:Es,method:As,vaultAddress:Tr,amount:vr}),vs=n.z.object({nativeTokenQuantity:vr}),Ss=n.z.object({vaultAddress:Tr}),ys=n.z.object({minFeePortion:vr,maxFeePortion:vr}),bs=n.z.enum(["both","held","created"]),Ns=rs.extend({type:bs.optional(),address:Ar.optional(),search:pr.optional(),tokenName:gr.optional()}),ks=n.z.object({address:Ar.optional(),refresh:n.z.boolean().optional()}),ws=n.z.object({profileImage:n.z.string().nullable().optional(),fullName:mr.optional(),address:Ar.optional(),privateKey:Lr.optional()}),_s=n.z.object({file:n.z.union([n.z.instanceof(File),n.z.instanceof(Buffer)]),address:Ar.optional(),privateKey:Lr.optional()}),Is=n.z.object({address:Ar,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:gr.optional(),withExpired:n.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function Cs(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.issues.map(e=>e.message)}}}const Ds=Cs(cr),Rs=Cs(ur),Os=Cs(hr),xs=Cs(Ar),Ls=Cs(Tr),Ms=Cs(vr),Us=Cs(mr),Fs=Cs(pr),Ps=Cs(gr),Bs=Cs(zr),Gs=Cs(Wr),$s=Cs(Yr),Ks=Cs(Qr),Hs=Cs(Ns),Ws=Cs(ks),Vs=Cs(ws),js=Cs(_s),qs=Cs(Is),zs=Cs(hs),Ys=Cs(gs),Xs=Cs(ps),Qs=Cs(ms),Js=Cs(fs),Zs=Cs(Ts),eo=Cs(vs),to=Cs(Ss);function no(e){const t=Bs(e);return t.success?[]:t.errors??["Unknown validation error"]}function ro(e){const t=no(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function so(e,t){return"string"==typeof e[t]}function oo(e,t){return void 0===e[t]||"string"==typeof e[t]}function io(e,t){return void 0===e[t]||"number"==typeof e[t]}function ao(e,t){switch(t){case"string":return"string"==typeof e;case"number":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return null!==e&&"object"==typeof e&&!Array.isArray(e);case"array":return Array.isArray(e);case"optional-string":return void 0===e||"string"==typeof e;case"optional-number":return void 0===e||"number"==typeof e;case"optional-boolean":return void 0===e||"boolean"==typeof e;case"optional-object":return void 0===e||null!==e&&"object"==typeof e&&!Array.isArray(e);case"optional-array":return void 0===e||Array.isArray(e);default:return!1}}function co(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,r]of Object.entries(e)){if(!ao(n[t],r))return!1}return!0}}pn({BUY:"buy",SELL:"sell"});const lo=co({nativeTokenQuantity:"string"});function uo(e,t="0"){return function(e,t="0"){if(jt(e))return new a(t);if(a.isBigNumber(e))return e.isNaN()?new a(t):e;try{const n=new a(e);return n.isNaN()||!n.isFinite()?new a(t):n}catch{return new a(t)}}(e,t)}function ho(e,t){return void 0!==t?uo(e).toFixed(t):uo(e).toFixed()}function go(e){const t=uo(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function po(e){return uo(e).isZero()}function mo(e,t){return uo(e).isLessThan(uo(t))}function fo(...e){e.forEach(e=>{if(e.isNaN())throw It("value","NaN");if(!e.isFinite())throw wt("value","finite");if(e.isLessThanOrEqualTo(0))throw kt("value","0",e.toString())})}function Eo(e,t,n){if(e.isNaN())throw It(t,"NaN");if(!e.isFinite())throw wt(t,"finite");if(e.isLessThanOrEqualTo(0))throw kt(t,"0",e.toString())}function Ao(e,t,n="0"){const r=uo(t);return po(r)?uo(n):uo(e).dividedBy(r)}const To={calculateBuyWithExact(e,t){const n=Qt(e),r=Qt(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:i,GAS_FEE:a}=$t,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((r+n)*o)-Math.exp(r*o))/o,8),l=ho(uo(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateBuyWithNative(e,t){const n=Qt(e),r=Qt(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:i,GAS_FEE:a}=$t,c=Math.log(n*o/s+Math.exp(r*o))/o-r,l=ho(uo(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}},calculateSellWithExact(e,t,n,r,s){const o=Qt(e),i=Qt(t),a=Qt(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=$t,h=c*(Math.exp(i*l)-Math.exp((i-o)*l))/l,g=uo(h),p=r+i/a*(s-r),m=ho(g.multipliedBy(p),8),f=ho(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:f,gasFee:u}},calculateSellWithNative(e,t,n,r,s){const o=Qt(e),i=Qt(t),a=Qt(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=$t;if(o>=c*(Math.exp(i*l)-1)/l){const e=uo(o),t=r+i/a*(s-r),n=ho(e.multipliedBy(t),8),c=ho(e.multipliedBy(d));return{amount:i.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=i-Math.log(Math.exp(i*l)-o*l/c)/l,g=uo(o),p=r+i/a*(s-r),m=ho(g.multipliedBy(p),8),f=ho(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:m,transactionFee:f,gasFee:u}}};function vo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function So(e,t){if(!function(e){if(!vo(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return vo(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw St(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:$t.GAS_FEE}}class yo{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:s,maxDecimals:o=yo.MAX_DECIMAL_PLACES,fieldName:i="amount"}=t;if(!dn(e))throw new rt(`${i} cannot be empty or whitespace-only. Provide a valid numeric string.`,i,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new rt(`${i} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,i,"INVALID_NUMERIC_STRING");const a=Qt(e,NaN);if(isNaN(a))throw new rt(`${i} must be a valid numeric string. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new rt(`${i} must be a finite number. Cannot be Infinity or -Infinity.`,i,"INVALID_NUMERIC_STRING");if(a<0)throw new rt(`${i} must be non-negative. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new rt(`${i} must be greater than zero. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");const c=uo(e),l=c.decimalPlaces()??0;if(l>o)throw new rt(`${i} cannot exceed ${o} decimal places. Received: ${l} decimal places`,i,"PRECISION_EXCEEDED");if(void 0!==r&&mo(c,r))throw new rt(`${i} must be at least ${r}. Received: "${e}"`,i,"BELOW_MINIMUM");if(void 0!==s&&(d=s,uo(c).isGreaterThan(uo(d))))throw new rt(`${i} cannot exceed ${s}. Received: "${e}"`,i,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return uo(e,t)}isValid(e,t={}){try{return null==e||""===e?!1!==t.allowZero:(this.validate(e,t),!0)}catch{return!1}}formatAmount(e,t){return ho(e,t)}clampAmount(e,t,n){const r=uo(e),s=uo(t),o=uo(n);return function(e,t,n){const r=uo(e),s=uo(t),o=uo(n);return r.isGreaterThanOrEqualTo(s)&&r.isLessThanOrEqualTo(o)}(r,s,o)?ho(r):mo(r,s)?ho(s):ho(o)}}function bo(e,t){throw new rt(e.join("; "),t,"VALIDATION_ERROR")}function No(e){const t=Ds(e);!t.success&&t.errors&&bo(t.errors,"tokenName")}function ko(e){const t=es.safeParse(e);var n;t.success||bo((n=t.error.issues,Array.isArray(n)?n.map(e=>null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:String(e)).filter(e=>""!==e):[]),"options")}function wo(e,t,n=!0){_o.validate(e,{fieldName:t,allowZero:n})}yo.MAX_DECIMAL_PLACES=18,yo.MIN_POSITIVE="0.00000000000000001";const _o=new yo;class Io{constructor(e,t,n,r="local",s){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=r,this.launchpadWrites=s,this.metadataCache=new In}createSale(e){if(void 0===this.launchpadWrites)throw new Error("Launchpad write transport is not configured.");return this.launchpadWrites.createSale(e)}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw vt("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[Qe.NATIVE,Qe.EXACT],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return So(await Ft(()=>this.http.get(He,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:o,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a}=e;if("external"===this.validateAmountCalculationInputs(t,n,r,e.mode,[Qe.EXACT,Qe.NATIVE],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==s&&{currentSupply:s},...void 0!==o&&{maxSupply:o},...void 0!==i&&{reverseBondingCurveMaxFeeFactor:i},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;return this.validateExternalAmountInputs(t,n),"exact"===r?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s}=e;if(!dn(n))throw Tt("amount","Amount");if(r!==Qe.NATIVE&&r!==Qe.EXACT)throw _t("type",'"native" or "exact"',r);void 0!==s&&wo(s,"currentSupply");const o=null==s||""===s;if(o&&(null==t||""===t))throw Tt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&No(t);let i=s;if(o){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===Qe.EXACT?To.calculateBuyWithExact(n,i):To.calculateBuyWithNative(n,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:s,maxSupply:o,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a}=e;if(!dn(n))throw Tt("amount","Amount");if(r!==Qe.EXACT&&r!==Qe.NATIVE)throw _t("type",'"exact" or "native"',r);void 0!==s&&wo(s,"currentSupply");const c=null==s||""===s||null==o||""===o||void 0===i||void 0===a;if(c&&(null==t||""===t))throw Tt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&No(t);let l=s,d=o,u=i,h=a;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===Qe.EXACT?To.calculateSellWithExact(n,l,d,h,u):To.calculateSellWithNative(n,l,d,h,u)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return so(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&oo(t,"currentSupply")}(e))throw _t("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:s}=t;No(n);const o=await this.fetchSaleDetails(n),i=s??ho(uo(o.maxSupply).minus(o.sellingTokenQuantity)),a=o.sellingTokenQuantity;if("0"===a)throw Tt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:a,type:"exact",currentSupply:i,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(c),remainingTokens:a}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw yt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");ro(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Qt(t);if(0===n&&"0"!==t)throw It("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw It("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;cn(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!lo(e))throw vt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return So(await Ft(()=>this.http.get(We,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=ho(uo(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.sellingTokenQuantity,s=t.maxSupply;let o=.5,i=.1;const a=t.reverseBondingCurveConfiguration;null!=a?.maxFeePortion&&(o=Zt(a.maxFeePortion,.5)),null!=a?.minFeePortion&&(i=Zt(a.minFeePortion,.1)),void 0===a&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=o-i;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:o,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){No(e);const t=await this.fetchSaleDetails(e),n=ho(uo(t.maxSupply).minus(t.sellingTokenQuantity)),r=t.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),n}async fetchPoolDetails(e){No(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...r}=t,s=n?.minFeePortion??"0",o=n?.maxFeePortion??"0";return{...r,reverseBondingCurveMinFeePortion:s,reverseBondingCurveMaxFeePortion:o,hasReverseBondingCurveFee:!po(s)||!po(o),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return fn(e,"tokenName",Cn),Ft(()=>this.http.get(Ke,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,r,s,o){const i=r??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw _t("mode",'"local" or "external"',i);if(!dn(e))throw Tt("tokenName","Token name");if(!dn(t))throw Tt("amount","Amount");if("string"!=typeof n||!s.includes(n))throw _t("type",o,n);return i}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new rt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new rt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Jn(e)}validateTokenName(e){return No(e)}validatePagination(e){void 0!==e.pageSize&&gn(0,void 0,100,e.pageSize)}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const Co={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class Do{constructor(){this.data=new Map}async get(e){return this.data.get(e)??null}async set(e,t){this.data.set(e,t)}async remove(e){this.data.delete(e)}}var Ro;exports.AuthErrorType=void 0,(Ro=exports.AuthErrorType||(exports.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",Ro.SIGNATURE_FAILED="SIGNATURE_FAILED",Ro.INVALID_ADDRESS="INVALID_ADDRESS",Ro.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class Oo extends Error{constructor(e,t,n,r){super(t),this.type=e,this.originalError=n,this.statusCode=r,this.name="AuthError"}}class xo{constructor(e,t=Co.REFRESH_THRESHOLD_MS){this.tokenState=null,this.STORAGE_KEYS={ACCESS_TOKEN:"lpad_access_token",ACCESS_EXPIRES:"lpad_access_expires",REFRESH_TOKEN:"lpad_refresh_token",REFRESH_EXPIRES:"lpad_refresh_expires"},this.storage=e??new Do,this.refreshThresholdMs=t}setToken(e,t){if(!dn(e))throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,r){if(this.setToken(e,t),n){const e=Date.now()+1e3*(r??7776e3);if(!this.tokenState)throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${Co.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Co.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),o=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&o){const e=Number(o);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}class Lo extends xo{getJwtHeaders(){return{}}}async function Mo(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const r=(pt(e)?e.response?.status:void 0)??(e instanceof at?e.statusCode:void 0);return St(`${t}: ${ut(e)}`,r,dt(e)?e:void 0)}(e,t,n))}}function Uo(e,t){return t instanceof Oo?t:new Oo(exports.AuthErrorType.SIGNATURE_FAILED,`${e}: ${ut(t)}`,dt(t)?t:void 0,function(e){if("object"==typeof e&&null!==e){if("statusCode"in e&&"number"==typeof e.statusCode)return e.statusCode;if("response"in e&&"object"==typeof e.response&&null!==e.response){const t=e.response;if("status"in t&&"number"==typeof t.status)return t.status}}}(t))}class Fo{constructor(e,t,n,r=!1,s){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=s,this.refreshPromise=null,this.loginPromise=null,this.logger=new Vt({debug:r,context:"SessionAuthService"})}async loginWithSignature(e){if(or(e.address,"address"),!dn(e.message)||!dn(e.signature))throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"A login needs the signed message and its signature.");const t={address:e.address,message:e.message,signature:e.signature,...void 0!==e.publicKey&&{publicKey:e.publicKey},...void 0!==this.session&&{cookieSession:!0}};return this.postLogin(t)}async loginWithDevBypass(e){return or(e,"address"),this.postLogin({address:e,...void 0!==this.session&&{cookieSession:!0}})}async postLogin(e){try{const t=await this.http.request({method:"POST",url:R,data:e,withSession:!1}),n=this.extractLoginData(t);return void 0===this.session&&await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),n}catch(e){throw Uo("Login failed",e)}}async login(){if(this.loginPromise)return this.logger.debug("Login already in progress, reusing existing promise"),this.loginPromise;if(!this.signatureAuth.hasWallet())throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return Mo(async()=>{const e=Date.now(),t=`${Co.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=this.signatureAuth.getAddress();or(r,"address");const s={address:r,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:r,message:t});const o=await this.http.post(R,s),i=this.extractLoginData(o);return await this.jwtAuth.setTokens(i.accessToken,i.expiresIn,i.refreshToken,i.refreshExpiresIn),this.logger.debug("Login successful",{address:i.address,expiresIn:i.expiresIn,hasRefreshToken:!!i.refreshToken}),i},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Oo)throw e;throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${ut(e)}`,dt(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(void 0!==this.session){this.refreshPromise=this.performCookieRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}if(!this.jwtAuth.hasToken())throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performCookieRefresh(){try{const e=await this.http.request({method:"POST",url:x,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw Uo("Token refresh failed",e)}}async performRefresh(){return Mo(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.jwtAuth.getRefreshToken();if(e){this.logger.debug("Using refresh token flow");const t=await this.http.post(x,{refreshToken:e}),n=this.extractLoginData(t);return await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),this.logger.debug("Token refreshed successfully via refresh token",{address:n.address,expiresIn:n.expiresIn,hasNewRefreshToken:!!n.refreshToken}),n}this.logger.debug("Using legacy access token refresh");const t=await this.http.post(x,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof Oo)throw e;throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${ut(e)}`,dt(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(void 0!==this.session){const n=e?.accessToken??null;try{await this.http.request({method:"POST",url:O,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${Co.BEARER_PREFIX}${n}`}}})}catch(e){throw Uo("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(O,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${ut(e)}`)}else t&&this.logger.debug("Skipping server-side revocation: no valid local token available");await this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Mo(async()=>{const e=await this.http.get(L,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Oo)throw e;throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${ut(e)}`,dt(e)?e:void 0)})}getAccessToken(){return this.jwtAuth.getToken()}isAuthenticated(){return this.jwtAuth.isValid()}shouldRefresh(e){return this.jwtAuth.shouldRefresh(e)}async ensureValidToken(e){if(void 0!==this.session){const e=await this.session.accessToken();if(null===e||""===e)throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${ut(e)} - attempting re-login`)}}else this.logger.debug("Token expired - no refresh token available, attempting re-login");return(await this.login()).accessToken}if(this.jwtAuth.shouldRefresh(e)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(e){if(e.error)throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,""!==ut(e)?ut(e):"Authentication failed");const t=Ut(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:s,refreshToken:o,refreshExpiresIn:i}=t;if(!dn(n))throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:s,...void 0!==o&&{refreshToken:o},...void 0!==i&&{refreshExpiresIn:i}}}extractSessionData(e){if(e.error)throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,""!==ut(e)?ut(e):"Failed to get session");return Ut(e,"No data in session response")}}class Po{constructor(e){if(this.wallet=e.wallet,e.walletProvider?this.walletProvider=e.walletProvider:e.wallet,this.messagePrefix=e.messagePrefix??"Create a GalaChain Wallet",void 0!==e.messagePrefix)try{an(e.messagePrefix,"messagePrefix",!1)}catch{throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=r.PrivateKeyProvider.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Jn(this.wallet.address)}catch(e){if(e instanceof Oo)throw e;if(e instanceof rt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Oo(exports.AuthErrorType.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Oo(exports.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=r.PrivateKeyProvider.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Jn(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(t){this.walletProvider=t,this.wallet=void 0;const n=void 0!==t&&r.isPrivateKeyProvider(t)?e.computeAddress(t.exportPrivateKey()):void 0;this.cachedAddress=n,this.cachedGalaAddress=void 0===n?void 0:Jn(n)}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=await this.walletProvider.getGalaAddress())}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof Oo)throw e;throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",dt(e)?e:new Error(ut(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getGalaAddress()}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null===this.wallet.privateKey||void 0===this.wallet.privateKey)throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&r.isPrivateKeyProvider(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.")}async getPrivateKeyAsync(){if(await this.validateWalletAsync(),!this.walletProvider.getPrivateKey)throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",dt(e)?e:void 0)}}formatAddress(e){try{return Jn(e)}catch{throw new Oo(exports.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Oo)throw e;throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,ut(e),dt(e)?e:new Error(ut(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(r);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof Oo)throw e;throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",dt(e)?e:new Error(ut(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof Oo)throw e;throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",dt(e)?e:new Error(ut(e)))}}async generateCustomSignature(e){if(!dn(e))throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getGalaAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Oo)throw e;throw new Oo(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",dt(e)?e:new Error(ut(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Oo(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Bo={prod:{...t.GALA_CHAIN_ENVIRONMENTS.prod,bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},stage:{...t.GALA_CHAIN_ENVIRONMENTS.stage,bundleBaseUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadBaseUrl:"https://lpad-backend.stage.defi.ovh.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",webSocketUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function Go(e){return Bo[e]}var $o,Ko;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}($o||($o={})),exports.SDKTransactionStatus=void 0,(Ko=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",Ko.PROCESSING="processing",Ko.COMPLETED="completed",Ko.FAILED="failed",Ko.TIMEOUT="timeout";const Ho={[$o.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[$o.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[$o.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[$o.FAILED]:exports.SDKTransactionStatus.FAILED,[$o.ERROR]:exports.SDKTransactionStatus.FAILED,[$o.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[$o.PENDING]:exports.SDKTransactionStatus.PENDING},Wo="9.0.0-rc.2",Vo={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function jo(e,t=1,n=Vo.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function qo(e){return"string"==typeof e||null===e?e:void 0}function zo(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),r=qo(Reflect.get(e,"endCursor")),s=qo(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===r?{}:{endCursor:r},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===s?{}:{startCursor:s}}}function Yo(e,t){const{hasNextPage:n,endCursor:r}=e;if(n&&"string"==typeof r&&""!==r&&r!==t)return r}function Xo(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Qo(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const r=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(r),n}const Jo={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function Zo(e,t){let n=e;for(const[e,r]of Object.entries(t)){const t=Jo[e];if(void 0===t)throw new Error(`buildEndpoint: path parameter :${e} has no casing in PATH_PARAM_CASING`);n=n.replace(`:${e}`,encodeURIComponent("lowercase"===t?r.toLowerCase():r))}return n}function ei(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=Xo(n))}return e}const ti="x-api-key";class ni extends kn{constructor(e,t,n,r=!1,s){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=s??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!dn(e))throw Tt("tokenName","Token name");const n=Kt(e);if(!t.PATTERN.test(n))throw vt("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!dn(e))throw Tt(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw _t(t,"string",typeof e,n);if(e.length>r)throw wt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,s,o,i){!function(e,t,n,r,s){if(null!=e){if("number"!=typeof e)throw _t(t,"number",typeof e,n);if(e<r||e>s)throw Nt(t,r,s,e,n)}}(e,t,n,r,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Xt(e))throw vt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){bn(e,t,n)}validateStatusFilter(e,t,n="status"){Nn(e,t,n)}buildPaginationParams(e,t){return Qo(e,t)}addOptionalFilterParams(e,t,n){return ei(e,t,n)}buildEndpoint(e,t){return Zo(e,t)}buildEndpointWithId(e,t){return e.replace(":id",encodeURIComponent(t))}validateAndBuildTokenEndpoint(e,t,n){return this.validateTokenName(e,t),this.buildEndpoint(n,{tokenName:e})}getAdminHeaders(){if(void 0===this.adminApiKey||""===this.adminApiKey)throw new ct("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[ti]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new ct("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return void 0!==this.adminApiKey&&""!==this.adminApiKey}getDualAuthHeaders(){return void 0!==this.adminApiKey&&""!==this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}getMultiAuthHeaders(){return void 0!==this.userApiKey&&""!==this.userApiKey?{[ti]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Lt(e,"Backend request failed",!0),Ut(e,"No data in backend response")}extractDataOrNull(e){return Lt(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(r,{},this.getAdminHeaders()),o=this.extractData(s);return{enabled:o.enabled,tokenName:o.tokenName??Kt(e)}}}class ri extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getSettings(){return{settings:(await this.http.get(Be.GET_SETTINGS,{},this.getDualAuthHeaders())).settings}}async updateSettings(e){const t={};void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.mode&&(t.mode=e.mode),void 0!==e.provider&&(t.provider=e.provider);return{settings:(await this.http.post(Be.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Be.GET_MODERATION.replace(":flagId",String(e.flagId));return{moderation:(await this.http.get(t,{},this.getDualAuthHeaders())).analysis}}async triggerModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Be.TRIGGER_MODERATION.replace(":flagId",String(e.flagId)),n=await this.http.post(t,{},this.getDualAuthHeaders());return{queued:n.queued,message:n.message.length>0?n.message:"Moderation queued successfully"}}async getStatus(){return{status:(await this.http.get(Be.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const si={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},oi=mn(si),ii={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},ai=Object.values(ii);function ci(e){return oi.includes(e)}function li(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):ci(e.role)||t.push(`Invalid role. Must be one of: ${oi.join(", ")}`),ui(e,t),t}function di(e){const t=[];return["role","description","delegateAllTokens","tokenNames","expiresAt","tokenPermissions"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||ci(e.role)||t.push(`Invalid role. Must be one of: ${oi.join(", ")}`),ui(e,t,!0),t}function ui(e,t,n=!1){const r=t.length;if(ft(t,()=>{Sn(e.description,"description",255)}),t.length>r&&(t[r]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;ft(t,()=>{if(!Array.isArray(e.tokenNames))throw _t("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw _t("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n?.includes("array")?t[e]="tokenNames must be an array":n?.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt&&(!n||null!==e.expiresAt)){const n=t.length;ft(t,()=>{yn(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}function hi(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>Ln))throw _t("pageSize",`number between 1 and ${Ln}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw _t("cursor","non-empty string",typeof e.cursor)}const gi={[si.MODERATOR]:1,[si.TECHNICAL_PRODUCER]:1,[si.MANAGER]:2,[si.OWNER]:3};class pi extends kn{constructor(e,t,n=!1){super(e,n,t)}extractData(e){let t;t="error"in e?e.error:"success"in e&&!e.success;const n={status:200,error:t,data:e.data};return void 0!==e.message&&(n.message=e.message),Lt(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=li(e);if(t.length>0)throw new rt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(W.CREATE,n,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){hi(e),this.logger.debug("Listing API keys",e);const t=Qo(e,Ln),n=await this.http.get(W.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=W.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=di(t);if(n.length>0)throw new rt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const s=W.UPDATE.replace(":id",String(e)),o=await this.http.patch(s,r,this.getJwtHeaders()),i=this.extractData(o);return this.logger.debug("Updated API key",{id:i.id,keyPrefix:i.keyPrefix}),i}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=W.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...oi]}}const mi={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},fi=pn(mi),Ei=An([{field:"id",type:"number"},{field:"userAddress",type:"string"},{field:"bannedBy",type:"string"},{field:"createdAt",type:"string"},{field:"isPermanent",type:"boolean"},{field:"tokenName",type:"string",nullable:!0},{field:"reason",type:"string",nullable:!0},{field:"expiresAt",type:"string",nullable:!0}]),Ai=An([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"},{field:"isPermanent",type:"boolean"}]),Ti=An([{field:"tokenName",type:"string",nullable:!0},{field:"isGlobal",type:"boolean"}]),vi=An([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function Si(e){return null==e||""===e||"string"==typeof e&&(!vn(e)&&e.length<=Bn.BAN_REASON.MAX_LENGTH)}function yi(e){return!!hn(e)||"number"==typeof e&&(e>=$n&&e<=Kn)}function bi(e){if(!dn(e.userAddress))throw Tt("userAddress");if(!Si(e.reason))throw new rt(`reason must be at most ${Bn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!yi(e.durationSeconds))throw new rt(`durationSeconds must be between ${$n} and ${Kn} seconds`,"durationSeconds","OUT_OF_RANGE")}class Ni extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createBan(e){!function(e){fn(e.tokenName,"tokenName",Rn),bi(e)}(e);const t=this.buildEndpoint(M,{tokenName:e.tokenName}),n=ki(e),r=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:Kt(e.tokenName)}}async removeBan(e){!function(e){if(fn(e.tokenName,"tokenName",Rn),!dn(e.userAddress))throw Tt("userAddress")}(e);const t=this.buildEndpoint(P,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,tokenName:Kt(e.tokenName),userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){fn(e.tokenName,"tokenName",Rn),gn(0,void 0,Ln,e.pageSize)}(e);const t=this.buildEndpoint(U,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Ln);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(fn(e.tokenName,"tokenName",Rn),!dn(e.userAddress))throw Tt("userAddress")}(e);const t=this.buildEndpoint(F,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Kt(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(fn(e.tokenName,"tokenName",Rn),void 0!==e.type&&!fi(e.type))throw new rt(`type must be one of: ${Object.values(mi).join(", ")}`,"type",nt.INVALID_VALUE)}(e);const t=this.buildEndpoint(B,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){bi(e)}(e);const t=ki(e),n=await this.http.post(G,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!dn(e.userAddress))throw Tt("userAddress")}(e);const t=this.buildEndpoint(H,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){gn(0,void 0,Ln,e.pageSize)}(t);const n=this.buildPaginationParams(t,Ln);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const r=await this.http.get($,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!dn(e.userAddress))throw Tt("userAddress")}(e);const t=this.buildEndpoint(K,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},userAddress:e.userAddress.toLowerCase()}}}function ki(e){const t={userAddress:e.userAddress};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function wi(e){return{maxAcceptableReverseBondingCurveFee:tn(e.maxAcceptableReverseBondingCurveFee)}}class _i extends s.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=tn(t),this.expectedToken=nn(n),this.extraFees=wi(r)}}class Ii extends s.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=nn(t),this.expectedNativeToken=tn(n),this.extraFees=wi(r)}}class Ci extends s.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=nn(t),this.expectedNativeToken=tn(n),this.extraFees=wi(r)}}class Di extends s.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=tn(t),this.expectedToken=nn(n),this.extraFees=wi(r)}}const Ri={BuyNativeDto:_i,BuyExactDto:Ii,SellExactDto:Ci,SellNativeDto:Di};function Oi(e,t,n){let r;rn(t,0,1,"slippageToleranceFactor");try{r=function(e,t){if(qt(e)||""===e)throw Tt(t);if(a.isBigNumber(e)){if(e.isNaN())throw It(t,"NaN");return e}try{const n=new a(e);if(n.isNaN())throw It(t,e);if(!n.isFinite())throw It(t,e);return n}catch(n){if(n instanceof rt)throw n;throw It(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=r.multipliedBy(t);let o;switch(n){case"buy-native":case"sell-exact":o=r.minus(s);break;case"buy-exact":case"sell-native":o=r.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return uo(o).isLessThan(0)&&(o=uo(0)),ho(o)}function xi(e,t){if(!dn(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);return n}function Li(e,t,n,r){const s=e?.split?.(t)??[],o=void 0!==n?` (${n})`:"";return new rt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${o}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${ut(r)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function Mi(e,t,n){try{const n=xi(e,t),r=n[n.length-1],s=n[n.length-2],o=n[n.length-3],i=n.slice(0,n.length-3).join(t);if(void 0===i||void 0===o||void 0===s||void 0===r||""===r||""===i||""===o||""===s)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:o,type:s,additionalKey:r}}catch(r){throw Li(e,t,n,r)}}function Ui(e){return function(e,t,n){try{const n=xi(e,t),[r,s,o,...i]=n;if(""===r||""===s||""===o)throw new Error("Collection, category, and type must be non-empty");const a=i.join(t);if(void 0===r||void 0===s||void 0===o||""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:s,type:o,additionalKey:a}}catch(r){throw Li(e,t,n,r)}}(e,"|","pipe-delimited token")}class Fi extends Error{constructor(e,t,n={}){super(e),this.name="LaunchpadSDKError",this.code=t,this.status=n.status,this.chainMessage=n.chainMessage,this.details=n.details}}const Pi={name:"GalaChain"},Bi={name:"ethereum",chainId:1};function Gi(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function $i(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=Ki(r));return t}function Ki(e){return Array.isArray(e)?e.map(Ki):"object"==typeof e&&null!==e?$i(e):e}function Hi(e,t,n,r){return{...e,signature:t,types:n,domain:r}}class Wi extends t.PrivateKeySigner{constructor(t){super(t),this.typedDataWallet=new e.Wallet(t),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,n){const r=$i(n),s=t.generateEIP712Types(e,r);return Hi(r,await this.typedDataWallet.signTypedData(Pi,s,r),s,Pi)}}class Vi extends t.GalaWalletSigner{constructor(e,n={}){const{verifyActiveAccount:r,...s}=n;if(super(e,s),this.typedDataWallet=n.wallet,!0===r){const e=t.ethereumAddressOfAccount(this.walletAddress)??(void 0===this.selectAddress?void 0:t.ethereumAddressOfAccount(this.selectAddress));if(void 0===e)throw new Fi("verifyActiveAccount needs the Ethereum account of the key (walletAddress or selectAddress as 0x... / eth|...); a client| alias names no key.","INVALID_SIGNER_OPTIONS",{details:{walletAddress:this.walletAddress,selectAddress:this.selectAddress}});this.verifiedKey=e}else this.verifiedKey=void 0}async signTypedData(e,n){const r=$i(n),s=t.generateEIP712Types(e,r),o={domain:Bi,types:s,message:r,Primary_type:e},i=this.typedDataWallet??function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();void 0!==this.verifiedKey&&await async function(e,n){let r="address"in e&&"string"==typeof e.address&&""!==e.address?e.address:void 0;if(void 0===r){const t=await e.request({method:"eth_accounts"}),n=Array.isArray(t)?t[0]:void 0;r="string"==typeof n&&""!==n?n:void 0}const s=void 0===r?void 0:t.ethereumAddressOfAccount(r);if(void 0===s||s.toLowerCase()!==n.toLowerCase())throw new Fi("Your wallet's active account has changed. Please switch back to the connected account or reconnect your wallet.","WALLET_ACCOUNT_CHANGED",{details:{walletAccount:r??null,signerAccount:n}})}(i,this.verifiedKey);const a=await this.typedDataAccount(i);return Hi(r,Gi(await t.withGalaWalletIdentity(i,this.selectAddress??a,()=>i.request({method:"eth_signTypedData",params:[JSON.stringify(o),a]}))),s,Bi)}async typedDataAccount(t){if(e.isAddress(this.walletAddress))return this.walletAddress;const n=await t.request({method:"eth_accounts"}),r=Array.isArray(n)?n[0]:void 0,s="string"==typeof r?r.replace(/^eth\|/,"0x"):"";if(!e.isAddress(s))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return s}}class ji extends t.BrowserWalletSigner{constructor(e,t,n){super(e,t,n),this.typedDataProvider=e}async signTypedData(n,r){const s=$i(r),o=this.typedDataProvider,i=await o.getNetwork(),a={name:i.name,chainId:Number(i.chainId)},c=t.generateEIP712Types(n,s),l=await o.getSigner(),d=e.getAddress(await l.getAddress());if(e.isAddress(this.walletAddress)&&d!==e.getAddress(this.walletAddress))throw new Fi(`Wallet account ${d} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:d,signerAccount:this.walletAddress}});return Hi(s,Gi(await l.signTypedData(a,c,s)),c,a)}static fromEip1193(n,r,s){const o=new e.BrowserProvider(n);return new ji({request:e=>n.request(e),getNetwork:()=>o.getNetwork(),getSigner:()=>o.getSigner()},t.ethereumAddressOfAccount(r)??r,s)}}function qi(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const r=n.split("$"),s=r[r.length-1],o=r.slice(0,-1),i=o.slice(0,-3).join("$"),[a,c,l]=o.slice(-3);if("launchpad"!==s||o.length<4||""===i||void 0===a||void 0===c||void 0===l||""===a||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:i,category:a,type:c,additionalKey:l}}function zi(e){const{collection:t,category:n,type:r}=qi(e),s=`${t}$${n}$${r}$none`,o="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${o}$${e}`,`$tokenBalance$${o}$${e}`]}function Yi(e){const t=`${e.tokenName}$Unit$none$none`,n=`$service$${t}$launchpad`;return Number(e.preBuyQuantity??"0")>0?[n,`$token$${t}$${n}`,`$tokenBalance$${t}$${n}`,`$tokenBalance$${t}$${n}`,`$tokenBalance$GALA$Unit$none$none$${n}`,`$tokenBalance$GALA$Unit$none$none$${n}`]:[n,`token$${t}$${n}`,`tokenBalance$${t}$${n}`]}function Xi(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Qi(e){if("string"==typeof e){if(!dn(n=e)||!n.includes("|"))throw new rt(`Invalid tokenId string format: "${e}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const t=e.split("|");if(t.length>=5){const e=Ui(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...Ui(e),instance:"0"}}var n;if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!t.isTokenClassKey(e))throw new rt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!t.isTokenClassKey(e))throw new rt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new rt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Ji(e){return function(e){try{if(!dn(e))throw new Error("Vault address must be a non-empty string");const t=e.split("|")[1];if(""===t||void 0===t)throw new Error("Missing token part after service prefix");const n=t.split("$");return Mi((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new rt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${ut(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Zi(e){return{...Ji(e),instance:"0"}}function ea(e){const t=Ji(e);if("Token"!==t.collection)throw new rt(`Cannot extract a token symbol from vault address "${e}": collection "${t.collection}" is not the launchpad "Token" collection, and a symbol cannot be derived from a class key.`,"vaultAddress","SYMBOL_NOT_DERIVABLE_FROM_KEY");return t.type}var ta,na,ra,sa,oa=Object.freeze({__proto__:null,extractTokenSymbolFromVault:ea,normalizeToTokenInstanceKey:Qi,parseVaultAddressToTokenClassKey:Ji,parseVaultAddressToTokenInstance:Zi});class ia extends wn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=zi(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=ut(e);throw new rt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}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(!dn(e))throw Tt("vaultAddress","Vault address");try{const t=ea(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof rt)throw vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!dn(e))throw Tt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw vt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw vt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!dn(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],r=t[2];return void 0===n||void 0===r?null:{tokenSymbol:n,creatorAddress:r.toLowerCase()}}(e);if(!t)throw vt("vaultAddress","valid vault address format (service|Token$Unit$SYMBOL$eth:address$launchpad)");const n=t.tokenSymbol;if(""===n||!/^[A-Za-z]{1,10}$/.test(n))throw vt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return Mi(e,"$","dollar-delimited token")}catch(e){if(e instanceof rt)throw vt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function aa(e){return"object"==typeof e&&null!==e?e:void 0}class ca extends kn{constructor(e,t,n=!1,r,s,o=.05,i=.01,a){if(super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=s,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=i,this.sellFeeCeiling=a,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=aa(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new Wi(t):function(e){const t=aa(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new ji(this._walletProvider,this.userAddress)),this.tokenKeyService=new ia(n)}}async submitTransaction(e){try{this.validateBundleData(e),this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)});const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});let n=null;try{n=await Pt(()=>this.http.post(this.bundleEndpoint,t),{errorContext:"Bundle transaction submission failed",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==n?{success:!1,error:"No response from bundle API"}:(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:xt(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof rt)return{success:!1,error:ut(e)};throw e}}validateBundleData(e){if(null==e)throw Tt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Tt("signedDto","Signed DTO");if(!dn(e.method))throw Tt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw vt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new rt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw vt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!dn(e))throw new rt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new rt(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT");var n}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){const t=Mt(e);if(null!=t&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",t),{success:!0,data:t};const n=("string"==typeof e.error?e.error:e.message)??"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",n),{success:!1,error:n}}formatErrorMessage(e){if("string"==typeof e)return e;if(pt(e)&&null!==e.response&&void 0!==e.response){const t=Mt(e.response);if(null!=t&&"object"==typeof t){const e=t;if(null!==e.error&&void 0!==e.error)return"string"==typeof e.error?e.error:JSON.stringify(e.error);if(null!==e.message&&void 0!==e.message)return"string"==typeof e.message?e.message:JSON.stringify(e.message)}}return ut(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!dn(e))throw Tt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Pt(()=>this.http.get(`${this.bundleEndpoint}?id=${e}`),{errorContext:"Failed to get bundler transaction result",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from bundler transaction query"}:(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t})}catch(e){if(e instanceof rt)return{success:!1,error:ut(e)};throw e}}async cancelTransaction(e){try{if(!dn(e))throw Tt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Pt(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from transaction cancellation"}:(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t})}catch(e){if(e instanceof rt)return{success:!1,error:ut(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Pt(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==s||""===s)throw new rt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Oi(s,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:o,adjustedMinTokens:e});const t=new Ri.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==s||""===s)throw new rt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Oi(s,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:o,adjustedMaxGalaCost:e});const t=new Ri.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:s}=e,{effectiveSlippageFactor:o,effectiveMaxFee:i,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,a):i;if("exact"===r){if(null==s||""===s)throw new rt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Oi(s,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:o,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Ri.SellExactDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellExactToken",a)}{if(null==s||""===s)throw new rt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Oi(s,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:o,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},r=new Ri.SellNativeDto(a,n,e,t);return await this.executeBundleTransaction(r,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:s,effectiveMaxFee:o}=this.calculateEffectiveSlippage(t,n,r),i=await this.resolveTokenNameToVault(e);if(null==i)throw At(e);return{effectiveSlippageFactor:s,effectiveMaxFee:o,vaultAddress:i}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw yt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let o=e??"0";return null!=e&&(o=Oi(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:o})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:s,effectiveMaxFee:o}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw yt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Tt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${o.v4().replace(/-/gu,"").substring(0,26)}`;const r=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:s,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(r)});const a=await this.submitTransaction(i);if(a.success){const e=Mt(a);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const c=a.error;throw new lt("string"==typeof c?c:"Bundle transaction failed",void 0,"BUNDLE_FAILED")}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}class la extends kn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(Xe),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}exports.ContentType=void 0,(ta=exports.ContentType||(exports.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",ta.COMMENT="COMMENT",ta.STREAM="STREAM",ta.RECORDING="RECORDING",exports.FlagReason=void 0,(na=exports.FlagReason||(exports.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",na.SPAM="SPAM",na.HARASSMENT="HARASSMENT",na.SCAM="SCAM",na.OTHER="OTHER",exports.FlagStatus=void 0,(ra=exports.FlagStatus||(exports.FlagStatus={})).PENDING="PENDING",ra.DISMISSED="DISMISSED",ra.ACTIONED="ACTIONED",exports.FlagAction=void 0,(sa=exports.FlagAction||(exports.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",sa.BAN_USER="BAN_USER",sa.DELETE_AND_BAN="DELETE_AND_BAN";const da={[exports.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[exports.FlagReason.SPAM]:"Spam",[exports.FlagReason.HARASSMENT]:"Harassment",[exports.FlagReason.SCAM]:"Scam",[exports.FlagReason.OTHER]:"Other"},ua={[exports.FlagStatus.PENDING]:"Pending",[exports.FlagStatus.DISMISSED]:"Dismissed",[exports.FlagStatus.ACTIONED]:"Actioned"},ha={[exports.FlagAction.DELETE_CONTENT]:"Delete Content",[exports.FlagAction.BAN_USER]:"Ban User",[exports.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},ga={[exports.ContentType.CHAT_MESSAGE]:"Chat Message",[exports.ContentType.COMMENT]:"Comment",[exports.ContentType.STREAM]:"Stream",[exports.ContentType.RECORDING]:"Recording"},pa=pn(exports.ContentType),ma=pn(exports.FlagReason),fa=pn(exports.FlagStatus),Ea=pn(exports.FlagAction),Aa=An([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:pa},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:fa}]),Ta={TOKEN_NAME:Cn,TOKEN_NAME_FILTER:Dn,CONTENT_ID:Bn.CONTENT_ID,DETAILS:Bn.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:Ln}};function va(e,t,n="tokenName"){fn(e,n,t)}function Sa(e){if(void 0!==e.contentType&&!pa(e.contentType))throw vt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!fa(e.status))throw vt("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!ma(e.reason))throw vt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!dn(e.reporterAddress))throw _t("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&sr(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!dn(e.reportedUserAddress))throw _t("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&sr(e.reportedUserAddress,"reportedUserAddress"),gn(0,void 0,Ta.PAGINATION.MAX_LIMIT,e.pageSize)}class ya extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async createFlag(e){!function(e){if(va(e.tokenName,Ta.TOKEN_NAME),void 0===e.contentType)throw Tt("contentType","Content type");if(!pa(e.contentType))throw vt("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(!dn(e.contentId))throw Tt("contentId","Content ID");if(e.contentId.length>Ta.CONTENT_ID.MAX_LENGTH)throw wt("contentId",Ta.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!dn(e.reportedUserAddress))throw Tt("reportedUserAddress","Reported user address");if(sr(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==exports.ContentType.STREAM&&e.contentType!==exports.ContentType.RECORDING||void 0!==e.reason&&null!==e.reason))throw Tt("reason","Reason");if(void 0!==e.reason&&!ma(e.reason))throw vt("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`,"Reason");if(void 0!==e.details&&!dn(e.details))throw _t("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Ta.DETAILS.MAX_LENGTH)throw wt("details",Ta.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};null!==e.reason&&void 0!==e.reason&&(t.reason=e.reason),null!==e.details&&void 0!==e.details&&(t.details=e.details);const n=await this.http.post(Z.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){va(e.tokenName,Ta.TOKEN_NAME_FILTER),Sa(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&va(e.tokenName,Ta.TOKEN_NAME_FILTER),Sa(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Tt("flagId","Flag ID");try{on(e.flagId,"flagId")}catch{throw vt("flagId","a positive integer","Flag ID")}}(e);const t=Z.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Tt("flagId","Flag ID");try{on(e.flagId,"flagId")}catch{throw vt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Tt("action","Action");if(!Ea(e.action))throw vt("action",`one of: ${Object.values(exports.FlagAction).join(", ")}`,"Action")}(e);const t=Z.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async fetchFlagList(e){const t=Qo(e,Ln);ei(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(Z.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}}const ba=["heart","fire","laugh","wow","thumbs_up"];class Na extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateMessageId(e){if(!dn(e))throw Tt("messageId","Message ID");if(sn(e,Gn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Gn.CONTENT_REACTION.PATTERN.test(e))throw vt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!dn(e))throw Tt("reactionType","Reaction type");if(!ba.includes(e))throw vt("reactionType",`one of: ${ba.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=we,n={messageId:e.messageId,reactionType:e.reactionType},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r),{created:o,...i}=s;return{data:i,created:o}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${_e}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}const ka="Token name is required and must be a string";const wa="GALA|Unit|none|none";class _a extends wn{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!dn(e))throw new rt(ka,"tokenName",nt.REQUIRED);let r;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(r=Xi(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${ut(t)}`)}if(void 0!==r)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(r);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),r=await this.fetchMarketUsdPrice(wa),s=Qt(n.amount,0)/1e18;if(s<=0)throw new rt(`Invalid token amount calculation: ${s}`,"amount","INVALID_CALCULATION");return{symbol:Ht(e),price:r.price/s}}catch(t){throw St(`Failed to calculate launchpad token spot price for ${e}: ${ut(t)}`,void 0,dt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===wa)return"GALA";const t=this.cache?.getByTokenId(e);if(null!=t?.symbol&&""!==t.symbol)return t.symbol;let n;this.logger.debug(`Symbol cache miss for ${e}, reading the token class`);try{if(void 0===this.fetchTokenDetails)throw St("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw St(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${ut(t)}`)}if(""===n)throw St(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!dn(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}(e);if(this.logger.debug(`Fetching swap backend price for token: ${t}`),void 0===this.dexBackendHttp)throw St("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),r=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),s=null!==r&&"object"==typeof r?r:{},o=Object.keys(s).find(e=>e.toUpperCase()===n.toUpperCase()),i=void 0!==o?s[o]:1===Object.keys(s).length?Object.values(s)[0]:void 0,a=i?.price;if("number"!=typeof a||!Number.isFinite(a))throw new rt(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${a}`),{symbol:n,price:a}}catch(e){if(e instanceof rt)throw e;throw St(`Failed to fetch DEX spot price: ${ut(e)}`)}}}const Ia={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1};class Ca{constructor(e,t={}){this.eventBuffer=[],this.flushTimer=null,this.isShuttingDown=!1,this.totalQueued=0,this.totalFlushed=0,this.totalDropped=0,this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.eventBuffer.length>0&&this.flushWithBeacon()},this.handleBeforeUnload=()=>{this.eventBuffer.length>0&&this.flushWithBeacon()},this.httpClient=e,this.logger=new Vt({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??Ia.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??Ia.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??Ia.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??Ia.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??Ia.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??Ia.DEBUG},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const r={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:n.userAddress},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}const Da=["createdAt","eventType","userAddress"],Ra=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],Oa=["sdk","frontend","backend","mcp"];function xa(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function La(e){return"number"==typeof e&&Number.isFinite(e)}function Ma(e){return xa(e)&&La(e.id)&&"string"==typeof e.eventType&&xa(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function Ua(e,t,n){if(!t.some(t=>t===e))throw new rt(`${n} must be one of: ${t.join(", ")}`,n,nt.INVALID_VALUE)}class Fa extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getEventStats(){return function(e){if(!(xa(e)&&La(e.totalEvents)&&La(e.todayEvents)&&La(e.uniqueUsers)&&La(e.uniqueTokens)&&xa(e.eventsByType)))throw St("Malformed event statistics response");const t={};for(const[n,r]of Object.entries(e.eventsByType)){if(!La(r))throw St("Malformed event statistics response");t[n]=r}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(Fe,void 0,this.getDualAuthHeaders()))}async queryEvents(e={}){!function(e){if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))throw new rt("limit must be an integer from 1 to 100","limit",nt.INVALID_VALUE);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new rt("page must be a positive integer","page",nt.INVALID_VALUE);void 0!==e.sortBy&&Ua(e.sortBy,Da,"sortBy"),void 0!==e.sortOrder&&Ua(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&Ua(e.timePreset,Ra,"timePreset"),void 0!==e.source&&Ua(e.source,Oa,"source")}(e);const t={},n=new URLSearchParams;for(const[r,s]of Object.entries(e))if(void 0!==s&&("string"!=typeof s||""!==s)){if(Array.isArray(s)){const e=s.map(String);if(0===e.length)continue;for(const t of 1===e.length?[...e,...e]:e)n.append(r,t);continue}t[r]=s}const r=n.toString(),s=""===r?Ue:`${Ue}?${r}`;return function(e){if(!xa(e)||!Array.isArray(e.data)||!xa(e.pagination))throw St("Malformed events response");const t=e.pagination,n=e.data;if(!(La(t.page)&&La(t.limit)&&La(t.total)&&La(t.totalPages)&&n.every(Ma)))throw St("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(s,t,this.getDualAuthHeaders()))}}function Pa(e){let t;return{requestor:async(n,r)=>{const s="string"==typeof r?.body?JSON.parse(r.body):void 0,{data:o,status:i,headers:a}=await e(n,s);t=o;const c=void 0===o?"":JSON.stringify(o),l="number"==typeof i?i:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(o),text:()=>Promise.resolve(c),headers:a??{}}},answer:()=>t}}const Ba=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class Ga extends kn{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,n=!1){try{const{requestor:r}=Pa(async(e,t)=>({data:await this.http.post(e,t)})),s=new t.GatewayReads({gatewayBaseUrl:"",httpRequestor:r,requestTimeoutMs:1/0}),{owner:o,collection:i,category:a,type:c,additionalKey:l}=e,d=await s.fetchTokenBalance({owner:o,tokenClassKey:{collection:i,category:a,type:c,additionalKey:l},includeExpiredHolds:n});return void 0===d?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,r={quantity:e.quantity,collection:t,category:n,tokenId:Xi(e.tokenClassKey)};return e.inUseHolds.length>0&&(r.inUseHolds=[...e.inUseHolds],r.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(r.lockedHolds=[...e.lockedHolds],r.lockedQuantity=e.lockedQuantity),void 0===r.lockedQuantity&&void 0===r.inUseQuantity||(r.availableQuantity=e.availableQuantity),r}(d)}catch(e){if(t.isGalaError(e)&&Ba.has(e.code))return null;throw St(`Failed to fetch token balance from GalaChain: ${ut(e)}`,void 0,dt(e)?e:void 0)}}}function $a(e){if(null==e||"object"!=typeof e)return!1;const t=e;return dn(t.amount)&&(void 0!==t.tokenId||dn(t.tokenName))&&(void 0===t.lockAuthority||"string"==typeof t.lockAuthority)&&(void 0===t.expires||"number"==typeof t.expires)&&(void 0===t.name||"string"==typeof t.name)}function Ka(e){if(null==e||"object"!=typeof e)return!1;const t=e;return dn(t.amount)&&(void 0!==t.tokenId||dn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function Ha(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every($a)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function Wa(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ka)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var Va,ja;exports.LockErrorType=void 0,(Va=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",Va.INVALID_AMOUNT="INVALID_AMOUNT",Va.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Va.SIGNATURE_FAILED="SIGNATURE_FAILED",Va.NETWORK_ERROR="NETWORK_ERROR",Va.WALLET_REQUIRED="WALLET_REQUIRED",Va.VALIDATION_ERROR="VALIDATION_ERROR",Va.LOCK_NOT_FOUND="LOCK_NOT_FOUND",Va.LOCK_EXPIRED="LOCK_EXPIRED",Va.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",Va.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",Va.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class qa extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="LockError"}}!function(e){e.INVALID_RECIPIENT="INVALID_RECIPIENT",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.DUPLICATE_TRANSFER="DUPLICATE_TRANSFER",e.TRANSFER_LIMIT_EXCEEDED="TRANSFER_LIMIT_EXCEEDED",e.WALLET_REQUIRED="WALLET_REQUIRED"}(ja||(ja={}));class za extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function Ya(e){const t=e?.tokens?.[0];if(void 0===t)return;const n={};return void 0!==t.tokenName&&(n.tokenName=t.tokenName),void 0!==t.amount&&(n.amount=t.amount),Object.keys(n).length>0?n:void 0}async function Xa(e,t,n,r="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=Zi(s);return n.debug(r,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new rt(`Token "${e}" is not a launchpad token (no vault address found), and a token class key cannot be derived from a name. Pass an explicit tokenId (collection|category|type|additionalKey) for standard GalaChain tokens.`,"tokenName","TOKEN_CLASS_KEY_NOT_DERIVABLE")}class Qa extends kn{constructor(e,t,n,r=!1,s){super(e,r),this.wallet=t,this.tokenResolver=n,this.writer=s,this.nativeSigner=t?new Wi(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:Jn(this.wallet.address)}:this.writer}}function Ja(e,t){const{collection:n,category:r,type:s,additionalKey:o,instance:i}=e;return{tokenClassKey:{collection:n,category:r,type:s,additionalKey:o},instance:i,quantity:t}}const Za=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function ec(e,{signer:n,walletAddress:r}){const{requestor:s,answer:o}=Pa((t,n)=>e.postWithMeta(t,n));return{writes:new t.GatewayWrites({gatewayBaseUrl:"",signer:n,walletAddress:r,httpRequestor:s,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:o}}async function tc(e,n,r){let s;try{s=await n(e.writes)}catch(n){throw function(e){return t.isGalaError(e)&&Za.has(e.code)}(n)&&r(e.answer(),void 0),n}return r(e.answer(),s)}function nc(e){return void 0===e||""===e?{}:{uniqueKey:e}}const rc=100,sc=100;class oc extends Qa{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new qa("Wallet required for token lock operations",exports.LockErrorType.WALLET_REQUIRED);return Mo(async()=>{const n=ec(this.http,t),r=n.writes.walletAddress,s=[],o=[];let i=r;const a=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==a?.lockAuthority&&(i=Jn(a.lockAuthority));const c=e.tokens.find(e=>void 0!==e.expires),l=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);o.push(Ja(e,t.amount)),s.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount,lockAuthority:void 0!==t.lockAuthority?Jn(t.lockAuthority):i})}return tc(n,t=>t.lockTokens({tokens:o,lockAuthority:i,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...nc(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token lock failed"),this.extractLockResult(e,t,s)))},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){this.validateUnlockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new qa("Wallet required for token unlock operations",exports.LockErrorType.WALLET_REQUIRED);return Mo(async()=>{const n=[],r=[],s=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);r.push(Ja(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return tc(ec(this.http,t),t=>t.unlockTokens({tokens:r,...void 0!==s?.name&&{name:s.name},...nc(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token unlock failed"),this.extractUnlockResult(e,t,n)))},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}assertLockAnswer(e,t){try{mt(e,t)}catch(t){const n=function(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}(e);throw new qa(`${ut(t)}${n}`,exports.LockErrorType.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new qa("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{En(e.tokenName,"tokenName",Rn)}catch{throw new qa("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{fo(uo(e.amount))}catch{throw new qa(vt(t,"a positive number",n).message,exports.LockErrorType.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!Ha(e))throw new qa("Invalid lock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>rc)throw new qa(`Batch size exceeds maximum limit of ${rc} tokens per lock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!tr(t.lockAuthority))throw new qa("Invalid lock authority address format",exports.LockErrorType.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{on(t.expires,"expires")}catch{throw new qa(vt("expires","a positive integer (epoch milliseconds)","Expires").message,exports.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!Wa(e))throw new qa("Invalid unlock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>sc)throw new qa(`Batch size exceeds maximum limit of ${sc} tokens per unlock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},locked:n}}extractUnlockResult(e,t,n){const r=this.transactionIdOf(e,t),s=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==s&&{blockNumber:s},unlocked:n}}handleLockError(e,n,r){if(e instanceof qa)return e;if(t.isGalaError(e)&&"pre_send"===e.phase)return new qa(`${n}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?exports.LockErrorType.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?exports.LockErrorType.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?exports.LockErrorType.INVALID_AMOUNT:exports.LockErrorType.VALIDATION_ERROR,Ya(r));var s;let o=n,i=exports.LockErrorType.NETWORK_ERROR;if(pt(e)){const t=e.response?.data;if("object"==typeof t&&null!==t){const e=t.Message;"string"==typeof e&&e.length>0&&(o=`${n}: ${e}`);const r="string"==typeof e?e.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?i=exports.LockErrorType.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?i=exports.LockErrorType.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?i=exports.LockErrorType.TOKEN_NOT_FOUND:r.includes("authority")?i=exports.LockErrorType.NOT_LOCK_AUTHORITY:r.includes("expired")&&(i=exports.LockErrorType.LOCK_EXPIRED)}}else dt(e)&&(o=`${n}: ${ut(e)}`);return new qa(o,i,Ya(r))}async resolveTokenInstance(e){return Mo(async()=>Xa(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof za)throw new qa(ut(t),exports.LockErrorType.TOKEN_NOT_FOUND);throw new qa(`Failed to resolve token '${e}': ${ut(t)}`,exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Qi(e.tokenId);return this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),t}if(void 0!==e.tokenName)return this.resolveTokenInstance(e.tokenName);throw new qa("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND)}}const ic=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function ac(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class cc extends kn{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Qi(e):e,{collection:n,category:r,type:s,additionalKey:o}=t,i={collection:n,category:r,type:s,additionalKey:o},a="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(i),e=>{if(mt(e,a),void 0===ac(e)?.[0])throw St(`Token not found on GalaChain: ${Xi(i)}`,404)},()=>St(`Token not found on GalaChain: ${Xi(i)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw Tt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(mt(e,"Failed to fetch token classes with supply from GalaChain"),0===(ac(e)?.length??0))throw St("No token supply data found for requested token classes",404)},void 0)}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}async readPublic(e,n,r){if(!this.publicAxios)throw Tt("publicAxios","Public Axios instance");const s=this.publicAxios,{requestor:o,answer:i}=Pa(async(e,t)=>{const n=await s.post(e,t);return{data:n.data,status:n.status}});try{return await e(new t.GatewayReads({gatewayBaseUrl:"",httpRequestor:o,requestTimeoutMs:1/0}))}catch(e){if(t.isGalaError(e)&&ic.has(e.code)&&(n(i()),"TOKEN_CLASS_NOT_FOUND"===e.code&&void 0!==r))throw r();throw e}}handleTokenServiceError(e,t,n){if(e instanceof rt)throw e;if(pt(e)&&404===e.response?.status)throw St(t,404,dt(e)?e:void 0);if(dt(e)&&"Error"===e.name&&ut(e).includes("status indicates failure"))throw St(ut(e),400,dt(e)?e:void 0);const r=ut(e);if(r.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(r)}throw St(`${n}: ${r}`,void 0,dt(e)?e:void 0)}}function lc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return dn(t.amount)&&(void 0!==t.tokenId||dn(t.tokenName))}function dc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(lc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var uc;exports.BurnErrorType=void 0,(uc=exports.BurnErrorType||(exports.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",uc.INVALID_AMOUNT="INVALID_AMOUNT",uc.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",uc.SIGNATURE_FAILED="SIGNATURE_FAILED",uc.NETWORK_ERROR="NETWORK_ERROR",uc.WALLET_REQUIRED="WALLET_REQUIRED",uc.VALIDATION_ERROR="VALIDATION_ERROR";class hc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const gc={validateAmount(e){const t=uo(e);try{Eo(t,"amount")}catch(t){throw new za(t.message,ja.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!hn(e)&&dn(e)){if(e.length>Hn.MAX_LENGTH)throw new rt(`Unique key too long. Maximum length: ${Hn.MAX_LENGTH}`);if(!Hn.PATTERN.test(e))throw new za('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',ja.INVALID_AMOUNT,{uniqueKey:e})}}},pc="gala-transfer-successful",mc="token-transfer-successful",fc="token-locked-successfully",Ec="token-unlocked-successfully",Ac="transfer-successful-no-id",Tc=50;class vc extends Qa{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new za("Wallet required for GALA transfer operations",ja.WALLET_REQUIRED);try{const n=Jn(e.recipientAddress),r=ec(this.http,t);return await tc(r,t=>t.transferGala({to:n,quantity:e.amount,...nc(e.uniqueKey)}),(e,t)=>this.extractTransferResult(e,t,"gala"))}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){this.validateTransferTokenData(e);const t=this.writeIdentity();if(void 0===t)throw new za("Wallet required for token transfer operations",ja.WALLET_REQUIRED);try{const n=Jn(e.to),r=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new za("Must provide either tokenId or tokenName for token identification",ja.TOKEN_NOT_FOUND)),s=ec(this.http,t);return await tc(s,t=>t.transferToken({to:n,...Ja(r,e.amount),...nc(e.uniqueKey)}),(e,t)=>this.extractTransferResult(e,t,"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}':`,{collection:t.collection,category:t.category,type:t.type}),t}catch(t){if(t instanceof za)throw t;throw new za(`Failed to resolve token class key for '${e}': ${ut(t)}`,ja.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new hc("Wallet required for token burn operations",exports.BurnErrorType.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new hc("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND));n.push(Ja(e,t.amount))}const r=ec(this.http,t);return await tc(r,t=>t.burnTokens({tokens:n,...nc(e.uniqueKey)}),(e,t)=>this.burnResultOf(e,t))}catch(t){throw this.handleBurnError(t,"Token burn failed",e)}}validateTransferGalaData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return dn(t.recipientAddress)&&dn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new rt("Invalid GALA transfer data: missing required fields");if(!tr(e.recipientAddress))throw new za("Invalid recipient address format",ja.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});gc.validateAmount(e.amount),gc.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return dn(t.to)&&dn(t.amount)&&(void 0!==t.tokenId||dn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new rt("Invalid token transfer data: missing required fields");if(!tr(e.to))throw new za("Invalid recipient address format",ja.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new za("Must provide either tokenId or tokenName for token identification",ja.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{En(e.tokenName,"tokenName",Rn)}catch{throw new za("Invalid token name format",ja.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}gc.validateAmount(e.amount),gc.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!dc(e))throw new hc("Invalid burn data: missing required fields",exports.BurnErrorType.VALIDATION_ERROR);if(e.tokens.length>Tc)throw new hc(`Batch size exceeds maximum limit of ${Tc} tokens per burn operation`,exports.BurnErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!(null!==t.tokenId&&void 0!==t.tokenId||null!==t.tokenName&&void 0!==t.tokenName))throw new hc("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);const e=uo(t.amount);try{fo(e)}catch{throw new hc("Burn amount must be a positive number",exports.BurnErrorType.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=Qi(e);return this.logger.debug("[DEBUG] Using provided tokenId:",e),t}if(null!=t)return this.resolveTokenInstance(t);throw n()}async resolveTokenInstance(e){try{return await Xa(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof za)throw t;throw new za(`Failed to resolve token '${e}': ${ut(t)}`,ja.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new za("No response from GalaChain transfer service",ja.NETWORK_ERROR);const r=t?.blockNumber,s="object"==typeof e&&"Status"in e;s&&mt(e,"Extract transaction ID");const o=s&&"Data"in e,i=t?.transactionId;if(void 0!==i)return{transactionId:i,...void 0!==r?{blockNumber:r}:{}};if(o){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==r?{blockNumber:r}:{}}}}let e=Ac;if(t.Data.length>0)switch(n){case"gala":e=pc;break;case"token":e=mc;break;case"lock":e=fc;break;case"unlock":e=Ec}return{transactionId:e,...void 0!==r?{blockNumber:r}:{}}}}throw new za("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",ja.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new hc("No response from GalaChain burn service",exports.BurnErrorType.NETWORK_ERROR);try{mt(e,"Token burn operation")}catch(e){throw new at(ut(e),500)}return this.extractBurnResult(e,t)}extractBurnResult(e,t){const n=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const t of e.Data)n.push({collection:t.collection??"",category:t.category??"",type:t.type??"",additionalKey:t.additionalKey??"",instance:t.instance??"0",quantity:t.quantity??"0",burnedBy:t.burnedBy??""});const r=Array.isArray(e.Data)?e.Data[0]:void 0,s=t?.transactionId??r?.transactionId??r?.txnId??r?.TxnId??r?.id??void 0,o=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==o&&{blockNumber:o},burned:n}}handleTransferError(e,n,r){if(e instanceof za)return e;if(e instanceof rt)return new za(ut(e),ja.INVALID_AMOUNT);if(t.isGalaError(e)&&"pre_send"===e.phase)return new za(e.message,"SIGNING_FAILED"===(s=e.code)?ja.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===s?ja.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===s?ja.TOKEN_NOT_FOUND:ja.INVALID_AMOUNT);var s;if(pt(e)&&e.response){const t=e.response.status,n=e.response.data;if(400===t){const e=n?.message;return new za(("string"==typeof e?e:void 0)??"Invalid transfer request",ja.INVALID_AMOUNT)}if(403===t)return new za("Insufficient balance for transfer",ja.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in r&&(e.tokenName=r.tokenName),new za("Token not found",ja.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===gt(e)||"ETIMEDOUT"===gt(e)))return new za("Transfer request timed out",ja.NETWORK_ERROR);const o=""!==ut(e)?ut(e):n;return new za(o,ja.NETWORK_ERROR)}handleBurnError(e,n,r){if(e instanceof hc)return e;if(t.isGalaError(e)&&"pre_send"===e.phase)return new hc(`${n}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?exports.BurnErrorType.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?exports.BurnErrorType.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?exports.BurnErrorType.INVALID_AMOUNT:exports.BurnErrorType.VALIDATION_ERROR,Ya(r));var s;let o=n,i=exports.BurnErrorType.NETWORK_ERROR;if(pt(e)){const t=e.response?.data;if("object"==typeof t){const e=t.Message;if("string"==typeof e&&e.length>0){o=`${n}: ${e}`;const t=e.toLowerCase();t.includes("insufficient")||t.includes("balance")?i=exports.BurnErrorType.INSUFFICIENT_BALANCE:(t.includes("not found")||t.includes("token"))&&(i=exports.BurnErrorType.TOKEN_NOT_FOUND)}}}else dt(e)&&(o=`${n}: ${ut(e)}`);return new hc(o,i,Ya(r))}}class Sc extends kn{constructor(e,t,n,r=!1,s,o){super(e,r),this.balanceService=new Ga(e,r),this.tokenService=new cc(e,r,s),this.lockService=new oc(e,t,n,r,o),this.transferService=new vc(e,t,n,r,o)}async fetchGalaBalance(e){return this.balanceService.fetchGalaBalance(e)}async fetchTokenBalance(e,t=!1){return this.balanceService.fetchTokenBalance(e,t)}async fetchTokenClassFromChain(e){return this.tokenService.fetchTokenClassFromChain(e)}async fetchTokenDetails(e){try{return t.tokenDetailsOf(await this.fetchTokenClassFromChain(e))}catch(t){if(dt(t)&&("NetworkError"===t.name||ut(t).includes("Token not found")))throw t;throw St(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:Xi(e)}: ${ut(t)}`,500)}}async fetchTokenClassesWithSupply(e){return this.tokenService.fetchTokenClassesWithSupply(e)}async transferGala(e){return this.transferService.transferGala(e)}async transferToken(e){return this.transferService.transferToken(e)}async resolveTokenClassKey(e){return this.transferService.resolveTokenClassKey(e)}async lockTokens(e){return this.lockService.lockTokens(e)}async unlockTokens(e){return this.lockService.unlockTokens(e)}async burnTokens(e){return this.transferService.burnTokens(e)}}class yc extends kn{async getHealth(){const e=(await this.http.get(Pe)).data;if(null==e)throw St("Health check answered no data");return e}}class bc extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Nc(e,t,n){if(null==e)throw new bc("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Br.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new bc(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new bc("Filename is required when uploading Buffer objects",t,n);const r=Gr.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new bc(e,t,n)}try{sn(t,255,"filename")}catch(e){throw new bc(e.message,t,n)}const s=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!s.includes(n))throw new bc(`Invalid file type "${n}" is not allowed. Allowed types: ${s.join(", ")}`,t,n);const o=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),i=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!i.includes(o))throw new bc(`File extension "${o}" is not allowed. Allowed extensions: ${i.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(o);if(a!==n&&"application/octet-stream"!==a)throw new bc(`File extension "${o}" does not match MIME type "${n}"`,t,n);return}throw new bc("File must be a File object (browser) or Buffer (Node.js)",t,n)}function kc(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw vt("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});r.append(t,s,n)}}return r}class wc extends kn{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;fn(t,"tokenName",Rn);const r=`${t}.png`;Nc(n.file,r,"image/png");try{const e=kc(n.file,"image",r),s=await Ft(()=>this.http.request({method:"POST",url:Zo(l.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof ct)throw e;if(dt(e)&&ut(e).includes("FormData"))throw yt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function _c(e){if(!!(void 0===e.chatEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl))throw new rt("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",nt.REQUIRED);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw _t("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw _t("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw _t("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw _t("streamLanguage","string");const t=["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"];for(const n of t){const t=e[n];if(null!=t&&"string"!=typeof t)throw _t(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw _t("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new rt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",nt.INVALID_FORMAT)}}function Ic(e){if(hn(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))hn(r)||(dn(r)?t[n]=r:"number"==typeof r||"boolean"==typeof r?t[n]=r.toString():Array.isArray(r)?t[n]=r.join(","):t[n]="object"==typeof r?JSON.stringify(r):String(r));return t}var Cc=Object.freeze({__proto__:null,adaptQueryParams:Ic});function Dc(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Rc(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Oc(e){return"string"==typeof e.quantity&&""!==e.quantity}class xc extends kn{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??Vo.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>et)throw Nt("pageSize",1,et,t);const n={pageSize:String(t)};dn(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=Fc("type",e.type,Je));dn(e.tokenName)&&(fn(e.tokenName,"tokenName",Cn),n.tokenName=e.tokenName);if(dn(e.search)){if(e.search.length>Lc)throw Rt("search",Lc,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(dn(e.language)){if(!Uc.test(e.language))throw vt("language",'an ISO 639-1 code such as "en" or "zh-CN"');n.language=e.language}if(void 0!==e.recentlyStreamed){const t=e.recentlyStreamed;if(!Number.isInteger(t)||t<1||t>Mc)throw Nt("recentlyStreamed",1,Mc,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=Fc("streamStatus",e.streamStatus,Ze));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw _t("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw _t("creatorAddress","string",e);sr(e,"creatorAddress");const t=e.toLowerCase().trim();if(t.startsWith("eth|")||t.startsWith("client|"))return t.replace(/0x/g,"");const n=t.replace(/^0x/,"");return/^[0-9a-f]{24}$/.test(n)?`client|${n}`:`eth|${n}`}(e.creatorAddress));return n}(e),n=Mt(await Bt(()=>this.http.get(l.FETCH_POOLS,t),{errorContext:"Failed to fetch pools"}));return{items:function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else null!==e.pools&&void 0!==e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at??e.createdAt??""})));return t}(n),pageInfo:zo(n?.pageInfo)}}async fetchAllPools(e){const t=[];let n;for(;;){const r={...e,pageSize:100,...void 0!==n&&{cursor:n}},s=await this.fetchPools(r);if(t.push(...s.items),0===s.items.length)break;const o=Yo(s.pageInfo,n);if(void 0===o)break;n=o}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=Ks(e);!t.success&&t.errors&&bo(t.errors,"options")}(e),dn(e.tokenName)&&fn(e.tokenName,"tokenName",On);try{const t=await this.http.post(l.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===dn(e.symbol)){return!n.symbolAvailable}if(!0===dn(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,r="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||r.includes("404")||r.includes("Pool not found"))return!1;const s="number"==typeof n.statusCode?n.statusCode:null;if(404===s)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||r.includes("400")||r.includes("Missing required pool identifier"))return!1;if(400===s&&r.includes("Missing required pool identifier"))return!1;throw e}}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(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return so(t,"tokenName")&&io(t,"from")&&io(t,"to")&&io(t,"resolution")}(e))throw new rt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:s}=e;if(fn(t,"tokenName",Cn),null==n||null==r||null==s)throw new rt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:n,to:r,resolution:s};ko(o);const i=Ic(o),a=await Ft(()=>this.http.get(l.CHART,i),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(a.data)||"boolean"!=typeof a.isPreviousData)throw new at("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:a.data,isPreviousData:a.isPreviousData,..."number"==typeof a.nextTime&&{nextTime:a.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw Tt("tokenName","Token name");let t;fn(e,"tokenName",Cn);try{t=await Bt(()=>this.http.get(`${l.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(pt(t)&&500===t.response?.status)throw St(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,dt(t)?t:void 0);throw t}return function(e,t,n=ho){if(!Array.isArray(e))throw St("Invalid API response: expected array of holders",t);for(const n of e){if(!Rc(n))throw St("Invalid holder data: missing or invalid owner field",t);if(!Oc(n))throw St("Invalid holder data: missing or invalid quantity field",t);const e=Qt(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw St(`Invalid holder quantity: "${n.quantity}"`,t)}const r=e,s=r.reduce((e,t)=>e.plus(t.quantity),uo(0));return{holders:r.map(e=>({address:e.owner,balance:e.quantity,percentage:Ao(uo(e.quantity),s,uo(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:r.length,lastUpdated:new Date}}(Mt(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Tt("tokenName","Token name");if(""===t||null==t)throw Tt("userAddress","User address");return fn(e,"tokenName",Cn),Ft(()=>this.http.get(`${l.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async resolveTokenNameToVault(e){const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0]?.vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");fn(e,"tokenName",Rn);try{const t=l.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=Mt(await this.http.get(t));if(null!=n?.tokens){const t=Array.isArray(n.tokens)?n.tokens[0]:n.tokens;if(null==t)throw new Error(`Token not found: ${e}`);return t}throw new Error(`Invalid response format when fetching token: ${e}`)}catch(t){const n=String(t);if(n.includes("404")||n.includes("not found"))throw t instanceof at?new at(`Token not found: ${e}`,t.statusCode,t):new Error(`Token not found: ${e}`);throw t}}async validateToken(e){if(!(null!==e.tokenName&&void 0!==e.tokenName||null!==e.symbol&&void 0!==e.symbol))throw new Error("At least one of tokenName or symbol is required");if(null!==e.tokenName&&void 0!==e.tokenName&&("string"!=typeof e.tokenName||""===e.tokenName.trim()))throw new Error("tokenName must be a non-empty string");if(null!==e.symbol&&void 0!==e.symbol&&("string"!=typeof e.symbol||""===e.symbol.trim()))throw new Error("symbol must be a non-empty string");null!==e.tokenName&&void 0!==e.tokenName&&fn(e.tokenName,"tokenName",On);try{const t=await this.http.post(l.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!dn(e))throw Tt("tokenName","Token name");fn(e,"tokenName",Rn);const t=l.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=Mt(await this.http.get(t));if(!function(e){if("object"!=typeof e||null===e)return!1;const t=new Map(Object.entries(e));return["holdersCount","chatMessageCount","commentCount","roomCount"].every(e=>{const n=t.get(e);return"number"==typeof n&&Number.isFinite(n)})}(e))throw new Error("Invalid response: missing stats data");return{success:!0,data:{holdersCount:e.holdersCount,chatMessageCount:e.chatMessageCount,commentCount:e.commentCount,roomCount:e.roomCount}}}catch(t){throw this.logger.warn(`Failed to fetch token stats for ${e}: ${String(t)}`),t}}async updateTokenConfig(e,t){if(""===e||null==e)throw Tt("tokenName","Token name");fn(e,"tokenName",Rn),_c(t);const n=l.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.chatEnabled&&(r.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}async getTokenConfig(e){if(!dn(e))throw Tt("tokenName","Token name");fn(e,"tokenName",Rn);const t=l.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=Mt(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const Lc=255,Mc=720,Uc=/^[a-z]{2}(-[A-Z]{2})?$/u;function Fc(e,t,n){const r="string"==typeof t?t.toUpperCase():void 0,s=n.find(e=>e===r);if(void 0===s)throw Ct(e,t,n);return s}function Pc(e){if(void 0!==e.tokenName){if(!dn(e.tokenName))throw _t("tokenName","a non-empty string",typeof e.tokenName);En(e.tokenName,"tokenName",Cn)}if(void 0!==e.userAddress){if(!dn(e.userAddress))throw _t("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>Pn)throw wt("userAddress",Pn,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw _t("search","a string",typeof e.search);if(e.search.length>256)throw wt("search",256,e.search.length)}if(gn(0,void 0,Un,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw vt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!dn(e.startDate))throw _t("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw vt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!dn(e.endDate))throw _t("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw vt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{rn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw vt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{rn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw vt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const r="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(s))throw _t(n,"numeric values",void 0,n);if(r>s)throw new rt(`Minimum value (${r}) must be less than or equal to maximum value (${s}) for ${n}`,n,nt.INVALID_RANGE)}(e.minAmount,e.maxAmount,"amountRange")}class Bc extends kn{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return so(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&oo(t,"userAddress")&&io(t,"offset")&&io(t,"pageSize")&&io(t,"page")&&io(t,"limit")}(e))throw new rt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:r=Vo.DEFAULT_LIMIT}=e;if(!dn(t))throw Tt("tokenName","Token name");const s={pageSize:String(Math.min(r,Mn))};void 0!==n&&(s.cursor=n);const o=await this.http.get(Zo(l.GET_TRADES,{tokenName:t}),s);if(null==o)throw new rt("No response from trade service","response","NO_RESPONSE");const i=Mt(o),a=Dc(i,"trades"),c=i?.pageInfo;return{items:a,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=Kt(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=e.userAddress),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?jo(e.pageSize,1,Un):Un;return void 0!==e.cursor&&(t.cursor=e.cursor),t.pageSize=String(n),null!==e.txnType&&void 0!==e.txnType&&e.txnType.length>0&&(t.txnType=e.txnType),null!==e.startDate&&void 0!==e.startDate&&e.startDate.length>0&&(t.startDate=e.startDate),null!==e.endDate&&void 0!==e.endDate&&e.endDate.length>0&&(t.endDate=e.endDate),void 0!==e.minAmount&&(t.minAmount=String(e.minAmount)),void 0!==e.maxAmount&&(t.maxAmount=String(e.maxAmount)),t}async getTrades(e){Pc(e);const t=this.buildTradesQueryParams(e);return Ft(()=>this.http.get(Ie,t),{errorContext:"Failed to fetch trades"})}}Rn.MIN_LENGTH,Rn.MAX_LENGTH;function Gc(e){return!!dn(e)&&Fn.PATTERN.test(e)}function $c(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const r=e.trim();return r.length<n?null:r}function Kc(e){if(""===e||"string"!=typeof e)return!1;const t=e.startsWith("0x")?e.slice(2):e;return/^[0-9a-fA-F]{40}$/.test(t)}function Hc(e){return e.startsWith("0x")?e.slice(2):e}pn({BOTH:"both",HELD:"held",CREATED:"created"});function Wc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Vc(e){return"number"==typeof e&&Number.isFinite(e)}function jc(e){return null===e||"string"==typeof e}function qc(e){return Array.isArray(e)&&e.every(e=>Wc(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function zc(e){return Wc(e)&&"string"==typeof e.address&&jc(e.fullName)&&jc(e.profileImage)&&jc(e.bio)&&function(e){return Wc(e)&&Vc(e.tokensCreated)&&Vc(e.tokensGraduated)&&Vc(e.graduationRate)&&Vc(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&jc(e.totalVolumeUsd)&&(null===e.holdingsCount||Vc(e.holdingsCount))&&jc(e.accountCreatedAt)&&Vc(e.accountAgeDays)}(e.stats)&&qc(e.launchBadge)&&qc(e.successBadge)&&qc(e.volumeBadge)&&qc(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&jc(e.liveStreamToken)}class Yc extends kn{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!Gc(t))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await Ft(()=>this.http.get(l.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(Wc(n=e)&&"string"==typeof n.address&&jc(n.fullName)&&jc(n.profileImage)&&"string"==typeof n.bio&&qc(n.launchBadge)&&qc(n.successBadge)))throw St("Malformed profile response");return e}var n;const r=await Ft(()=>this.http.get(l.GET_PROFILE.replace(":address",t)),{errorContext:"Failed to fetch profile"});if(!zc(r))throw St("Malformed profile response");return r}async updateProfile(e){this.validateUpdateProfileData(e);const t={};void 0!==e.fullName&&(t.fullName=e.fullName.trim()),void 0!==e.profileImage&&(t.profileImage=e.profileImage),await Ft(()=>this.http.put(l.UPDATE_PROFILE,t,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);try{const t=void 0===e.address?"profile-image.png":`profile-image-${e.address}.png`,n=kc(e.file,"image",t),r=await Ft(()=>this.http.request({method:"POST",url:l.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof rt||e instanceof ct)throw e;if(e instanceof at)throw new at(`Profile image upload failed: ${ut(e)}`,e.statusCode,e);throw new rt(`Profile image upload failed: ${ut(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new rt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},r="created"===e.type;r&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(l.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:r?"launches":"token",errorMessage:"Failed to fetch token list"});return r&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new rt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new rt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(l.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:s,status:o}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new rt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const i=e?.address??this.http.getAddress();if(null==i||""===i)throw new rt("Wallet address not available - wallet not configured","address","NO_WALLET");const a={type:"created",address:i,pageSize:n??Vo.DEFAULT_LIMIT};return void 0!==t&&(a.cursor=t),void 0!==r&&(a.search=r),void 0!==s&&void 0===r&&(a.search=s),void 0!==s&&(a.tokenName=s),void 0!==o&&(a.status=o),this.fetchTokenList(a)}async getManagedTokens(e={}){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=String(Math.min(e.pageSize,Mn))),Ft(()=>this.http.get(l.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw Tt("address","Address");return Ft(()=>this.http.get(Zo(l.GET_GALA_BALANCE,{address:e.trim()})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return Ft(()=>this.http.get(l.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=Qo({pageSize:t.pageSize??Vo.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},Mn);ei(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type=n.requestType);let s=e;const o=t.address??this.http.getAddress();if(e.includes(":address")){if(0===o.length)throw Tt("address","User address");s=e.replace(":address",o),delete r.address}const i=Mt(await Bt(()=>this.http.get(s,r),{errorContext:n.errorMessage}));return{tokens:Dc(i,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",r="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",i=e.metadata,a={...e};return delete a.metadata,{...a,id:"string"==typeof e.id?e.id:t,name:r,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:o,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==i&&"object"==typeof i?{metadata:i}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),pageInfo:zo(i?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??Vo.DEFAULT_LIMIT;if(t<1||t>Mn)throw new rt(`pageSize must be between 1 and ${Mn}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!Gc(e.address))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=$c(e.search);if(null!==n&&!(dn(r=n)&&r.length>=Vn&&r.length<=jn))throw Nt("search",Vn,jn,n.length,"Search query");var r;const s=$c(e.tokenName);if(!(null===s||dn(o=s)&&Rn.PATTERN.test(o)))throw vt("tokenName",Rn.DESCRIPTION,"Token name");var o}validateUpdateProfileData(e){if(void 0!==e.address&&!Gc(e.address))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new rt("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(dn(t)&&t.length>=qn.FULL_NAME.MIN_LENGTH&&t.length<=qn.FULL_NAME.MAX_LENGTH&&qn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw Nt("fullName",qn.FULL_NAME.MIN_LENGTH,qn.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new rt("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!Gc(e.address))throw vt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class Xc{constructor(e,t,n=!1){this.http=e,this.poolService=new xc(e,t,n),this.tradeService=new Bc(e,n),this.userService=new Yc(e,t,n),this.imageService=new wc(e,t,n)}setJwtAuth(e){this.poolService.setJwtAuth(e),this.userService.setJwtAuth(e),this.imageService.setJwtAuth(e)}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 checkPoolExists(e,t){const n={};return void 0!==e&&(n.tokenName=e),void 0!==t&&(n.symbol=t),this.poolService.checkPool(n)}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 fetchUserHolderContext(e,t){return this.poolService.fetchUserHolderContext(e,t)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async getTrades(e){return this.tradeService.getTrades(e)}async fetchProfile(e){return void 0===e?this.userService.fetchProfile():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 getManagedTokens(e={}){return this.userService.getManagedTokens(e)}async getUserGalaBalance(e){return this.userService.getUserGalaBalance(e)}async fetchReferralCode(){return this.userService.fetchReferralCode()}getAddress(){return this.http.getAddress()}validateTokenName(e){return No(e)}async fetchToken(e){return this.poolService.fetchToken(e)}async validateToken(e){return this.poolService.validateToken(e)}async fetchTokenStats(e){return this.poolService.fetchTokenStats(e)}async updateTokenConfig(e,t){return this.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.poolService.getTokenConfig(e)}}function Qc(e,t){if(void 0!==e){if(!dn(e))throw _t("tokenName","string");En(e,"tokenName",Cn)}if(void 0!==t){if(!dn(t))throw _t("userAddress","string");if(t.length>Pn)throw new rt(`userAddress must be at most ${Pn} characters`,"userAddress",nt.TOO_LONG)}}const Jc={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},Zc={PAGINATION:{MAX_LIMIT:Un},CONTENT:{CHAT_MAX_LENGTH:Bn.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:Bn.COMMENTS_V1.MAX_LENGTH}};function el(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function tl(e){return null===e||"string"==typeof e}function nl(e){return el(e)&&tl(e.fullName)&&tl(e.profileImage)}class rl extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateContent(e,t){if(!dn(e))throw Tt("content","Message content");if(0===e.trim().length)throw Tt("content","Message content");sn(e,t===Jc.CHAT_MESSAGE?Bn.CHAT_MESSAGES_V1.MAX_LENGTH:Bn.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!dn(e))throw Tt("id","Message ID");if(e.length<10||e.length>64)throw vt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==Jc.CHAT_MESSAGE&&e!==Jc.COMMENT)throw new rt(`type must be one of: ${Object.values(Jc).join(", ")}`,"type","INVALID_VALUE")}async fetchMessages(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName;t&&this.validateMessageType(e.type),n&&this.validateTokenName(e.tokenName,Cn);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Vo.DEFAULT_LIMIT;const s=Qo(r,Un),o={};void 0!==s.pageSize&&(o.pageSize=s.pageSize),void 0!==s.cursor&&(o.cursor=s.cursor),t&&(o.type=e.type.toUpperCase()),n&&(o.tokenName=Kt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(o.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(o.search=e.search);const i=await this.http.get(Ce.GET_MESSAGES,o),a=this.extractData(i);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,Cn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:Kt(e.tokenName),content:e.content.trim()},n=await this.http.post(Ce.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content,t.type);const n=this.buildEndpointWithId(Ce.UPDATE_MESSAGE,e),r={content:t.content.trim()},s=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Ce.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Rn);const t=await this.http.get(Ce.GET_PINNED,{tokenName:Kt(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Ce.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Ce.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){return function(e){const t=e=>"number"==typeof e&&Number.isFinite(e),n=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);if(!n(e))throw St("Malformed message statistics response");const r=e.totalMessages,s=e.todayMessages,o=e.uniqueUsers,i=e.uniqueTokens,a=e.messagesByType;if(!(t(r)&&t(s)&&t(o)&&t(i)&&n(a)))throw St("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(a)){if(!t(n))throw St("Malformed message statistics response");c[e]=n}return{totalMessages:r,todayMessages:s,uniqueUsers:o,uniqueTokens:i,messagesByType:c}}(await this.http.get(Ce.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const sl={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},ol=mn(sl),il={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},al=mn(il),cl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},ll=mn(cl);function dl(e){return ol.includes(e)}function ul(e){return ll.includes(e)}function hl(e){return Wn.PATTERN.test(e)}const gl=An([{field:"id",type:"number"},{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"role",type:"string"},{field:"inviteCode",type:"string"},{field:"inviteUrl",type:"string"},{field:"status",type:"string"},{field:"createdAt",type:"string"}]),pl=An([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),ml=An([{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"tokenSymbol",type:"string",nullable:!0},{field:"role",type:"string"},{field:"status",type:"string"},{field:"invitedBy",type:"string"}]);function fl(e){return al.includes(e)}class El extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateRole(e){if(!dn(e))throw Tt("role","Role");if(!dl(e))throw vt("role",`one of: ${ol.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!dn(e))throw Tt("inviteCode","Invite code");if(e.length>Wn.MAX_LENGTH)throw vt("inviteCode",`at most ${String(Wn.MAX_LENGTH)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&!fl(e))throw new rt(`Invalid invite scope. Must be one of: ${al.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??il.TOKEN;if(t===il.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new rt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,Cn)}else if(t===il.ALL_OWNER_TOKENS&&e.tokenName)throw new rt("Token name should not be provided for ALL_OWNER_TOKENS scope invites","tokenName","INVALID_VALUE");this.validateRole(e.role),this.validateOptionalString(e.description,"description","Description",Bn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=V,r={inviteScope:t,role:e.role};t===il.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(r.tokenName=Kt(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const s=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,Cn),this.validateStatusFilter(e.status,cl);const t=z,n={...this.buildPaginationParams(e,Un)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=Kt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Y,{id:String(e)});Lt(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(X,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new rt("At least one of role or description must be provided","options","REQUIRED");void 0!==e.role&&this.validateRole(e.role),void 0!==e.description&&this.validateOptionalString(e.description,"description","Description",Bn.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Q,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=j,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=q,n=this.buildPaginationParams(e??{},Un),r=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(r);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(J,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const Al={COLLECTION_CLAIM_FEE:"10000",TOKEN_CLASS_CREATE_FEE:"1000",DESCRIPTIONS:{COLLECTION_CLAIM:"10,000 GALA to claim a collection name",TOKEN_CLASS_CREATE:"1,000 GALA to create a token class",MINT:"Dynamic fee estimated via DryRun endpoint"}};function Tl(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function vl(){return Date.now()+6e4}function Sl(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function yl(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function bl(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class Nl extends kn{constructor(e){super(e)}getCollectionClaimFee(){return Al.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return Al.TOKEN_CLASS_CREATE_FEE}async estimateMintFee(e){try{if(this.logger.debug("Estimating mint fee",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for mint fee estimation");if(!bl(e.ownerAddress))throw new Error(`Invalid owner address format: ${e.ownerAddress}`);const t="0";return this.logger.debug("Estimated mint fee:",t),t}catch(e){throw this.logger.error("Failed to estimate mint fee",e),e}}estimateNftOperationFees(e){let t="0";const n={};if(e.claimCollection){const e=Al.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=Al.TOKEN_CLASS_CREATE_FEE,s=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(s))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!Sl(e.collectionName))throw new Error(`Invalid collection name format. Must be alphanumeric, 3-50 characters: ${e.collectionName}`);if(!await this.isCollectionAvailable(e.collectionName))throw new Error(`Collection name already claimed: ${e.collectionName}`);const t={collectionName:e.collectionName,expiresAt:vl(),uniqueKey:Tl("auth")};this.logger.debug("Built claim DTO",t);return{transactionId:`claim-${Date.now()}`,collection:e.collectionName,authorizedUser:"",status:"pending"}}catch(e){throw this.logger.error("Failed to claim collection",e),e}}async fetchUserCollections(e){try{if(this.logger.debug("Fetching user collections for",e),!bl(e))throw new Error(`Invalid wallet address format: ${e}`);const t=e.toLowerCase(),n=(await this.allAuthorizations()).filter(e=>e.authorizedUsers.some(e=>e.toLowerCase()===t)).map(t=>({authorizedUser:e,collection:t.collection}));return this.logger.debug(`Found ${n.length} collections for user`),n}catch(e){throw this.logger.error("Failed to fetch user collections",e),e}}async isCollectionAvailable(e){try{if(this.logger.debug("Checking collection availability",e),!Sl(e))throw new Error(`Invalid collection name format: ${e}`);const t=!(await this.allAuthorizations()).some(t=>t.collection===e);return this.logger.debug(`Collection ${e} available:`,t),t}catch(e){throw this.logger.error("Failed to check collection availability",e),e}}async createTokenClass(e){try{if(this.logger.debug("Creating NFT token class",e),null===e.collection||void 0===e.collection||0===e.collection.length||null===e.type||void 0===e.type||0===e.type.length||null===e.category||void 0===e.category||0===e.category.length)throw new Error("Missing required parameters: collection, type, category");if(!Sl(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);if(void 0!==e.symbol&&(""===(t=e.symbol)||"string"!=typeof t||!/^[a-zA-Z]{1,8}$/.test(t)))throw new Error(`Invalid token symbol: ${e.symbol}`);const n={collection:e.collection,type:e.type,category:e.category,name:e.name,description:e.description,image:e.image,symbol:e.symbol,rarity:e.rarity,maxSupply:void 0!==e.maxSupply?yl(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?yl(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:vl(),uniqueKey:Tl("create")};this.logger.debug("Built token class DTO",n);return{transactionId:`create-${Date.now()}`,tokenClass:{collection:e.collection,type:e.type,category:e.category,additionalKey:e.additionalKey??""},status:"pending"}}catch(e){throw this.logger.error("Failed to create token class",e),e}var t}async fetchTokenClasses(e){try{if(this.logger.debug("Fetching token classes",e),!Sl(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);const t=(await this.reads().fetchAllTokenClasses({collection:e.collection,category:e.category,type:e.type},{pageSize:1e3})).map(e=>({collection:e.collection,type:e.type,category:e.category,additionalKey:e.additionalKey,totalSupply:e.totalSupply,maxSupply:e.maxSupply,isNonFungible:e.isNonFungible,name:e.name,description:e.description,image:e.image,symbol:e.symbol,...void 0===e.rarity?{}:{rarity:e.rarity}}));return this.logger.debug(`Found ${t.length} token classes`),t}catch(e){throw this.logger.error("Failed to fetch token classes",e),e}}async mintNft(e){try{if(this.logger.debug("Minting NFT",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for minting");const t=parseInt(e.quantity,10);if(t<=0)throw new Error("Quantity must be greater than 0");if(!bl(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const r={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:vl(),uniqueKey:Tl("mint")};this.logger.debug("Built mint DTO",r);const s=`mint-${Date.now()}`,o=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:o,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!bl(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:e,collection:t})).map(e=>({owner:e.owner,collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instanceIds:[...e.instanceIds],totalOwned:e.instanceIds.length}));return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}reads(){const{requestor:e}=Pa(async(e,t)=>({data:await this.http.post(e,t)}));return new t.GatewayReads({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class kl extends kn{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(je,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:qe,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(ze,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(Ye,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class wl extends kn{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(l.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(l.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=l.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=l.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=l.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:r.title}),{oembed:r}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=l.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function _l(e){if(!dn(e))throw Tt("address","Address")}const Il={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Cl={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Dl=pn(Il),Rl=pn(Cl);function Ol(e){try{Sn(e.description,"description",255)}catch(e){if(e instanceof rt){throw e.message.includes("255")?new Error("description must be at most 255 characters"):new Error("description must be a string")}throw e}if(void 0!==e.expiresAt){if(!dn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{yn(e.expiresAt,"expiresAt")}catch(e){if(e instanceof rt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Xt(e.expiresAt)){if(Yt(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function xl(e){if(void 0!==e.status&&!Dl(e.status))throw Ct("status",e.status,Object.values(Il),"status");gn(0,void 0,50,e.pageSize,e.cursor)}function Ll(e){if(void 0!==e.status&&!Rl(e.status))throw Ct("status",e.status,Object.values(Cl),"status");gn(0,void 0,50,e.pageSize,e.cursor)}function Ml(e){if(!dn(e))throw new Error("Invite code must be a non-empty string");sn(e,Wn.MAX_LENGTH,"code")}function Ul(e){if(!dn(e))throw new Error("Address must be a non-empty string");try{or(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Fl(e){try{on(e,"id")}catch(e){if(e instanceof rt)throw new Error("Invite ID must be a positive integer");throw e}}function Pl(e){if(null==e||"object"!=typeof e)throw new rt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new rt("Search must be a string");if(0===e.search.length)throw new rt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new rt("Sort field must be a string");if(0===e.sortBy.length)throw new rt("Sort field cannot be empty string")}if(void 0!==e.sortOrder){const t="string"==typeof e.sortOrder?e.sortOrder.toLowerCase():"";if("asc"!==t&&"desc"!==t)throw new rt('Sort order must be "asc" or "desc"')}}function Bl(e){if(null==e||"object"!=typeof e)throw new rt("Options are required");if(!dn(e.userAddress))throw new rt("userAddress is required and must be a non-empty string");try{or(e.userAddress,"userAddress")}catch{throw new rt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new rt("description must be a string");if(e.description.length>255)throw new rt("description must be at most 255 characters")}}class Gl extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}validateInviteCodeFormat(e){if(!dn(e))throw Tt("inviteCode","Invite code");Ml(e)}validateWalletAddressFormat(e){if(!dn(e))throw Tt("address","Address");Ul(e)}async createInvite(e={}){Ol(e),this.validateOptionalString(e.description,"description","Description",Bn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=ee,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){xl(e),this.validateStatusFilter(e.status,Il);const t=te,n={...this.buildPaginationParams(e,Un)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ne,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){Fl(e);const t=this.buildEndpoint(se,{id:String(e)});Lt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=re,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){Ll(e),this.validateStatusFilter(e.status,Cl);const t=oe,n={...this.buildPaginationParams(e,Un)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.overseers,pageInfo:s.pageInfo}}async createOverseerDirect(e){Bl(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",Bn.DESCRIPTION.MAX_LENGTH);const t=ie,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(ae,{address:e});Lt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=ce,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=de,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=he,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=ge,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=pe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&Pl(t);const n=me,r=this.buildPaginationParams(t,Un);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const s=await this.http.get(n,r,this.getDualAuthHeaders()),o=this.extractData(s);return{items:o.users,pageInfo:o.pageInfo}}async getOverseerUserSummary(e){if(!dn(e))throw Tt("address","User address");Ul(e);const t=this.buildEndpoint(fe,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){_l(e);const t=this.buildEndpoint(Ee,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!dn(e))throw Tt("tokenName","Token name")}(e);const t=this.buildEndpoint(Ae,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new rt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Te,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){_l(e);const t=this.buildEndpoint(ve,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Se,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function $l(e){const t=[];return 0===Object.keys(e).length&&t.push("At least one field (streamingEnabled, chatEnabled, commentsEnabled, webhooksEnabled, aiModerationEnabled) must be provided"),void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled&&t.push("streamingEnabled must be a boolean"),void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled&&t.push("chatEnabled must be a boolean"),void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled&&t.push("commentsEnabled must be a boolean"),void 0!==e.webhooksEnabled&&"boolean"!=typeof e.webhooksEnabled&&t.push("webhooksEnabled must be a boolean"),void 0!==e.aiModerationEnabled&&"boolean"!=typeof e.aiModerationEnabled&&t.push("aiModerationEnabled must be a boolean"),t}class Kl extends kn{constructor(e,t,n=!1){super(e,n,t)}extractData(e){const t={status:200,error:"error"in e?e.error:"success"in e?!e.success:!("data"in e),data:e.data};return void 0!==e.message&&(t.message=e.message),Lt(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(N);return this.extractData(e)}async updatePlatformConfig(e){const t=$l(e);if(t.length>0)throw new rt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(k,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(I);return this.extractData(e)}}class Hl extends kn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Platform stats operation failed";throw new Error(t)}return e.data}async getStats(){this.logger.debug("Fetching platform stats");const e=await this.http.get(Ge),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class Wl extends ni{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(De,void 0,this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if("string"!=typeof e.content)throw new rt("Content is required");return{success:!0,data:(await this.http.put(Re,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class Vl extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async getChatStatus(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,Rn),Mo(async()=>{const t=this.buildEndpoint(Oe,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,Rn),Mo(async()=>{const t=this.buildEndpoint(Le,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw Tt("tokenName","Token name");return this.validateTokenName(e,Rn),Mo(async()=>{const t=this.buildEndpoint(xe,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResponse(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??Kt(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),"global"!==t.reason&&"token"!==t.reason||(n.reason=t.reason),"number"==typeof t.slowModeSeconds&&(n.slowModeSeconds=t.slowModeSeconds),n}async setSlowMode(e,t){if(null==e||""===e)throw Tt("tokenName","Token name");if(this.validateTokenName(e,Rn),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Mo(async()=>{const n=this.buildEndpoint(Me,{tokenName:e}),r=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(r)},`Failed to set slow mode for token: ${e}`,this.logger)}}const jl={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},ql={PREPARING:"preparing",READY:"ready",ERRORED:"errored"},zl={YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"},Yl=pn(jl),Xl=pn(ql),Ql=pn(zl);const Jl={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},Zl={OWNER:"OWNER",MODERATOR:"MODERATOR"};pn(Jl),pn(Zl);const ed={...Jl,OVERSEER:"OVERSEER"},td=pn(ed);function nd(e,t="tokenName"){fn(e,t,Rn)}const rd=/^rtmps?:\/\/\S+$/u,sd=255;function od(e){if(nd(e.tokenName),!dn(e.language))throw Tt("language");if(t=e.language,!dn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new rt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",nt.INVALID_FORMAT);var t}class id extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async startStream(e){this.validateTokenName(e,Rn);const t=this.buildEndpoint(g,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Rn);const t=this.buildEndpoint(p,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,m,Rn)}async enableStream(e){return this.toggleFeature(e,f,Rn)}async resetStreamKey(e){this.validateTokenName(e,Rn);const t=this.buildEndpoint(E,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Rn);const t=this.buildEndpoint(D,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){nd(e.tokenName)}(e);const t=this.buildEndpoint(A,{tokenName:e.tokenName}),n=await this.http.get(t),r=this.extractData(n);if(!Array.isArray(r))throw St("Invalid recordings response: expected an array of recordings");return{recordings:r,tokenName:Kt(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,Rn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(T,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,Rn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(v,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Rn);const t=this.buildEndpoint(S,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),r=this.extractData(n);if(!Array.isArray(r))throw St("Invalid simulcast response: expected an array of targets");return{targets:r,tokenName:Kt(e)}}async addSimulcastTarget(e){!function(e){if(nd(e.tokenName),!dn(e.platform))throw Tt("platform");if(!Ql(e.platform))throw new rt("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",nt.INVALID_VALUE);if(!dn(e.url))throw Tt("url");if(!rd.test(e.url))throw new rt("url must be a valid RTMP or RTMPS URL","url",nt.INVALID_FORMAT);if(e.url.length>2048)throw new rt(`url must not exceed ${String(2048)} characters`,"url",nt.TOO_LONG);if(!dn(e.streamKey))throw Tt("streamKey");if(e.streamKey.length>sd)throw new rt(`streamKey must not exceed ${String(sd)} characters`,"streamKey",nt.TOO_LONG);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new rt("passthrough must be a string","passthrough",nt.INVALID_TYPE);if(e.passthrough.length>sd)throw new rt(`passthrough must not exceed ${String(sd)} characters`,"passthrough",nt.TOO_LONG)}}(e);const t=this.buildEndpoint(y,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,url:e.url,streamKey:e.streamKey,...void 0!==e.passthrough&&{passthrough:e.passthrough}},this.getJwtHeaders());return{target:this.extractData(n),tokenName:Kt(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,Rn),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(b,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(N);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(k,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(w,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(nd(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||dn(e.nextLiveStreamAt)))throw new rt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",nt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new rt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",nt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,Rn);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){od(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){nd(e.tokenName)}(e);const t=this.buildEndpoint(_,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(I);return this.extractData(e)}async getTokenAccess(e){!function(e){nd(e.tokenName)}(e);const t=await this.http.get(C,{tokenName:Kt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const ad={SUBSCRIBE:"subscribe_token",UNSUBSCRIBE:"unsubscribe_token",SUBSCRIBE_COMMENT:"subscribe_comment",UNSUBSCRIBE_COMMENT:"unsubscribe_comment",SUBSCRIBE_GLOBAL_FEED:"subscribe_global_feed",UNSUBSCRIBE_GLOBAL_FEED:"unsubscribe_global_feed",SUBSCRIBE_EVENTS_FIREHOSE:"subscribe_events_firehose",UNSUBSCRIBE_EVENTS_FIREHOSE:"unsubscribe_events_firehose",AUTHENTICATE:"authenticate",SEND_CHAT:"send_stream_chat",SEND_REACTION:"SEND_STREAM_REACTION",TYPING_START:"typing_start",TYPING_STOP:"typing_stop",STREAM_STATUS:"STREAM_STATUS",RECORDING_STATUS:"RECORDING_STATUS",RECORDINGS_COUNT_UPDATED:"RECORDINGS_COUNT_UPDATED",SIMULCAST_STATUS:"SIMULCAST_STATUS",DOWNLOAD_READY:"DOWNLOAD_READY",STREAM_COUNTDOWN_UPDATED:"STREAM_COUNTDOWN_UPDATED",STREAM_LANGUAGE_UPDATED:"STREAM_LANGUAGE_UPDATED",VIEWER_COUNT:"VIEWER_COUNT",STREAM_CONTROL_STATUS_CHANGED:"STREAM_CONTROL_STATUS_CHANGED",STREAM_GLOBAL_STATUS:"STREAM_GLOBAL_STATUS",ENGAGEMENT_STATS_UPDATED:"ENGAGEMENT_STATS_UPDATED",CHAT_MESSAGE:"STREAM_CHAT_MESSAGE",CHAT_SENT:"STREAM_CHAT_SENT",CHAT_UPDATED:"STREAM_CHAT_UPDATED",CHAT_DELETED:"STREAM_CHAT_DELETED",CHAT_PINNED:"STREAM_CHAT_PINNED",CHAT_UNPINNED:"STREAM_CHAT_UNPINNED",CHAT_STATUS:"CHAT_STATUS_CHANGED",SLOW_MODE_CHANGED:"SLOW_MODE_CHANGED",CHAT_GLOBAL_STATUS:"STREAM_CHAT_GLOBAL_STATUS",USER_TYPING:"USER_TYPING",CHAT_ERROR:"stream_chat_error",REACTION:"STREAM_REACTION",REACTION_ERROR:"stream_reaction_error",CONTENT_REACTION_ADDED:"CONTENT_REACTION_ADDED",CONTENT_REACTION_REMOVED:"CONTENT_REACTION_REMOVED",COMMENT_CREATED:"COMMENT_CREATED",COMMENT_UPDATED:"COMMENT_UPDATED",COMMENT_DELETED:"COMMENT_DELETED",TRADE_EXECUTED:"TRADE_EXECUTED",TRADE_UPDATE_NOTIFY:"TRADE_UPDATE_NOTIFY",BALANCE_UPDATED:"BALANCE_UPDATED",STATS_UPDATED:"STATS_UPDATED",USER_BANNED:"USER_BANNED",USER_UNBANNED:"USER_UNBANNED",BAN_ENFORCEMENT:"BAN_ENFORCEMENT",TOKEN_BANNED:"TOKEN_BANNED",TOKEN_UNBANNED:"TOKEN_UNBANNED",CONTENT_FLAGGED:"CONTENT_FLAGGED",FLAG_RESOLVED:"FLAG_RESOLVED",AI_MODERATION_COMPLETE:"AI_MODERATION_COMPLETE",AI_MODERATION_FAILED:"AI_MODERATION_FAILED",MODERATOR_INVITE_CREATED:"MODERATOR_INVITE_CREATED",MODERATOR_ADDED:"MODERATOR_ADDED",MODERATOR_REMOVED:"MODERATOR_REMOVED",MODERATOR_ROLE_UPDATED:"MODERATOR_ROLE_UPDATED",OVERSEER_ADDED:"OVERSEER_ADDED",OVERSEER_REMOVED:"OVERSEER_REMOVED",POOL_CREATED:"POOL_CREATED",POOL_METADATA_UPDATED:"POOL_METADATA_UPDATED",POOL_SOCIAL_LINKS_UPDATED:"POOL_SOCIAL_LINKS_UPDATED",POOL_BADGE_ASSIGNED:"POOL_BADGE_ASSIGNED",TOKEN_CONFIG_UPDATED:"TOKEN_CONFIG_UPDATED",HOLDER_COUNT_UPDATED:"HOLDER_COUNT_UPDATED",USER_PROFILE_UPDATED:"USER_PROFILE_UPDATED",API_KEY_CREATED:"API_KEY_CREATED",API_KEY_UPDATED:"API_KEY_UPDATED",API_KEY_REVOKED:"API_KEY_REVOKED",SITE_CONFIG_CHANGED:"SITE_CONFIG_CHANGED",COMMENTS_GLOBAL_STATUS:"COMMENTS_GLOBAL_STATUS",WEBHOOKS_GLOBAL_STATUS:"WEBHOOKS_GLOBAL_STATUS",AI_MODERATION_GLOBAL_STATUS:"AI_MODERATION_GLOBAL_STATUS",EVENT:"EVENT",CONNECTION:"connection",CHAT_AUTHENTICATED:"authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",EXCEPTION:"exception",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",ROOM_SUBSCRIBED:"room_subscribed",ROOM_LEFT:"room_left",GLOBAL_FEED_SUBSCRIBED:"global_feed_subscribed",GLOBAL_FEED_UNSUBSCRIBED:"global_feed_unsubscribed",EVENTS_FIREHOSE_SUBSCRIBED:"events_firehose_subscribed",EVENTS_FIREHOSE_UNSUBSCRIBED:"events_firehose_unsubscribed"},cd=e=>ld(e.flagId);function ld(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function dd(e,t){const n=t.map(t=>ld(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const ud={STREAM_STATUS:{},RECORDING_STATUS:{},RECORDINGS_COUNT_UPDATED:{},SIMULCAST_STATUS:{},DOWNLOAD_READY:{},STREAM_COUNTDOWN_UPDATED:{},STREAM_LANGUAGE_UPDATED:{},VIEWER_COUNT:{},STREAM_CONTROL_STATUS_CHANGED:{},STREAM_GLOBAL_STATUS:{token:"none"},ENGAGEMENT_STATS_UPDATED:{},STREAM_CHAT_MESSAGE:{},STREAM_CHAT_SENT:{},STREAM_CHAT_UPDATED:{},STREAM_CHAT_DELETED:{},STREAM_CHAT_PINNED:{},STREAM_CHAT_UNPINNED:{},CHAT_STATUS_CHANGED:{},SLOW_MODE_CHANGED:{},STREAM_CHAT_GLOBAL_STATUS:{token:"none"},USER_TYPING:{},stream_chat_error:{},STREAM_REACTION:{},stream_reaction_error:{},CONTENT_REACTION_ADDED:{},CONTENT_REACTION_REMOVED:{},COMMENT_CREATED:{},COMMENT_UPDATED:{},COMMENT_DELETED:{},TRADE_EXECUTED:{},TRADE_UPDATE_NOTIFY:{token:"none"},BALANCE_UPDATED:{},STATS_UPDATED:{},USER_BANNED:{},USER_UNBANNED:{},BAN_ENFORCEMENT:{},TOKEN_BANNED:{},TOKEN_UNBANNED:{},CONTENT_FLAGGED:{duplicateKey:e=>ld(e.id)},FLAG_RESOLVED:{duplicateKey:e=>dd(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:cd},AI_MODERATION_FAILED:{duplicateKey:cd},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>dd(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>dd(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>dd(e,["tokenName","createdAt"])},POOL_METADATA_UPDATED:{},POOL_SOCIAL_LINKS_UPDATED:{},POOL_BADGE_ASSIGNED:{},TOKEN_CONFIG_UPDATED:{},HOLDER_COUNT_UPDATED:{},USER_PROFILE_UPDATED:{token:"none"},API_KEY_CREATED:{token:"none"},API_KEY_UPDATED:{token:"none"},API_KEY_REVOKED:{token:"none"},SITE_CONFIG_CHANGED:{token:"none"},COMMENTS_GLOBAL_STATUS:{token:"none"},WEBHOOKS_GLOBAL_STATUS:{token:"none"},AI_MODERATION_GLOBAL_STATUS:{token:"none"},EVENT:{token:"none"},connection:{token:"none"},authenticated:{token:"none"},stream_chat_auth_error:{token:"none"},exception:{token:"none"},token_subscribed:{},token_unsubscribed:{token:"room"},room_subscribed:{token:"none"},room_left:{token:"none"},global_feed_subscribed:{token:"none"},global_feed_unsubscribed:{token:"none"},events_firehose_subscribed:{token:"none"},events_firehose_unsubscribed:{token:"none"}};function hd(e){return ud[e]}const gd=Object.keys(ud);const pd="token:",md="comment:",fd="global:feed",Ed="global:events_firehose";function Ad(e){if(e.startsWith(pd)){const t={tokenName:e.slice(pd.length)};return{join:{event:ad.SUBSCRIBE,payload:t},leave:{event:ad.UNSUBSCRIBE,payload:t}}}if(e.startsWith(md)){const t={tokenName:e.slice(8)};return{join:{event:ad.SUBSCRIBE_COMMENT,payload:t},leave:{event:ad.UNSUBSCRIBE_COMMENT,payload:t}}}return e===Ed?{join:{event:ad.SUBSCRIBE_EVENTS_FIREHOSE},leave:{event:ad.UNSUBSCRIBE_EVENTS_FIREHOSE}}:{join:{event:ad.SUBSCRIBE_GLOBAL_FEED},leave:{event:ad.UNSUBSCRIBE_GLOBAL_FEED}}}const Td=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const vd={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},Sd=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],yd=new Set(["STREAM_STATUS","RECORDING_STATUS","RECORDINGS_COUNT_UPDATED","SIMULCAST_STATUS","DOWNLOAD_READY","STREAM_COUNTDOWN_UPDATED","STREAM_LANGUAGE_UPDATED","VIEWER_COUNT","STREAM_CONTROL_STATUS_CHANGED","ENGAGEMENT_STATS_UPDATED","STREAM_CHAT_MESSAGE","STREAM_CHAT_SENT","STREAM_CHAT_UPDATED","STREAM_CHAT_DELETED","STREAM_CHAT_PINNED","STREAM_CHAT_UNPINNED","CHAT_STATUS_CHANGED","SLOW_MODE_CHANGED","USER_TYPING","stream_chat_error","STREAM_REACTION","stream_reaction_error","CONTENT_REACTION_ADDED","CONTENT_REACTION_REMOVED","TRADE_EXECUTED","BALANCE_UPDATED","STATS_UPDATED","TOKEN_BANNED","TOKEN_UNBANNED","CONTENT_FLAGGED","FLAG_RESOLVED","MODERATOR_INVITE_CREATED","MODERATOR_ADDED","MODERATOR_REMOVED","MODERATOR_ROLE_UPDATED","POOL_METADATA_UPDATED","POOL_SOCIAL_LINKS_UPDATED","POOL_BADGE_ASSIGNED","TOKEN_CONFIG_UPDATED","HOLDER_COUNT_UPDATED","token_subscribed","token_unsubscribed"]),bd=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const Nd={onStreamStatus:"STREAM_STATUS",onStreamSubscribed:"token_subscribed",onStreamUnsubscribed:"token_unsubscribed",onViewerCount:"VIEWER_COUNT",onStreamGlobalStatus:"STREAM_GLOBAL_STATUS",onCountdownUpdated:"STREAM_COUNTDOWN_UPDATED",onLanguageUpdated:"STREAM_LANGUAGE_UPDATED",onRecordingStatus:"RECORDING_STATUS",onRecordingsCountUpdated:"RECORDINGS_COUNT_UPDATED",onSimulcastStatus:"SIMULCAST_STATUS",onDownloadReady:"DOWNLOAD_READY",onStreamControlStatusChanged:"STREAM_CONTROL_STATUS_CHANGED",onChatMessage:"STREAM_CHAT_MESSAGE",onChatSent:"STREAM_CHAT_SENT",onChatUpdated:"STREAM_CHAT_UPDATED",onChatDeleted:"STREAM_CHAT_DELETED",onChatError:"stream_chat_error",onChatStatus:"CHAT_STATUS_CHANGED",onChatSlowMode:"SLOW_MODE_CHANGED",onChatGlobalStatus:"STREAM_CHAT_GLOBAL_STATUS",onChatAuthenticated:"authenticated",onChatAuthError:"stream_chat_auth_error",onChatPinned:"STREAM_CHAT_PINNED",onChatUnpinned:"STREAM_CHAT_UNPINNED",onTypingIndicator:"USER_TYPING",onReaction:"STREAM_REACTION",onReactionError:"stream_reaction_error",onContentReactionAdded:"CONTENT_REACTION_ADDED",onContentReactionRemoved:"CONTENT_REACTION_REMOVED",onCommentCreated:"COMMENT_CREATED",onCommentUpdated:"COMMENT_UPDATED",onCommentDeleted:"COMMENT_DELETED",onUserBanned:"USER_BANNED",onUserUnbanned:"USER_UNBANNED",onBanEnforcement:"BAN_ENFORCEMENT",onTokenBanned:"TOKEN_BANNED",onTokenUnbanned:"TOKEN_UNBANNED",onContentFlagged:"CONTENT_FLAGGED",onFlagResolved:"FLAG_RESOLVED",onAIModerationComplete:"AI_MODERATION_COMPLETE",onAIModerationFailed:"AI_MODERATION_FAILED",onModeratorInviteCreated:"MODERATOR_INVITE_CREATED",onModeratorAdded:"MODERATOR_ADDED",onModeratorRemoved:"MODERATOR_REMOVED",onModeratorRoleUpdated:"MODERATOR_ROLE_UPDATED",onOverseerAdded:"OVERSEER_ADDED",onOverseerRemoved:"OVERSEER_REMOVED",onTradeExecuted:"TRADE_EXECUTED",onTradeUpdateNotify:"TRADE_UPDATE_NOTIFY",onBalanceUpdated:"BALANCE_UPDATED",onStatsUpdated:"STATS_UPDATED",onEngagementStatsUpdated:"ENGAGEMENT_STATS_UPDATED",onPoolCreated:"POOL_CREATED",onPoolMetadataUpdated:"POOL_METADATA_UPDATED",onPoolSocialLinksUpdated:"POOL_SOCIAL_LINKS_UPDATED",onPoolBadgeAssigned:"POOL_BADGE_ASSIGNED",onHolderCountUpdated:"HOLDER_COUNT_UPDATED",onTokenConfigUpdated:"TOKEN_CONFIG_UPDATED",onUserProfileUpdated:"USER_PROFILE_UPDATED",onApiKeyCreated:"API_KEY_CREATED",onApiKeyUpdated:"API_KEY_UPDATED",onApiKeyRevoked:"API_KEY_REVOKED",onException:"exception"},kd={onGlobalFeedSubscribed:"global_feed_subscribed",onGlobalFeedUnsubscribed:"global_feed_unsubscribed",onStreamStatus:"STREAM_STATUS",onTradeExecuted:"TRADE_EXECUTED",onHolderCountUpdated:"HOLDER_COUNT_UPDATED",onPoolBadgeAssigned:"POOL_BADGE_ASSIGNED",onViewerCount:"VIEWER_COUNT",onTokenConfigUpdated:"TOKEN_CONFIG_UPDATED",onStatsUpdated:"STATS_UPDATED",onPoolCreated:"POOL_CREATED",onSiteConfigChanged:"SITE_CONFIG_CHANGED",onStreamGlobalStatus:"STREAM_GLOBAL_STATUS",onStreamChatGlobalStatus:"STREAM_CHAT_GLOBAL_STATUS",onCommentsGlobalStatus:"COMMENTS_GLOBAL_STATUS",onWebhooksGlobalStatus:"WEBHOOKS_GLOBAL_STATUS",onAIModerationGlobalStatus:"AI_MODERATION_GLOBAL_STATUS"},wd=()=>{};function _d(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Id(e,t){return t}function Cd(e){return`${pd}${e}`}function Dd(e){return`${md}${e}`}function Rd(e){const t=Kt(e);if(""===t)throw Tt("tokenName","Token name");return t}class Od extends wn{constructor(e,t=!1){if(super(t),this.socket=null,this.disposed=!1,this.epoch=0,this.connectionGeneration=0,this.hasConnected=!1,this.connectAttempt=null,this.reconnectExhausted=!1,this.managerCleanups=[],this.connectionStateListeners=new Set,this.reconnectListeners=new Set,this.subscribers=new Map,this.roomRefs=new Map,this.roomStates=new Map,this.roomWaiters=new Map,this.explicitHolds=new Map,this.recentOccurrences=new Map,this.siteConfig={chatEnabled:void 0,streamingEnabled:void 0,commentsEnabled:void 0,webhooksEnabled:void 0,aiModerationEnabled:void 0},this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authSequence=0,this.inFlight=null,this.lastEmitted=null,this.pendingAuthenticate=null,""===e.url)throw new ct("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,reconnectDelayMax:e.reconnectDelayMax,subscriptionTimeout:e.subscriptionTimeout??1e4,tokenProvider:e.tokenProvider,autoConnect:e.autoConnect??!0},this.isSocketIOAvailable="function"==typeof i.io}register(e,t,n={}){if(this.disposed)return wd;const r={name:e,deliver:t,token:n.token,filter:n.filter,room:n.room,active:!0};let s=this.subscribers.get(e);return void 0===s&&(s=new Set,this.subscribers.set(e,s)),s.add(r),void 0!==n.room&&this.acquireRoom(n.room),this.openIfNeeded(),()=>{this.release(r)}}release(e){if(!e.active)return;e.active=!1;const t=this.subscribers.get(e.name);t?.delete(e),0===t?.size&&this.subscribers.delete(e.name),void 0!==e.room&&this.releaseRoom(e.room)}hold(e){if(this.disposed)return wd;let t=!0;return this.acquireRoom(e),this.openIfNeeded(),()=>{t&&(t=!1,this.releaseRoom(e))}}openIfNeeded(){this.config.autoConnect&&!this.disposed&&(null===this.socket||this.reconnectExhausted)&&this.connect().catch(e=>{this.logger.warn(`Stream WebSocket connect failed: ${ut(e)}`)})}acquireRoom(e){this.roomRefs.set(e,(this.roomRefs.get(e)??0)+1),this.syncRoom(e)}releaseRoom(e){const t=(this.roomRefs.get(e)??1)-1;t<=0?this.roomRefs.delete(e):this.roomRefs.set(e,t),this.syncRoom(e)}syncRoom(e){const t=this.liveSocket();if(null===t)return;const n=(this.roomRefs.get(e)??0)>0,r=this.roomStates.get(e);if(n&&void 0===r){if(function(e){return e===Ed}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==r?.phase||(t.emit(Ad(e).leave.event,Ad(e).leave.payload),this.roomStates.delete(e))}syncAllRooms(){for(const e of new Set([...this.roomRefs.keys(),...this.roomStates.keys()]))this.syncRoom(e)}joinRoom(e,t){const n=setTimeout(()=>{const e=this.roomStates.get(t);"joining"===e?.phase&&(this.roomStates.delete(t),this.rejectWaiters(t,new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`)))},this.config.subscriptionTimeout);this.roomStates.set(t,{phase:"joining",timer:n});const r=Ad(t).join;e.emit(r.event,r.payload)}onRoomAcknowledged(e){const t=this.roomStates.get(e);void 0!==t?.timer&&clearTimeout(t.timer),this.roomStates.set(e,{phase:"joined",timer:void 0});const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);const t=e.startsWith(pd)?e.slice(pd.length):e;for(const r of n)clearTimeout(r.timer),r.resolve({room:e,tokenName:t})}this.syncRoom(e)}rejectWaiters(e,t){const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);for(const e of n)clearTimeout(e.timer),e.reject(t)}}clearRoomStates(){for(const e of this.roomStates.values())void 0!==e.timer&&clearTimeout(e.timer);this.roomStates.clear()}onServerEvent(e,t){try{this.applyEffects(e,t)}catch(t){this.logger.error(`Error handling ${e}:`,t)}if((!_d(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,_d(t)?function(e,t){const n=hd(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(pd)?e.slice(pd.length):void 0}const r=t.tokenName;return"string"==typeof r&&""!==r?r:void 0}(e,t):void 0),_d(t)))for(const n of function(e,t){if("TOKEN_CONFIG_UPDATED"!==e)return[];const n=t.tokenName;if("string"!=typeof n)return[];const r=[];if("nextLiveStreamAt"in t){const e=t.nextLiveStreamAt;r.push({name:"STREAM_COUNTDOWN_UPDATED",payload:{tokenName:n,nextLiveStreamAt:"string"==typeof e?e:null}})}const s=t.streamLanguage;return"string"==typeof s&&r.push({name:"STREAM_LANGUAGE_UPDATED",payload:{tokenName:n,language:s}}),r}(e,t))this.deliver(n.name,n.payload,n.payload.tokenName)}isDuplicate(e,t){const n=hd(e).duplicateKey?.(t);if(void 0===n)return!1;const r=Date.now(),s=`${e}:${n}`,o=this.recentOccurrences.get(s);if(void 0!==o&&r-o<5e3)return!0;if(this.recentOccurrences.set(s,r),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)r-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const r=this.subscribers.get(e);if(void 0===r)return;const s=void 0===n?void 0:Kt(n);for(const n of[...r])n.active&&(void 0!==n.token&&n.token!==s||(void 0===n.filter||this.passes(n,t))&&this.invoke(e,n.deliver,t))}passes(e,t){try{return e.filter?.(t)??!0}catch(t){return this.logger.error(`Error in a ${e.name} filter:`,t),!1}}invoke(e,t,n){try{const r=t(n);r instanceof Promise&&r.catch(t=>{this.logger.error(`Error in a ${e} subscriber:`,t)})}catch(t){this.logger.error(`Error in a ${e} subscriber:`,t)}}applyEffects(e,t){if("authenticated"===e)null!==this.inFlight?this.inFlight.settle(!0):this.adoptLateAuthentication();else if("stream_chat_auth_error"===e)this.authenticated=!1,this.inFlight?.settle(!1);else if("exception"===e)this.inFlight?.settle(!1);else if(function(e){return Td.has(e)}(e))_d(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=vd[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:xd(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new ct("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new ct('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,r)=>{e=n,t=r});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=i.io(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,...void 0!==this.config.reconnectDelayMax&&{reconnectionDelayMax:this.config.reconnectDelayMax}});return this.socket=e,this.attachListeners(e),e}attachListeners(e){e.on("connect",()=>{this.onSocketConnect()}),e.on("disconnect",e=>{this.onSocketDisconnect(e)}),e.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),this.settleConnectWaiters(e)}),e.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)});for(const t of gd)e.on(t,e=>{this.onServerEvent(t,e)});const t=e=>{this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${String(e)}`)},n=()=>{this.reconnectExhausted=!0,this.logger.error("❌ Stream WebSocket max reconnection attempts reached")};e.io.on("reconnect_attempt",t),e.io.on("reconnect_failed",n),this.managerCleanups.push(()=>e.io.off("reconnect_attempt",t),()=>e.io.off("reconnect_failed",n))}onSocketConnect(){this.connectionGeneration+=1;const e=this.connectionGeneration,t=this.hasConnected;this.hasConnected=!0,this.logger.debug(`✅ Stream WebSocket connected: ${String(this.socket?.id)}`),this.reconnectExhausted=!1,this.clearRoomStates(),this.authenticated=!1,this.notifyConnectionState(!0),this.settleConnectWaiters(void 0),this.wantsAuthentication?this.restoreAfterReconnect(e):(this.syncAllRooms(),t&&this.notifyReconnect())}async restoreAfterReconnect(e){try{await this.authenticate()}catch(e){this.logger.warn(`Re-authentication after reconnect failed: ${ut(e)}`)}e!==this.connectionGeneration||this.disposed||(this.syncAllRooms(),this.notifyReconnect())}onSocketDisconnect(e){this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.authenticated=!1,this.inFlight?.settle(!1),this.clearRoomStates(),this.notifyConnectionState(!1),"io server disconnect"!==e||null===this.socket||this.disposed||this.socket.connect()}settleConnectWaiters(e){const t=this.connectAttempt;this.connectAttempt=null,null!==t&&(void 0===e?t.resolve():t.reject(e))}notifyConnectionState(e){for(const t of[...this.connectionStateListeners])this.invoke("connection state",t,e)}notifyReconnect(){for(const e of[...this.reconnectListeners])this.invoke("reconnect",e,void 0)}onConnectionStateChange(e){return this.disposed?wd:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?wd:(this.reconnectListeners.add(e),()=>{this.reconnectListeners.delete(e)})}async resolveToken(){const e=this.config.tokenProvider;if(void 0===e)return this.lastExplicitToken;try{const t=await e();return null!==t&&""!==t?t:null}catch(e){return this.logger.warn(`The token provider failed: ${ut(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(Tt("token","Authentication token"));const t=this.pendingAuthenticate;if(null!==t&&t.token===e&&t.generation===this.connectionGeneration)return t.promise;this.authSequence+=1;const n=this.authSequence,r=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===r&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:r},r}async runAuthenticate(e,t){if(this.disposed)return!1;const n=e??await this.resolveToken();if(t!==this.authSequence||null===n)return!1;void 0!==e&&(this.lastExplicitToken=e);try{await this.connect()}catch(e){return this.logger.warn(`Cannot authenticate, the connection failed: ${ut(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const r=this.liveSocket();if(t!==this.authSequence||null===r)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const s=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),r.emit(ad.AUTHENTICATE,{token:n});return await s.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const r=new Promise(e=>{n=e}),s={seq:e,token:t,generation:this.connectionGeneration,result:r,settled:r.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(s,e,n)}};return s.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),s.settle(!1)},this.config.subscriptionTimeout),this.inFlight=s,s}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const r=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&r&&this.markAuthenticated(e.token,e.generation),n(t&&r)}markAuthenticated(e,t){this.authenticated=!0,this.authenticatedToken=e,this.authenticatedGeneration=t,this.wantsAuthentication=!0,this.syncAllRooms()}adoptLateAuthentication(){const e=this.lastEmitted;null===e||this.authenticated||e.seq===this.authSequence&&e.generation===this.connectionGeneration&&this.markAuthenticated(e.token,e.generation)}deauthenticate(){this.authSequence+=1;const e=this.authenticated||null!==this.inFlight;this.inFlight?.settle(!1),this.pendingAuthenticate=null,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,e&&null!==this.socket&&!this.disposed&&(this.socket.disconnect(),this.socket.connect())}isAuthenticatedForChat(){return this.authenticated}isConnected(){return this.socket?.connected??!1}requireReady(){const e=this.liveSocket();if(null===e)throw new rt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new rt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw Tt("tokenName","Token name");if(""===t)throw Tt("content","Message content");const n=this.requireReady(),r=Kt(e);this.logger.debug(`📡 Sending chat message to ${r}: ${t.slice(0,30)}...`),n.emit(ad.SEND_CHAT,{tokenName:r,content:t})}sendReaction(e,t,n=0){if(""===e)throw Tt("tokenName","Token name");if(""===t)throw Tt("emoji");const r=this.requireReady(),s=Kt(e);this.logger.debug(`📡 Sending reaction to ${s}: ${t}`),r.emit(ad.SEND_REACTION,{tokenName:s,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,ad.TYPING_START)}sendTypingStop(e){this.sendTypingEvent(e,ad.TYPING_STOP)}sendTypingEvent(e,t){if(""===e)throw Tt("tokenName","Token name");this.requireReady().emit(t,{tokenName:Kt(e)})}subscribeToken(e,t,n){const r=Rd(t);return this.register(e,e=>n(Id(0,e)),{token:r,room:Cd(r)})}joinTokenRoom(e){return this.hold(Cd(Rd(e)))}subscribeComment(e,t,n){const r=Rd(t);return this.register(e,e=>n(Id(0,e)),{token:r,room:Dd(r)})}subscribeFeed(e,t){return this.register(e,e=>t(Id(0,e)),{room:fd})}subscribeEvent(e,t){return this.register(e,e=>t(Id(0,e)))}subscribeEventsFirehose(e,t){const n=function(e){if(void 0===e)return;const t=e.eventTypes?.map(e=>e.toLowerCase()),n=void 0===e.tokenName?void 0:Kt(e.tokenName),r=e.userAddress?.toLowerCase();return void 0!==t||void 0!==n||void 0!==r?e=>{if(!_d(e))return!1;const s=e.eventType;if(void 0!==t&&("string"!=typeof s||!t.includes(s.toLowerCase())))return!1;const o=e.tokenName;if(void 0!==n&&("string"!=typeof o||Kt(o)!==n))return!1;const i=e.userAddress;return void 0===r||"string"==typeof i&&i.toLowerCase()===r}:void 0}(t);return this.register("EVENT",t=>e(Id(0,t)),{room:Ed,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=Sd.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:Id(0,t)}}(t,n)),{room:fd}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,kd,()=>({})),n=this.hold(fd);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,Nd,()=>({}))}registerCallbacks(e,t,n){const r=[],s={...e};for(const[e,o]of Object.entries(t)){const t=s[e];"function"==typeof t&&r.push(this.register(o,e=>Reflect.apply(t,void 0,[e]),n(o)))}return()=>{for(const e of r)e()}}async subscribeToStream(e,t={}){const n=Rd(e),r=Cd(n),s=this.epoch;if(await this.connect(),s!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const o=this.registerCallbacks(t,Nd,e=>{return t=e,yd.has(t)?{token:n}:function(e){return bd.has(e)}(e)?{token:n,room:Dd(n)}:{};var t}),i=this.hold(r),a={release:()=>{o(),i()}},c=this.explicitHolds.get(n)??[];c.push(a),this.explicitHolds.set(n,c);try{return await this.waitForRoom(r,n)}catch(e){throw this.dropExplicitHold(n,a),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,r)=>{const s={resolve:n,reject:r,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(s),r(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},o=this.roomWaiters.get(e)??new Set;o.add(s),this.roomWaiters.set(e,o)})}dropExplicitHold(e,t){t.release();const n=(this.explicitHolds.get(e)??[]).filter(e=>e!==t);0===n.length?this.explicitHolds.delete(e):this.explicitHolds.set(e,n)}unsubscribeFromStream(e){const t=Kt(e),n=this.explicitHolds.get(t);if(void 0!==n){this.explicitHolds.delete(t);for(const e of n)e.release()}else this.logger.debug(`📡 Not subscribed to ${t} through subscribeToStream, skipping unsubscribe`)}subscribeStreamStatus(e,t){return this.subscribeToken("STREAM_STATUS",e,t)}subscribeViewerCount(e,t){return this.subscribeToken("VIEWER_COUNT",e,t)}subscribeRecordingStatus(e,t){return this.subscribeToken("RECORDING_STATUS",e,t)}subscribeRecordingsCountUpdated(e,t){return this.subscribeToken("RECORDINGS_COUNT_UPDATED",e,t)}subscribeSimulcastStatus(e,t){return this.subscribeToken("SIMULCAST_STATUS",e,t)}subscribeDownloadReady(e,t){return this.subscribeToken("DOWNLOAD_READY",e,t)}subscribeCountdownUpdated(e,t){return this.subscribeToken("STREAM_COUNTDOWN_UPDATED",e,t)}subscribeLanguageUpdated(e,t){return this.subscribeToken("STREAM_LANGUAGE_UPDATED",e,t)}subscribeStreamControlStatusChanged(e,t){return this.subscribeToken("STREAM_CONTROL_STATUS_CHANGED",e,t)}subscribeEngagementStatsUpdated(e,t){return this.subscribeToken("ENGAGEMENT_STATS_UPDATED",e,t)}subscribeChatMessages(e,t){return this.subscribeToken("STREAM_CHAT_MESSAGE",e,t)}subscribeChatSent(e,t){return this.subscribeToken("STREAM_CHAT_SENT",e,t)}subscribeChatUpdated(e,t){return this.subscribeToken("STREAM_CHAT_UPDATED",e,t)}subscribeChatDeleted(e,t){return this.subscribeToken("STREAM_CHAT_DELETED",e,t)}subscribeChatPinned(e,t){return this.subscribeToken("STREAM_CHAT_PINNED",e,t)}subscribeChatUnpinned(e,t){return this.subscribeToken("STREAM_CHAT_UNPINNED",e,t)}subscribeChatStatus(e,t){return this.subscribeToken("CHAT_STATUS_CHANGED",e,t)}subscribeChatSlowMode(e,t){return this.subscribeToken("SLOW_MODE_CHANGED",e,t)}subscribeTypingIndicator(e,t){return this.subscribeToken("USER_TYPING",e,t)}subscribeReactions(e,t){return this.subscribeToken("STREAM_REACTION",e,t)}subscribeContentReactionAdded(e,t){return this.subscribeToken("CONTENT_REACTION_ADDED",e,t)}subscribeContentReactionRemoved(e,t){return this.subscribeToken("CONTENT_REACTION_REMOVED",e,t)}subscribeTradeExecuted(e,t){return this.subscribeToken("TRADE_EXECUTED",e,t)}subscribeBalanceUpdated(e,t){return this.subscribeToken("BALANCE_UPDATED",e,t)}subscribeTokenBanned(e,t){return this.subscribeToken("TOKEN_BANNED",e,t)}subscribeTokenUnbanned(e,t){return this.subscribeToken("TOKEN_UNBANNED",e,t)}subscribeModeratorInviteCreated(e,t){return this.subscribeToken("MODERATOR_INVITE_CREATED",e,t)}subscribeModeratorAdded(e,t){return this.subscribeToken("MODERATOR_ADDED",e,t)}subscribeModeratorRemoved(e,t){return this.subscribeToken("MODERATOR_REMOVED",e,t)}subscribeModeratorRoleUpdated(e,t){return this.subscribeToken("MODERATOR_ROLE_UPDATED",e,t)}subscribePoolMetadataUpdated(e,t){return this.subscribeToken("POOL_METADATA_UPDATED",e,t)}subscribePoolSocialLinksUpdated(e,t){return this.subscribeToken("POOL_SOCIAL_LINKS_UPDATED",e,t)}subscribePoolBadgeAssigned(e,t){return this.subscribeToken("POOL_BADGE_ASSIGNED",e,t)}subscribeHolderCountUpdated(e,t){return this.subscribeToken("HOLDER_COUNT_UPDATED",e,t)}subscribeTokenConfigUpdated(e,t){return this.subscribeToken("TOKEN_CONFIG_UPDATED",e,t)}subscribeCommentCreated(e,t){return this.subscribeComment("COMMENT_CREATED",e,t)}subscribeCommentUpdated(e,t){return this.subscribeComment("COMMENT_UPDATED",e,t)}subscribeCommentDeleted(e,t){return this.subscribeComment("COMMENT_DELETED",e,t)}subscribeStatsUpdated(e){return this.subscribeFeed("STATS_UPDATED",e)}subscribePoolCreated(e){return this.subscribeFeed("POOL_CREATED",e)}subscribeStreamGlobalStatus(e){return this.subscribeFeed("STREAM_GLOBAL_STATUS",e)}subscribeChatGlobalStatus(e){return this.subscribeFeed("STREAM_CHAT_GLOBAL_STATUS",e)}subscribeCommentsGlobalStatus(e){return this.subscribeFeed("COMMENTS_GLOBAL_STATUS",e)}subscribeWebhooksGlobalStatus(e){return this.subscribeFeed("WEBHOOKS_GLOBAL_STATUS",e)}subscribeAIModerationGlobalStatus(e){return this.subscribeFeed("AI_MODERATION_GLOBAL_STATUS",e)}subscribeSiteConfigChanged(e){return this.subscribeFeed("SITE_CONFIG_CHANGED",e)}getSiteConfigState(){return{...this.siteConfig}}subscribeOverseerAdded(e){return this.subscribeEvent("OVERSEER_ADDED",e)}subscribeOverseerRemoved(e){return this.subscribeEvent("OVERSEER_REMOVED",e)}subscribeUserProfileUpdated(e){return this.subscribeEvent("USER_PROFILE_UPDATED",e)}subscribeApiKeyCreated(e){return this.subscribeEvent("API_KEY_CREATED",e)}subscribeApiKeyUpdated(e){return this.subscribeEvent("API_KEY_UPDATED",e)}subscribeApiKeyRevoked(e){return this.subscribeEvent("API_KEY_REVOKED",e)}subscribeGlobalTokenBanned(e){return this.subscribeEvent("TOKEN_BANNED",e)}subscribeGlobalTokenUnbanned(e){return this.subscribeEvent("TOKEN_UNBANNED",e)}subscribeGlobalModeratorAdded(e){return this.subscribeEvent("MODERATOR_ADDED",e)}subscribeGlobalModeratorRemoved(e){return this.subscribeEvent("MODERATOR_REMOVED",e)}subscribeGlobalModeratorRoleUpdated(e){return this.subscribeEvent("MODERATOR_ROLE_UPDATED",e)}subscribeGlobalModeratorInviteCreated(e){return this.subscribeEvent("MODERATOR_INVITE_CREATED",e)}subscribeContentFlagged(e){return this.subscribeEvent("CONTENT_FLAGGED",e)}subscribeFlagResolved(e){return this.subscribeEvent("FLAG_RESOLVED",e)}subscribeAIModerationComplete(e){return this.subscribeEvent("AI_MODERATION_COMPLETE",e)}subscribeAIModerationFailed(e){return this.subscribeEvent("AI_MODERATION_FAILED",e)}subscribeUserBanned(e){return this.subscribeEvent("USER_BANNED",e)}subscribeUserUnbanned(e){return this.subscribeEvent("USER_UNBANNED",e)}subscribeBanEnforcement(e){return this.subscribeEvent("BAN_ENFORCEMENT",e)}subscribeTradeUpdateNotify(e){return this.subscribeEvent("TRADE_UPDATE_NOTIFY",e)}subscribeReactionErrors(e){return this.subscribeEvent("stream_reaction_error",e)}subscribeChatErrors(e){return this.subscribeEvent("stream_chat_error",e)}subscribeException(e){return this.subscribeEvent("exception",e)}getSubscribedTokens(){const e=[];for(const t of this.roomRefs.keys())t.startsWith(pd)&&e.push(t.slice(pd.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(fd)??0)>0}getSocket(){return this.socket}disconnect(){this.epoch+=1,this.authSequence+=1,this.pendingAuthenticate=null,this.inFlight?.settle(!1);const e=new Error("WebSocket disconnected");this.settleConnectWaiters(e);for(const t of[...this.roomWaiters.keys()])this.rejectWaiters(t,e);this.clearRoomStates();for(const e of this.subscribers.values())for(const t of e)t.active=!1;this.subscribers.clear(),this.roomRefs.clear(),this.explicitHolds.clear(),this.recentOccurrences.clear(),this.connectionStateListeners.clear(),this.reconnectListeners.clear();const t=this.socket;if(this.socket=null,null!==t){this.logger.debug("🔌 Disconnecting from Stream WebSocket");for(const e of this.managerCleanups)e();t.removeAllListeners();try{t.disconnect()}catch(e){this.logger.error("Error disconnecting socket:",e)}}this.managerCleanups=[],this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.lastEmitted=null,this.reconnectExhausted=!1,this.hasConnected=!1,this.connectionGeneration+=1,this.siteConfig={chatEnabled:void 0,streamingEnabled:void 0,commentsEnabled:void 0,webhooksEnabled:void 0,aiModerationEnabled:void 0},this.logger.debug("✅ Stream WebSocket disconnected and cleaned up")}dispose(){this.disposed=!0,this.disconnect()}}function xd(e){if(!_d(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function Ld(e){return null==e||""===e||"string"==typeof e&&(!vn(e)&&e.length<=Bn.BAN_REASON.MAX_LENGTH)}function Md(e){if(fn(e.tokenName,"tokenName",Cn),!Ld(e.reason))throw new rt(`reason must be at most ${Bn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function Ud(e){fn(e.tokenName,"tokenName",Rn)}function Fd(e){gn(0,void 0,Ln,e.pageSize)}function Pd(e){fn(e.tokenName,"tokenName",Rn)}class Bd extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async banToken(e){Md(e);const t=ye,n={tokenName:Kt(e.tokenName)};if(void 0!==e.reason)try{an(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:Kt(e.tokenName)}}async unbanToken(e){Ud(e);const t=this.buildEndpoint(ke,{tokenName:e.tokenName});return Lt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:Kt(e.tokenName)}}async listTokenBans(e={}){Fd(e);const t=be,n=this.buildPaginationParams(e,Ln);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(r);return{items:s.bans,pageInfo:s.pageInfo}}async getTokenBan(e){Pd(e);const t=this.buildEndpoint(Ne,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Kt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class Gd extends wn{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map,this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}async resolveTokenToVault(e){if(!dn(e))throw Tt("tokenName","Token name");const t=Kt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null!==r&&""!==r){const e=this.parseVaultAddressToTokenClassKey(r);this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:e,cachedAt:Date.now()})}return r}async resolveTokenClassKey(e){if(!dn(e))throw Tt("tokenName","Token name");const t=Kt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw At(e);const s=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(Kt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=Gd.MAX_CACHE_SIZE&&!this.cache.has(e)&&this.evictOldestEntry(),this.cache.set(e,t),this.updateAccessOrder(e)}updateAccessOrder(e){this.accessOrder.delete(e),this.accessOrder.add(e)}evictOldestEntry(){const e=this.accessOrder.values().next().value;void 0!==e&&""!==e&&(this.cache.delete(e),this.accessOrder.delete(e))}set(e,t){const n=Kt(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:Gd.MAX_CACHE_SIZE,hits:this.cacheHits,misses:this.cacheMisses,hitRate:t>0?this.cacheHits/t:0,oldestEntry:e.length>0?Math.min(...e):null,newestEntry:e.length>0?Math.max(...e):null}}getCachedTokenClassKey(e){const t=this.getCacheEntry(Kt(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=Kt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Ji(e)}catch(e){if(e instanceof rt)throw vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}Gd.MAX_CACHE_SIZE=1e4;class $d extends kn{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await Ft(()=>this.http.get($e),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new rt("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return Ft(()=>this.http.get(Ke,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){const t={tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method},{signal:n}=e;return So(await Ft(()=>void 0===n?this.http.get(He,t):this.http.request({method:"GET",url:He,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return So(await Ft(()=>this.http.get(We,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class Kd extends ni{constructor(e,t,n,r=!1,s){super(e,t,n,r,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,xn);const n={action:"trade_executed",tokenName:e,payload:t};await this.emitEvent(n)}async emitBalanceUpdated(e,t,n){this.validateRequiredString(e,"userAddress","User Address"),this.validateTokenName(t,xn);const r={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,xn);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,xn);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,xn);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,xn);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,xn);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,xn);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,xn);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,xn);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,xn);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,xn);const r={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:e,payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=e.userAddress),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const r=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(r)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new ct("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.includes(e)),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,xn);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const r=await this.getConnectedClients(n);return{clients:r.clients,count:r.summary.totalConnected,authenticatedCount:r.summary.authenticatedCount}}async getOnlineOverseers(){const e=await this.getConnectedClients({isOverseer:!0});return{clients:e.clients,count:e.summary.totalConnected}}async emitRecordingStatus(e,t){this.validateTokenName(e,xn);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,xn);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,xn);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class Hd{constructor(e={}){this.attempts=0,this.config={maxAttempts:e.maxAttempts??5,baseDelayMs:e.baseDelayMs??2e3,useExponentialBackoff:e.useExponentialBackoff??!1,maxDelayMs:e.maxDelayMs??3e4,backoffMultiplier:e.backoffMultiplier??2},this.currentDelayMs=this.config.baseDelayMs}shouldRetry(){return this.attempts<this.config.maxAttempts}getNextDelay(){return this.currentDelayMs}recordAttempt(){this.attempts++,this.config.useExponentialBackoff&&(this.currentDelayMs=Math.min(this.currentDelayMs*this.config.backoffMultiplier,this.config.maxDelayMs))}reset(){this.attempts=0,this.currentDelayMs=this.config.baseDelayMs}getAttempts(){return this.attempts}getMaxAttempts(){return this.config.maxAttempts}isExhausted(){return this.attempts>=this.config.maxAttempts}getState(){return{attempts:this.attempts,maxAttempts:this.config.maxAttempts,canRetry:this.shouldRetry(),nextDelayMs:this.currentDelayMs,exhausted:this.isExhausted()}}getStatusString(){return`${this.attempts}/${this.config.maxAttempts} attempts`}}class Wd{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const r=n??this.defaultTtlMs,s={value:t};r>0&&(s.expiresAt=Date.now()+r),this.cache.set(e,s)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}class Vd extends wn{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.hasOnAnyListener=!1,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.reconnectionManager=new Hd({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Wd(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),Vd.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof i.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)=>{Mo(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",ut(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=i.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.reconnectionManager.reset(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Socket.IO connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Socket.IO disconnected: ${e}`),this.handleReconnect()}),this.socket.on("error",e=>{this.logger.error("❌ Socket.IO error:",e)}),this.socket.onAny((e,...t)=>{if(""!==e&&t.length>0&&"object"==typeof t[0]&&null!==t[0]){const n=t[0],r=n.status??n.Status;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=dt(e)?e:new Error(ut(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const r=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),s={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,s),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,s=r?.data,o=r?.status??r?.Status??s?.status??s?.Status;let i=r?.message??r?.Message??s?.message??s?.Message??r?.error??s?.error;dn(i)||(i=o===$o.FAILED||o===$o.ERROR?"Transaction failed - check transaction details":o===$o.COMPLETED||o===$o.PROCESSED||o===$o.SUCCESS?"Transaction completed successfully":null!=o?`Transaction status: ${String(o)}`:"Unknown transaction status");const a=r?.blockHash??s?.blockHash,c=r?.gasUsed??s?.gasUsed,l=r?.Data??s?.Data,d={transactionId:e,status:this.mapSocketStatus(o),message:"string"==typeof i?i:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(o)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(i)}"`),n(d),d.status===exports.SDKTransactionStatus.COMPLETED||d.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} (${d.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Ho[t]??exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):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.logger.debug("🧹 Cleared event buffer"),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")),Vd.instances.delete(this)}static cleanupAll(e=!1){for(const e of Vd.instances)e.disconnect();Vd.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}Vd.instances=new Set;class jd extends kn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Weekly challenge operation failed";throw new Error(t)}return e.data}async getLeaderboard(e={}){const{limit:t=10}=e;if(t<1||t>50)throw new rt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(Ve.GET_LEADERBOARD,n),s=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new rt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=Ve.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),s=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}const qd=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class zd{constructor(e){this.bundleId=e.bundleId,this.uniqueKey=e.uniqueKey,this.method=e.method,this.waitForResult=e.wait}wait(e){return this.waitForResult(e)}}class Yd{constructor(e){this.bundleBaseUrl=ou(e.bundleBaseUrl),this.launchpadBaseUrl=ou(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>i.io(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:r,tokenName:s}=e;if("string"!=typeof t||""===t)throw Qd("bundleId");if(o=n,!qd.some(e=>e===o))throw Qd("method");var o;if("string"!=typeof r||""===r)throw Qd("uniqueKey");if(void 0!==s&&("string"!=typeof s||""===s))throw Qd("tokenName");if("CreateSale"===n&&void 0===s)throw Qd("tokenName");const i={method:n,dto:{uniqueKey:r,...void 0===s?{}:{tokenName:s}},stringsInstructions:[]};return new zd({bundleId:t,uniqueKey:r,method:n,wait:e=>this.waitForResult(i,t,e)})}async submit(e){let n;try{n=await this.signer.signTypedData(e.method,e.dto)}catch(e){throw function(e){if(e instanceof Fi)return e;if(t.isWalletUserRejection(e)){const n=e instanceof Error?e.message:"The signature was rejected in the wallet.",r=t.walletDeclineCode(e);return new Fi(n,"WALLET_USER_REJECTED",{details:void 0===r?{}:{walletCode:r}})}const n=e instanceof Error?e.message:"Launchpad signing failed.";return new Fi(n,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:n})}(e)}const r=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(n),s=`${this.bundleBaseUrl}/bundle`,o=await this.requestor(s,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:r})}),i=await ru(o);if(!o.ok)throw Zd(o.status,i,s);const a=function(e){if("string"==typeof e&&""!==e)return e;if(!su(e))throw new Fi("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(su(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new Fi("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),c=nu(e.dto,"uniqueKey");return new zd({bundleId:a,uniqueKey:c,method:e.method,wait:t=>this.waitForResult(e,a,t)})}waitForResult(e,t,n={}){const r=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,o=n.signal;return new Promise((n,i)=>{const a=this.confirmationUrl(e,t);if(!0===o?.aborted)return void i(Xd(e.method,t));const c=Date.now(),l=new AbortController,d=void 0===this.bundleSocketFactory;let u,h,g,p=!1;const m=()=>{f(()=>i(Xd(e.method,t)))},f=e=>{p||(p=!0,clearTimeout(A),o?.removeEventListener("abort",m),l.abort(),void 0!==u&&(void 0!==h&&u.off(t,h),d&&u.disconnect()),e())},E=()=>{f(()=>i(function(e,t){const n="string"==typeof e.dto.uniqueKey?e.dto.uniqueKey:"";return new Fi(`Timed out waiting for bundle ${n}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method,...void 0===t?{}:{lastReadFailure:{message:t.message,...void 0===t.status?{}:{status:t.status}}}}})}(e,g)))};o?.addEventListener("abort",m,{once:!0});const A=setTimeout(E,r);try{u=(this.bundleSocketFactory??this.socketFactory)(this.bundleBaseUrl),h=e=>{const t=function(e){if(!su(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(e);void 0!==t&&f(()=>{"FAILED"===t.status?i(Jd(t.data)):n(t)})},u.on(t,h)}catch{u=void 0,h=void 0}this.pollConfirmation({request:e,confirmationUrl:a,startedAt:c,timeoutMs:r,pollIntervalMs:s,signal:l.signal,onReadFailure:e=>{g=e}}).then(e=>{void 0===e?E():f(()=>n(e))},e=>f(()=>i(e instanceof Error?e:new Error(String(e)))))})}confirmationUrl(e,t){return"CreateSale"===e.method?function(e,t){const n=nu(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`}async pollConfirmation(e){const{request:t,confirmationUrl:n,startedAt:r,timeoutMs:s,pollIntervalMs:o,signal:i,onReadFailure:a}=e;for(;!i.aborted&&Date.now()-r<=s;){const e=await this.readConfirmation(t,n,i);if(i.aborted)return;if("processed"===e.kind)return e.result;if("failed"===e.kind)throw Jd(e.data);a("read-failed"===e.kind?e.error:void 0);const c=s-(Date.now()-r);if(c<=0)break;await iu(Math.min(Math.max(0,o),c),i)}}async readConfirmation(e,t,n){try{const r=await this.requestor(t,{method:"GET",signal:n}),s=await ru(r);if("CreateSale"===e.method)return r.ok?{kind:"processed",result:{status:"PROCESSED",data:tu(s)}}:404===r.status||202===r.status?{kind:"pending"}:{kind:"read-failed",error:Zd(r.status,s,t)};if(!r.ok)return{kind:"read-failed",error:Zd(r.status,s,t)};const o=su(s)?s.status:void 0;return"COMPLETED"===o||"PROCESSED"===o?{kind:"processed",result:{status:"PROCESSED",data:s}}:"FAILED"===o?{kind:"failed",data:s}:{kind:"pending"}}catch(e){const n=e instanceof Error?e.message:"The bundle confirmation read failed.";return{kind:"read-failed",error:new Fi(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function Xd(e,t){return new Fi("Waiting for the launchpad bundle was aborted. The bundle itself may still be processed: `attach` resumes it.","BUNDLE_WAIT_ABORTED",{details:{method:e,bundleId:t}})}function Qd(e){return new Fi(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function Jd(e){const t=eu(e)??"Launchpad bundle failed on chain.";return new Fi(t,"BUNDLE_FAILED",{chainMessage:t})}function Zd(e,t,n){const r=eu(t)??`Bundle request failed with HTTP ${e}`;return new Fi(r,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:r,details:{body:t,url:n}})}function eu(e){if("string"==typeof e&&""!==e)return e;if(su(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(su(n)){const e=eu(n);if(void 0!==e)return e}}}function tu(e){return su(e)?e.data??e.Data??e:e}function nu(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new Fi(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function ru(e){try{return await e.json()}catch{return e.text()}}function su(e){return"object"==typeof e&&null!==e}function ou(e){return e.replace(/\/$/u,"")}function iu(e,t){return new Promise(n=>{if(t.aborted)return void n();const r=()=>{clearTimeout(s),n()},s=setTimeout(()=>{t.removeEventListener("abort",r),n()},e);t.addEventListener("abort",r,{once:!0})})}function au(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new rt(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new rt(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new a(e).multipliedBy(new a(1).plus(new a(String(t)))).decimalPlaces(8,a.ROUND_UP).toFixed()}function cu(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=qi(t).type,r=await e.findTokenNameByVault(t,n);if(void 0===r)throw new rt(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return r}(e,t.vaultAddress);return au((await e.getTradeQuote("SellExactToken"===t.method?{tokenName:n,amount:t.quantity,type:"MEME",method:"IN"}:{tokenName:n,amount:t.quantity,type:"NATIVE",method:"OUT"})).reverseBondingCurveFee,t.feeSlippageFactor??e.defaultFeeSlippageFactor())}}const lu={minFeePortion:"0.1",maxFeePortion:"0.5"},du=/^(?:\d+\.?\d*|\.\d+)$/u,uu=/^[0-9A-Z]+$/u,hu=/^[A-Za-z0-9]+$/u,gu=new a("0.1"),pu=new a("0.5");function mu(e){if("string"!=typeof e||!du.test(e))return;const t=new a(e);return t.isFinite()?t.toFixed():void 0}function fu(e){return"string"==typeof e&&""!==e}function Eu(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function Au(e,t,n){void 0===n||fu(n)||e.push(`${t} must be a non-empty string`)}function Tu(e){const t=[];if("object"!=typeof e||null===e)throw new rt("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},r=n.tokenName;fu(r)?hu.test(r)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const s=n.tokenSymbol;fu(s)?uu.test(s.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const o=n.tokenDescription;fu(o)?o.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const i=n.tokenImage;fu(i)?i.length>500&&t.push("Token image must be at most 500 characters"):t.push("Token image is required");const c=n.preBuyQuantity;void 0!==c&&void 0===mu(c)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])Eu(t,e,n[e]);Au(t,"tokenCategory",n.tokenCategory),Au(t,"tokenCollection",n.tokenCollection);const l=n.saleStartTime;if(void 0===l||Number.isInteger(l)||t.push("saleStartTime must be an integer"),function(e,t){if(void 0!==t&&("object"!=typeof t||null===t))return void e.push("reverseBondingCurveConfiguration must be an object");const n=t??{},r=n.minFeePortion??lu.minFeePortion,s=n.maxFeePortion??lu.maxFeePortion,o=mu(r),i=mu(s);if(void 0===o&&e.push("minFeePortion must be a decimal number"),void 0===i&&e.push("maxFeePortion must be a decimal number"),void 0===o||void 0===i)return;const c=new a(o),l=new a(i);c.isLessThan(gu)&&e.push("minFeePortion must be greater than or equal to 0.1"),l.isGreaterThan(pu)&&e.push("maxFeePortion must be less than or equal to 0.5"),c.isGreaterThan(l)&&e.push("minFeePortion must be less than or equal to maxFeePortion")}(t,n.reverseBondingCurveConfiguration),t.length>0)throw new rt(t.join("; "),"data","VALIDATION_ERROR")}class vu{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress,this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){Tu(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:mu(e.preBuyQuantity??"0"),websiteUrl:e.websiteUrl??"",telegramUrl:e.telegramUrl??"",twitterUrl:e.twitterUrl??"",instagramUrl:e.instagramUrl??"",facebookUrl:e.facebookUrl??"",redditUrl:e.redditUrl??"",tiktokUrl:e.tiktokUrl??"",tokenCategory:e.tokenCategory??"Unit",tokenCollection:e.tokenCollection??"Token",uniqueKey:e.uniqueKey??Su(t)},r=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:mu(r?.minFeePortion??lu.minFeePortion),maxFeePortion:mu(r?.maxFeePortion??lu.maxFeePortion)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Yi(e)})}attach(e){return this.transport.attach(e)}buyWithNative(e){return this.submitTrade("BuyWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}buyExactToken(e){return this.submitTrade("BuyExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}sellWithNative(e){return this.submitTrade("SellWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}sellExactToken(e){return this.submitTrade("SellExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}async submitTrade(e,t,n){const r={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??await this.defaultExtraFees(e,t),uniqueKey:t.uniqueKey??Su(this.walletAddress)};return this.transport.submit({method:e,dto:r,stringsInstructions:zi(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new rt("A sell needs a reverse bonding curve fee ceiling and no quote source is configured: pass extraFees.maxAcceptableReverseBondingCurveFee.","extraFees","FEE_CEILING_REQUIRED");return{maxAcceptableReverseBondingCurveFee:await this.sellFeeCeiling({method:e,vaultAddress:t.vaultAddress,quantity:t.quantity,...void 0===t.tokenName?{}:{tokenName:t.tokenName}})}}}function Su(e){return`galaswap-operation-${o.v4()}-${Date.now()}-${e}`}function yu(e,t=3e4){return c.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const bu=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function Nu(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>Nu(e,t+1));if(e instanceof Map){const n={};for(const[r,s]of e.entries()){const e=String(r);n[e]=bu.has(e.toLowerCase())?"[REDACTED]":Nu(s,t+1)}return n}if("object"==typeof e){const n={};for(const[r,s]of Object.entries(e))n[r]=bu.has(r.toLowerCase())?"[REDACTED]":Nu(s,t+1);return n}return e}class ku{constructor(e,t={},n={signRequests:!0}){this.auth=e,this.signRequests=n.signRequests,this.session=n.session,this.debug=t.debug??!1,this.logger=new Vt({debug:this.debug,context:"HttpClient"});const r=t.baseUrl??Go("stage").launchpadBaseUrl,s=t.timeout??6e4;this.axios=yu(r,s),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),void 0!==this.session&&"omit"!==this.session.credentials&&(this.axios.defaults.withCredentials=!0),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return Mo(async()=>{const t=void 0!==this.session&&!1!==e.withSession&&!function(e){return void 0!==e&&Object.keys(e).some(e=>"authorization"===e.toLowerCase())}(e.headers),n=t&&void 0!==this.session?await this.session.accessToken():null,r=this.toAxiosConfig(e,n);e.headers&&this.logger.debug("Custom headers provided:",Object.keys(r.headers??{}));const s=e.data instanceof FormData?"[FormData object - multipart/form-data]":Nu(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:Nu(r.params),data:s,isFormData:e.data instanceof FormData,contentType:r.headers?.["Content-Type"]??"not set"});const o=await this.sendWithSession(e,r,t,n),i=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,r]of Object.entries(e))"string"==typeof r?t[n.toLowerCase()]=r:"number"!=typeof r&&"boolean"!=typeof r||(t[n.toLowerCase()]=String(r));return t}(o.headers);return this.logger.debug("Response:",{status:o.status,data:Nu(o.data),transactionId:i["x-transaction-id"],blockNumber:i["x-block-number"]}),{data:o.data,headers:i,status:o.status}},`HTTP ${e.method} ${e.url}`,this.logger)}toAxiosConfig(e,t){const n=null===t?e.headers:{...e.headers,Authorization:`Bearer ${t}`},r={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Ic(e.params)},...void 0!==n&&{headers:{...n}},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};if(e.data instanceof FormData){const e=new c.AxiosHeaders(n);e.set("Content-Type",void 0),r.headers=e,this.logger.debug("FormData detected - clearing the JSON Content-Type default for the multipart upload")}return r}async sendWithSession(e,t,n,r){try{return await this.axios.request(t)}catch(t){if(!n||void 0===this.session||!function(e){if("object"!=typeof e||null===e||!("response"in e))return!1;const t=e.response;return"object"==typeof t&&null!==t&&"status"in t&&401===t.status}(t))throw t;const s=await this.session.onUnauthorized(r);if(null===s)throw t;return this.logger.debug("Retrying once with the refreshed session token"),await this.axios.request(this.toAxiosConfig(e,s))}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return Mo(async()=>{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()}},"Failed to generate custom signature for message",this.logger)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.signRequests&&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("Skipping signature header (no wallet, or signRequests is off)");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e instanceof Error?e:new Error(String(e)))),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,r={message:n?.message??ut(e),...n&&"string"==typeof n.error&&""!==n.error&&{error:n.error},statusCode:t.response.status,...n&&Boolean(n.details)&&{details:n.details},...n&&Boolean(n.timestamp)&&{timestamp:n.timestamp},...n&&Boolean(n.path)&&{path:n.path}};t.launchpadError=r,this.logger.error("Backend error:",r)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(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")}}class wu extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class _u extends Error{constructor(e,t,n){super(`Transaction ${e} failed with status: ${t}${void 0!==n?` - ${n}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function Iu(e,t){if(hn(e))throw new wu(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new wu(`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 wu(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Cu(e,t,n,r){Iu(e,t);const s=e,o=s.data??{};if(!function(e){if(hn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(o))throw new wu(`Invalid trade data received for transaction ${t}`);const i={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:o.inputQuantity??r.amount,outputAmount:o.outputQuantity??r.expectedAmount??"0",totalFees:o.totalFees??"0",tokenName:r.tokenName,vaultAddress:o.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(i.blockHash=s.blockHash),void 0!==s.gasUsed&&(i.gasUsed=s.gasUsed),void 0!==r.slippageToleranceFactor&&(i.slippageTolerance=r.slippageToleranceFactor),i}function Du(t){return void 0!==t&&r.isPrivateKeyProvider(t)?new e.Wallet(t.exportPrivateKey()):void 0}const Ru={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function Ou(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const xu=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function Lu(e,t,n){if(void 0===e||void 0===t)return;const r=xu.exec(e)?.[1],s=xu.exec(t)?.[1];if(void 0!==r&&void 0!==s&&r.toLowerCase()!==s.toLowerCase())throw yt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class Mu{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=Du(e.walletProvider)):e.wallet&&(n=e.wallet,t=r.PrivateKeyProvider.fromWallet(e.wallet)),this.wallet=n;const s=e.env??"prod",o=Go(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??o.launchpadBaseUrl,gatewayBaseUrl:o.gatewayBaseUrl,bundleBaseUrl:o.bundleBaseUrl,webSocketUrl:o.webSocketUrl,dexApiBaseUrl:o.dexApiBaseUrl,dexBackendBaseUrl:o.dexBackendBaseUrl,launchpadFrontendUrl:o.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==n?new Wi(n.privateKey):void 0),a=void 0!==n?`eth|${n.address.slice(2)}`:Ou(i);Lu(a,e.walletAddress,"walletAddress"),Lu(a,e.galaChainAddress,"galaChainAddress");const c=e.walletAddress??e.galaChainAddress??(void 0!==n?`eth|${n.address.slice(2)}`:Ou(i)),l=i??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},d=c??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==c?{signer:e.signer,walletAddress:c}:void 0;const u=new Yd({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:l,walletAddress:d,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),h=cu({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=h,this.launchpad=new vu({transport:u,walletAddress:d,sellFeeCeiling:h}),this.logger=new Vt({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Mu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Mu.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??Mu.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===n?c:void 0),this.auth=new Po({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"});const g=e.session;if(void 0!==g){if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.credentials;return"function"==typeof t.accessToken&&"function"==typeof t.onUnauthorized&&(void 0===n||"include"===n||"omit"===n)}(g))throw yt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw yt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===g?new xo:new Lo,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new ku(this.auth,this.config,{signRequests:!0,session:g}),this.sessionAuth=new Fo(this.http,this.auth,this.jwtAuth,e.debug??!1,g);const p={signRequests:!1};this.galaChainHttp=new ku(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},p),this.bundleHttp=new ku(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},p),this.dexApiHttp=new ku(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},p),this.dexBackendHttp=new ku(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},p),this.galaChainPublicAxios=yu(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new In(e.debug??!1),this.launchpadService=new Xc(this.http,this.jwtAuth),this.tokenResolverService=new Gd(this.launchpadService.poolService),this.launchpadAPI=new Io(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new Sc(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new _a(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new Vd({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new Nl(this.galaChainHttp),this.tradingQuotesService=new $d(this.http,e.debug??!1)}createOverrideSdk(t){if(!dn(t))throw yt("Invalid privateKey: must be a non-empty string","privateKey");if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw yt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new e.Wallet(t),r={...this.config,wallet:n};return new Mu(r)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Tt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw Tt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new rt("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e),this.onWalletChanged()}onWalletChanged(){this.walletGeneration+=1,this.galaChainAddressOverride=void 0,this.signerWalletAddress=void 0,this.rebuildTokenWrites(),this.bundleService=this.createBundleService(),this._bridgeService=void 0,this._wrapService=void 0,this._galaConnectClient=void 0,this._streamWebSocketService?.deauthenticate()}createBundleService(){return new ca(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,this.wallet,this.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor,this.sellFeeCeiling)}rebuildTokenWrites(){this.tokenWriter=void 0,this.galaChainService=new Sc(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?Du(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:r,streamAdminApiKey:s,userApiKey:o,accessToken:i,headers:a,...c}=this.config;return{...c,...void 0!==s&&{streamAdminApiKey:"[REDACTED]"},...void 0!==o&&{userApiKey:"[REDACTED]"},...void 0!==i&&{accessToken:"[REDACTED]"},...void 0!==a&&{headers:Object.fromEntries(Object.keys(a).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:$t.GAS_FEE}}getVersion(){return Wo}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw yt("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.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=await this.fetchTokenDistribution(e),r=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===r)return null;const s=n.holders[r];return void 0===s?null:{rank:r+1,balance:s.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,s=t?.maxBalance??1/0,o=Math.min(t?.limit??100,1e3),i=new Map;return n.holders.forEach((e,t)=>{i.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=s}).map(e=>({...e,rank:i.get(e.address)??0})).slice(0,o)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const t="object"==typeof e&&null!==e?e:{};if(void 0!==t.tokenId)throw new rt("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",nt.INVALID_PARAMETERS);const n=t.tokenName;return this.priceService.fetchLaunchpadTokenSpotPrice("string"==typeof n?n:"",e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.galaChainService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.launchpadAPI.fetchPoolDetails(e),n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return t.currentSupply=n.currentSupply,t.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,t.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,t.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,t.tokenName=e,t}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 ar}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none"})}loadCoreBridge(){const e=this.config.bridge;return void 0===e?Promise.reject(yt("The bridge and wrap methods need gala-core-sdk's ./bridge: create the SDK with `bridge: () => import('@gala-chain/gala-core-sdk/bridge')` (it needs the optional peers ethers, @solana/web3.js and @solana/spl-token).","bridge")):(this.coreBridgeLoad??(this.coreBridgeLoad=Promise.resolve().then(()=>e()).then(e=>{if("object"!=typeof(t=e)||null===t||"function"!=typeof t.BridgeService)throw new Error("the module has no BridgeService export");var t;return e}).catch(e=>{throw this.coreBridgeLoad=void 0,yt(`The bridge and wrap methods use @gala-chain/gala-core-sdk/bridge, which needs its optional peers ethers, @solana/web3.js and @solana/spl-token installed: ${ut(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw yt("The wallet changed while this bridge or wrap call was starting; nothing was sent. Call it again.","wallet");return t}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new e.BridgeService({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(e),environment:this.environment,...void 0!==this.config.ethereumRpcUrl&&""!==this.config.ethereumRpcUrl?{ethereumRpcUrl:this.config.ethereumRpcUrl}:{},...void 0!==this.config.solanaRpcUrl&&""!==this.config.solanaRpcUrl?{solanaRpcUrl:this.config.solanaRpcUrl}:{}})}return this._bridgeService}getBridgeableTokenService(e){return this._bridgeableTokenService??(this._bridgeableTokenService=new e.BridgeableTokenService(this.dexApiHttp)),this._bridgeableTokenService}getWrappableTokenService(e){return this._wrappableTokenService??(this._wrappableTokenService=new e.WrappableTokenService(this.dexApiHttp)),this._wrappableTokenService}getGalaConnectClient(e){if(void 0===this._galaConnectClient){const t=this.getAddress();if(void 0===this.config.dexApiBaseUrl||""===this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new e.GalaConnectClient({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:t})}return this._galaConnectClient}getWrapService(e){if(!this._wrapService){const t=this.getWallet();this._wrapService=new e.WrapService({galaConnectClient:this.getGalaConnectClient(e),wrappableTokenService:this.getWrappableTokenService(e),...void 0!==t&&{walletAddress:this.getAddress(),signer:new Wi(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new id(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new Vl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Ni(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Bd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new ri(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new jd(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new wl(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Hl(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new yc(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new Fa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new kl(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new la(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new pi(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new El(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new ya(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new Gl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Kd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Na(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}async resolveReferralAddress(e){if(void 0===e||""===e)return this.getAddress();if(e.startsWith("client|"))return e;const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar}),n=t(e);if(void 0===n)throw new rt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new rl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new Wl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new Kl(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new Ca(this.http,this.config.events)),this._eventsBatcherService}getStreamWebSocketService(){if(null===this._streamWebSocketService||void 0===this._streamWebSocketService){if(void 0===this.config.streamWebSocketUrl||""===this.config.streamWebSocketUrl)throw new Error('Stream WebSocket URL is required for real-time streaming features.\n\nConfigure SDK:\n const sdk = createLaunchpadSDK({\n wallet: yourWallet,\n streamWebSocketUrl: getEnvironmentConfig("stage").launchpadBaseUrl\n });\n\nFor MCP Server, set STREAM_WEBSOCKET_URL environment variable.\nSee SDK documentation for streaming configuration details.');this._streamWebSocketService=new Od({url:this.config.streamWebSocketUrl,tokenProvider:()=>this.streamSocketToken(),...void 0!==this.config.streamReconnectAttempts&&{reconnectAttempts:this.config.streamReconnectAttempts},...void 0!==this.config.streamReconnectDelay&&{reconnectDelay:this.config.streamReconnectDelay},...void 0!==this.config.streamReconnectDelayMax&&{reconnectDelayMax:this.config.streamReconnectDelayMax}},this.config.debug??!1)}return this._streamWebSocketService}async streamSocketToken(){const e=this.config.session;return void 0!==e?e.accessToken():this.ensureValidToken()}get realtime(){return this.getStreamWebSocketService()}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService(await this.coreBridge()).requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService(await this.coreBridge()).fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService(await this.coreBridge()).fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService(await this.coreBridge()).getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService(await this.coreBridge()).getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService(await this.coreBridge()).isTokenWrappable(e)}async wrapToken(e){return this.getWrapService(await this.coreBridge()).wrapToken(e)}async unwrapToken(e){return this.getWrapService(await this.coreBridge()).unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateUnwrapFee(e,t)}async login(){return this.sessionAuth.login()}async loginWithSignature(e){return this.sessionAuth.loginWithSignature(e)}async loginWithDevBypass(e){return this.sessionAuth.loginWithDevBypass(e)}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService();return{tokenName:e,pinnedMessage:(await t.getPinnedMessage(e)).message}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);return{tokenName:e,pinnedMessage:(await n.getPinnedMessage(e)).message}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.messageId),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.messageId}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async getHealth(){return this.getHealthService().getHealth()}async getEventStats(){return this.getEventsQueryService().getEventStats()}async queryEvents(e={}){return this.getEventsQueryService().queryEvents(e)}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content,type:"COMMENT"})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content,type:"CHAT_MESSAGE"})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async getPoolRealtimeState(e){const[t,n,r,s]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{recentTradesError:String(r.reason)},price:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{priceError:String(s.reason)}}}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.addCallbacks(e)}async authenticateStreamWebSocket(e){return this.getStreamWebSocketService().authenticate(e)}deauthenticateStreamWebSocket(){this._streamWebSocketService?.deauthenticate()}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_STATUS",e)}onUserBanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_BANNED",e)}onUserUnbanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_UNBANNED",e)}onBanEnforcement(e){return this.getStreamWebSocketService().subscribeEvent("BAN_ENFORCEMENT",e)}watchBanEnforcement(e,t={}){const n=(e,n,r,s)=>(void 0===t.actionType||t.actionType===e)&&((void 0===t.userAddress||t.userAddress===n)&&((void 0===t.tokenName||t.tokenName===r)&&!!(void 0===t.reason||null!==s&&s.includes(t.reason)))),r=this.onUserBanned(t=>{const r=t.userAddress??null,s=t.reason??null;n("BANNED",r,t.tokenName,s)&&e({actionType:"BANNED",userAddress:r,tokenName:t.tokenName,reason:s,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})}),s=this.onUserUnbanned(t=>{const r=t.userAddress??null;n("UNBANNED",r,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:r,tokenName:t.tokenName,reason:null})}),o=this.onBanEnforcement(t=>{const r=t.reason??null;n("ENFORCEMENT",null,t.tokenName,r)&&e({actionType:"ENFORCEMENT",userAddress:null,tokenName:t.tokenName,reason:r,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})});return()=>{r(),s(),o()}}watchTokenRoomEvent(e,t,n,r){const s=r.tokenName;if(void 0===s||""===s)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);return t(s,n)}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{void 0!==t.authorAddress&&t.authorAddress!==n.userAddress||void 0!==t.minLength&&n.content.length<t.minLength||e(n)},t)}watchHolderCountUpdated(e,t={}){return this.watchTokenRoomEvent("watchHolderCountUpdated",(e,t)=>this.getStreamWebSocketService().subscribeHolderCountUpdated(e,t),n=>{void 0!==t.minThreshold&&Math.abs(n.change??0)<t.minThreshold||e(n)},t)}watchModeratorAdded(e,t={}){return this.watchTokenRoomEvent("watchModeratorAdded",(e,t)=>this.getStreamWebSocketService().subscribeModeratorAdded(e,t),e,t)}watchPoolMetadataUpdated(e,t={}){return this.watchTokenRoomEvent("watchPoolMetadataUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolMetadataUpdated(e,t),e,t)}watchTradeExecuted(e,t={}){return this.watchTokenRoomEvent("watchTradeExecuted",(e,t)=>this.getStreamWebSocketService().subscribeTradeExecuted(e,t),n=>{void 0!==t.tradeType&&t.tradeType!==n.tradeType||void 0!==t.userAddress&&t.userAddress!==n.userAddress||void 0!==t.minAmount&&Number(n.inputAmount)<t.minAmount||e(n)},t)}watchTokenBanned(e,t={}){return this.watchTokenRoomEvent("watchTokenBanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenBanned(e,t),e,t)}watchModeratorChanged(e,t={}){const n=(e,n)=>(void 0===t.eventType||t.eventType===e)&&(void 0===t.moderatorAddress||t.moderatorAddress===n),r=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),s=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),o=this.watchTokenRoomEvent("watchModeratorRoleUpdated",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRoleUpdated(e,t),t=>{n("ROLE_UPDATED",t.userAddress)&&e({actionType:"ROLE_UPDATED",tokenName:t.tokenName,moderatorAddress:t.userAddress,oldRole:t.oldRole,newRole:t.newRole})},t);return()=>{r(),s(),o()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,r=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),s=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),o=this.watchTokenRoomEvent("watchPoolBadgeAssigned",(e,t)=>this.getStreamWebSocketService().subscribePoolBadgeAssigned(e,t),t=>{n("BADGE_ASSIGNED")&&e({updateType:"BADGE_ASSIGNED",tokenName:t.tokenName,details:t})},t);return()=>{r(),s(),o()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,r=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),s=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{r(),s()}}onContentFlagged(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_FLAGGED",e)}onFlagResolved(e){return this.getStreamWebSocketService().subscribeEvent("FLAG_RESOLVED",e)}onStreamChatMessage(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_MESSAGE",e)}onStreamChatUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UPDATED",e)}onStreamChatDeleted(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_DELETED",e)}onStreamChatPinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_PINNED",e)}onStreamChatUnpinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UNPINNED",e)}onChatStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("CHAT_STATUS_CHANGED",e)}onViewerCountChanged(e){return this.getStreamWebSocketService().subscribeEvent("VIEWER_COUNT",e)}onRecordingStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("RECORDING_STATUS",e)}onSimulcastStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("SIMULCAST_STATUS",e)}onDownloadReady(e){return this.getStreamWebSocketService().subscribeEvent("DOWNLOAD_READY",e)}onRecordingsCountUpdated(e){return this.getStreamWebSocketService().subscribeEvent("RECORDINGS_COUNT_UPDATED",e)}onUserTyping(e){return this.getStreamWebSocketService().subscribeEvent("USER_TYPING",e)}onStreamReaction(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_REACTION",e)}onContentReactionAdded(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_ADDED",e)}onContentReactionRemoved(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_REMOVED",e)}onStreamCountdownUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_COUNTDOWN_UPDATED",e)}onStreamLanguageUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_LANGUAGE_UPDATED",e)}onStreamControlStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CONTROL_STATUS_CHANGED",e)}onConnection(e){return this.getStreamWebSocketService().subscribeEvent("connection",e)}onAuthenticated(e){return this.getStreamWebSocketService().subscribeEvent("authenticated",e)}onTokenSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_subscribed",e)}onTokenUnsubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_unsubscribed",e)}onRoomSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("room_subscribed",e)}onRoomLeft(e){return this.getStreamWebSocketService().subscribeEvent("room_left",e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEvent("ENGAGEMENT_STATS_UPDATED",e)}async estimateBridgeFee(e){return this.getBridgeService(await this.coreBridge()).estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService(await this.coreBridge()).bridgeOut(e)}async bridgeIn(e){return this.getBridgeService(await this.coreBridge()).bridgeIn(e)}async getBridgeStatus(e){return this.getBridgeService(await this.coreBridge()).getBridgeStatus(e)}async getSupportedBridgeTokens(){const e=this.getBridgeService(await this.coreBridge()),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return oa}),r=t(e.tokenId),{collection:s,category:o,type:i,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:o,additionalKey:a,type:i},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Ht(e.tokenName),r=Ru[t];if(void 0!==r)return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:"Unit",additionalKey:"none",type:"none"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,pageSize:1,...void 0!==n?{address:n}:{}})).tokens[0];if(void 0===t)return null;const r=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:r.collection,category:r.category,tokenId:Xi(r)}}throw Tt("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:s,calculateAmountMode:o,currentSupply:i}=e;let a=t;void 0===o&&void 0===i||(a={tokenName:t,...void 0!==o&&{calculateAmountMode:o},...void 0!==i&&{currentSupply:i}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==s&&(l.privateKey=s),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw bt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Cu(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw bt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Cu(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.launchToken(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{Iu(n,t);const r=n.data??{};if(!function(e){if(hn(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)}(r))throw new wu(`Invalid launch data received for transaction ${t}`);const s={transactionId:t,vaultAddress:r.vaultAddress??"",tokenStringKey:r.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:r.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(s.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(s.preBuyQuantity=e.preBuyQuantity),""!==s.vaultAddress&&this.tokenResolverService.set(e.tokenName,s.vaultAddress),s})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(d,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,r=e?.limit??10,s={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},o=await this.dexApiHttp.get(u,s,{"x-wallet-address":t});if(!Array.isArray(o))throw new at("Unexpected API response: expected array, got "+typeof o);return{referrals:o,page:n,limit:r,hasMore:o.length===r}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:s=20,concurrency:o=1,startPage:i=1}=t,a=[];let c=i;const l=i+n-1;let d=!0,u=0;if(o<=1)for(;d&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),u=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${o}`);d&&c<=l;){const t=[];for(let e=0;e<o&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,o=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===o||404===o)return r&&r.debug(`Auto-pagination: page ${t} returned ${o} (end of pagination)`,{statusCode:o}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),i=await Promise.all(n);for(const e of i){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(a.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${u}`),{items:a,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=await this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(h,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new at(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar}),{address:n,...r}=e,s=void 0===n?void 0:t(n),o={...r,...void 0!==s&&{address:s}};if(void 0!==o.privateKey&&""!==o.privateKey){const e=this.createOverrideSdk(o.privateKey),{privateKey:t,...n}=o;return e.updateProfile(n)}return this.launchpadService.updateProfile(o)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar}),n=void 0===e.address?void 0:t(e.address)??e.address,r={...e,...void 0!==n&&{address:n}};if(void 0!==r.privateKey&&""!==r.privateKey){const e=this.createOverrideSdk(r.privateKey),{privateKey:t,...n}=r;return e.uploadProfileImage(n)}return this.launchpadService.uploadProfileImage(r)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar}),n=t(e?.address)??this.getAddress(),r={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(r.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar}),n={type:"created",address:t(e?.address)??this.getAddress(),pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(n.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(n.search=e.search),void 0!==e?.status&&(n.status=e.status),this.launchpadService.fetchTokenList(n)}async getManagedTokens(e){return this.launchpadService.getManagedTokens(e??{})}async getUserGalaBalance(e){return this.launchpadService.getUserGalaBalance(e)}async fetchReferralCode(){return this.launchpadService.fetchReferralCode()}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferGala(r)}return this.assertTokenWriter(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferToken(r)}return this.assertTokenWriter(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async convertTokenNameToTokenClassKey(e){return this.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(void 0!==e.lockAuthority&&""!==e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ar});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.assertTokenWriter(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.assertTokenWriter(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let r=0;r<10;r+=1){const r=await this.launchpadService.poolService.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),s=r.items.find(t=>t.vaultAddress===e);if(void 0!==s)return s.tokenName;const o=Yo(r.pageInfo,n);if(void 0===o)return;n=o}}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{rn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw yt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw yt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw yt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw yt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw yt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw yt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw yt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Qt("string"==typeof e||"number"==typeof e?e:String(e),Mu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${Mu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Mu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Qt("string"==typeof e||"number"==typeof e?e:String(e),Mu.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${String(e)}, using default: ${Mu.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Mu.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if(n.status!==exports.SDKTransactionStatus.COMPLETED)throw new _u(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof wu)throw t;throw new wu(`Failed to transform WebSocket response for transaction ${e}`,dt(t)?t:new Error(ut(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof _u||t instanceof wu)throw t;throw new wu(`WebSocket confirmation failed for transaction ${e}`,dt(t)?t:new Error(ut(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return yh});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const s=t?.creatorAddress,o=new Map;let i=!0,a=null;let c=0;const l=async()=>{if(i){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{o.has(t.tokenName)||((e=>{if(o.set(e,!0),o.size>1e3){const e=o.keys().next().value;void 0!==e&&o.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=ut(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=r*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{i=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw yt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const s=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n=(e,t="")=>{const n=r[e];return"string"==typeof n&&""!==n?n:t},s={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===r.isFinalized};this.matchesCreatorFilter(s,t?.creatorFilter)&&e(s)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${ut(e)}`)}};let o=this.websocketService.getSocket();if(o)o.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${ut(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(o=this.websocketService.getSocket(),!o&&e<Mu.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),Mu.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!o&&e>=Mu.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Mu.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Mu.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}o&&(o.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};i()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.dispose(),this._streamWebSocketService=void 0),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new Vt({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),Vd.cleanupAll(e),t.debug("Global cleanup completed")}}function Uu(n){const r=t.createWallet(n);return{...r,wallet:new e.Wallet(r.privateKey)}}function Fu(){const e=globalThis;return e.process?.env??{}}Mu.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Mu.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Mu.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=$t.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Mu.DEFAULT_CALCULATE_AMOUNT_MODE=tt.LOCAL,Mu.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Mu.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;function Pu(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function Bu(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Gu(e){if(null==e||"object"!=typeof e)return 0;const t=e;if("number"==typeof t.status)return t.status;if("number"==typeof t.statusCode)return t.statusCode;if("number"==typeof t.code)return t.code;const n=t.response;return n&&"number"==typeof n.status?n.status:0}function $u(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function Ku(e){if(void 0!==e&&e.length>0&&!/^[a-z0-9]+$/.test(e.toLowerCase()))throw new Error(`Invalid asset extension format: "${e}". Must contain only alphanumeric characters.`)}function Hu(e,t){return`${e.replace(/\/$/,"")}${t}`}const Wu=new Map;const Vu={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},ju=co({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),qu=co({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});Rn.MIN_LENGTH,Rn.MAX_LENGTH,Rn.PATTERN;pn({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function zu(e){return"global"===e||"token"===e}function Yu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.tokenName&&"string"==typeof t.createdAt}function Xu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}const Qu=pn({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function Ju(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}var Zu,eh,th,nh,rh,sh;exports.AnalysisStatus=void 0,(Zu=exports.AnalysisStatus||(exports.AnalysisStatus={})).PENDING="PENDING",Zu.PROCESSING="PROCESSING",Zu.COMPLETED="COMPLETED",Zu.FAILED="FAILED",exports.AnalysisType=void 0,(eh=exports.AnalysisType||(exports.AnalysisType={})).TEXT="TEXT",eh.IMAGE="IMAGE",eh.VIDEO="VIDEO",exports.AIRecommendation=void 0,(th=exports.AIRecommendation||(exports.AIRecommendation={})).NO_ACTION="NO_ACTION",th.REVIEW_REQUIRED="REVIEW_REQUIRED",th.DELETE_CONTENT="DELETE_CONTENT",th.BAN_USER="BAN_USER",th.DELETE_AND_BAN="DELETE_AND_BAN",exports.AnalysisCategory=void 0,(nh=exports.AnalysisCategory||(exports.AnalysisCategory={})).VIOLENCE="VIOLENCE",nh.HATE_SPEECH="HATE_SPEECH",nh.SEXUAL_CONTENT="SEXUAL_CONTENT",nh.HARASSMENT="HARASSMENT",nh.SPAM="SPAM",nh.SCAM="SCAM",nh.SELF_HARM="SELF_HARM",nh.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",nh.MISINFORMATION="MISINFORMATION",nh.COPYRIGHT="COPYRIGHT",nh.SAFE="SAFE",exports.AnalysisTier=void 0,(rh=exports.AnalysisTier||(exports.AnalysisTier={})).QUICK="QUICK",rh.DETAILED="DETAILED",exports.AIModerationMode=void 0,(sh=exports.AIModerationMode||(exports.AIModerationMode={})).DISABLED="DISABLED",sh.ADVISORY="ADVISORY";const oh={[exports.AnalysisStatus.PENDING]:"Pending",[exports.AnalysisStatus.PROCESSING]:"Processing",[exports.AnalysisStatus.COMPLETED]:"Completed",[exports.AnalysisStatus.FAILED]:"Failed"},ih={[exports.AIRecommendation.NO_ACTION]:"No Action Needed",[exports.AIRecommendation.REVIEW_REQUIRED]:"Human Review Required",[exports.AIRecommendation.DELETE_CONTENT]:"Delete Content",[exports.AIRecommendation.BAN_USER]:"Ban User",[exports.AIRecommendation.DELETE_AND_BAN]:"Delete & Ban"},ah={[exports.AnalysisCategory.VIOLENCE]:"Violence",[exports.AnalysisCategory.HATE_SPEECH]:"Hate Speech",[exports.AnalysisCategory.SEXUAL_CONTENT]:"Sexual Content",[exports.AnalysisCategory.HARASSMENT]:"Harassment",[exports.AnalysisCategory.SPAM]:"Spam",[exports.AnalysisCategory.SCAM]:"Scam",[exports.AnalysisCategory.SELF_HARM]:"Self Harm",[exports.AnalysisCategory.ILLEGAL_ACTIVITY]:"Illegal Activity",[exports.AnalysisCategory.MISINFORMATION]:"Misinformation",[exports.AnalysisCategory.COPYRIGHT]:"Copyright",[exports.AnalysisCategory.SAFE]:"Safe"},ch={[exports.AnalysisTier.QUICK]:"Quick Scan",[exports.AnalysisTier.DETAILED]:"Detailed Scan"},lh={[exports.AnalysisType.TEXT]:"Text",[exports.AnalysisType.IMAGE]:"Image",[exports.AnalysisType.VIDEO]:"Video"},dh={[exports.AIModerationMode.DISABLED]:"Disabled",[exports.AIModerationMode.ADVISORY]:"Advisory"},uh=pn(exports.AnalysisStatus),hh=pn(exports.AnalysisType),gh=pn(exports.AIRecommendation),ph=pn(exports.AnalysisCategory),mh=pn(exports.AnalysisTier),fh=pn(exports.AIModerationMode),Eh=An([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:uh},{field:"analysisType",type:"string",validator:hh},{field:"provider",type:"string"}]),Ah=An([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:fh},{field:"provider",type:"string"}]);function Th(e){return null!==e.analysisTier}function vh(e){if(!dn(e))throw Tt("content");if(0===e.trim().length)throw Ot("content","Content");if(e.length>Bn.COMMENTS_V1.MAX_LENGTH)throw Rt("content",Bn.COMMENTS_V1.MAX_LENGTH,e.length)}function Sh(e){if(!dn(e))throw Tt("content");if(0===e.trim().length)throw new rt("content cannot be empty","content",nt.REQUIRED);if(e.length>Bn.CHAT_MESSAGES_V1.MAX_LENGTH)throw new rt(`content must be at most ${Bn.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",nt.TOO_LONG)}var yh=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=Qt(e.reverseBondingCurveMinFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=r}if(void 0!==e.reverseBondingCurveMaxFeePortion){const r=Qt(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.ACTIVE_USER_TYPE=mi,exports.AI_MODE_LABELS=dh,exports.AI_RECOMMENDATION_LABELS=ih,exports.ALL_PERMISSIONS=ai,exports.ANALYSIS_CATEGORY_LABELS=ah,exports.ANALYSIS_STATUS_LABELS=oh,exports.ANALYSIS_TIER_LABELS=ch,exports.ANALYSIS_TYPE_LABELS=lh,exports.API_KEY_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.API_KEY_ROLE=si,exports.API_KEY_ROLES=oi,exports.API_KEY_ROLE_HIERARCHY=gi,exports.AddressFormatter=Yn,exports.AgentConfig=class{constructor(){this.utilityInstance=!0,this.utilityInstance}static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=this.buildSdkConfig(e,t,n),s=new Mu(r),o={sdk:s,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(s,n);return{...o,validation:e}}return o}static readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.buildSdkConfig(e,t),r=new Mu(n);return Promise.resolve({sdk:r,config:n})}static async validateSetup(e,t){const n=[],r=[],s={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(s.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=Qt(t.quantity,0);s.hasBalance=e>0,s.canTrade=e>=.1,s.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${ut(e)}`)}try{const t=await e.fetchPools({type:"recent",pageSize:1});null!==t.items&&void 0!==t.items&&0!==t.items.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${ut(e)}`)}return{ready:0===n.length&&s.connectionHealthy,sdk:e,wallet:t??Uu(),issues:n,warnings:r,capabilities:s}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"prod":Object.assign(n,{debug:!1,timeout:3e4});break;case"stage":Object.assign(n,{debug:!0,timeout:45e3})}switch(t){case"trading":n.timeout=1.5*(n.timeout??3e4);break;case"creation":n.timeout=2*(n.timeout??3e4);break;case"monitoring":n.timeout=.5*(n.timeout??3e4);break;case"general":break;default:throw new Error(`Unexpected useCase: ${String(t)}`)}return n}static async multiWalletSetup(e,t="stage"){const n={};for(const[r,s]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:s,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){return"stage"===(Fu().LAUNCHPAD_ENV??Fu().ENVIRONMENT)?"stage":"prod"}static setupWallet(e){if(void 0===e||""===e){const e=Fu().PRIVATE_KEY;return void 0!==e&&""!==e?Uu(e):Uu()}return"generate"===e?Uu():Uu(e)}static buildSdkConfig(e,t,n){const r=e.galaChainAddress??Fu().WALLET_ADDRESS;return{wallet:n?.wallet,baseUrl:e.baseUrl??this.getDefaultBaseUrl(t),timeout:e.timeout??this.getDefaultTimeout(t),debug:e.debug??"prod"!==t,...this.getEnvironmentDefaults(t),...e.config??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{},env:t}}static getDefaultBaseUrl(e){return Go(e).launchpadBaseUrl}static getDefaultTimeout(e){switch(e){case"prod":return 3e4;case"stage":return 45e3}}static getEnvironmentDefaults(e){const t=Go(e);return{bundleBaseUrl:t.bundleBaseUrl,gatewayBaseUrl:t.gatewayBaseUrl}}},exports.AuthError=Oo,exports.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},exports.BrowserWalletSigner=ji,exports.BundleSubmission=zd,exports.BundlerTransport=Yd,exports.BurnError=hc,exports.CALCULATION_MODES=tt,exports.CONTENT_REACTION_TYPES=ba,exports.CONTENT_TYPE_LABELS=ga,exports.ChartService=class extends kn{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Tt("options","Chart options");const{tokenName:t,from:n,to:r,resolution:s}=e;if(null==t||""===t)throw Tt("tokenName","Token name");if(null==n)throw Tt("from","Start timestamp");if(null==r)throw Tt("to","End timestamp");if(null==s)throw Tt("resolution","Data resolution interval");fn(t,"tokenName",Cn);const o=173e6;if("number"!=typeof n||n<o)throw new rt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<o)throw new rt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof s||s<1)throw new rt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:i}=await Promise.resolve().then(function(){return Cc}),a=i({tokenName:t,from:n,to:r,resolution:s}),c=await Bt(()=>this.http.get(l.CHART,a),{errorContext:"Failed to fetch chart data"}),d=Mt(c);if(null==d||"object"!=typeof d)throw St("Invalid API response: missing or invalid data",c.status??500);const u=d,h=u.data;if(!Array.isArray(h))throw St("Invalid API response: expected data array",c.status??500);const g={dataPoints:h.map(e=>{if("object"!=typeof e||null===e)throw St("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,s=t.closePrice??t.value,o=t.lowPrice??t.value,i=t.highPrice??t.value,a=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(s),lowPrice:String(o),highPrice:String(i),volume:String(a)}})};return"boolean"==typeof u.isPreviousData&&(g.isPreviousData=u.isPreviousData),g}},exports.ConfigurationError=ct,exports.DEFAULT_EVENTS_CONFIG=Ia,exports.DEFAULT_PRICING_CONCURRENCY=5,exports.DEFAULT_REVERSE_BONDING_CURVE_CONFIGURATION=lu,exports.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,exports.ENVIRONMENT_URLS=Bo,exports.ERROR_CODES=nt,exports.EVENT_SORT_FIELDS=Da,exports.EVENT_SOURCES=Oa,exports.EVENT_TIME_PRESETS=Ra,exports.EVENT_TYPES={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"},exports.EXTENDED_STREAM_ROLE=ed,exports.EventBufferWithAutoCleanup=class{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}},exports.EventsBatcherService=Ca,exports.EventsQueryService=Fa,exports.FLAG_ACTION_LABELS=ha,exports.FLAG_DETAILS_MAX_LENGTH=500,exports.FLAG_REASON_LABELS=da,exports.FLAG_STATUS_LABELS=ua,exports.FileValidationError=bc,exports.GALA_DECIMALS=8,exports.GalaWalletSigner=Vi,exports.GlobalAndRoomCallbackDispatcher=class{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${ut(e)}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${ut(t)}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}},exports.HOLDER_DELTA_TYPES=Vu,exports.HealthService=yc,exports.IMAGE_EXTENSIONS=Fr,exports.INVITE_STATUS=cl,exports.INVITE_STATUSES=ll,exports.JWT_CONSTANTS=Co,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LAUNCHPAD_WRITE_METHODS=qd,exports.LaunchpadSDK=Mu,exports.LaunchpadSDKError=Fi,exports.LaunchpadWrites=vu,exports.ListenerCleanupManager=class{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const n=this.listeners[t];if(void 0===n)continue;const{id:r,cleanup:s}=n;try{await s()}catch(t){const n=t instanceof Error?t:new Error(String(t));e.push(n),this.logger?.error(`Cleanup error for listener ${r}:`,n)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}},exports.LockError=qa,exports.MAX_BURN_BATCH_SIZE=50,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.MAX_LOCK_BATCH_SIZE=100,exports.MAX_UNLOCK_BATCH_SIZE=100,exports.MESSAGES_CONSTRAINTS=Zc,exports.MESSAGE_TYPES=Jc,exports.MODERATOR_ROLE=sl,exports.MODERATOR_ROLES=ol,exports.NFT_FEES=Al,exports.NetworkError=at,exports.NftCollectionService=Nl,exports.OEmbedService=wl,exports.OVERSEER_INVITE_STATUS=Il,exports.OVERSEER_STATUS=Cl,exports.PAGINATION_DEFAULTS=Vo,exports.PERMISSION=ii,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20},exports.POOL_FETCH_TYPES=Je,exports.POOL_LIST_MAX_PAGE_SIZE=et,exports.POOL_STREAM_STATUSES=Ze,exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PayloadWalkerWithDeduplication=class{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,s=0)=>{if(s>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const o=this.extractor(e);if(null!==o){const e=this.dedupeKeyFn(o);this.seen.has(e)||(this.seen.add(e),t.push(o))}for(const t of Object.values(e))r(t,s+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}},exports.PendingSubscriptionTracker=class{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}},exports.PlatformStatsService=Hl,exports.PrivateKeySigner=Wi,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.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},exports.RECORDING_STATUS=ql,exports.ROLE_SOURCE=Zl,exports.RoomSubscriptionManager=class{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}},exports.SDK_VERSION=Wo,exports.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},exports.SIMULCAST_PLATFORM=zl,exports.SIMULCAST_STATUS={IDLE:"idle",STARTING:"starting",BROADCASTING:"broadcasting",ERRORED:"errored"},exports.STREAM_EVENTS=ad,exports.STREAM_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.STREAM_ROLE=Jl,exports.STREAM_STATUS=jl,exports.SelectiveEventForwarding=class{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}},exports.StreamWebSocketService=Od,exports.TIME_CONSTANTS={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6},exports.TOKEN_NAME_AVAILABILITY_CONSTRAINT=On,exports.TOKEN_NAME_DTO_CONSTRAINT=Cn,exports.TOKEN_NAME_EVENT_CONSTRAINT=xn,exports.TOKEN_NAME_FILTER_CONSTRAINT=Dn,exports.TOKEN_NAME_PATH_CONSTRAINT=Rn,exports.TRADING_TYPES=Qe,exports.TokenRestrictedError=class extends rt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}},exports.TradingQuotesService=$d,exports.TransactionError=lt,exports.TransactionFailedError=_u,exports.TypingIndicatorDebouncer=class{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const s=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,s)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}},exports.ValidationError=rt,exports.WebSocketError=wu,exports.WebSocketTimeoutError=class extends wu{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.WeeklyChallengeService=jd,exports.addCursorToPagination=function(e,t){return void 0===t?e:{...e,cursor:t}},exports.addressFormatSchema=fr,exports.aggregateMultipleApiSources=async function(e,t,n){const r=n?.logger,s=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const o=e.map(async(t,n)=>{try{const o=await s(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),o}catch(s){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${ut(s)}`)}}),i=(await Promise.allSettled(o)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${i.filter(e=>void 0!==e).length} successful results`),t(i)},exports.amountMethodSchema=Zr,exports.amountTypeSchema=Jr,exports.assertValidWalletAddress=or,exports.availabilityTokenNameSchema=dr,exports.bidirectionalTokenMatch=function(e,t,n,r){return e===n&&t===r||e===r&&t===n},exports.browserFileSchema=Br,exports.bufferFileSchema=Gr,exports.buildConcurrentBatchRequests=async function(e,t,n,r){const s=r?.logger,o=[];o.length=e.length;let i=0,a=0;s?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return o[c]=r,i++,s?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,s?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${ut(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){const t=r[e];"rejected"===t?.status&&s?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){s?.error(`Batch processing error at index ${r}: ${ut(e)}`)}}return s?.debug(`Batch complete: ${i} succeeded, ${a} failed`),o},exports.buildQueryParametersWithValidation=function(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(un(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>Bu(e)).join(","):Bu(r);const s=encodeURIComponent(n),o=encodeURIComponent(e);t.push(`${s}=${o}`)}return t.length>0?`?${t.join("&")}`:""},exports.buildSafePaginationOptions=Pu,exports.buyTokensDataSchema=gs,exports.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new a(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const s=n-t;return new a(t).plus(new a(s).multipliedBy(r))},exports.calculatePreMintDataSchema=vs,exports.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return uo(e).multipliedBy(t).integerValue(a.ROUND_DOWN)},exports.calculateTotalPages=function(e,t){if("number"!=typeof e||!Number.isInteger(e))throw _t("total","a non-negative integer",e);if(e<0)throw Nt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw _t("limit","a non-negative integer",t);if(t<0)throw Nt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)},exports.capitalize=Et,exports.caseInsensitiveTokenComparison=function(e,t){return e.toLowerCase()===t.toLowerCase()},exports.checkPoolOptionsSchema=Qr,exports.commonValidators=Tn,exports.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},exports.conditionalTrimAndValidateString=$c,exports.createLaunchpadSDK=function(n){hn(n)&&(n={});const{wallet:r,env:s,config:o={},...i}=n,a={...{...i,...o}};delete a.wallet,delete a.env,delete a.config;const c=!hn(a.signer)||!hn(a.walletProvider);let l;if(hn(r))l=c?void 0:new e.Wallet(t.createWallet().privateKey);else if("string"==typeof r)l=new e.Wallet(t.createWallet(r).privateKey);else{if(!(r instanceof e.Wallet))throw yt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");l=r}const d={...void 0!==l?{wallet:l}:{},...void 0!==s?{env:s}:{},debug:!1,timeout:3e4,...a};return new Mu(d)},exports.createLimitSchema=kr,exports.createOptionsValidator=function(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:s,type:o,validator:i}=t,a=r[e];if(s){if(hn(a)){n.push(`${e} is required`);continue}if("string"===o){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!hn(a))if(void 0===o||typeof a===o){if(void 0!==i){const e=i(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${o}`)}return n}},exports.createPaginatedResultSchema=function(e){return n.z.object({data:n.z.array(e),...cs})},exports.createPaginationQuery=function(e,t=Vo.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw _t("offset","a non-negative integer",e);return on(t,"limit"),{offset:e,limit:t}},exports.createTradeDataSchema=hs,exports.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=uo(e),r=new a(10).pow(t);return n.multipliedBy(r).integerValue(a.ROUND_UP).dividedBy(r)},exports.deduplicateByKey=function(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const s=t(e);r.set(s,n)}),n){const n=new Set;return e.filter(e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)})}return e.filter((e,n)=>{const s=t(e);return r.get(s)===n})},exports.dtoTokenNameSchema=lr,exports.errorMessageCaseNormalization=function(e){return e.toLowerCase()},exports.ethereumAddressSchema=Er,exports.extractFieldWithFallbackPath=function(e,t,n=null){if(null==e||"object"!=typeof e)return n;const r=e;for(const e of t){const t=e.split(".");let n=r;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(dn(n))return n;if(null!=n&&""!==n)return n}return n},exports.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=Jt(Bu(n.page??n.Page??n.current??1),t.page),s=Jt(Bu(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),o=n.data,i=o?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof i?.totalItems?i.totalItems:"number"==typeof o?.count?o.count:Jt(Bu(n.totalCount??n.total??-1),t.totalCount);let c=t.hasMore;return"boolean"==typeof n.hasMore?c=n.hasMore:"boolean"==typeof n.has_more?c=n.has_more:"boolean"==typeof i?.hasMore&&(c=i.hasMore),{page:r,pageSize:s,totalCount:a,hasMore:c}},exports.feeCeilingFromQuotedFee=au,exports.fetchGalaBalanceOptionsSchema=ks,exports.fetchPoolDetailsDataSchema=Ss,exports.fetchTokenBalanceOptionsSchema=Is,exports.fileSizeSchema=Cr,exports.fileUploadSchema=Pr,exports.filenameSchema=Dr,exports.flexibleAddressSchema=Ar,exports.flexibleFileSchema=$r,exports.formatGalaForDTO=tn,exports.formatLaunchpadTokenForDTO=nn,exports.fromBackendAddressFormat=Zn,exports.fullNameSchema=mr,exports.generateBuySellStringsInstructions=zi,exports.generateCreateSaleStringsInstructions=Yi,exports.getAmountOptionsSchema=Ts,exports.getEnvironmentConfig=Go,exports.getIntervalRegistryStats=function(){const e=Array.from(Wu.entries()).map(([e,t])=>({id:e,...t}));return{size:Wu.size,entries:e}},exports.getLaunchTokenDataValidationErrors=no,exports.getNftFeeAsNumber=function(e){return parseFloat(Al[e])},exports.getRecordingAnimatedUrl=function(e,t,n,r="gif"){const s=$u(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return Ku(r),Hu(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/animated.${r.toLowerCase()}`)},exports.getRecordingAssetUrl=function(e,t,n,r,s){const o=$u(e),i=t.trim(),a=n.trim().toLowerCase();if(0===i.length)throw new Error("Recording ID cannot be empty");if(0===a.length)throw new Error("Asset type cannot be empty");Ku(s);const c=void 0!==s&&s.length>0?`.${s.toLowerCase()}`:"";return Hu(r,`/v1/tokens/${encodeURIComponent(o)}/recordings/${encodeURIComponent(i)}/assets/${encodeURIComponent(a)}${c}`)},exports.getRecordingPosterUrl=function(e,t,n){const r=$u(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Hu(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/poster.jpg`)},exports.getRecordingStoryboardUrl=function(e,t,n,r="vtt"){const s=$u(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return Ku(r),Hu(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/storyboard.${r.toLowerCase()}`)},exports.getRecordingStreamUrl=function(e,t,n){const r=$u(e),s=t.trim();if(0===s.length)throw new Error("Recording ID cannot be empty");return Hu(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(s)}/assets/stream.m3u8`)},exports.getRecordingThumbnailUrl=function(e,t,n,r="jpg"){const s=$u(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return Ku(r),Hu(n,`/v1/tokens/${encodeURIComponent(s)}/recordings/${encodeURIComponent(o)}/assets/thumbnail.${r.toLowerCase()}`)},exports.getTieredModerationSavings=function(e,t){if(!Th(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))},exports.getTokenAnimatedUrl=function(e,t,n="gif"){const r=$u(e);return Ku(n),Hu(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)},exports.getTokenAssetUrl=function(e,t,n,r){const s=$u(e),o=t.trim().toLowerCase();if(0===o.length)throw new Error("Asset type cannot be empty");Ku(r);const i=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return Hu(n,`/v1/tokens/${encodeURIComponent(s)}/assets/${encodeURIComponent(o)}${i}`)},exports.getTokenImageUrl=function(e,t){const n=$u(e);return Hu(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)},exports.getTokenLiveStreamUrl=function(e,t){const n=$u(e);return Hu(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)},exports.getTokenPosterUrl=function(e,t){const n=$u(e);return Hu(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)},exports.getTokenStoryboardUrl=function(e,t,n="vtt"){const r=$u(e);return Ku(n),Hu(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)},exports.getTokenThumbnailUrl=function(e,t,n="jpg"){const r=$u(e);return Ku(n),Hu(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)},exports.getTradeOptionsSchema=ms,exports.graduateTokenOptionsSchema=ts,exports.graphDataOptionsSchema=es,exports.groupByKey=function(e,t){const n=new Map;for(const r of e){const e=t(r);n.has(e)||n.set(e,[]),n.get(e).push(r)}return n},exports.hasMorePages=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw _t("offset","a non-negative integer",e);if(e<0)throw Nt("offset",0,1/0,e);return e+t<n},exports.hexStringExtractionAndNormalization=function(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(void 0!==e&&Kc(e))return Hc(e)}return null}return Kc(e)?Hc(e):null},exports.imageExtensionSchema=Kr,exports.imageFilenameSchema=Hr,exports.imageMimeTypeSchema=Rr,exports.imageUploadOptionsSchema=Yr,exports.isAIModerationData=Eh,exports.isAIModerationMode=fh,exports.isAIModerationSettings=Ah,exports.isAIRecommendation=gh,exports.isActiveUserType=fi,exports.isAnalysisCategory=ph,exports.isAnalysisStatus=uh,exports.isAnalysisTier=mh,exports.isAnalysisType=hh,exports.isBanData=Ei,exports.isBanEnforcementEvent=vi,exports.isBurnTokenEntry=lc,exports.isBurnTokensData=dc,exports.isChatDisabledReason=zu,exports.isChatStatusResponse=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||zu(t.reason))},exports.isClaimableInvite=function(e){if(e.status!==Il.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(Yt(e.expiresAt)<=new Date)return!1}return!0},exports.isContentType=pa,exports.isEmptyValue=un,exports.isExtendedStreamRole=td,exports.isFlagAction=Ea,exports.isFlagData=Aa,exports.isFlagReason=ma,exports.isFlagStatus=fa,exports.isHolderDelta=ju,exports.isHolderDeltaType=function(e){return"string"==typeof e&&(e===Vu.NEW_HOLDER||e===Vu.EXITED_HOLDER||e===Vu.BALANCE_CHANGED)},exports.isLockTokenEntry=$a,exports.isLockTokensData=Ha,exports.isMessage=function(e){if(!el(e))return!1;const t=e.reactions;return"string"==typeof e.id&&"string"==typeof e.messageId&&"string"==typeof e.tokenName&&tl(e.tokenImage)&&"string"==typeof e.userAddress&&nl(e.user)&&nl(e.userProfile)&&"string"==typeof e.content&&"string"==typeof e.createdAt&&tl(e.updatedAt)&&tl(e.deletedAt)&&"number"==typeof e.flagCount&&el(t)&&el(t.counts)},exports.isMessageType=function(e){return e===Jc.CHAT_MESSAGE||e===Jc.COMMENT},exports.isModeratedToken=pl,exports.isModerationTiered=Th,exports.isModeratorInvite=gl,exports.isNonEmptyString=dn,exports.isOverseerInviteStatus=Dl,exports.isOverseerStatus=Rl,exports.isPinnedMessage=Xu,exports.isPublicInviteInfo=ml,exports.isReactionErrorCode=Qu,exports.isRecordingStatus=Xl,exports.isSimulcastPlatform=Ql,exports.isStreamChatDeletedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt},exports.isStreamChatErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamChatMessage=Yu,exports.isStreamChatMessageEvent=function(e){return Yu(e)},exports.isStreamChatPinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Xu(t.pinnedMessage)},exports.isStreamChatUnpinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},exports.isStreamReactionErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamReactionEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime},exports.isStreamStatus=Yl,exports.isStreamStatusEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Yl(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},exports.isTokenAccessResult=function(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.permissions;return Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(null===t.source||"owner"===t.source||"moderator_invite"===t.source||"api_key"===t.source||"overseer"===t.source)&&(void 0===t.matchedPreset||null===t.matchedPreset||"MODERATOR"===t.matchedPreset||"TECHNICAL_PRODUCER"===t.matchedPreset||"MANAGER"===t.matchedPreset)&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},exports.isTokenBanData=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)},exports.isTypingIndicatorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(Ju)},exports.isTypingUser=Ju,exports.isUnlockTokenEntry=Ka,exports.isUnlockTokensData=Wa,exports.isUserBannedEvent=Ai,exports.isUserHoldingData=qu,exports.isUserUnbannedEvent=Ti,exports.isValidAddress=tr,exports.isValidApiKeyRole=ci,exports.isValidBanDuration=yi,exports.isValidBanReason=Si,exports.isValidChatContent=function(e){return!!dn(e)&&(e.length>=Bn.CHAT_MESSAGE.MIN_LENGTH&&e.length<=Bn.CHAT_MESSAGE.MAX_LENGTH)},exports.isValidChatTokenName=function(e){return!!dn(e)&&Rn.PATTERN.test(e)},exports.isValidInviteCode=hl,exports.isValidInviteStatus=ul,exports.isValidLaunchTokenData=function(e){return Bs(e).success},exports.isValidModeratorRole=dl,exports.isValidTokenBanReason=Ld,exports.isValidTokenName=function(e,t){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},exports.isViewerCountEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},exports.isoDateStringSchema=Or,exports.launchTokenDataSchema=zr,exports.mergeSafePaginationOptions=function(e,t){return Pu({...e,...t})},exports.nonNegativeDecimalStringSchema=Sr,exports.normalizeAddressInput=er,exports.normalizeDataWithMapping=function(e,t){return e.map(e=>{const n={};for(const[r,s]of Object.entries(t)){const t=s(e);void 0!==t&&(n[r]=t)}return n})},exports.normalizeErrorMessage=function(e,t){return e.toLowerCase().includes(t.toLowerCase())},exports.normalizeLimit=jo,exports.normalizeTokenKey=function(e){return e.trim().toUpperCase()},exports.normalizeTokenName=Kt,exports.normalizeTokenSymbol=Ht,exports.optionalUrlSchema=br,exports.pageNumberSchema=Nr,exports.paginationResultMetaSchema=ls,exports.parseHttpErrorResponse=function(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let s,o=t.errorMessage;"string"==typeof n.message?o=n.message:"string"==typeof n.error?o=n.error:e instanceof Error?o=e.message:"string"==typeof e&&(o=e);const i=n.response;if(i){const e=i.data;if("object"==typeof e&&null!==e){s=e;const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error)}}const a={statusCode:r,errorMessage:o,raw:e};return null!=s&&(a.errorData=s),a},exports.parseLaunchpadVaultAddress=qi,exports.percentileIndexCalculation=function(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)},exports.poolFetchTypeSchema=Xr,exports.poolPaginationSchema=os,exports.positiveDecimalStringSchema=vr,exports.priceTickRangeMapping=function(e,t,n=60){const r=uo(e),s=uo(t);if(r.isLessThanOrEqualTo(0)||s.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(r.isGreaterThanOrEqualTo(s))throw new Error(`minPrice must be < maxPrice, got: ${r.toString()} >= ${s.toString()}`);const o=Math.floor(go(r)),i=Math.ceil(go(s)),c=Math.floor(o/n)*n,l=Math.ceil(i/n)*n;return{minTick:c,maxTick:l,actualMinPrice:new a(1.0001).pow(c),actualMaxPrice:new a(1.0001).pow(l)}},exports.privateKeySchema=Lr,exports.registerInterval=function(e,t){const n=e;return Wu.set(n,{createdAt:Date.now(),label:t}),n},exports.requireNonNegative=function(...e){e.forEach(e=>{if(e.isNaN())throw It("value","NaN");if(!e.isFinite())throw wt("value","finite");if(e.isLessThan(0))throw kt("value","0",e.toString())})},exports.requirePositive=fo,exports.requirePositiveWithContext=Eo,exports.retryableHttpRequest=async function(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,s=t?.retryableStatus??[429,503,504];let o,i=0;for(;i<=n;)try{return await e()}catch(e){o=e,i++;const t=Gu(e),a=s.includes(t);if(i>n||!a)throw e;const c=r*Math.pow(2,i-1);await new Promise(e=>setTimeout(e,c))}throw o},exports.reverseBondingCurveConfigSchema=qr,exports.reverseBondingCurveConfigurationSchema=ys,exports.roleHasSufficientPermission=function(e,t){return e===si.MANAGER?t!==si.OWNER:e===si.OWNER||e===t},exports.roundTickBoundaries=function(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}},exports.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},exports.safeDivideWithMinimum=function(e,t,n,r="0"){const s=uo(t);if(po(s))return uo(r);const o=uo(e).dividedBy(s);if(null!=n){const e=uo(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(o.isLessThan(e))return e}return o},exports.searchQuerySchema=pr,exports.sellTokensDataSchema=ps,exports.standardLimitSchema=wr,exports.standardPaginationSchema=ns,exports.timestampSchema=xr,exports.toBackendAddressFormat=Jn,exports.toBackendAddressFromEthers=ir,exports.tokenCategorySchema=Vr,exports.tokenCollectionSchema=jr,exports.tokenDescriptionSchema=hr,exports.tokenListOptionsSchema=Ns,exports.tokenNameSchema=cr,exports.tokenSymbolSchema=ur,exports.tokenUrlsSchema=Wr,exports.tradeCalculationMethodSchema=As,exports.tradeCalculationTypeSchema=Es,exports.tradeLimitSchema=Ir,exports.tradeListParamsSchema=fs,exports.tradePaginationSchema=ss,exports.tradePaginationWithFiltersSchema=as,exports.tradeTypeBackendSchema=us,exports.tradeTypeSchema=ds,exports.transactionIdSchema=Mr,exports.transformRawApiTokenToDomainModel=function(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(dn(t.name)?t.name:void 0)??(dn(t.tokenName)?t.tokenName:void 0)??"";if(!dn(n))throw new Error("Token name is required and must be a non-empty string");const r=(dn(t.symbol)?t.symbol:void 0)??(dn(t.tokenSymbol)?t.tokenSymbol:void 0)??"";if(!dn(r))throw new Error("Token symbol is required and must be a non-empty string");let s=8;"number"==typeof t.decimals&&t.decimals>=0&&(s=Math.floor(t.decimals));const o={name:n,symbol:r,decimals:s};return dn(t.address)&&(o.address=t.address),"boolean"==typeof t.verified&&(o.verified=t.verified),o},exports.trimmedLengthValidation=function(e){return null==e||"string"!=typeof e||0===e.trim().length},exports.uniqueKeySchema=Ur,exports.unregisterAllIntervals=function(){const e=Wu.size;return Wu.clear(),e},exports.unregisterInterval=function(e){const t=e;Wu.delete(t)},exports.updateProfileDataSchema=ws,exports.uploadProfileImageOptionsSchema=_s,exports.urlSchema=yr,exports.userLimitSchema=_r,exports.userPaginationSchema=rs,exports.userTokenNameSchema=gr,exports.userTokenTypeSchema=bs,exports.userTokensPaginationSchema=is,exports.validateAddress=xs,exports.validateAmountString=Ms,exports.validateBanTokenOptions=Md,exports.validateBuyTokensData=Ys,exports.validateCalculatePreMintData=eo,exports.validateChatMessageId=function(e){if(!dn(e))throw Tt("id","Message ID");if(!Gn.CHAT_MESSAGE.PATTERN.test(e))throw new rt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",nt.INVALID_FORMAT)},exports.validateCheckPoolOptions=Ks,exports.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new rt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},exports.validateCreateApiKeyOptions=li,exports.validateCreateChatMessageOptions=function(e){if(!dn(e.tokenName))throw Tt("tokenName");En(e.tokenName,"tokenName",Cn),Sh(e.content)},exports.validateCreateCommentOptions=function(e){if(!dn(e.tokenName))throw Tt("tokenName","Token name");En(e.tokenName,"tokenName",Cn),vh(e.content)},exports.validateCreateMessageOptions=function(e){if(void 0===e.type||null===e.type)throw Tt("type");if(e.type!==Jc.CHAT_MESSAGE&&e.type!==Jc.COMMENT)throw new rt(`type must be one of: ${Object.values(Jc).join(", ")}`,"type",nt.INVALID_VALUE);if(!dn(e.tokenName))throw Tt("tokenName");if(En(e.tokenName,"tokenName",Cn),!dn(e.content))throw Tt("content");if(0===e.content.trim().length)throw Ot("content","Content");const t=e.type===Jc.CHAT_MESSAGE?Zc.CONTENT.CHAT_MAX_LENGTH:Zc.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw Rt("content",t,e.content.length)},exports.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??il.TOKEN;return void 0===e.inviteScope||fl(e.inviteScope)||ft(t,()=>{throw Ct("inviteScope",e.inviteScope,al,"Invite scope")}),n===il.TOKEN?ft(t,()=>{fn(e.tokenName??"","tokenName",Cn)}):n===il.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),dl(e.role)||ft(t,()=>{throw Ct("role",e.role,ol,"Role")}),void 0!==e.description&&""!==e.description&&ft(t,()=>{sn(e.description,Bn.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||Xt(e.expiresAt)||ft(t,()=>{throw function(e,t="a valid date",n){const r=Et(e,n);return new rt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},exports.validateCreateOverseerDirectOptions=Bl,exports.validateCreateOverseerInviteOptions=Ol,exports.validateCreateTradeData=zs,exports.validateDecimalRangeStrict=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e;if(!isFinite(s))throw new rt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(s<t||s>n)throw Nt(r,t,n,s,r)},exports.validateFeePortionConstraints=cn,exports.validateFetchGalaBalanceOptions=Ws,exports.validateFetchMessagesOptions=function(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw Dt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==Jc.CHAT_MESSAGE&&e.type!==Jc.COMMENT)throw new rt(`type must be one of: ${Object.values(Jc).join(", ")}`,"type",nt.INVALID_VALUE);Qc(e.tokenName,e.userAddress),void 0!==e.pageSize&&gn(0,void 0,Un,e.pageSize)},exports.validateFetchPoolDetailsData=to,exports.validateFetchTokenBalanceOptions=qs,exports.validateFullName=Us,exports.validateGetAmountOptions=Zs,exports.validateGetChatMessagesOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new rt("At least one of tokenName or userAddress is required","options",nt.REQUIRED);Qc(e.tokenName,e.userAddress),void 0!==e.pageSize&&gn(0,void 0,Un,e.pageSize)},exports.validateGetCommentsOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw Dt(["tokenName","userAddress"]);void 0!==e.tokenName&&""!==e.tokenName&&En(e.tokenName,"tokenName",Cn),gn(0,void 0,Un,e.pageSize,e.cursor)},exports.validateGetTokenBanOptions=Pd,exports.validateGetTradeOptions=Qs,exports.validateGetTradesOptions=Pc,exports.validateImageUploadOptions=$s,exports.validateInviteCode=function(e){const t=[];return dn(e)?hl(e)||t.push("Invalid invite code format"):t.push(Tt("inviteCode","Invite code").message),t},exports.validateLaunchTokenData=ro,exports.validateListApiKeysOptions=hi,exports.validateListModeratorInvitesOptions=function(e){const t=[];return ft(t,()=>{fn(e.tokenName??"","tokenName",Cn)}),void 0===e.status||ul(e.status)||ft(t,()=>{throw Ct("status",e.status,ll,"Status")}),ft(t,()=>{gn(0,void 0,Ln,e.pageSize)}),t},exports.validateListOverseerInvitesOptions=xl,exports.validateListOverseersOptions=Ll,exports.validateListTokenBansOptions=Fd,exports.validateListUsersOptions=Pl,exports.validateMessageId=function(e){if(!dn(e))throw Tt("id","Message ID");const t=Gn.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new rt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",nt.INVALID_FORMAT)},exports.validateMinMaxRelationship=function(e,t,n,r){const s="string"==typeof e?parseFloat(e):e,o="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new rt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(o))throw new rt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(s>o)throw new rt(`${n} (${s}) must be less than or equal to ${r} (${o})`,n,"INVALID_RANGE")},exports.validateOptionalTokenName=function(e,t,n){if(null==e)return;if("string"!=typeof e)throw _t(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new rt(`${t} must be ${n.DESCRIPTION}`,t,nt.INVALID_FORMAT)},exports.validateOverseerInviteCode=Ml,exports.validateOverseerInviteId=Fl,exports.validateOverseerWalletAddress=Ul,exports.validatePaginationParams=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw _t("offset","a non-negative integer",e);on(t,"limit")},exports.validateSearchQuery=Fs,exports.validateSellTokensData=Xs,exports.validateSortOrderDirection=function(e,t){if("ASC"!==e&&"DESC"!==e)throw new rt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")},exports.validateTokenDescription=Os,exports.validateTokenListOptions=Hs,exports.validateTokenName=En,exports.validateTokenSymbol=Rs,exports.validateTokenUrls=Gs,exports.validateTradeListParams=Js,exports.validateUnbanTokenOptions=Ud,exports.validateUpdateApiKeyOptions=di,exports.validateUpdateChatMessageOptions=function(e){Sh(e.content)},exports.validateUpdateCommentOptions=function(e){vh(e.content)},exports.validateUpdateMessageOptions=function(e){if(!dn(e.content))throw Tt("content");if(0===e.content.trim().length)throw Ot("content","Content");const t=Math.max(Zc.CONTENT.CHAT_MAX_LENGTH,Zc.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw Rt("content",t,e.content.length)},exports.validateUpdatePlatformConfigOptions=$l,exports.validateUpdateProfileData=Vs,exports.validateUpdateTokenConfigOptions=_c,exports.validateUploadProfileImageOptions=js,exports.validateUserTokenName=Ps,exports.validateVaultAddress=Ls,exports.vaultAddressSchema=Tr,exports.wasModerationEscalated=function(e){return!0===e.escalatedFromQuick};
|