@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/native.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("zod"),t=require("ethers"),n=require("@gala-chain/gala-core-sdk/providers"),s=require("@gala-chain/gala-core-sdk"),a=require("@gala-chain/api"),r=require("uuid"),i=require("socket.io-client"),o=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 s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{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",v="/v1/tokens/:tokenName/stream/enable",k="/v1/tokens/:tokenName/reset-key",y="/v1/tokens/:tokenName/recordings",b="/v1/tokens/:tokenName/recordings/:assetId/download",A="/v1/tokens/:tokenName/recordings/:assetId",S="/v1/tokens/:tokenName/simulcasts",E="/v1/tokens/:tokenName/simulcasts",w="/v1/tokens/:tokenName/simulcasts/:targetId",T="/v1/config",N="/v1/config",C="/v1/config",I="/v1/tokens/:tokenName/role",_="/v1/roles",D="/v1/permissions",R="/v1/tokens/:tokenName/credentials",O="/auth/login",F="/auth/logout",U="/auth/refresh",x="/auth/session",M="/v1/tokens/:tokenName/bans",L="/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",W="/v1/user-bans/:userAddress",H="/v1/user-bans/:userAddress",z={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},j="/v1/moderator-invites",q="/v1/moderator-invites/claim",V="/v1/moderated-tokens",Q="/v1/moderator-invites",X="/v1/moderator-invites/:id",J="/v1/moderator-invites/:id/role",Y="/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",se="/v1/overseer-invites/code/:code",ae="/v1/overseer-invites/claim",re="/v1/overseer-invites/:id",ie="/v1/overseers",oe="/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",ve="/v1/users/:address/summary",ke="/v1/cache/flush/address/:address",ye="/v1/cache/flush/token/:tokenName",be="/v1/cache/flush/all",Ae="/v1/cache/flush/wallet-aliases/:address",Se="/v1/cache/flush/wallet-aliases",Ee="/v1/token-bans",we="/v1/token-bans",Te="/v1/token-bans/:tokenName",Ne="/v1/token-bans/:tokenName",Ce="/v1/reactions",Ie="/v1/reactions",_e="/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",Fe="/live/:tokenName/chat",Ue="/live/:tokenName/chat",xe="/live/:tokenName/chat",Me="/live/:tokenName/chat/slow-mode",Le={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",We={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},He="/v1/notifications/register",ze="/v1/notifications/unregister",je="/v1/notifications/preferences",qe="/v1/notifications/preferences",Ve="/v1/config/client-flags",Qe="native",Xe="exact",Je="REQUIRED",Ye="INVALID_TYPE",Ze="INVALID_VALUE",et="INVALID_FORMAT",tt="TOO_LARGE",nt="INVALID_RANGE",st="INVALID_PARAMETERS";class at extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class rt extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class it extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class ot extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function ct(e){return e instanceof Error}function lt(e){return ct(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 dt(e){return ct(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function ut(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 ht(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function gt(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 s=n.Status;if("number"!=typeof s)throw new Error(`${t}: Response Status must be a number, got ${typeof s}`);if(1!==s)throw new Error(`${t}: Response status indicates failure (Status: ${s})`);return n}function mt(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 pt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function ft(e,t){return new at(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function vt(e,t){const n=pt(e,t);return new at(`${n} is required`,e,"REQUIRED")}function kt(e,t,n){const s=pt(e,n);return new at(`${s} must be ${t}`,e,"INVALID_FORMAT")}function yt(e,t,n){return new rt(e,t,n)}function bt(e,t){return new it(e,t)}function At(e,t,n){return new ot(e,t,n)}function St(e,t,n,s,a){const r=pt(e,a);return new at(`${r} must be between ${t} and ${n}${void 0!==s?`, received: ${s}`:""}`,e,"OUT_OF_RANGE")}function Et(e,t,n,s){const a=pt(e,s);return new at(`${a} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function wt(e,t,n,s){const a=pt(e,s);return new at(`${a} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Tt(e,t,n,s){const a=pt(e,s),r=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new at(`${a} must be ${t}${r}`,e,"INVALID_TYPE")}function Nt(e,t,n){const s=pt(e,n);return new at(`${s} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Ct(e,t,n,s){const a=pt(e,s);return new at(`Invalid ${a}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function It(e){return null!=e&&"object"==typeof e&&"data"in e}function _t(e,t,n=!1){const s=!0===e.error,a=n&&(null===e.data||void 0===e.data);if(s||a){const n=e?.statusCode??e.status??void 0;throw yt(e?.message??t,n)}}function Dt(e){if(It(e))return e.data}function Rt(e,t="No data found in response"){if(!It(e))throw yt(t);const n=e.data;if(null==n)throw yt(t);return n}async function Ot(e,t={}){return xt(e,t,e=>{if(void 0===e.data)throw new at(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function Ft(e,t={}){const{errorContext:n="Operation failed",logger:s,debugLogEnabled:a=!1}=t;a&&s&&s.debug(`${n}: starting operation`);try{const t=await e();return a&&s&&s.debug(`${n}: completed successfully`),t}catch(e){throw s&&s.error(n,{error:e}),e}}async function Ut(e,t={}){return xt(e,t,e=>e)}async function xt(e,t,n){const{errorContext:s="Operation failed",logger:a,debugLogEnabled:r=!1}=t;r&&a&&a.debug(`${s}: starting operation`);try{const t=await e();if(null==t)throw new at(`${s}: No response from server`,"response","NO_RESPONSE");return _t(t,s,!0),r&&a&&a.debug(`${s}: completed successfully`),n(t)}catch(e){throw a&&a.error(s,{error:e}),e}}const Mt={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function Lt(e){return e.trim().toLowerCase()}function Pt(e){return e.trim().toUpperCase()}var Bt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Bt||(Bt={}));class $t{constructor(e){this.levelPriority={[Bt.DEBUG]:0,[Bt.INFO]:1,[Bt.WARN]:2,[Bt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Bt.DEBUG:Bt.INFO)}debug(e,t){this.log(Bt.DEBUG,e,t)}info(e,t){this.log(Bt.INFO,e,t)}warn(e,t){this.log(Bt.WARN,e,t)}error(e,t){this.log(Bt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Bt.DEBUG&&!this.debugEnabled)return;const s=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,a=this.getConsoleMethod(e);void 0!==n?ct(n)?a(`${s} ${t}`,n.message,dt(n)??""):a(`${s} ${t}`,n):a(`${s} ${t}`)}getConsoleMethod(e){switch(e){case Bt.DEBUG:return console.debug;case Bt.INFO:return console.info;case Bt.WARN:return console.warn;case Bt.ERROR:return console.error;default:return console.log}}child(e){return new $t({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Bt.DEBUG]>=this.levelPriority[this.minLevel]}}function Gt(e){return null==e||""===e}function Kt(e){return null==e}const Wt=new $t({debug:!1,context:"DateUtils"});function Ht(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 zt={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},jt={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},qt={MIN_LENGTH:1,MAX_LENGTH:50},Vt=100,Qt=20,Xt={MAX_LIMIT:50},Jt={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},Yt={COMMENTS_V1:{MAX_LENGTH:2e3},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}},Zt={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})$/}},en=60,tn=31536e3,nn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},sn={PATTERN:/^[a-fA-F0-9]{64}$/},an={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},rn=50,on=1,cn=100,ln={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function dn(e,t=0){if(Gt(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 un(e,t=0){if(Kt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return dn(String(e).replace("%","").trim(),t)}function hn(e,t=18){const n=dn(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,s){if("number"!=typeof e)throw Tt(s,"a number",e,s);if(e<t||e>n)throw St(s,t,n,e)}function fn(e,t,n){if("string"!=typeof e)throw Tt(n,"a string",e,n);if(e.length>t)throw wt(n,t,e.length)}function vn(e,t){if("number"!=typeof e)throw Tt(t,"a number",e,t);if(!Number.isInteger(e))throw Tt(t,"an integer",e,t);if(e<=0)throw Et(t,1,e,t)}function kn(e,t,n=!1){if("string"!=typeof e)throw Tt(t,"a string",e,t);if(!n&&0===e.trim().length)throw vt(t,`${t} (non-empty string)`)}const yn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},bn=function(e){return"string"==typeof e&&e.trim().length>0},An=Kt;function Sn(e,t,n=100,s,a){if(void 0!==a&&"string"!=typeof a)throw new at("cursor must be a string","cursor",Ye);const r=s??t,i=void 0!==s?"pageSize":"limit";if(void 0!==r&&(vn(r,i),r>n))throw new at(`${i} must be at most ${n}`,i,tt)}function En(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function wn(e){return Object.values(e)}function Tn(e,t="tokenName",n=zt){if(!bn(e))throw vt(t);const s=e.trim();if(0===s.length)throw vt(t);if(s.length<n.MIN_LENGTH)throw St(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(s.length>n.MAX_LENGTH)throw St(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(!n.PATTERN.test(s))throw new at(`${t} must contain only alphanumeric characters`,t,et)}function Nn(e,t="tokenName",n=zt){if(null==e)throw vt(t,t);if("string"!=typeof e)throw Tt(t,"a string",e);const s=e.trim();if(0===s.length)throw vt(t,t);if(!n.PATTERN.test(s))throw new at(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,et)}function Cn(e){return""===e||0===e.trim().length}function In(e,t,n){if(!An(e)){if("string"!=typeof e)throw Tt(t,"a string",e,t);if(e.length>n)throw new at(`${t} must be at most ${n} characters`,t,tt)}}function _n(e,t){An(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 Tt(t,"a date",e,t);if(isNaN(n.getTime()))throw new at(`${t} must be a valid date`,t,et)}(e,t)}function Dn(e,t,n){try{vn(e,t)}catch{throw function(e,t,n,s="OPERATION_FAILED"){return new at(`${e} failed: ${t}`,n,s)}(n,"must be a positive integer",t)}}function Rn(e,t,n="status"){void 0!==e&&function(e,t,n){const s=Object.values(t);if(!s.includes(e))throw new at(`${n} must be one of: ${s.join(", ")}`,n,et)}(e,t,n)}class On{constructor(e,t=!1,n){this.http=e,this.logger=new $t({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 it("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=dt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Dn(e,t,n)}}class Fn{constructor(e=!1,t){this.logger=t||new $t({debug:e,context:this.constructor.name})}}class Un 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 xn extends Un{constructor(e=!1){super(e)}normalizeKey(e){return Lt(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>=xn.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??Mt.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,s)=>{n.lastUpdated<e&&(e=n.lastUpdated);let a=0;a+=2*s.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(a+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(a+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(a+=8),a+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(a+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(a+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(a+=2*n.symbol.length),a+=32,t+=a}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${Lt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${Lt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${Lt(e)}`;return this.cache.has(t)}}xn.MAX_CACHE_SIZE=1e4;const Mn={ETHEREUM:yn.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:yn.BACKEND_ADDRESS,CLIENT:yn.CLIENT_ADDRESS};class Ln{toBackendFormat(e){if(!bn(e))throw new at("Address is required and must be a string","address","REQUIRED");let n=e;if(e.startsWith("eth|")){if(n=e.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new at(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${e}"`,"address","INVALID_FORMAT");return e}if(n=Bn(e),!/^[a-fA-F0-9]{40}$/.test(n))throw new at(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${e}"`,"address","INVALID_FORMAT");return`eth|${t.getAddress(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!bn(e))throw new at("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 at(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],s=void 0!==n&&""!==n?6:4;return`0x${e.substring(s)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!Mn.CLIENT.test(e))throw new at(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!Mn.BACKEND.test(e))throw new at(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!bn(e)&&(!!Mn.ETHEREUM.test(e)||(!!Mn.ETHEREUM_NO_PREFIX.test(e)||(!!Mn.BACKEND.test(e)||!!Mn.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new at(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return bn(e)?Mn.ETHEREUM.test(e)||Mn.ETHEREUM_NO_PREFIX.test(e)?"ethereum":Mn.BACKEND.test(e)?"backend":Mn.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 Bn(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new at(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Pn=new Ln;function Bn(e){return e.startsWith("0x")?e.slice(2):e}function $n(e){return Pn.toBackendFormat(e)}function Gn(e){return Pn.isValid(e)}function Kn(e,t="address"){Pn.assertValid(e,t)}var Wn=Object.freeze({__proto__:null,AddressFormatter:Ln,assertValidWalletAddress:Kn,isValidAddress:Gn,normalizeAddressInput:function(e){return Pn.normalizeInput(e)},stripHexPrefix:Bn,toBackendAddressFormat:$n});const Hn=e.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"),zn=e.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"),jn=e.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),qn=e.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Vn=e.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Qn=e.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");e.z.string().regex(yn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.z.string().regex(yn.ETH_ADDRESS,"Invalid Ethereum address format");const Xn=e.z.string().refine(e=>yn.BACKEND_ADDRESS.test(e)||yn.ETH_ADDRESS.test(e)||yn.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new Ln).normalizeInput(e)??e),Jn=e.z.string().refine(e=>yn.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Yn=e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>dn(e,0)>0,"Amount must be greater than zero"),Zn=e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>dn(e,0)>=0,"Amount must be zero or greater");e.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://");const es=e.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function ts(t=100){return e.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(t,`Limit must be at most ${t}`).default(10)}e.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),ts(100),ts(20),ts(20);const ns=e.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"),ss=e.z.string().max(255,"Filename must be at most 255 characters"),as=e.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]);e.z.string().datetime("Must be a valid ISO 8601 date string"),e.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative");const rs=e.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters");e.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"),e.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}");const is=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),name:ss,size:ns,type:as});const os=e.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"),cs=e.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.z.union([os,cs]),e.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),ss.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return is.includes(t)},`Filename must end with one of: ${is.join(", ")}`),e.z.object({websiteUrl:es,telegramUrl:es,twitterUrl:es,instagramUrl:es,facebookUrl:es,redditUrl:es,tiktokUrl:es}).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");const ls=e.z.string().min(1,"Token category must not be empty").default("Unit"),ds=e.z.string().min(1,"Token collection must not be empty").default("Token"),us=e.z.object({minFeePortion:e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>dn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>dn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>dn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>dn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>dn(e.maxFeePortion,0)>=dn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),hs=e.z.object({tokenName:Hn,tokenSymbol:zn,tokenDescription:jn,tokenImage:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer),e.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Zn.default("0"),websiteUrl:es,telegramUrl:es,twitterUrl:es,instagramUrl:es,facebookUrl:es,redditUrl:es,tiktokUrl:es,tokenCategory:ls,tokenCollection:ds,reverseBondingCurveConfiguration:us.optional(),saleStartTime:e.z.number().int().positive().optional(),privateKey:rs.optional()});e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),tokenName:Hn}),e.z.enum(["RECENT","POPULAR"]);const gs=e.z.object({tokenName:Hn.optional(),symbol:zn.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required");e.z.enum(["NATIVE","MEME"]),e.z.enum(["IN","OUT"]);const ms=e.z.object({from:e.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:e.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:e.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Hn});e.z.object({tokenName:Hn,slippageToleranceFactor:e.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.z.number().min(0).max(1).optional(),privateKey:rs.optional()});const ps=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(100).default(10)}),fs=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(20).default(10)}),vs=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(20).default(10)});ps.extend({type:e.z.enum(["RECENT","POPULAR"]).optional(),tokenName:e.z.string().min(1).max(50).optional(),search:e.z.string().min(1).max(100).optional()}),fs.extend({tokenName:e.z.string().min(1).max(50).optional(),search:e.z.string().min(1).max(100).optional()}),vs.extend({tradeType:e.z.enum(["BUY","SELL"]).optional(),tokenName:e.z.string().min(1).max(50).optional(),userAddress:e.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),sortOrder:e.z.enum(["ASC","DESC"]).default("DESC")});const ks={page:e.z.number().int().min(1),limit:e.z.number().int().min(1),total:e.z.number().int().min(0),totalPages:e.z.number().int().min(0),hasNext:e.z.boolean(),hasPrevious:e.z.boolean()};e.z.object(ks);const ys=e.z.enum(["buy","sell"]);e.z.enum(["BUY","SELL"]),e.z.object({tradeType:ys,tokenAmount:Yn,vaultAddress:Jn,userAddress:Xn,slippageTolerance:Yn.optional(),deadline:e.z.number().int().positive().optional()}),e.z.object({tokenSymbol:zn,nativeTokenQuantity:Yn,expectedToken:Yn,maxAcceptableReverseBondingCurveFee:Zn.default("0").optional()}),e.z.object({tokenSymbol:zn,tokenQuantity:Yn,expectedNativeToken:Yn,maxAcceptableReverseBondingCurveFee:Zn.default("0").optional()}),vs.extend({tokenName:qn.optional()}),e.z.object({page:e.z.number().int().min(1).max(1e3).default(1).optional(),limit:e.z.number().int().min(1).max(20).default(10).optional()});const bs=e.z.enum(["NATIVE","MEME"]),As=e.z.enum(["IN","OUT"]);e.z.object({type:bs,method:As,vaultAddress:Jn,amount:Yn}),e.z.object({nativeTokenQuantity:Yn}),e.z.object({vaultAddress:Jn}),e.z.object({minFeePortion:Yn,maxFeePortion:Yn});const Ss=e.z.enum(["both","held","created"]);function Es(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)}}}fs.extend({type:Ss.optional(),address:Xn.optional(),search:Vn.optional(),tokenName:qn.optional()}),e.z.object({address:Xn.optional(),refresh:e.z.boolean().optional()}),e.z.object({profileImage:e.z.string(),fullName:Qn,address:Xn,privateKey:rs.optional()}),e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),address:Xn.optional(),privateKey:rs.optional()}),e.z.object({address:Xn,tokenId:e.z.union([e.z.string(),e.z.object({collection:e.z.string(),category:e.z.string(),type:e.z.string(),additionalKey:e.z.string()}),e.z.object({collection:e.z.string(),category:e.z.string(),type:e.z.string(),additionalKey:e.z.string(),instance:e.z.string()})]).optional(),tokenName:qn.optional(),withExpired:e.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");const ws=Es(Hn),Ts=Es(hs),Ns=Es(gs);function Cs(e){const t=function(e){const t=Ts(e);return t.success?[]:t.errors??["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Is(e,t){return"string"==typeof e[t]}function _s(e,t){return void 0===e[t]||"string"==typeof e[t]}function Ds(e,t){return void 0===e[t]||"number"==typeof e[t]}function Rs(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}}En({BUY:"buy",SELL:"sell"});const Os=(Fs={nativeTokenQuantity:"string"},e=>{if(null==e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;for(const[e,n]of Object.entries(Fs))if(!Rs(t[e],n))return!1;return!0});var Fs;function Us(e){if(An(e)||"object"!=typeof e)return{};const t={};for(const[n,s]of Object.entries(e))An(s)||(bn(s)?t[n]=s:"number"==typeof s||"boolean"==typeof s?t[n]=s.toString():Array.isArray(s)?t[n]=s.join(","):t[n]="object"==typeof s?JSON.stringify(s):String(s));return t}function xs(e,t="0"){return function(e,t="0"){if(Gt(e))return new o(t);if(o.isBigNumber(e))return e.isNaN()?new o(t):e;try{const n=new o(e);return n.isNaN()||!n.isFinite()?new o(t):n}catch{return new o(t)}}(e,t)}function Ms(e,t){return void 0!==t?xs(e).toFixed(t):xs(e).toFixed()}function Ls(e){return xs(e).isZero()}function Ps(e,t){return xs(e).isLessThan(xs(t))}function Bs(...e){e.forEach(e=>{if(e.isNaN())throw Nt("value","NaN");if(!e.isFinite())throw wt("value","finite");if(e.isLessThanOrEqualTo(0))throw Et("value","0",e.toString())})}function $s(e,t,n="0"){const s=xs(t);return Ls(s)?xs(n):xs(e).dividedBy(s)}const Gs={calculateBuyWithExact(e,t){const n=dn(e),s=dn(t),{BASE_PRICE:a,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=Mt,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(a*(Math.exp((s+n)*r)-Math.exp(s*r))/r,8),l=Ms(xs(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateBuyWithNative(e,t){const n=dn(e),s=dn(t),{BASE_PRICE:a,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=Mt,c=Math.log(n*r/a+Math.exp(s*r))/r-s,l=Ms(xs(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateSellWithExact(e,t,n,s,a){const r=dn(e),i=dn(t),o=dn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=Mt,h=c*(Math.exp(i*l)-Math.exp((i-r)*l))/l,g=xs(h),m=s+i/o*(a-s),p=Ms(g.multipliedBy(m),8),f=Ms(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}},calculateSellWithNative(e,t,n,s,a){const r=dn(e),i=dn(t),o=dn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=Mt;if(r>=c*(Math.exp(i*l)-1)/l){const e=xs(r),t=s+i/o*(a-s),n=Ms(e.multipliedBy(t),8),c=Ms(e.multipliedBy(d));return{amount:i.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=i-Math.log(Math.exp(i*l)-r*l/c)/l,g=xs(r),m=s+i/o*(a-s),p=Ms(g.multipliedBy(m),8),f=Ms(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}}};class Ks extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Ws(e,t,n){if(null==e)throw new Ks("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=os.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Ks(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Ks("Filename is required when uploading Buffer objects",t,n);const s=cs.safeParse(e);if(!s.success){const e=s.error.issues.map(e=>e.message).join("; ");throw new Ks(e,t,n)}try{fn(t,255,"filename")}catch(e){throw new Ks(e.message,t,n)}const a=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!a.includes(n))throw new Ks(`Invalid file type "${n}" is not allowed. Allowed types: ${a.join(", ")}`,t,n);const r=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(r))throw new Ks(`File extension "${r}" is not allowed. Allowed extensions: ${i.join(", ")}`,t,n);const o=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(r);if(o!==n&&"application/octet-stream"!==o)throw new Ks(`File extension "${r}" does not match MIME type "${n}"`,t,n);return}throw new Ks("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Hs(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function zs(e,t){if(!function(e){if(!Hs(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return Hs(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw yt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:Mt.GAS_FEE}}class js{validate(e,t={}){const{allowZero:n=!0,minimum:s,maximum:a,maxDecimals:r=js.MAX_DECIMAL_PLACES,fieldName:i="amount"}=t;if(!bn(e))throw new at(`${i} cannot be empty or whitespace-only. Provide a valid numeric string.`,i,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new at(`${i} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,i,"INVALID_NUMERIC_STRING");const o=dn(e,NaN);if(isNaN(o))throw new at(`${i} must be a valid numeric string. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new at(`${i} must be a finite number. Cannot be Infinity or -Infinity.`,i,"INVALID_NUMERIC_STRING");if(o<0)throw new at(`${i} must be non-negative. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new at(`${i} must be greater than zero. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");const c=xs(e),l=c.decimalPlaces()??0;if(l>r)throw new at(`${i} cannot exceed ${r} decimal places. Received: ${l} decimal places`,i,"PRECISION_EXCEEDED");if(void 0!==s&&Ps(c,s))throw new at(`${i} must be at least ${s}. Received: "${e}"`,i,"BELOW_MINIMUM");if(void 0!==a&&(d=a,xs(c).isGreaterThan(xs(d))))throw new at(`${i} cannot exceed ${a}. Received: "${e}"`,i,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return xs(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 Ms(e,t)}clampAmount(e,t,n){const s=xs(e),a=xs(t),r=xs(n);return function(e,t,n){const s=xs(e),a=xs(t),r=xs(n);return s.isGreaterThanOrEqualTo(a)&&s.isLessThanOrEqualTo(r)}(s,a,r)?Ms(s):Ps(s,a)?Ms(a):Ms(r)}}function qs(e,t){throw new at(e.join("; "),t,"VALIDATION_ERROR")}function Vs(e){const t=ws(e);!t.success&&t.errors&&qs(t.errors,"tokenName")}function Qs(e){const t=ms.safeParse(e);var n;t.success||qs((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 Xs(e,t,n=!0){Js.validate(e,{fieldName:t,allowZero:n})}js.MAX_DECIMAL_PLACES=18,js.MIN_POSITIVE="0.00000000000000001";const Js=new js;function Ys(e,t,n=Ms){if(!Array.isArray(e))throw yt("Invalid API response: expected array of holders",t);for(const n of e){if(!Zs(n))throw yt("Invalid holder data: missing or invalid owner field",t);if(!ea(n))throw yt("Invalid holder data: missing or invalid quantity field",t);const e=dn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw yt(`Invalid holder quantity: "${n.quantity}"`,t)}const s=e,a=s.reduce((e,t)=>e.plus(t.quantity),xs(0));return{holders:s.map(e=>({address:e.owner,balance:e.quantity,percentage:$s(xs(e.quantity),a,xs(0)).multipliedBy(100).toNumber()})),totalSupply:n(a),totalHolders:s.length,lastUpdated:new Date}}function Zs(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function ea(e){return"string"==typeof e.quantity&&""!==e.quantity}class ta{constructor(e,t,n,s="local",a){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=s,this.launchpadWrites=a,this.metadataCache=new xn}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;Vs(t);const s=`${t}.png`;Ws(n.file,s,"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 kt("file","a File object (browser) or Buffer (Node.js)");{const s=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,a=new Blob([n.file],{type:"image/png"});e.append("image",a,s)}}const s=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===s.error||200!==s.status)throw yt(void 0!==s.message&&""!==s.message?s.message:"Image upload failed - no URL returned",s.status);const a=Dt(s);if(!a?.imageUrl)throw yt("Image upload failed - no URL returned",s.status);return a.imageUrl}catch(e){if(ct(e)&&e.message.includes("FormData"))throw bt("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&&Sn(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&Vs(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=Us(t),s=await this.http.get(d.FETCH_POOLS,n);if(!0===s.error||200!==s.status)throw yt(void 0!==s.message&&""!==s.message?s.message:"Failed to fetch pools",s.status);const a=Dt(s);if(null==a)throw yt("Failed to fetch pools - no data returned",s.status);let r=[];if(a.tokens)if(Array.isArray(a.tokens))r=a.tokens.map(e=>this.normalizePoolData(e));else{const e=a.tokens;r=[this.normalizePoolData(e)]}else a.pools&&Array.isArray(a.pools)&&(r=a.pools.map(e=>this.normalizePoolData(e)));const{extractMetadataFromPoolData:i,isValidPoolForCaching:o}=await Promise.resolve().then(function(){return ol});r.forEach(e=>{if(!o(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=i(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=a.count??a.total??0,l={hasNextPage:a.hasNextPage??!1};return void 0!==a.hasPrevPage&&(l.hasPrevPage=a.hasPrevPage),void 0!==a.nextCursor&&(l.nextCursor=a.nextCursor),void 0!==a.prevCursor&&(l.prevCursor=a.prevCursor),c>0&&(l.totalCount=c),{items:r,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 kt("options","an options object");const{tokenName:t,amount:n,type:s,currentSupply:a}=e;return"external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[Qe,Xe],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:s}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:s},"currentSupply",a))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?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 zs(await Ot(()=>this.http.get(Ge,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:s,currentSupply:a,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if("external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[Xe,Qe],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:s});{const e={tokenName:t,amount:n,type:s,...void 0!==a&&{currentSupply:a},...void 0!==r&&{maxSupply:r},...void 0!==i&&{reverseBondingCurveMaxFeeFactor:i},...void 0!==o&&{reverseBondingCurveMinFeeFactor:o}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?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:s,currentSupply:a}=e;if(!bn(n))throw vt("amount","Amount");if(s!==Qe&&s!==Xe)throw Tt("type",'"native" or "exact"',s);void 0!==a&&Xs(a,"currentSupply");const r=null==a||""===a;if(r&&(null==t||""===t))throw vt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Vs(t);let i=a;if(r){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return s===Xe?Gs.calculateBuyWithExact(n,i):Gs.calculateBuyWithNative(n,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:s,currentSupply:a,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if(!bn(n))throw vt("amount","Amount");if(s!==Xe&&s!==Qe)throw Tt("type",'"exact" or "native"',s);void 0!==a&&Xs(a,"currentSupply");const c=null==a||""===a||null==r||""===r||void 0===i||void 0===o;if(c&&(null==t||""===t))throw vt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Vs(t);let l=a,d=r,u=i,h=o;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 s===Xe?Gs.calculateSellWithExact(n,l,d,h,u):Gs.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 Is(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&_s(t,"currentSupply")}(e))throw Tt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:s,currentSupply:a}=t;Vs(n);const r=await this.fetchSaleDetails(n),i=a??Ms(xs(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.sellingTokenQuantity;if("0"===o)throw vt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:o,type:"exact",currentSupply:i,...void 0!==s&&{mode:s}};return{...await this.calculateBuyAmount(c),remainingTokens:o}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw bt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Cs(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=dn(t);if(0===n&&"0"!==t)throw Nt("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Nt("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;!function(e,t,n){const s="string"==typeof e?parseFloat(e):e,a="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new at(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(a))throw new at(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(s<.1)throw new at(`${n} minFee must be >= 0.1, received ${s}`,n,"INVALID_FEE_MINIMUM");if(a>.5)throw new at(`${n} maxFee must be <= 0.5, received ${a}`,n,"INVALID_FEE_MAXIMUM");if(s>a)throw new at(`${n} minFee (${s}) must be <= maxFee (${a})`,n,"INVALID_FEE_RANGE")}(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 vt("tokenName","Token name");Vs(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw yt(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=Dt(t);if(null==n)throw yt("Failed to fetch token distribution - no data returned",t.status);return Ys(n,t.status)}async calculateInitialBuyAmount(e){if(!Os(e))throw kt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return zs(await Ot(()=>this.http.get(Ke,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Ms(xs(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.sellingTokenQuantity,a=t.maxSupply;let r=.5,i=.1;const o=t.reverseBondingCurveConfiguration;null!=o?.maxFeePortion&&(r=un(o.maxFeePortion,.5)),null!=o?.minFeePortion&&(i=un(o.minFeePortion,.1)),void 0===o&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=r-i;return this.metadataCache.set(e,{maxSupply:a,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:s,maxSupply:a,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Vs(e);const t=await this.fetchSaleDetails(e),n=Ms(xs(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.maxSupply;return this.metadataCache.set(e,{maxSupply:s}),n}async fetchPoolDetails(e){Vs(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...s}=t,a=n?.minFeePortion??"0",r=n?.maxFeePortion??"0";return{...s,reverseBondingCurveMinFeePortion:a,reverseBondingCurveMaxFeePortion:r,hasReverseBondingCurveFee:!Ls(a)||!Ls(r),isGraduated:"Finished"===t.saleStatus}}normalizePoolData(e){const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0";return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:!Ls(t)||!Ls(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 Ot(()=>this.http.get($e,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,s,a,r){const i=s??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw Tt("mode",'"local" or "external"',i);if(!bn(e))throw vt("tokenName","Token name");if(!bn(t))throw vt("amount","Amount");if("string"!=typeof n||!a.includes(n))throw Tt("type",r,n);return i}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new at("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new at("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return $n(e)}validateTokenName(e){return Vs(e)}validatePagination(e){void 0!==e.pageSize&&Sn(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 na=3e5,sa="Sign in to Launchpad t:",aa="Authorization",ra="Bearer ";class ia{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 oa;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(oa||(oa={}));class ca extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class la{constructor(e,t=na){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 ia,this.refreshThresholdMs=t}setToken(e,t){if(!bn(e))throw new ca(oa.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new ca(oa.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new ca(oa.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new ca(oa.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,s){if(this.setToken(e,t),n){const e=Date.now()+1e3*(s??7776e3);if(!this.tokenState)throw new ca(oa.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:`${ra}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new ca(oa.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[aa]: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 s=Date.now();this.tokenState={token:e,issuedAt:s,expiresAt:n};const a=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),r=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(a&&r){const e=Number(r);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=a,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 da(e,t,n,s){try{return await e()}catch(e){throw s?(s(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const s=ht(e)?e.response?.status:void 0;return yt(`${t}: ${lt(e)}`,s,ct(e)?e:void 0)}(e,t,n))}}class ua{constructor(e,t,n,s=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new $t({debug:s,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 ca(oa.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 da(async()=>{const e=Date.now(),t=`${sa}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),s=this.signatureAuth.getAddress();Kn(s,"address");const a={address:s,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:s,message:t});const r=await this.http.post(O,a),i=this.extractLoginData(r);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 ca)throw e;throw new ca(oa.SIGNATURE_FAILED,`Login failed: ${lt(e)}`,ct(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 ca(oa.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 da(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(U,{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(U,{},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 ca)throw e;throw new ca(oa.SIGNATURE_FAILED,`Token refresh failed: ${lt(e)}`,ct(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(F,{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): ${lt(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 ca(oa.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return da(async()=>{const e=await this.http.get(x,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof ca)throw e;throw new ca(oa.SIGNATURE_FAILED,`Failed to get session: ${lt(e)}`,ct(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 ca(oa.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: ${lt(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 ca(oa.SIGNATURE_FAILED,""!==lt(e)?lt(e):"Authentication failed");const t=Rt(e,"No data in authentication response"),{accessToken:n,expiresIn:s,address:a,refreshToken:r,refreshExpiresIn:i}=t;if(!bn(n))throw new ca(oa.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof s||s<=0)throw new ca(oa.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:s,address:a,...void 0!==r&&{refreshToken:r},...void 0!==i&&{refreshExpiresIn:i}}}extractSessionData(e){if(e.error)throw new ca(oa.SIGNATURE_FAILED,""!==lt(e)?lt(e):"Failed to get session");return Rt(e,"No data in session response")}}class ha{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{kn(e.messagePrefix,"messagePrefix",!1)}catch{throw new ca(oa.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=n.PrivateKeyProvider.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=$n(this.wallet.address)}catch(e){if(e instanceof ca)throw e;if(e instanceof at&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new ca(oa.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new ca(oa.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new ca(oa.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new ca(oa.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=n.PrivateKeyProvider.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=$n(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(e){this.walletProvider=e,this.wallet=void 0;const s=void 0!==e&&n.isPrivateKeyProvider(e)?t.computeAddress(e.exportPrivateKey()):void 0;this.cachedAddress=s,this.cachedGalaAddress=void 0===s?void 0:$n(s)}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 ca)throw e;throw new ca(oa.SIGNATURE_FAILED,"Failed to generate signature for authentication",ct(e)?e:new Error(lt(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new ca(oa.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 ca(oa.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 ca(oa.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&n.isPrivateKeyProvider(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new ca(oa.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 ca(oa.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new ca(oa.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",ct(e)?e:void 0)}}formatAddress(e){try{return $n(e)}catch{throw new ca(oa.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 ca)throw e;throw new ca(oa.SIGNATURE_FAILED,lt(e),ct(e)?e:new Error(lt(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),s=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,a=await this.walletProvider.signMessage(s);return{"x-signature":a,"x-address":await this.walletProvider.getGalaAddress(),"x-message":s,"x-timestamp":n.toString()}}catch(e){if(e instanceof ca)throw e;throw new ca(oa.SIGNATURE_FAILED,"Failed to generate authentication headers",ct(e)?e:new Error(lt(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const s={};for(const[e,n]of Object.entries(t))s[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,s,n)}catch(e){if(e instanceof ca)throw e;throw new ca(oa.SIGNATURE_FAILED,"Failed to sign typed data",ct(e)?e:new Error(lt(e)))}}async generateCustomSignature(e){if(!bn(e))throw new ca(oa.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 ca)throw e;throw new ca(oa.SIGNATURE_FAILED,"Failed to generate custom message signature",ct(e)?e:new Error(lt(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new ca(oa.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new ca(oa.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new ca(oa.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const ga={prod:{...s.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:{...s.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 ma(e){return ga[e]}var pa,fa;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(pa||(pa={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(fa||(fa={}));const va={[pa.PROCESSED]:fa.COMPLETED,[pa.COMPLETED]:fa.COMPLETED,[pa.SUCCESS]:fa.COMPLETED,[pa.FAILED]:fa.FAILED,[pa.ERROR]:fa.FAILED,[pa.PROCESSING]:fa.PROCESSING,[pa.PENDING]:fa.PENDING},ka="9.0.0-rc.0",ya={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function ba(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Aa(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const s=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(s),n}function Sa(e,t,n){for(const s of n){const n=t[s];null!=n&&""!==n&&(e[s]=ba(n))}return e}const Ea="x-api-key";class wa extends On{constructor(e,t,n,s=!1,a){super(e,s),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=a??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!bn(e))throw vt("tokenName","Token name");const n=Lt(e);if(!t.PATTERN.test(n))throw kt("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!bn(e))throw vt(t,n)}(e,t,n)}validateOptionalString(e,t,n,s){!function(e,t,n,s){if(null!=e){if("string"!=typeof e)throw Tt(t,"string",typeof e,n);if(e.length>s)throw wt(t,s,e.length,n)}}(e,t,n,s)}validateOptionalNumber(e,t,n,s,a,r,i){!function(e,t,n,s,a){if(null!=e){if("number"!=typeof e)throw Tt(t,"number",typeof e,n);if(e<s||e>a)throw St(t,s,a,e,n)}}(e,t,n,s,a)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Ht(e))throw kt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Dn(e,t,n)}validateStatusFilter(e,t,n="status"){Rn(e,t,n)}buildPaginationParams(e,t){return Aa(e,t)}addOptionalFilterParams(e,t,n){return Sa(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,s]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(s.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 it("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[Ea]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new it("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?{[Ea]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return _t(e,"Backend request failed",!0),Rt(e,"No data in backend response")}extractDataOrNull(e){return _t(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const s=this.buildEndpoint(t,{tokenName:e}),a=await this.http.post(s,{},this.getAdminHeaders()),r=this.extractData(a);return{enabled:r.enabled,tokenName:r.tokenName??Lt(e)}}}class Ta extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}async getSettings(){return{settings:(await this.http.get(Le.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(Le.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Le.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=Le.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(Le.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const Na=wn({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"});function Ca(e){return Na.includes(e)}function Ia(e,t,n=!1){const s=t.length;if(mt(t,()=>{In(e.description,"description",255)}),t.length>s&&(t[s]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;mt(t,()=>{if(!Array.isArray(e.tokenNames))throw Tt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Tt("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;mt(t,()=>{_n(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}class _a extends On{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),_t(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=function(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):Ca(e.role)||t.push(`Invalid role. Must be one of: ${Na.join(", ")}`),Ia(e,t),t}(e);if(t.length>0)throw new at(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 s=await this.http.post(z.CREATE,n,this.getJwtHeaders()),a=this.extractData(s);return this.logger.debug("API key created",{id:a.id,keyPrefix:a.keyPrefix}),a}async findAll(e={}){!function(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>Vt))throw Tt("pageSize",`number between 1 and ${Vt}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Tt("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=Aa(e,Vt),n=await this.http.get(z.LIST,t,this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Listed API keys",{count:s.apiKeys.length,total:s.pageInfo.totalCount}),s}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=z.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Got API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async update(e,t){this.validateApiKeyId(e);const n=function(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||Ca(e.role)||t.push(`Invalid role. Must be one of: ${Na.join(", ")}`),Ia(e,t,!0),t}(t);if(n.length>0)throw new at(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const s={};void 0!==t.role&&(s.role=t.role),void 0!==t.description&&(s.description=t.description),void 0!==t.delegateAllTokens&&(s.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(s.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(s.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(s.tokenPermissions=t.tokenPermissions);const a=z.UPDATE.replace(":id",String(e)),r=await this.http.patch(a,s,this.getJwtHeaders()),i=this.extractData(r);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=z.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Na]}}const Da={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},Ra=En(Da);function Oa(e){if(!bn(e.userAddress))throw vt("userAddress");if(!(null==(t=e.reason)||""===t||"string"==typeof t&&!Cn(t)&&t.length<=Yt.BAN_REASON.MAX_LENGTH))throw new at(`reason must be at most ${Yt.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t,n;if(n=e.durationSeconds,!(An(n)||"number"==typeof n&&n>=en&&n<=tn))throw new at(`durationSeconds must be between ${en} and ${tn} seconds`,"durationSeconds","OUT_OF_RANGE")}class Fa extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}async createBan(e){!function(e){Tn(e.tokenName,"tokenName",zt),Oa(e)}(e);const t=this.buildEndpoint(M,{tokenName:e.tokenName}),n=Ua(e),s=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(s),tokenName:Lt(e.tokenName)}}async removeBan(e){!function(e){if(Tn(e.tokenName,"tokenName",zt),!bn(e.userAddress))throw vt("userAddress")}(e);const t=this.buildEndpoint(B,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(n);return{removed:s?.removed??!0,tokenName:Lt(e.tokenName),userAddress:s?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){Tn(e.tokenName,"tokenName",zt),Sn(0,void 0,Vt,e.pageSize)}(e);const t=this.buildEndpoint(L,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Vt);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const s=await this.http.get(t,n,this.getMultiAuthHeaders()),a=this.extractData(s);return{items:a.bans,pageInfo:a.pageInfo}}async getBanStatus(e){!function(e){if(Tn(e.tokenName,"tokenName",zt),!bn(e.userAddress))throw vt("userAddress")}(e);const t=this.buildEndpoint(P,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},tokenName:Lt(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(Tn(e.tokenName,"tokenName",zt),void 0!==e.type&&!Ra(e.type))throw new at(`type must be one of: ${Object.values(Da).join(", ")}`,"type",Ze)}(e);const t=this.buildEndpoint($,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const s=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(s)}async createGlobalBan(e){!function(e){Oa(e)}(e);const t=Ua(e),n=await this.http.post(G,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!bn(e.userAddress))throw vt("userAddress")}(e);const t=this.buildEndpoint(H,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{removed:s?.removed??!0,userAddress:s?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){Sn(0,void 0,Vt,e.pageSize)}(t);const n=this.buildPaginationParams(t,Vt);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const s=await this.http.get(K,n,this.getDualAuthHeaders()),a=this.extractData(s);return{items:a.bans,pageInfo:a.pageInfo}}async getGlobalBan(e){!function(e){if(!bn(e.userAddress))throw vt("userAddress")}(e);const t=this.buildEndpoint(W,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},userAddress:e.userAddress.toLowerCase()}}}function Ua(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 xa(e){return{maxAcceptableReverseBondingCurveFee:gn(e.maxAcceptableReverseBondingCurveFee)}}class Ma extends a.ChainCallDTO{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=gn(t),this.expectedToken=mn(n),this.extraFees=xa(s)}}class La extends a.ChainCallDTO{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=mn(t),this.expectedNativeToken=gn(n),this.extraFees=xa(s)}}class Pa extends a.ChainCallDTO{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=mn(t),this.expectedNativeToken=gn(n),this.extraFees=xa(s)}}class Ba extends a.ChainCallDTO{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=gn(t),this.expectedToken=mn(n),this.extraFees=xa(s)}}const $a={BuyNativeDto:Ma,BuyExactDto:La,SellExactDto:Pa,SellNativeDto:Ba};function Ga(e,t,n){let s;pn(t,0,1,"slippageToleranceFactor");try{s=function(e,t){if(Kt(e)||""===e)throw vt(t);if(o.isBigNumber(e)){if(e.isNaN())throw Nt(t,"NaN");return e}try{const n=new o(e);if(n.isNaN())throw Nt(t,e);if(!n.isFinite())throw Nt(t,e);return n}catch(n){if(n instanceof at)throw n;throw Nt(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const a=s.multipliedBy(t);let r;switch(n){case"buy-native":case"sell-exact":r=s.minus(a);break;case"buy-exact":case"sell-native":r=s.plus(a);break;default:throw new Error(`Unknown operation type: ${n}`)}return xs(r).isLessThan(0)&&(r=xs(0)),Ms(r)}function Ka(e,t){if(!bn(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 Wa(e,t,n,s){const a=e?.split?.(t)??[],r=void 0!==n?` (${n})`:"";return new at(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${a.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${a.map(e=>`"${e}"`).join(", ")}]. Error: ${lt(s)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function Ha(e,t,n){try{const n=Ka(e,t),s=n[n.length-1],a=n[n.length-2],r=n[n.length-3],i=n.slice(0,n.length-3).join(t);if(void 0===i||void 0===r||void 0===a||void 0===s||""===s||""===i||""===r||""===a)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:r,type:a,additionalKey:s}}catch(s){throw Wa(e,t,n,s)}}function za(e){return function(e,t,n){try{const n=Ka(e,t),[s,a,r,...i]=n;if(""===s||""===a||""===r)throw new Error("Collection, category, and type must be non-empty");const o=i.join(t);if(void 0===s||void 0===a||void 0===r||""===o)throw new Error("AdditionalKey must be non-empty");return{collection:s,category:a,type:r,additionalKey:o}}catch(s){throw Wa(e,t,n,s)}}(e,"|","pipe-delimited token")}const ja={name:"GalaChain"},qa={name:"ethereum",chainId:1};function Va(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function Qa(e){const t={};for(const[n,s]of Object.entries(e))void 0!==s&&(t[n]=Xa(s));return t}function Xa(e){return Array.isArray(e)?e.map(Xa):"object"==typeof e&&null!==e?Qa(e):e}function Ja(e,t,n,s){return{...e,signature:t,types:n,domain:s}}class Ya extends s.PrivateKeySigner{constructor(e){super(e),this.typedDataWallet=new t.Wallet(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=Qa(t),a=s.generateEIP712Types(e,n);return Ja(n,await this.typedDataWallet.signTypedData(ja,a,n),a,ja)}}class Za extends s.GalaWalletSigner{async signTypedData(e,t){const n=Qa(t),a=s.generateEIP712Types(e,n),r={domain:qa,types:a,message:n,Primary_type:e},i=function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();return Ja(n,Va(await i.request({method:"eth_signTypedData",params:[JSON.stringify(r),await this.typedDataAccount(i)]})),a,qa)}async typedDataAccount(e){if(t.isAddress(this.walletAddress))return this.walletAddress;const n=await e.request({method:"eth_accounts"}),s=Array.isArray(n)?n[0]:void 0,a="string"==typeof s?s.replace(/^eth\|/,"0x"):"";if(!t.isAddress(a))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return a}}class er extends s.BrowserWalletSigner{constructor(e,t,n){super(e,t,n),this.typedDataProvider=e}async signTypedData(e,n){const a=Qa(n),r=this.typedDataProvider,i=await r.getNetwork(),o={name:i.name,chainId:Number(i.chainId)},c=s.generateEIP712Types(e,a),l=await r.getSigner(),d=t.getAddress(await l.getAddress());if(t.isAddress(this.walletAddress)&&d!==t.getAddress(this.walletAddress))throw new Error(`Wallet account ${d} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`);return Ja(a,Va(await l.signTypedData(o,c,a)),c,o)}}function tr(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 s=n.split("$"),a=s[s.length-1],r=s.slice(0,-1),i=r.slice(0,-3).join("$"),[o,c,l]=r.slice(-3);if("launchpad"!==a||r.length<4||""===i||void 0===o||void 0===c||void 0===l||""===o||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:i,category:o,type:c,additionalKey:l}}function nr(e){const{collection:t,category:n,type:s}=tr(e),a=`${t}$${n}$${s}$none`,r="GALA$Unit$none$none";return[`$service$${a}$launchpad`,`$tokenBalance$${a}$${e}`,`$tokenBalance$${a}$${e}`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${r}$${e}`]}function sr(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 ar(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function rr(e){if("string"==typeof e){if(!bn(t=e)||!t.includes("|"))throw new at(`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 n=e.split("|");if(n.length>=5){const e=za(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...za(e),instance:"0"}}var t;if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!s.isTokenClassKey(e))throw new at("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!s.isTokenClassKey(e))throw new at("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new at(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function ir(e){return function(e){try{if(!bn(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 Ha((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new at(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${lt(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function or(e){return{...ir(e),instance:"0"}}function cr(e){const t=ir(e);if("Token"!==t.collection)throw new at(`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 lr,dr,ur,hr,gr=Object.freeze({__proto__:null,extractTokenSymbolFromVault:cr,normalizeToTokenInstanceKey:rr,parseVaultAddressToTokenClassKey:ir,parseVaultAddressToTokenInstance:or});class mr extends Fn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=nr(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=lt(e);throw new at(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new a.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(!bn(e))throw vt("vaultAddress","Vault address");try{const t=cr(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof at)throw kt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!bn(e))throw vt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw kt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw kt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!bn(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],s=t[2];return void 0===n||void 0===s?null:{tokenSymbol:n,creatorAddress:s.toLowerCase()}}(e);if(!t)throw kt("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 kt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,s){return`${e}$${t}$${n}$${s}`}parseTokenClassKeyString(e){try{return Ha(e,"$","dollar-delimited token")}catch(e){if(e instanceof at)throw kt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function pr(e){return"object"==typeof e&&null!==e?e:void 0}class fr extends On{constructor(e,t,n=!1,s,a,r=.05,i=.01,o){if(super(e,n),this.tokenResolver=t,this._walletProvider=s,this.userAddress=a,this.defaultSlippageToleranceFactor=r,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=i,this.sellFeeCeiling=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=a){const e=pr(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new Ya(t):function(e){const t=pr(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new er(this._walletProvider,this.userAddress)),this.tokenKeyService=new mr(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 Ft(()=>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:It(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof at)return{success:!1,error:lt(e)};throw e}}validateBundleData(e){if(null==e)throw vt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw vt("signedDto","Signed DTO");if(!bn(e.method))throw vt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw kt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new at("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw kt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!bn(e))throw new at(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new at(`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=Dt(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(ht(e)&&null!==e.response&&void 0!==e.response){const t=Dt(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 lt(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!bn(e))throw vt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Ft(()=>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 at)return{success:!1,error:lt(e)};throw e}}async cancelTransaction(e){try{if(!bn(e))throw vt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Ft(()=>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 at)return{success:!1,error:lt(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Ft(()=>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:s,expectedAmount:a}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===s){if(null==a||""===a)throw new at("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ga(a,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:a,slippageFactor:r,adjustedMinTokens:e});const t=new $a.BuyNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",o)}{if(null==a||""===a)throw new at("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ga(a,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:a,slippageFactor:r,adjustedMaxGalaCost:e});const t=new $a.BuyExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyExactToken",o)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:s,expectedAmount:a}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,o):i;if("exact"===s){if(null==a||""===a)throw new at("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ga(a,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:a,slippageFactor:r,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new $a.SellExactDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellExactToken",o)}{if(null==a||""===a)throw new at("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ga(a,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:a,slippageFactor:r,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new $a.SellNativeDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellWithNative",o)}}async prepareTradingOperation(e,t,n,s){const{effectiveSlippageFactor:a,effectiveMaxFee:r}=this.calculateEffectiveSlippage(t,n,s),i=await this.resolveTokenNameToVault(e);if(null==i)throw ft(e);return{effectiveSlippageFactor:a,effectiveMaxFee:r,vaultAddress:i}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw bt("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 s=n??this.defaultSlippageToleranceFactor,a=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let r=e??"0";return null!=e&&(r=Ga(e,a,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:a,adjustedMaxFee:r})),{effectiveSlippageFactor:s,effectiveFeeSlippageFactor:a,effectiveMaxFee:r}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw bt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw vt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${r.v4().replace(/-/gu,"").substring(0,26)}`;const s=await this.signer.signObject(t,e),a=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:a,method:t,signedDto:s};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:a,dtoKeys:Object.keys(s)});const o=await this.submitTransaction(i);if(o.success){const e=Dt(o);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=o.error;throw new ot("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 vr extends On{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(Ve),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(lr||(lr={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(dr||(dr={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(ur||(ur={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(hr||(hr={})),dr.INAPPROPRIATE_CONTENT,dr.SPAM,dr.HARASSMENT,dr.SCAM,dr.OTHER,ur.PENDING,ur.DISMISSED,ur.ACTIONED,hr.DELETE_CONTENT,hr.BAN_USER,hr.DELETE_AND_BAN,lr.CHAT_MESSAGE,lr.COMMENT,lr.STREAM,lr.RECORDING;const kr=En(lr),yr=En(dr),br=En(ur),Ar=En(hr),Sr={TOKEN_NAME:jt,CONTENT_ID:Yt.CONTENT_ID,DETAILS:Yt.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:Vt}};function Er(e,t="tokenName"){Tn(e,t,Sr.TOKEN_NAME)}function wr(e){if(void 0!==e.contentType&&!kr(e.contentType))throw kt("contentType",`one of: ${Object.values(lr).join(", ")}`,"Content type");if(void 0!==e.status&&!br(e.status))throw kt("status",`one of: ${Object.values(ur).join(", ")}`);if(void 0!==e.reason&&!yr(e.reason))throw kt("reason",`one of: ${Object.values(dr).join(", ")}`);if(void 0!==e.reporterAddress&&!bn(e.reporterAddress))throw Tt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Kn(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!bn(e.reportedUserAddress))throw Tt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Kn(e.reportedUserAddress,"reportedUserAddress"),Sn(0,void 0,Sr.PAGINATION.MAX_LIMIT,e.pageSize)}class Tr extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}async createFlag(e){!function(e){if(Er(e.tokenName),void 0===e.contentType)throw vt("contentType","Content type");if(!kr(e.contentType))throw kt("contentType",`one of: ${Object.values(lr).join(", ")}`,"Content type");if(!bn(e.contentId))throw vt("contentId","Content ID");if(e.contentId.length>Sr.CONTENT_ID.MAX_LENGTH)throw wt("contentId",Sr.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!bn(e.reportedUserAddress))throw vt("reportedUserAddress","Reported user address");if(Kn(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==lr.STREAM&&e.contentType!==lr.RECORDING||void 0!==e.reason&&null!==e.reason))throw vt("reason","Reason");if(void 0!==e.reason&&!yr(e.reason))throw kt("reason",`one of: ${Object.values(dr).join(", ")}`,"Reason");if(void 0!==e.details&&!bn(e.details))throw Tt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Sr.DETAILS.MAX_LENGTH)throw wt("details",Sr.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){Er(e.tokenName),wr(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&Er(e.tokenName),wr(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw vt("flagId","Flag ID");try{vn(e.flagId,"flagId")}catch{throw kt("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 vt("flagId","Flag ID");try{vn(e.flagId,"flagId")}catch{throw kt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw vt("action","Action");if(!Ar(e.action))throw kt("action",`one of: ${Object.values(hr).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=Aa(e,Vt);Sa(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(ee.LIST,t,this.getMultiAuthHeaders()),s=this.extractData(n);return{items:s.flags,pageInfo:s.pageInfo}}}const Nr=["heart","fire","laugh","wow","thumbs_up"];class Cr extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}validateReactionTokenName(e){this.validateTokenName(e,jt)}validateMessageId(e){if(!bn(e))throw vt("messageId","Message ID");if(fn(e,Zt.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Zt.CONTENT_REACTION.PATTERN.test(e))throw kt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!bn(e))throw vt("reactionType","Reaction type");if(!Nr.includes(e))throw kt("reactionType",`one of: ${Nr.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=Lt(e.tokenName));const s=await this.http.post(t,n,this.getMultiAuthHeaders()),a=this.extractData(s),{created:r,...i}=a;return{data:i,created:r}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Ie}?${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 Ir="Token name is required and must be a string";const _r="GALA|Unit|none|none";class Dr extends Fn{constructor(e,t,n,s=!1){super(s),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!bn(e))throw new at(Ir,"tokenName",Je);let s;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(s=ar(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${lt(t)}`)}if(void 0!==s)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(s);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),s=await this.fetchMarketUsdPrice(_r),a=dn(n.amount,0)/1e18;if(a<=0)throw new at(`Invalid token amount calculation: ${a}`,"amount","INVALID_CALCULATION");return{symbol:Pt(e),price:s.price/a}}catch(t){throw yt(`Failed to calculate launchpad token spot price for ${e}: ${lt(t)}`)}}async resolveAuthoritativeSymbol(e){if(e===_r)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 yt("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw yt(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${lt(t)}`)}if(""===n)throw yt(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!bn(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 yt("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),s=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),a=null!==s&&"object"==typeof s?s:{},r=Object.keys(a).find(e=>e.toUpperCase()===n.toUpperCase()),i=void 0!==r?a[r]:1===Object.keys(a).length?Object.values(a)[0]:void 0,o=i?.price;if("number"!=typeof o||!Number.isFinite(o))throw new at(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${o}`),{symbol:n,price:o}}catch(e){if(e instanceof at)throw e;throw yt(`Failed to fetch DEX spot price: ${lt(e)}`)}}}const Rr=20,Or=3e3,Fr=1e3,Ur=!0,xr=!0,Mr=!1;class Lr{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 $t({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??Rr,flushIntervalMs:t.flushIntervalMs??Or,maxQueueSize:t.maxQueueSize??Fr,flushOnPageHide:t.flushOnPageHide??Ur,flushOnPageUnload:t.flushOnPageUnload??xr,debug:t.debug??Mr},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const s={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(s),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 Pr(e){let t;return{requestor:async(n,s)=>{const a="string"==typeof s?.body?JSON.parse(s.body):void 0,{data:r,status:i,headers:o}=await e(n,a);t=r;const c=void 0===r?"":JSON.stringify(r),l="number"==typeof i?i:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(r),text:()=>Promise.resolve(c),headers:o??{}}},answer:()=>t}}const Br=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class $r extends On{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const{requestor:n}=Pr(async(e,t)=>({data:await this.http.post(e,t)})),a=new s.GatewayReads({gatewayBaseUrl:"",httpRequestor:n,requestTimeoutMs:1/0}),{owner:r,collection:i,category:o,type:c,additionalKey:l}=e,d=await a.fetchTokenBalance({owner:r,tokenClassKey:{collection:i,category:o,type:c,additionalKey:l},includeExpiredHolds:t});return void 0===d?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,s={quantity:e.quantity,collection:t,category:n,tokenId:ar(e.tokenClassKey)};return e.inUseHolds.length>0&&(s.inUseHolds=[...e.inUseHolds],s.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(s.lockedHolds=[...e.lockedHolds],s.lockedQuantity=e.lockedQuantity),void 0===s.lockedQuantity&&void 0===s.inUseQuantity||(s.availableQuantity=e.availableQuantity),s}(d)}catch(e){if(s.isGalaError(e)&&Br.has(e.code))return null;throw yt(`Failed to fetch token balance from GalaChain: ${lt(e)}`,void 0,ct(e)?e:void 0)}}}function Gr(e){if(null==e||"object"!=typeof e)return!1;const t=e;return bn(t.amount)&&(void 0!==t.tokenId||bn(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 Kr(e){if(null==e||"object"!=typeof e)return!1;const t=e;return bn(t.amount)&&(void 0!==t.tokenId||bn(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var Wr,Hr;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(Wr||(Wr={}));class zr 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"}(Hr||(Hr={}));class jr extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function qr(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 Vr(e,t,n,s="[DEBUG] Token resolution (launchpad)"){const a=await t.resolveTokenToVault(e);if(null!==a){const t=or(a);return n.debug(s,{tokenName:e,vaultAddress:a,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new at(`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 Qr extends On{constructor(e,t,n,s=!1,a){super(e,s),this.wallet=t,this.tokenResolver=n,this.writer=a,this.nativeSigner=t?new Ya(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:$n(this.wallet.address)}:this.writer}}function Xr(e,t){const{collection:n,category:s,type:a,additionalKey:r,instance:i}=e;return{tokenClassKey:{collection:n,category:s,type:a,additionalKey:r},instance:i,quantity:t}}const Jr=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function Yr(e,{signer:t,walletAddress:n}){const{requestor:a,answer:r}=Pr((t,n)=>e.postWithMeta(t,n));return{writes:new s.GatewayWrites({gatewayBaseUrl:"",signer:t,walletAddress:n,httpRequestor:a,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:r}}async function Zr(e,t,n){let a;try{a=await t(e.writes)}catch(t){throw function(e){return s.isGalaError(e)&&Jr.has(e.code)}(t)&&n(e.answer(),void 0),t}return n(e.answer(),a)}function ei(e){return void 0===e||""===e?{}:{uniqueKey:e}}const ti=100,ni=100;class si extends Qr{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new zr("Wallet required for token lock operations",Wr.WALLET_REQUIRED);return da(async()=>{const n=Yr(this.http,t),s=n.writes.walletAddress,a=[],r=[];let i=s;const o=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==o?.lockAuthority&&(i=$n(o.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);r.push(Xr(e,t.amount)),a.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount,lockAuthority:void 0!==t.lockAuthority?$n(t.lockAuthority):i})}return Zr(n,t=>t.lockTokens({tokens:r,lockAuthority:i,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...ei(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token lock failed"),this.extractLockResult(e,t,a)))},"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 zr("Wallet required for token unlock operations",Wr.WALLET_REQUIRED);return da(async()=>{const n=[],s=[],a=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);s.push(Xr(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return Zr(Yr(this.http,t),t=>t.unlockTokens({tokens:s,...void 0!==a?.name&&{name:a.name},...ei(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{gt(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 zr(`${lt(t)}${n}`,Wr.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new zr("Must provide either tokenId or tokenName for token identification",Wr.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{Nn(e.tokenName,"tokenName")}catch{throw new zr("Invalid token name format",Wr.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{Bs(xs(e.amount))}catch{throw new zr(kt(t,"a positive number",n).message,Wr.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Gr)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new zr("Invalid lock data: missing required fields",Wr.VALIDATION_ERROR);if(e.tokens.length>ti)throw new zr(`Batch size exceeds maximum limit of ${ti} tokens per lock operation`,Wr.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Gn(t.lockAuthority))throw new zr("Invalid lock authority address format",Wr.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{vn(t.expires,"expires")}catch{throw new zr(kt("expires","a positive integer (epoch milliseconds)","Expires").message,Wr.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Kr)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new zr("Invalid unlock data: missing required fields",Wr.VALIDATION_ERROR);if(e.tokens.length>ni)throw new zr(`Batch size exceeds maximum limit of ${ni} tokens per unlock operation`,Wr.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 s=this.transactionIdOf(e,t),a=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==a&&{blockNumber:a},locked:n}}extractUnlockResult(e,t,n){const s=this.transactionIdOf(e,t),a=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==a&&{blockNumber:a},unlocked:n}}handleLockError(e,t,n){if(e instanceof zr)return e;if(s.isGalaError(e)&&"pre_send"===e.phase)return new zr(`${t}: ${e.message}`,"SIGNING_FAILED"===(a=e.code)?Wr.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===a?Wr.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===a?Wr.INVALID_AMOUNT:Wr.VALIDATION_ERROR,qr(n));var a;let r=t,i=Wr.NETWORK_ERROR;if(ht(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(r=`${t}: ${e}`);const s="string"==typeof e?e.toLowerCase():"";s.includes("insufficient")||s.includes("balance")?i=Wr.INSUFFICIENT_BALANCE:s.includes("lock")&&s.includes("not found")?i=Wr.LOCK_NOT_FOUND:s.includes("not found")||s.includes("token")?i=Wr.TOKEN_NOT_FOUND:s.includes("authority")?i=Wr.NOT_LOCK_AUTHORITY:s.includes("expired")&&(i=Wr.LOCK_EXPIRED)}}else ct(e)&&(r=`${t}: ${lt(e)}`);return new zr(r,i,qr(n))}async resolveTokenInstance(e){return da(async()=>Vr(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof jr)throw new zr(lt(t),Wr.TOKEN_NOT_FOUND);throw new zr(`Failed to resolve token '${e}': ${lt(t)}`,Wr.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=rr(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 zr("Must provide either tokenId or tokenName for token identification",Wr.TOKEN_NOT_FOUND)}}const ai=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function ri(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class ii extends On{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?rr(e):e,{collection:n,category:s,type:a,additionalKey:r}=t,i={collection:n,category:s,type:a,additionalKey:r},o="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(i),e=>{if(gt(e,o),void 0===ri(e)?.[0])throw yt(`Token not found on GalaChain: ${ar(i)}`,404)},()=>yt(`Token not found on GalaChain: ${ar(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 vt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(gt(e,"Failed to fetch token classes with supply from GalaChain"),0===(ri(e)?.length??0))throw yt("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,t,n){if(!this.publicAxios)throw vt("publicAxios","Public Axios instance");const a=this.publicAxios,{requestor:r,answer:i}=Pr(async(e,t)=>{const n=await a.post(e,t);return{data:n.data,status:n.status}});try{return await e(new s.GatewayReads({gatewayBaseUrl:"",httpRequestor:r,requestTimeoutMs:1/0}))}catch(e){if(s.isGalaError(e)&&ai.has(e.code)&&(t(i()),"TOKEN_CLASS_NOT_FOUND"===e.code&&void 0!==n))throw n();throw e}}handleTokenServiceError(e,t,n){if(e instanceof at)throw e;if(ht(e)&&404===e.response?.status)throw yt(t,404,ct(e)?e:void 0);if(ct(e)&&"Error"===e.name&<(e).includes("status indicates failure"))throw yt(lt(e),400,ct(e)?e:void 0);const s=lt(e);if(s.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(s)}throw yt(`${n}: ${s}`,void 0,ct(e)?e:void 0)}}function oi(e){if(null==e||"object"!=typeof e)return!1;const t=e;return bn(t.amount)&&(void 0!==t.tokenId||bn(t.tokenName))}var ci;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(ci||(ci={}));class li extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const di={validateAmount(e){const t=xs(e);try{!function(e,t){if(e.isNaN())throw Nt(t,"NaN");if(!e.isFinite())throw wt(t,"finite");if(e.isLessThanOrEqualTo(0))throw Et(t,"0",e.toString())}(t,"amount")}catch(t){throw new jr(t.message,Hr.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!An(e)&&bn(e)){if(e.length>nn.MAX_LENGTH)throw new at(`Unique key too long. Maximum length: ${nn.MAX_LENGTH}`);if(!nn.PATTERN.test(e))throw new jr('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Hr.INVALID_AMOUNT,{uniqueKey:e})}}},ui="gala-transfer-successful",hi="token-transfer-successful",gi="token-locked-successfully",mi="token-unlocked-successfully",pi="transfer-successful-no-id",fi=50;class vi extends Qr{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new jr("Wallet required for GALA transfer operations",Hr.WALLET_REQUIRED);try{const n=$n(e.recipientAddress),s=Yr(this.http,t);return await Zr(s,t=>t.transferGala({to:n,quantity:e.amount,...ei(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 jr("Wallet required for token transfer operations",Hr.WALLET_REQUIRED);try{const n=$n(e.to),s=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new jr("Must provide either tokenId or tokenName for token identification",Hr.TOKEN_NOT_FOUND)),a=Yr(this.http,t);return await Zr(a,t=>t.transferToken({to:n,...Xr(s,e.amount),...ei(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 jr)throw t;throw new jr(`Failed to resolve token class key for '${e}': ${lt(t)}`,Hr.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new li("Wallet required for token burn operations",ci.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new li("Must provide either tokenId or tokenName for token identification",ci.TOKEN_NOT_FOUND));n.push(Xr(e,t.amount))}const s=Yr(this.http,t);return await Zr(s,t=>t.burnTokens({tokens:n,...ei(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 bn(t.recipientAddress)&&bn(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new at("Invalid GALA transfer data: missing required fields");if(!Gn(e.recipientAddress))throw new jr("Invalid recipient address format",Hr.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});di.validateAmount(e.amount),di.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return bn(t.to)&&bn(t.amount)&&(void 0!==t.tokenId||bn(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new at("Invalid token transfer data: missing required fields");if(!Gn(e.to))throw new jr("Invalid recipient address format",Hr.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new jr("Must provide either tokenId or tokenName for token identification",Hr.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Nn(e.tokenName,"tokenName")}catch{throw new jr("Invalid token name format",Hr.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}di.validateAmount(e.amount),di.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(oi)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new li("Invalid burn data: missing required fields",ci.VALIDATION_ERROR);if(e.tokens.length>fi)throw new li(`Batch size exceeds maximum limit of ${fi} tokens per burn operation`,ci.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 li("Must provide either tokenId or tokenName for token identification",ci.TOKEN_NOT_FOUND);const e=xs(t.amount);try{Bs(e)}catch{throw new li("Burn amount must be a positive number",ci.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=rr(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 Vr(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof jr)throw t;throw new jr(`Failed to resolve token '${e}': ${lt(t)}`,Hr.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new jr("No response from GalaChain transfer service",Hr.NETWORK_ERROR);const s=t?.blockNumber,a="object"==typeof e&&"Status"in e;a&>(e,"Extract transaction ID");const r=a&&"Data"in e,i=t?.transactionId;if(void 0!==i)return{transactionId:i,...void 0!==s?{blockNumber:s}:{}};if(r){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!==s?{blockNumber:s}:{}}}}let e=pi;if(t.Data.length>0)switch(n){case"gala":e=ui;break;case"token":e=hi;break;case"lock":e=gi;break;case"unlock":e=mi}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}throw new jr("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Hr.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new li("No response from GalaChain burn service",ci.NETWORK_ERROR);try{gt(e,"Token burn operation")}catch(e){throw new rt(lt(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 s=Array.isArray(e.Data)?e.Data[0]:void 0,a=t?.transactionId??s?.transactionId??s?.txnId??s?.TxnId??s?.id??void 0,r=t?.blockNumber;return{...void 0!==a&&{transactionId:a},...void 0!==r&&{blockNumber:r},burned:n}}handleTransferError(e,t,n){if(e instanceof jr)return e;if(e instanceof at)return new jr(lt(e),Hr.INVALID_AMOUNT);if(s.isGalaError(e)&&"pre_send"===e.phase)return new jr(e.message,"SIGNING_FAILED"===(a=e.code)?Hr.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===a?Hr.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===a?Hr.TOKEN_NOT_FOUND:Hr.INVALID_AMOUNT);var a;if(ht(e)&&e.response){const t=e.response.status,s=e.response.data;if(400===t){const e=s?.message;return new jr(("string"==typeof e?e:void 0)??"Invalid transfer request",Hr.INVALID_AMOUNT)}if(403===t)return new jr("Insufficient balance for transfer",Hr.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new jr("Token not found",Hr.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===ut(e)||"ETIMEDOUT"===ut(e)))return new jr("Transfer request timed out",Hr.NETWORK_ERROR);const r=""!==lt(e)?lt(e):t;return new jr(r,Hr.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof li)return e;if(s.isGalaError(e)&&"pre_send"===e.phase)return new li(`${t}: ${e.message}`,"SIGNING_FAILED"===(a=e.code)?ci.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===a?ci.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===a?ci.INVALID_AMOUNT:ci.VALIDATION_ERROR,qr(n));var a;let r=t,i=ci.NETWORK_ERROR;if(ht(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){r=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?i=ci.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(i=ci.TOKEN_NOT_FOUND)}}}else ct(e)&&(r=`${t}: ${lt(e)}`);return new li(r,i,qr(n))}}class ki extends On{constructor(e,t,n,s=!1,a,r){super(e,s),this.balanceService=new $r(e,s),this.tokenService=new ii(e,s,a),this.lockService=new si(e,t,n,s,r),this.transferService=new vi(e,t,n,s,r)}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 s.tokenDetailsOf(await this.fetchTokenClassFromChain(e))}catch(t){if(ct(t)&&("NetworkError"===t.name||lt(t).includes("Token not found")))throw t;throw yt(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:ar(e)}: ${lt(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 yi(e,t="image",n){const s=new FormData;if("undefined"!=typeof File&&e instanceof File)s.append(t,e);else{if(!Buffer.isBuffer(e))throw kt("file","a File object (browser) or Buffer (Node.js)");{const a=new Blob([e],{type:"image/png"});s.append(t,a,n)}}return s}class bi extends On{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Vs(t);const s=`${t}.png`;Ws(n.file,s,"image/png");try{const e=`${n.tokenName??t}.png`,s=yi(n.file,"image",e),a=await Ot(()=>this.http.request({method:"POST",url:`${d.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:s,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof a?a:""}catch(e){if(e instanceof it)throw e;if(ct(e)&<(e).includes("FormData"))throw bt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}const Ai={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};function Si(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class Ei extends On{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!An(e.search)&&{search:e.search},...!An(e.tokenName)&&{tokenName:e.tokenName},...!An(e.type)&&{type:e.type},...!An(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!An(e.language)&&{language:e.language},...!An(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!An(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!An(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,s={pageSize:String(t)};void 0!==n&&(s.cursor=n),An(e.type)||(s.type=e.type),An(e.tokenName)||(s.tokenName=e.tokenName),An(e.search)||(s.search=e.search),An(e.hasUpcomingShows)||(s.hasUpcomingShows=e.hasUpcomingShows.toString()),An(e.language)||(s.language=e.language),An(e.recentlyStreamed)||(s.recentlyStreamed=e.recentlyStreamed.toString()),An(e.hasRecordings)||(s.hasRecordings=e.hasRecordings.toString()),An(e.streamStatus)||(s.streamStatus=e.streamStatus);const a=Us(s),r=Dt(await Ut(()=>this.http.get(d.FETCH_POOLS,a),{errorContext:"Failed to fetch pools"})),i=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else 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}(r),o={hasNextPage:r.hasNextPage??r.pageInfo?.hasNextPage??!1},c=r.count??r.total;void 0!==c&&(o.totalCount=c);const l=r.nextCursor??r.pageInfo?.endCursor;null!=l&&(o.nextCursor=l);const u=r.prevCursor??r.pageInfo?.startCursor;null!=u&&(o.prevCursor=u);const h=r.hasPrevPage??r.pageInfo?.hasPreviousPage;return void 0!==h&&(o.hasPrevPage=h),{items:i,pageInfo:o}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??ya.DEFAULT_LIMIT;bn(e?.tokenName)&&Vs(e.tokenName);const s=void 0!==e?.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,a=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,r={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:s,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:a}),pageSize:n,...void 0!==t&&{cursor:t}},i=await this.fetchSinglePage(r);return{items:i.items,pageInfo:i.pageInfo}}async fetchAllPools(e){const t=[];let n;const s=ya.BACKEND_MAX_PAGE_SIZE;for(;;){const a={...e,pageSize:s,...void 0!==n&&{cursor:n}},r=await this.fetchPools(a);if(t.push(...r.items),0===r.items.length)break;if(!r.pageInfo.hasNextPage)break;n=r.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=Ns(e);!t.success&&t.errors&&qs(t.errors,"options")}(e),bn(e.tokenName)&&Vs(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===bn(e.symbol)){return!n.symbolAvailable}if(!0===bn(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,s="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||s.includes("404")||s.includes("Pool not found"))return!1;const a="number"==typeof n.statusCode?n.statusCode:null;if(404===a)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||s.includes("400")||s.includes("Missing required pool identifier"))return!1;if(400===a&&s.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 Is(t,"tokenName")&&Ds(t,"from")&&Ds(t,"to")&&Ds(t,"resolution")}(e))throw new at("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:s,resolution:a}=e;if(Vs(t),null==n||null==s||null==a)throw new at("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:n,to:s,resolution:a};Qs(r);const i=Us(r);return{dataPoints:await Ot(()=>this.http.get(d.CHART,i),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw vt("tokenName","Token name");let t;Vs(e);try{t=await Ut(()=>this.http.get(`${d.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(ht(t)&&500===t.response?.status)throw yt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return Ys(Dt(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw vt("tokenName","Token name");if(""===t||null==t)throw vt("userAddress","User address");return Vs(e),Ot(()=>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");Vs(e);try{const t=d.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=Dt(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&&Vs(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(!bn(e))throw vt("tokenName","Token name");Vs(e);const t=d.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=Dt(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 vt("tokenName","Token name");Vs(e),function(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 at("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",Je);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw Tt("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Tt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Tt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Tt("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 Tt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Tt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new at("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",et)}}(t);const n=d.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),s={};void 0!==t.messagesEnabled&&(s.messagesEnabled=t.messagesEnabled),void 0!==t.commentsEnabled&&(s.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(s.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(s.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(s.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(s.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(s.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(s.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(s.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(s.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(s.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(s.tiktokUrl=t.tiktokUrl),await this.http.patch(n,s,this.getJwtHeaders())}async getTokenConfig(e){if(!bn(e))throw vt("tokenName","Token name");Vs(e);const t=d.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=Dt(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const wi=Xt,Ti=qt,Ni={MAX_LENGTH:100};function Ci(e){if(void 0!==e.tokenName){if(!bn(e.tokenName))throw Tt("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>Ti.MAX_LENGTH)throw wt("tokenName",Ti.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!bn(e.userAddress))throw Tt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>Ni.MAX_LENGTH)throw wt("userAddress",Ni.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Tt("search","a string",typeof e.search);if(e.search.length>256)throw wt("search",256,e.search.length)}if(Sn(0,void 0,wi.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw kt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!bn(e.startDate))throw Tt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw kt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!bn(e.endDate))throw Tt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw kt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{pn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw kt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{pn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw kt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const s="number"==typeof e?e:Number(e),a="number"==typeof t?t:Number(t);if(isNaN(s)||isNaN(a))throw Tt(n,"numeric values",void 0,n);if(s>a)throw new at(`Minimum value (${s}) must be less than or equal to maximum value (${a}) for ${n}`,n,nt)}(e.minAmount,e.maxAmount,"amountRange")}class Ii extends On{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 Is(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&_s(t,"userAddress")&&Ds(t,"offset")&&Ds(t,"pageSize")&&Ds(t,"page")&&Ds(t,"limit")}(e))throw new at("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:s=ya.DEFAULT_LIMIT}=e;if(!bn(t))throw vt("tokenName","Token name");const a={pageSize:String(Math.min(s,Qt))};void 0!==n&&(a.cursor=n);const r={...a};r.tokenName=t;const i=await this.http.get(d.GET_TRADES,r);if(null==i)throw new at("No response from trade service","response","NO_RESPONSE");const o=Dt(i),c=Si(o,"trades"),l=o?.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=Lt(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?function(e,t=1,n=ya.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}(e.pageSize,1,wi.MAX_LIMIT):wi.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){Ci(e);const t=this.buildTradesQueryParams(e);return Ot(()=>this.http.get(_e,t),{errorContext:"Failed to fetch trades"})}}function _i(e){return!!bn(e)&&Jt.PATTERN.test(e)}function Di(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const s=e.trim();return s.length<n?null:s}En({BOTH:"both",HELD:"held",CREATED:"created"});class Ri extends On{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!_i(t))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,s=n?d.GET_CURRENT_USER:d.GET_PROFILE.replace(":address",t),a=await this.http.get(s,void 0,n?this.getJwtHeaders():void 0);if(null==a)throw new at("No response from user service","response","NO_RESPONSE");return a}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!bn(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await Ot(()=>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 at("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,s=yi(e.file,"image",n),a=await Ot(()=>this.http.request({method:"POST",url:`${d.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:s,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof a?a:""}catch(e){if(e instanceof at||e instanceof it)throw e;throw new at(`Profile image upload failed: ${lt(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new at("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},s="created"===e.type;s&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const a=await this.buildFetchRequest(d.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:s?"launches":"token",errorMessage:"Failed to fetch token list"});return s&&void 0!==t?{...a,tokens:a.tokens.filter(e=>e.tokenName===t||e.name===t)}:a}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new at("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new at("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:s,tokenName:a,status:r}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new at("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const i=e?.address??this.http.getAddress();if(null==i||""===i)throw new at("Wallet address not available - wallet not configured","address","NO_WALLET");const o={type:"created",address:i,pageSize:n??ya.DEFAULT_LIMIT};return void 0!==t&&(o.cursor=t),void 0!==s&&(o.search=s),void 0!==a&&void 0===s&&(o.search=a),void 0!==a&&(o.tokenName=a),void 0!==r&&(o.status=r),this.fetchTokenList(o)}async getManagedTokens(e={}){const t=Aa({pageSize:e.pageSize??ya.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},Qt);return Ot(()=>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 s=Aa({pageSize:t.pageSize??ya.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},Qt);Sa(s,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(s.type=n.requestType);let a=e;const r=t.address??this.http.getAddress();if(e.includes(":address")){if(0===r.length)throw vt("address","User address");a=e.replace(":address",r),delete s.address}const i=Dt(await Ut(()=>this.http.get(a,s),{errorContext:n.errorMessage})),o=Si(i,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",s="string"==typeof e.name?e.name:t,a="string"==typeof e.createdAt?e.createdAt:"",i=e.metadata,o={...e};return delete o.metadata,{...o,id:"string"==typeof e.id?e.id:t,name:s,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:r,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:a,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:a}}),c={hasNextPage:i.hasNextPage??!1},l=i.pageInfo,d=i.count??i.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!==i.nextCursor&&(c.nextCursor=i.nextCursor),void 0!==i.prevCursor&&(c.prevCursor=i.prevCursor),void 0!==i.hasPrevPage&&(c.hasPrevPage=i.hasPrevPage);const u={tokens:o,pageInfo:c};return void 0!==d&&(u.total=d),u}validateGetTokenListOptions(e){const t=e.pageSize??ya.DEFAULT_LIMIT;if(t<1||t>Qt)throw new at(`pageSize must be between 1 and ${Qt}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!_i(e.address))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Di(e.search);if(null!==n&&!(bn(s=n)&&s.length>=on&&s.length<=cn))throw St("search",on,cn,n.length,"Search query");var s;const a=Di(e.tokenName);if(null!==a&&!(bn(r=a)&&r.length>=qt.MIN_LENGTH&&r.length<=qt.MAX_LENGTH))throw St("tokenName",qt.MIN_LENGTH,qt.MAX_LENGTH,a.length,"Token name");var r}validateUpdateProfileData(e){if(!_i(e.address))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(bn(t)&&t.length>=ln.FULL_NAME.MIN_LENGTH&&t.length<=ln.FULL_NAME.MAX_LENGTH&&ln.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw St("fullName",ln.FULL_NAME.MIN_LENGTH,ln.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!_i(e.address))throw kt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class Oi{constructor(e,t,n=!1){this.http=e,this.poolService=new Ei(e,t,n),this.tradeService=new Ii(e,n),this.userService=new Ri(e,t,n),this.imageService=new bi(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 Vs(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 Fi extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}validateContent(e,t){if(!bn(e))throw vt("content","Message content");if(0===e.trim().length)throw vt("content","Message content");fn(e,t===Ai.CHAT_MESSAGE?Yt.CHAT_MESSAGES_V1.MAX_LENGTH:Yt.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!bn(e))throw vt("id","Message ID");if(e.length<10||e.length>64)throw kt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==Ai.CHAT_MESSAGE&&e!==Ai.COMMENT)throw new at(`type must be one of: ${Object.values(Ai).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,jt);const s={};void 0!==e.cursor&&(s.cursor=e.cursor),s.pageSize=e.pageSize??ya.DEFAULT_LIMIT;const a=Aa(s,Xt.MAX_LIMIT),r={};void 0!==a.pageSize&&(r.pageSize=a.pageSize),void 0!==a.cursor&&(r.cursor=a.cursor),t&&(r.type=e.type.toUpperCase()),n&&(r.tokenName=Lt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(r.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(r.search=e.search);const i=await this.http.get(De.GET_MESSAGES,r),o=this.extractData(i);return{messages:o.messages,pageInfo:o.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,jt),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:Lt(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),s={content:t.content.trim()},a=await this.http.put(n,s,this.getJwtHeaders());return{message:this.extractData(a)}}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,jt);const t=await this.http.get(De.GET_PINNED,{tokenName:Lt(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 Ui=wn({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),xi={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},Mi=wn(xi),Li={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};wn(Li);class Pi extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}validateRole(e){if(!bn(e))throw vt("role","Role");if(!function(e){return Ui.includes(e)}(e))throw kt("role",`one of: ${Ui.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!bn(e))throw vt("inviteCode","Invite code");if(t=e,!sn.PATTERN.test(t))throw kt("inviteCode","valid invite code format","Invite code");var t}validateInviteScope(e){if(void 0!==e&&(t=e,!Mi.includes(t)))throw new at(`Invalid invite scope. Must be one of: ${Mi.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??xi.TOKEN;if(t===xi.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new at("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,zt)}else if(t===xi.ALL_OWNER_TOKENS&&e.tokenName)throw new at("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=j,s={inviteScope:t,role:e.role};t===xi.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(s.tokenName=Lt(e.tokenName)),void 0!==e.description&&(s.description=e.description),void 0!==e.expiresAt&&(s.expiresAt=e.expiresAt);const a=await this.http.post(n,s,this.getMultiAuthHeaders());return{invite:this.extractData(a)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,zt),this.validateStatusFilter(e.status,Li);const t=Q,n={...this.buildPaginationParams(e,Xt.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=Lt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getMultiAuthHeaders()),a=this.extractData(s);return{items:a.invites,pageInfo:a.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(X,{id:String(e)});_t(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(J,{id:String(e.inviteId)}),n={role:e.role},s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new at("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(Y,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=q,n={inviteCode:e.inviteCode},s=await this.http.post(t,n,this.getMultiAuthHeaders()),a=this.extractData(s);return"tokenName"in a&&void 0!==a.tokenName?{token:a}:{blanketAccess:a}}async getModeratedTokens(e){const t=V,n=this.buildPaginationParams(e??{},Xt.MAX_LIMIT),s=await this.http.get(t,n,this.getMultiAuthHeaders()),a=this.extractData(s);return{items:a.tokens,pageInfo:a.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 Bi="10000",$i="1000";function Gi(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Ki(){return Date.now()+6e4}function Wi(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Hi(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function zi(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class ji extends On{constructor(e){super(e)}getCollectionClaimFee(){return Bi}getTokenClassCreateFee(){return $i}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(!zi(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=Bi;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const s=$i,a=String(BigInt(s)*BigInt(e.createTokenClasses));n.tokenClassCreate=s,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(a))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!Wi(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:Ki(),uniqueKey:Gi("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),!zi(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),!Wi(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(!Wi(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?Hi(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?Hi(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Ki(),uniqueKey:Gi("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),!Wi(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(!zi(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 s={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:Ki(),uniqueKey:Gi("mint")};this.logger.debug("Built mint DTO",s);const a=`mint-${Date.now()}`,r=Array.from({length:t},(e,t)=>t+1);return{transactionId:a,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:r,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}),!zi(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}=Pr(async(e,t)=>({data:await this.http.post(e,t)}));return new s.GatewayReads({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class qi extends On{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(He,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),s=this.extractData(n);return this.logger.debug("Push token registered",{registered:s.registered}),s}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:ze,data:{token:e},headers:t}),s=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:s.unregistered}),s}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(je,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(qe,e,t),s=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:s.tradesEnabled,streamsEnabled:s.streamsEnabled}),{preferences:s}}}class Vi extends On{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 at("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()),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:s.title}),{oembed:s}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new at("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()),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:s}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new at("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())),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:s.title}),{oembed:s}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new at("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())),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:s}}}function Qi(e){if(!bn(e))throw vt("address","Address")}const Xi={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Ji={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Yi=En(Xi),Zi=En(Ji);function eo(e){try{In(e.description,"description",255)}catch(e){if(e instanceof at){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(!bn(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{_n(e.expiresAt,"expiresAt")}catch(e){if(e instanceof at)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Ht(e.expiresAt)){if(function(e){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())?(Wt.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return Wt.warn(`Date parsing error for "${e}":`,t),new Date}}(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function to(e){if(!bn(e))throw new Error("Address must be a non-empty string");try{Kn(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function no(e){try{vn(e,"id")}catch(e){if(e instanceof at)throw new Error("Invite ID must be a positive integer");throw e}}class so extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}validateInviteCodeFormat(e){if(!bn(e))throw vt("inviteCode","Invite code");!function(e){if(!bn(e))throw new Error("Invite code must be a non-empty string");fn(e,100,"code")}(e)}validateWalletAddressFormat(e){if(!bn(e))throw vt("address","Address");to(e)}async createInvite(e={}){eo(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 s=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e={}){!function(e){if(void 0!==e.status&&!Yi(e.status))throw Ct("status",e.status,Object.values(Xi),"status");Sn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Xi);const t=ne,n={...this.buildPaginationParams(e,Xt.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),a=this.extractData(s);return{items:a.invites,pageInfo:a.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(se,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){no(e);const t=this.buildEndpoint(re,{id:String(e)});_t(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=ae,n={inviteCode:e},s=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(s)}}async listOverseers(e={}){!function(e){if(void 0!==e.status&&!Zi(e.status))throw Ct("status",e.status,Object.values(Ji),"status");Sn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Ji);const t=ie,n={...this.buildPaginationParams(e,Xt.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),a=this.extractData(s);return{items:a.overseers,pageInfo:a.pageInfo}}async createOverseerDirect(e){!function(e){if(null==e||"object"!=typeof e)throw new at("Options are required");if(!bn(e.userAddress))throw new at("userAddress is required and must be a non-empty string");try{Kn(e.userAddress,"userAddress")}catch{throw new at("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new at("description must be a string");if(e.description.length>255)throw new at("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",Yt.DESCRIPTION.MAX_LENGTH);const t=oe,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const s=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(s)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(ce,{address:e});_t(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&&function(e){if(null==e||"object"!=typeof e)throw new at("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new at("Search must be a string");if(0===e.search.length)throw new at("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new at("Sort field must be a string");if(0===e.sortBy.length)throw new at("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new at('Sort order must be "asc" or "desc"')}(t);const n=fe,s=this.buildPaginationParams(t,Xt.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(s.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(s.sortBy=t.sortBy),void 0!==t.sortOrder&&(s.sortOrder=t.sortOrder);const a=await this.http.get(n,s,this.getDualAuthHeaders()),r=this.extractData(a);return{items:r.users,pageInfo:r.pageInfo}}async getOverseerUserSummary(e){if(!bn(e))throw vt("address","User address");to(e);const t=this.buildEndpoint(ve,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Qi(e);const t=this.buildEndpoint(ke,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!bn(e))throw vt("tokenName","Token name")}(e);const t=this.buildEndpoint(ye,{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 at("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=be,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Qi(e);const t=this.buildEndpoint(Ae,{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)}}class ao extends On{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),_t(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(T);return this.extractData(e)}async updatePlatformConfig(e){const t=function(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}(e);if(t.length>0)throw new at(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(N,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(_);return this.extractData(e)}}class ro extends On{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 io extends wa{constructor(e,t,n,s){super(e,t,n,!1,s)}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(!bn(e.content))throw new at("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 oo extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}async getChatStatus(e){if(null==e||""===e)throw vt("tokenName","Token name");return this.validateTokenName(e,zt),da(async()=>{const t=this.buildEndpoint(Fe,{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 vt("tokenName","Token name");return this.validateTokenName(e,zt),da(async()=>{const t=this.buildEndpoint(xe,{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 vt("tokenName","Token name");return this.validateTokenName(e,zt),da(async()=>{const t=this.buildEndpoint(Ue,{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??Lt(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw vt("tokenName","Token name");if(this.validateTokenName(e,zt),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return da(async()=>{const n=this.buildEndpoint(Me,{tokenName:e}),s=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(s)},`Failed to set slow mode for token: ${e}`,this.logger)}}class co 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 s of n)try{const e=s(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)}}En({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),En({READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"});const lo=En({YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"});const uo={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};En(uo),En({OWNER:"OWNER",MODERATOR:"MODERATOR"});function ho(e,t="tokenName"){Tn(e,t,zt)}function go(e){if(ho(e.tokenName),!bn(e.language))throw vt("language");if(t=e.language,!bn(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new at('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",et);var t}En({...uo,OVERSEER:"OVERSEER"});class mo extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}async startStream(e){this.validateTokenName(e,zt);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,zt);const t=this.buildEndpoint(p,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,f,zt)}async enableStream(e){return this.toggleFeature(e,v,zt)}async resetStreamKey(e){this.validateTokenName(e,zt);const t=this.buildEndpoint(k,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,zt);const t=this.buildEndpoint(R,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){ho(e.tokenName),Sn(0,void 0,rn,e.pageSize)}(e);const t=this.buildEndpoint(y,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,rn),s=e.offset;"number"==typeof s&&(n.offset=String(s));const a=await this.http.get(t,n),r=this.extractData(a),i=e,o=r.pageSize??r.limit??e.pageSize??("number"==typeof i.limit?i.limit:20),c="number"==typeof i.offset?i.offset:0,l=Math.floor(c/o)+1;return{recordings:r.recordings,tokenName:Lt(e.tokenName),page:r.page??l,limit:o,total:r.total,hasNext:r.recordings.length===o}}async getRecordingDownload(e,t){this.validateTokenName(e,zt),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(b,{tokenName:e,assetId:t}),s=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(s)}async deleteRecording(e,t){this.validateTokenName(e,zt),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(A,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,zt);const t=this.buildEndpoint(S,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(ho(e.tokenName),!bn(e.platform))throw vt("platform");if(!lo(e.platform))throw new at("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",Ze);if(!bn(e.rtmpUrl))throw vt("rtmpUrl");if(!an.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new at("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",et);if(!bn(e.streamKey))throw vt("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new at("name must be a string","name",Ye)}(e);const t=this.buildEndpoint(E,{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,zt),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(w,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(T);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(N,{},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(ho(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||bn(e.nextLiveStreamAt)))throw new at("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",Ye);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new at("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",et)}}}(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,zt);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){go(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){ho(e.tokenName)}(e);const t=this.buildEndpoint(I,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},s=await this.http.get(t,{},n);return this.extractData(s)}async getAvailableRoles(){const e=await this.http.get(_);return this.extractData(e)}async getTokenAccess(e){!function(e){ho(e.tokenName)}(e);const t=await this.http.get(D,{tokenName:Lt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}class po{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 fo="subscribe_token",vo="unsubscribe_token",ko="authenticate",yo="send_stream_chat",bo="SEND_STREAM_REACTION",Ao="typing_start",So="typing_stop",Eo="STREAM_STATUS",wo="STREAM_COUNTDOWN_UPDATED",To="STREAM_LANGUAGE_UPDATED",No="VIEWER_COUNT",Co="token_subscribed",Io="token_unsubscribed",_o="STREAM_GLOBAL_STATUS",Do="ENGAGEMENT_STATS_UPDATED",Ro="STREAM_CHAT_MESSAGE",Oo="STREAM_CHAT_SENT",Fo="stream_chat_error",Uo="CHAT_STATUS_CHANGED",xo="STREAM_CHAT_GLOBAL_STATUS",Mo="authenticated",Lo="stream_chat_auth_error",Po="STREAM_REACTION",Bo="stream_reaction_error",$o="USER_TYPING",Go="STREAM_CHAT_PINNED",Ko="STREAM_CHAT_UNPINNED",Wo="COMMENT_CREATED",Ho="USER_BANNED",zo="USER_UNBANNED",jo="BAN_ENFORCEMENT",qo="TOKEN_BANNED",Vo="TOKEN_UNBANNED",Qo="MODERATOR_INVITE_CREATED",Xo="MODERATOR_ADDED",Jo="MODERATOR_REMOVED",Yo="MODERATOR_ROLE_UPDATED",Zo="OVERSEER_ADDED",ec="OVERSEER_REMOVED",tc="TRADE_EXECUTED",nc="BALANCE_UPDATED",sc="STATS_UPDATED",ac="POOL_METADATA_UPDATED",rc="POOL_SOCIAL_LINKS_UPDATED",ic="POOL_BADGE_ASSIGNED",oc="HOLDER_COUNT_UPDATED",cc="USER_PROFILE_UPDATED",lc="API_KEY_CREATED",dc="API_KEY_UPDATED",uc="API_KEY_REVOKED",hc="TOKEN_CONFIG_UPDATED",gc="SITE_CONFIG_CHANGED",mc="COMMENTS_GLOBAL_STATUS",pc="WEBHOOKS_GLOBAL_STATUS",fc="subscribe_global_feed",vc="unsubscribe_global_feed",kc="global_feed_subscribed",yc="global_feed_unsubscribed";class bc 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 it("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 po({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}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:",lt(e)),!1}}getRoomName(e){return`token:${Lt(e)}`}bufferEvent(e,t,n){const s=`${e}:${t}`;let a=this.eventBuffer.get(s);a||(a=[],this.eventBuffer.set(s,a)),a.length>=this.MAX_BUFFER_SIZE&&(a.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${s} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),a.push(n);const r=this.eventBufferTimeouts.get(s);r&&clearTimeout(r);const i=setTimeout(()=>{this.eventBuffer.delete(s),this.eventBufferTimeouts.delete(s),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${s}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(s,i)}processBufferedEvents(e,t){const n=Lt(e),s=[{key:`${Eo}:${n}`,callback:t.onStreamStatus},{key:`${No}:${n}`,callback:t.onViewerCount},{key:`${Ro}:${n}`,callback:t.onChatMessage},{key:`${Uo}:${n}`,callback:t.onChatStatus},{key:`${Go}:${n}`,callback:t.onChatPinned},{key:`${Ko}:${n}`,callback:t.onChatUnpinned},{key:`${wo}:${n}`,callback:t.onCountdownUpdated},{key:`${To}:${n}`,callback:t.onLanguageUpdated},{key:`${qo}:${n}`,callback:t.onTokenBanned},{key:`${Vo}:${n}`,callback:t.onTokenUnbanned},{key:`${Qo}:${n}`,callback:t.onModeratorInviteCreated},{key:`${Xo}:${n}`,callback:t.onModeratorAdded},{key:`${Jo}:${n}`,callback:t.onModeratorRemoved},{key:`${Yo}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${tc}:${n}`,callback:t.onTradeExecuted},{key:`${nc}:${n}`,callback:t.onBalanceUpdated},{key:`${ac}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${rc}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${ic}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${oc}:${n}`,callback:t.onHolderCountUpdated},{key:`${Wo}:${n}`,callback:t.onCommentCreated}];for(const{key:e,callback:t}of s){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const s of n)try{t(s)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const s=this.eventBufferTimeouts.get(e);s&&(clearTimeout(s),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(Eo,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(Eo,e.tokenName,e);const t=this.roomCallbacks.get(Lt(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(Co,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=Lt(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const s=this.roomCallbacks.get(t);s?.onStreamSubscribed&&s.onStreamSubscribed(e)}),this.socket.on(Io,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(Lt(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(No,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(No,e.tokenName,e);const t=this.roomCallbacks.get(Lt(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(_o,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Ro,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(Ro,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(Oo,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(Fo,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(Uo,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(Uo,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(xo,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(Mo,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(Lo,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(Po,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(Bo,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on($o,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(Lt(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(Go,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(Go,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(Ko,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(Ko,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(wo,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(wo,e.tokenName,e);const n=this.roomCallbacks.get(Lt(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(To,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(To,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(qo,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(qo,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(Vo,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(Vo,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(Ho,e=>{this.logger.debug(`📡 [User Banned] ${e.tokenName}: ${e.userAddress}`),this.streamingEventService?.emitUserBanned(e)}),this.socket.on(zo,e=>{this.logger.debug(`📡 [User Unbanned] ${e.tokenName}: ${e.userAddress}`),this.streamingEventService?.emitUserUnbanned(e)}),this.socket.on(jo,e=>{this.logger.debug(`📡 [Ban Enforcement] ${e.tokenName}: ${e.action}`),this.streamingEventService?.emitBanEnforcement(e)}),this.socket.on(Qo,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(Qo,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(Xo,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Xo,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(Jo,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Jo,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(Yo,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Yo,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(Zo,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(ec,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(tc,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(tc,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(nc,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(nc,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(ac,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(ac,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(rc,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(rc,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(ic,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(ic,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(oc,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(oc,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(Wo,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(Wo,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(cc,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(lc,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(dc,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(uc,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(hc,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(hc,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(sc,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(sc,e.tokenName,e);const t=this.roomCallbacks.get(Lt(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(Do,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(Do,e.tokenName,e);const t=this.roomCallbacks.get(Lt(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(kc,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(yc,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(gc,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(_o,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(xo,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(mc,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(pc,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(fo,{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(fc)}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)=>{da(async()=>{if(!this.isSocketIOAvailable)throw new it('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=i.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 at("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw vt("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(ko,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw vt("tokenName","Token name");if(!this.socket?.connected)throw new at("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=Lt(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((s,a)=>{const r=setTimeout(()=>{this.pendingSubscriptions.delete(n),a(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:s,reject:a,timeoutId:r}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(fo,{tokenName:n})})}unsubscribeFromStream(e){const t=Lt(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(vo,{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 vt("tokenName","Token name");if(""===t)throw vt("content","Message content");if(!this.socket?.connected)throw new at("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new at("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=Lt(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(yo,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw vt("tokenName","Token name");if(""===t)throw vt("emoji");if(!this.socket?.connected)throw new at("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new at("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const s=Lt(e);this.logger.debug(`📡 Sending reaction to ${s}: ${t}`),this.socket.emit(bo,{tokenName:s,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Ao,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,So,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw vt("tokenName","Token name");if(!this.socket?.connected)throw new at("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new at("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const s=Lt(e);this.logger.debug(`📡 Sending ${n} to ${s}`),this.socket.emit(t,{tokenName:s})}subscribeTokenBanned(e,t){const n=Lt(e),s={onTokenBanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenBanned,this.roomCallbacks.set(n,t)}}}subscribeTokenUnbanned(e,t){const n=Lt(e),s={onTokenUnbanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenUnbanned,this.roomCallbacks.set(n,t)}}}subscribeModeratorInviteCreated(e,t){const n=Lt(e),s={onModeratorInviteCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorInviteCreated,this.roomCallbacks.set(n,t)}}}subscribeModeratorAdded(e,t){const n=Lt(e),s={onModeratorAdded:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorAdded,this.roomCallbacks.set(n,t)}}}subscribeModeratorRemoved(e,t){const n=Lt(e),s={onModeratorRemoved:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRemoved,this.roomCallbacks.set(n,t)}}}subscribeModeratorRoleUpdated(e,t){const n=Lt(e),s={onModeratorRoleUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{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=Lt(e),s={onTradeExecuted:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTradeExecuted,this.roomCallbacks.set(n,t)}}}subscribePoolMetadataUpdated(e,t){const n=Lt(e),s={onPoolMetadataUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolMetadataUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolSocialLinksUpdated(e,t){const n=Lt(e),s={onPoolSocialLinksUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolSocialLinksUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolBadgeAssigned(e,t){const n=Lt(e),s={onPoolBadgeAssigned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolBadgeAssigned,this.roomCallbacks.set(n,t)}}}subscribeHolderCountUpdated(e,t){const n=Lt(e),s={onHolderCountUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onHolderCountUpdated,this.roomCallbacks.set(n,t)}}}subscribeCommentCreated(e,t){const n=Lt(e),s={onCommentCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...s}),()=>{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 at("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 s=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:s},e&&(this.globalFeedCallbacks=e),this.logger.debug("📡 Subscribing to global feed"),this.socket.emit(fc)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(vc),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 Ac(e){if(Tn(e.tokenName,"tokenName",zt),!(null==(t=e.reason)||""===t||"string"==typeof t&&!Cn(t)&&t.length<=Yt.BAN_REASON.MAX_LENGTH))throw new at(`reason must be at most ${Yt.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class Sc extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}async banToken(e){Ac(e);const t=Ee,n={tokenName:Lt(e.tokenName)};if(void 0!==e.reason)try{kn(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const s=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(s),tokenName:Lt(e.tokenName)}}async unbanToken(e){!function(e){Tn(e.tokenName,"tokenName",zt)}(e);const t=this.buildEndpoint(Ne,{tokenName:e.tokenName});return _t(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:Lt(e.tokenName)}}async listTokenBans(e={}){!function(e){Sn(0,void 0,Vt,e.pageSize)}(e);const t=we,n=this.buildPaginationParams(e,Vt);this.addOptionalFilterParams(n,e,["search"]);const s=await this.http.get(t,n,this.getDualAuthHeaders()),a=this.extractData(s);return{items:a.bans,pageInfo:a.pageInfo}}async getTokenBan(e){!function(e){Tn(e.tokenName,"tokenName",zt)}(e);const t=this.buildEndpoint(Te,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},tokenName:Lt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class Ec 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(!bn(e))throw vt("tokenName","Token name");const t=Lt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null!==s&&""!==s){const e=this.parseVaultAddressToTokenClassKey(s);this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:e,cachedAt:Date.now()})}return s}async resolveTokenClassKey(e){if(!bn(e))throw vt("tokenName","Token name");const t=Lt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null===s||""===s)throw ft(e);const a=this.parseVaultAddressToTokenClassKey(s);return this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:a,cachedAt:Date.now()}),a}get(e){const t=this.getCacheEntry(Lt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=Ec.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=Lt(e),s=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:s,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:Ec.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(Lt(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:s}of e){const e=Lt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:s,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return ir(e)}catch(e){if(e instanceof at)throw kt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}Ec.MAX_CACHE_SIZE=1e4;class wc extends On{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return Ot(()=>this.http.get(Be),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return Ot(()=>this.http.get($e,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return zs(await Ot(()=>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 zs(await Ot(()=>this.http.get(Ke,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class Tc extends wa{constructor(e,t,n,s=!1,a){super(e,t,n,s,a)}async emitTradeExecuted(e,t){this.validateTokenName(e,jt);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,jt);const s={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(s)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,jt);const s={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,jt);const s={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,jt);const s={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,jt);const s={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,jt);const s={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,jt);const s={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTokenBanned(e,t){this.validateTokenName(e,jt);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,jt);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,jt);const s={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,jt);const s={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}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 s=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(s)}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 it("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,jt);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const s=await this.getConnectedClients(n);return{clients:s.clients,count:s.summary.totalConnected,authenticatedCount:s.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,jt);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,jt);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,jt);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class Nc{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 s=n??this.defaultTtlMs,a={value:t};s>0&&(a.expiresAt=Date.now()+s),this.cache.set(e,a)}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 Cc 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 po({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Nc(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),Cc.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)=>{da(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:",lt(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],s=n.status??n.Status;"string"==typeof s&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${s}`),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=ct(e)?e:new Error(lt(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 s=this.config.timeout??3e5,a=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(s/1e3),a={transactionId:e,status:fa.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(a),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},s);if(this.timeouts.set(e,a),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:fa.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 s=t,a=s?.data,r=s?.status??s?.Status??a?.status??a?.Status;let i=s?.message??s?.Message??a?.message??a?.Message??s?.error??a?.error;bn(i)||(i=r===pa.FAILED||r===pa.ERROR?"Transaction failed - check transaction details":r===pa.COMPLETED||r===pa.PROCESSED||r===pa.SUCCESS?"Transaction completed successfully":null!=r?`Transaction status: ${String(r)}`:"Unknown transaction status");const o=s?.blockHash??a?.blockHash,c=s?.gasUsed??a?.gasUsed,l=s?.Data??a?.Data,d={transactionId:e,status:this.mapSocketStatus(r),message:"string"==typeof i?i:"Transaction update received",timestamp:Date.now(),...null!=o?{blockHash:o}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(r)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(i)}"`),n(d),d.status===fa.COMPLETED||d.status===fa.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===fa.COMPLETED?t(e):e.status!==fa.FAILED&&e.status!==fa.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return va[t]??fa.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")),Cc.instances.delete(this)}static cleanupAll(e=!1){for(const e of Cc.instances)e.disconnect();Cc.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}Cc.instances=new Set;class Ic extends On{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 at("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},s=await this.http.get(We.GET_LEADERBOARD,n),a=this.extractData(s);return this.logger.debug("Fetched weekly challenge leaderboard",{count:a.count}),{leaderboard:a}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new at("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=We.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),s=await this.http.get(n),a=this.extractData(s);return this.logger.debug("Fetched token weekly history",{count:a.length}),{snapshots:a}}}class _c 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 Dc{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 Rc{constructor(e){this.bundleBaseUrl=Bc(e.bundleBaseUrl),this.launchpadBaseUrl=Bc(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"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof _c)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new _c(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),s=`${this.bundleBaseUrl}/bundle`,a=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:n})}),r=await Lc(a);if(!a.ok)throw Fc(a.status,r,s);const i=function(e){if("string"==typeof e&&""!==e)return e;if(!Pc(e))throw new _c("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(Pc(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new _c("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(r),o=Mc(e.dto,"uniqueKey");return new Dc({bundleId:i,uniqueKey:o,method:e.method,wait:t=>this.waitForResult(e,i,t)})}async waitForResult(e,t,n={}){const s=n.timeoutMs??6e4,a=n.pollIntervalMs??2500,r=Date.now();let i,o,c=!1,l=new Promise(()=>{});try{i=this.socketFactory(this.bundleBaseUrl),l=new Promise((e,n)=>{o=t=>{const s=function(e){if(!Pc(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(t);void 0===s||c||(c=!0,"FAILED"===s.status?n(Oc(s.data)):e(s))},i?.on(t,o)})}catch{i=void 0}const d=this.pollConfirmation(e,t,r,s,a);try{return await Promise.race([l,d])}finally{c=!0,void 0!==i&&(void 0!==o&&i.off(t,o),i.disconnect())}}async pollConfirmation(e,t,n,s,a){const r="CreateSale"===e.method,i=r?function(e,t){const n=Mc(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`;for(;Date.now()-n<=s;){const e=await this.requestor(i,{method:"GET"}),t=await Lc(e);if(r){if(e.ok)return{status:"PROCESSED",data:xc(t)};if(404!==e.status&&202!==e.status)throw Fc(e.status,t,i)}else{if(!e.ok)throw Fc(e.status,t,i);const n=Pc(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw Oc(t)}const o=s-(Date.now()-n);if(o<=0)break;await $c(Math.min(Math.max(0,a),o))}throw new _c(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function Oc(e){const t=Uc(e)??"Launchpad bundle failed on chain.";return new _c(t,"BUNDLE_FAILED",{chainMessage:t})}function Fc(e,t,n){const s=Uc(t)??`Bundle request failed with HTTP ${e}`;return new _c(s,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:s,details:{body:t,url:n}})}function Uc(e){if("string"==typeof e&&""!==e)return e;if(Pc(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(Pc(n)){const e=Uc(n);if(void 0!==e)return e}}}function xc(e){return Pc(e)?e.data??e.Data??e:e}function Mc(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new _c(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function Lc(e){try{return await e.json()}catch{return e.text()}}function Pc(e){return"object"==typeof e&&null!==e}function Bc(e){return e.replace(/\/$/u,"")}function $c(e){return new Promise(t=>setTimeout(t,e))}function Gc(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=tr(t).type,s=await e.findTokenNameByVault(t,n);if(void 0===s)throw new at(`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 s}(e,t.vaultAddress);return function(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new at(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new at(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new o(e).multipliedBy(new o(1).plus(new o(String(t)))).decimalPlaces(8,o.ROUND_UP).toFixed()}((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 Kc="0.1",Wc="0.5";class Hc{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress,this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){!function(e){const t=Ts(e);!t.success&&t.errors&&qs(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??zc(t)},s=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:s?.minFeePortion??Kc,maxFeePortion:s?.maxFeePortion??Wc},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:sr(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 s={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??await this.defaultExtraFees(e,t),uniqueKey:t.uniqueKey??zc(this.walletAddress)};return this.transport.submit({method:e,dto:s,stringsInstructions:nr(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new at("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 zc(e){return`galaswap-operation-${r.v4()}-${Date.now()}-${e}`}function jc(e,t=3e4){return c.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const qc=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function Vc(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>Vc(e,t+1));if(e instanceof Map){const n={};for(const[s,a]of e.entries()){const e=String(s);n[e]=qc.has(e.toLowerCase())?"[REDACTED]":Vc(a,t+1)}return n}if("object"==typeof e){const n={};for(const[s,a]of Object.entries(e))n[s]=qc.has(s.toLowerCase())?"[REDACTED]":Vc(a,t+1);return n}return e}class Qc{constructor(e,t={},n={signRequests:!0}){this.auth=e,this.signRequests=n.signRequests,this.debug=t.debug??!1,this.logger=new $t({debug:this.debug,context:"HttpClient"});const s=t.baseUrl??ma("stage").launchpadBaseUrl,a=t.timeout??6e4;this.axios=jc(s,a),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 da(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Us(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]":Vc(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:Vc(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const s=await this.axios.request(t),a=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,s]of Object.entries(e))"string"==typeof s?t[n.toLowerCase()]=s:"number"!=typeof s&&"boolean"!=typeof s||(t[n.toLowerCase()]=String(s));return t}(s.headers);return this.logger.debug("Response:",{status:s.status,data:Vc(s.data),transactionId:a["x-transaction-id"],blockNumber:a["x-block-number"]}),{data:s.data,headers:a,status:s.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 da(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,s={message:n?.message??lt(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=s,this.logger.error("Backend error:",s)}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 Xc extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Jc 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 Yc(e,t){if(An(e))throw new Xc(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Xc(`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 Xc(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Zc(e,t,n,s){Yc(e,t);const a=e,r=a.data??{};if(!function(e){if(An(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(r))throw new Xc(`Invalid trade data received for transaction ${t}`);const i={transactionId:t,type:n,method:"native"===s.type?"native":"exact",inputAmount:r.inputQuantity??s.amount,outputAmount:r.outputQuantity??s.expectedAmount??"0",totalFees:r.totalFees??"0",tokenName:s.tokenName,vaultAddress:r.vaultAddress??"",timestamp:Date.now()};return void 0!==a.blockHash&&(i.blockHash=a.blockHash),void 0!==a.gasUsed&&(i.gasUsed=a.gasUsed),void 0!==s.slippageToleranceFactor&&(i.slippageTolerance=s.slippageToleranceFactor),i}function el(e){return void 0!==e&&n.isPrivateKeyProvider(e)?new t.Wallet(e.exportPrivateKey()):void 0}const tl={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function nl(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const sl=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function al(e,t,n){if(void 0===e||void 0===t)return;const s=sl.exec(e)?.[1],a=sl.exec(t)?.[1];if(void 0!==s&&void 0!==a&&s.toLowerCase()!==a.toLowerCase())throw bt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}let rl;class il{constructor(e){let t,s;this.walletGeneration=0,this._tokenRoomRefCounts=new Map,this._tokenRoomListeners=new Map,this._tokenRoomUnsubscribers=new Map,e.walletProvider?(t=e.walletProvider,s=el(e.walletProvider)):e.wallet&&(s=e.wallet,t=n.PrivateKeyProvider.fromWallet(e.wallet)),this.wallet=s;const a=e.env??"prod",r=ma(a);this.environment=a,this.config={baseUrl:e.launchpadBaseUrl??r.launchpadBaseUrl,gatewayBaseUrl:r.gatewayBaseUrl,bundleBaseUrl:r.bundleBaseUrl,webSocketUrl:r.webSocketUrl,dexApiBaseUrl:r.dexApiBaseUrl,dexBackendBaseUrl:r.dexBackendBaseUrl,launchpadFrontendUrl:r.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==s?new Ya(s.privateKey):void 0),o=void 0!==s?`eth|${s.address.slice(2)}`:nl(i);al(o,e.walletAddress,"walletAddress"),al(o,e.galaChainAddress,"galaChainAddress");const c=e.walletAddress??e.galaChainAddress??(void 0!==s?`eth|${s.address.slice(2)}`:nl(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===s&&void 0!==e.signer&&void 0!==c?{signer:e.signer,walletAddress:c}:void 0;const u=new Rc({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:l,walletAddress:d,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}}),h=Gc({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});if(this.sellFeeCeiling=h,this.launchpad=new Hc({transport:u,walletAddress:d,sellFeeCeiling:h}),this.logger=new $t({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?il.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?il.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??il.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===s?c:void 0),this.auth=new ha({wallet:s,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new la,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Qc(this.auth,this.config),this.sessionAuth=new ua(this.http,this.auth,this.jwtAuth,e.debug??!1);const g={signRequests:!1};this.galaChainHttp=new Qc(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},g),this.bundleHttp=new Qc(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},g),this.dexApiHttp=new Qc(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},g),this.dexBackendHttp=new Qc(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},g),this.galaChainPublicAxios=jc(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new xn(e.debug??!1),this.launchpadService=new Oi(this.http,this.jwtAuth),this.tokenResolverService=new Ec(this.launchpadService.poolService),this.launchpadAPI=new ta(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new ki(this.galaChainHttp,s,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new Dr(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new Cc({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new ji(this.galaChainHttp),this.tradingQuotesService=new wc(this.http,e.debug??!1)}createOverrideSdk(e){if(!bn(e))throw bt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw bt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t.Wallet(e),s={...this.config,wallet:n};return new il(s)}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 vt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw vt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new at("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 fr(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 ki(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?el(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:s,streamAdminApiKey:a,userApiKey:r,accessToken:i,headers:o,...c}=this.config;return{...c,...void 0!==a&&{streamAdminApiKey:"[REDACTED]"},...void 0!==r&&{userApiKey:"[REDACTED]"},...void 0!==i&&{accessToken:"[REDACTED]"},...void 0!==o&&{headers:Object.fromEntries(Object.keys(o).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:Mt.GAS_FEE}}getVersion(){return ka}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw bt("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),s=Math.min(t,100);return n.holders.slice(0,s).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),s=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===s)return null;const a=n.holders[s];return void 0===a?null:{rank:s+1,balance:a.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),s=t?.minBalance??0,a=t?.maxBalance??1/0,r=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>=s&&t<=a}).map(e=>({...e,rank:i.get(e.address)??0})).slice(0,r)}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 at("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",st);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 Wn}),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(rl??(rl=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 rl=void 0,bt(`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: ${lt(e)}`,"bridge")})),rl);if(e!==this.walletGeneration)throw bt("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 Ya(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new mo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new oo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Fa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Sc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new Ta(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new Ic(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new Vi(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new ro(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new qi(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new vr(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new _a(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Pi(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new Tr(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new so(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Tc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Cr(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 Wn}),n=t(e);if(void 0===n)throw new at(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new Fi(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new io(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new ao(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new Lr(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 bc({url:this.config.streamWebSocketUrl},this.config.debug??!1),this._streamWebSocketService.setStreamingEventService(this.getStreamingEventService())}return this._streamWebSocketService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new co(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 s=await n.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===s.message?null:this.toLegacyPinnedMessage(s.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,s,a]=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"===s.status?s.value:null,..."rejected"===s.status&&{recentTradesError:String(s.reason)},price:"fulfilled"===a.status?a.value:null,..."rejected"===a.status&&{priceError:String(a.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,s,a)=>(void 0===t.actionType||t.actionType===e)&&((void 0===t.userAddress||t.userAddress===n)&&((void 0===t.tokenName||t.tokenName===s)&&!!(void 0===t.reason||null!==a&&a.includes(t.reason)))),s=this.onUserBanned(t=>{n("BANNED",t.userAddress,t.tokenName,t.reason)&&e({actionType:"BANNED",userAddress:t.userAddress,tokenName:t.tokenName,reason:t.reason})}),a=this.onUserUnbanned(t=>{n("UNBANNED",t.userAddress,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:t.userAddress,tokenName:t.tokenName,reason:null,timestamp:t.timestamp})}),r=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()=>{s(),a(),r()}}watchTokenRoomEvent(e,t,n,s){const a=s.tokenName;if(void 0===a||""===a)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);const r=a.toLowerCase(),i=`${e}:${r}`,o=n;let c=this._tokenRoomListeners.get(i);const l=void 0===c;void 0===c&&(c=new Set,this._tokenRoomListeners.set(i,c)),c.add(o),this._tokenRoomRefCounts.set(r,(this._tokenRoomRefCounts.get(r)??0)+1);const d=this.getStreamWebSocketService(),u=(async()=>{d.isConnected()||await this.connectStreamWebSocket(),await d.subscribeToStream(r),l&&this._tokenRoomUnsubscribers.set(i,t.call(d,r,e=>{for(const t of c)t(e)}))})();let h=!1;return()=>{if(h)return;h=!0,c.delete(o);const e=(this._tokenRoomRefCounts.get(r)??1)-1,t=e<=0;t?this._tokenRoomRefCounts.delete(r):this._tokenRoomRefCounts.set(r,e),u.then(()=>{if(0===c.size){this._tokenRoomListeners.delete(i);const e=this._tokenRoomUnsubscribers.get(i);this._tokenRoomUnsubscribers.delete(i),e?.()}t&&!this._tokenRoomRefCounts.has(r)&&d.unsubscribeFromStream(r)})}}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),s=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),a=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),r=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()=>{s(),a(),r()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,s=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),a=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),r=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()=>{s(),a(),r()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,s=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),a=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{s(),a()}}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 Wn}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return gr}),s=t(e.tokenId),{collection:a,category:r,type:i,additionalKey:o}=s;return this.galaChainService.fetchTokenBalance({owner:n,collection:a,category:r,additionalKey:o,type:i},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Pt(e.tokenName),s=tl[t];if(void 0!==s)return this.galaChainService.fetchTokenBalance({owner:n,collection:s,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 s=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:s.collection,category:s.category,tokenId:ar(s)}}throw vt("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:s,privateKey:a,calculateAmountMode:r,currentSupply:i}=e;let o=t;void 0===r&&void 0===i||(o={tokenName:t,...void 0!==r&&{calculateAmountMode:r},...void 0!==i&&{currentSupply:i}});const c=await this.calculateBuyAmountForGraduation(o),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!==s&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=s),void 0!==a&&(l.privateKey=a),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.buy(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw At("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Zc(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.sell(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw At("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Zc(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,...s}=e;return t.launchToken(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{Yc(n,t);const s=n.data??{};if(!function(e){if(An(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)}(s))throw new Xc(`Invalid launch data received for transaction ${t}`);const a={transactionId:t,vaultAddress:s.vaultAddress??"",tokenStringKey:s.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:s.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&&(a.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(a.preBuyQuantity=e.preBuyQuantity),""!==a.vaultAddress&&this.tokenResolverService.set(e.tokenName,a.vaultAddress),a})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.uploadTokenImage(s)}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 Wn}),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,s=e?.limit??10,a={pageNumber:n,limit:s,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},r=await this.dexApiHttp.get(h,a,{"x-wallet-address":t});if(!Array.isArray(r))throw new rt("Unexpected API response: expected array, got "+typeof r);return{referrals:r,page:n,limit:s,hasMore:r.length===s}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:s,pageSize:a=20,concurrency:r=1,startPage:i=1}=t,o=[];let c=i;const l=i+n-1;let d=!0,u=0;if(r<=1)for(;d&&c<=l;){s&&s.debug(`Auto-pagination: fetching page ${c} with limit ${a}`);const t=await e(c,a);if(null==t||!Array.isArray(t.items)){s&&s.warn("Auto-pagination: received invalid result structure, stopping");break}if(o.push(...t.items),u=t.total,s&&s.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){s&&s.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(s&&s.debug(`Auto-pagination: using concurrent mode with concurrency=${r}`);d&&c<=l;){const t=[];for(let e=0;e<r&&c+e<=l;e++)t.push(c+e);s&&s.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,a).catch(e=>{const n=e,r=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===r||404===r)return s&&s.debug(`Auto-pagination: page ${t} returned ${r} (end of pagination)`,{statusCode:r}),{items:[],total:0,totalPages:0,page:t,limit:a,hasNext:!1,hasPrevious:!1};throw e})),i=await Promise.all(n);for(const e of i){if(null==e||!Array.isArray(e.items)){s&&s.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){s&&s.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(o.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,s&&s.debug(`Auto-pagination: batch complete, total items so far: ${o.length}`)}return c>l&&s&&s.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),s&&s.debug(`Auto-pagination: completed with total items: ${o.length}, total count: ${u}`),{items:o,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 rt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Wn}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.updateProfile(s)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Wn}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.uploadProfileImage(s)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Wn}),n=t(e?.address)??this.getAddress(),s={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(s.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(s.search=e.search),this.launchpadService.fetchTokensHeld(s)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Wn}),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 Wn}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferGala(s)}return this.assertTokenWriter(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Wn}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferToken(s)}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 Wn});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,...s}=n;return e.lockTokens(s)}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,...s}=e;return t.unlockTokens(s)}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,...s}=e;return t.burnTokens(s)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let s=0;s<10;s+=1){const s=await this.launchpadAPI.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),a=s.items.find(t=>t.vaultAddress===e);if(void 0!==a)return a.tokenName;if(!s.pageInfo.hasNextPage||void 0===s.pageInfo.nextCursor)return;n=s.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 bt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw bt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw bt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw bt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw bt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw bt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw bt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=dn("string"==typeof e||"number"==typeof e?e:String(e),il.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${il.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),il.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=dn("string"==typeof e||"number"==typeof e?e:String(e),il.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: ${il.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),il.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!==fa.COMPLETED)throw new Jc(e,n.status,n.message);let s;try{s=t(n)}catch(t){if(t instanceof Xc)throw t;throw new Xc(`Failed to transform WebSocket response for transaction ${e}`,ct(t)?t:new Error(lt(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,s),s}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Jc||t instanceof Xc)throw t;throw new Xc(`WebSocket confirmation failed for transaction ${e}`,ct(t)?t:new Error(lt(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return ol});e.forEach(e=>{if(!n(e))return;const s=t(e,this.logger);s&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,s)})}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,s=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 a=t?.creatorAddress,r=new Map;let i=!0,o=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=>{r.has(t.tokenName)||((e=>{if(r.set(e,!0),r.size>1e3){const e=r.keys().next().value;void 0!==e&&r.delete(e)}})(t.tokenName),void 0!==a&&""!==a&&t.creatorAddress!==a||e(t))})}catch(e){c++;const t=lt(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=s*Math.pow(2,e);o=setTimeout(()=>{l()},t)}}};return l(),()=>{i=!1,o&&clearTimeout(o),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 bt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,s=null;const a=(n,...s)=>{try{if(s.length>0&&"object"==typeof s[0]&&null!==s[0]){const n=s[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const s=n.Data;if("CreateSale"===s.functionName){const n=(e,t="")=>{const n=s[e];return"string"==typeof n&&""!==n?n:t},a={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===s.isFinalized};this.matchesCreatorFilter(a,t?.creatorFilter)&&e(a)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${lt(e)}`)}};let r=this.websocketService.getSocket();if(r)r.onAny(a),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: ${lt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(r=this.websocketService.getSocket(),!r&&e<il.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(s=setTimeout(()=>i(),il.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!r&&e>=il.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${il.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*il.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}r&&(r.onAny(a),n=!0,this.logger.debug("Token creation broadcast listener registered"))};i()}return()=>{try{if(null!==s&&(clearTimeout(s),s=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(a),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 $t({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),Cc.cleanupAll(e),t.debug("Global cleanup completed")}}il.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,il.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,il.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=Mt.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,il.DEFAULT_CALCULATE_AMOUNT_MODE="local",il.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,il.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;var ol=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const s=dn(e.reverseBondingCurveMinFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=s}if(void 0!==e.reverseBondingCurveMaxFeePortion){const s=dn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=s}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.BrowserWalletSigner=er,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.GalaWalletSigner=Za,exports.LaunchpadSDK=il,exports.LaunchpadSDKError=_c,exports.PrivateKeySigner=Ya,exports.SDK_VERSION=ka,exports.TransactionFailedError=Jc,exports.WebSocketError=Xc,exports.WebSocketTimeoutError=class extends Xc{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.createLaunchpadSDK=function(e){An(e)&&(e={});const{wallet:n,env:a,config:r={},...i}=e,o={...{...i,...r}};delete o.wallet,delete o.env,delete o.config;const c=!An(o.signer)||!An(o.walletProvider);let l;if(An(n))l=c?void 0:new t.Wallet(s.createWallet().privateKey);else if("string"==typeof n)l=new t.Wallet(s.createWallet(n).privateKey);else{if(!(n instanceof t.Wallet))throw bt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");l=n}const d={...void 0!==l?{wallet:l}:{},...void 0!==a?{env:a}:{},debug:!1,timeout:3e4,...o};return new il(d)};
|
|
1
|
+
"use strict";var e=require("zod"),t=require("ethers"),n=require("@gala-chain/gala-core-sdk/providers"),s=require("@gala-chain/gala-core-sdk"),r=require("@gala-chain/api"),i=require("uuid"),a=require("socket.io-client"),o=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",m="/v1/tokens/:tokenName/stop-stream",f="/v1/tokens/:tokenName/stream/disable",p="/v1/tokens/:tokenName/stream/enable",v="/v1/tokens/:tokenName/reset-key",A="/v1/tokens/:tokenName/recordings",E="/v1/tokens/:tokenName/recordings/:assetId/download",y="/v1/tokens/:tokenName/recordings/:assetId",T="/v1/tokens/:tokenName/simulcasts",S="/v1/tokens/:tokenName/simulcasts",b="/v1/tokens/:tokenName/simulcasts/:targetId",k="/v1/config",w="/v1/config",N="/v1/config",_="/v1/tokens/:tokenName/role",I="/v1/roles",C="/v1/permissions",D="/v1/tokens/:tokenName/credentials",R="/auth/login",O="/auth/logout",M="/auth/refresh",L="/auth/session",U="/v1/tokens/:tokenName/bans",F="/v1/tokens/:tokenName/bans",x="/v1/tokens/:tokenName/bans/:userAddress",P="/v1/tokens/:tokenName/bans/:userAddress",B="/v1/tokens/:tokenName/active-users",$="/v1/user-bans",G="/v1/user-bans",K="/v1/user-bans/:userAddress",W="/v1/user-bans/:userAddress",H={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},j="/v1/moderator-invites",q="/v1/moderator-invites/claim",z="/v1/moderated-tokens",V="/v1/moderator-invites",Q="/v1/moderator-invites/:id",X="/v1/moderator-invites/:id/role",J="/v1/moderator-invites/:id",Y="/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",se="/v1/overseer-invites/claim",re="/v1/overseer-invites/:id",ie="/v1/overseers",ae="/v1/overseers",oe="/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",me="/v1/overseer-summary/users",fe="/v1/users",pe="/v1/users/:address/summary",ve="/v1/cache/flush/address/:address",Ae="/v1/cache/flush/token/:tokenName",Ee="/v1/cache/flush/all",ye="/v1/cache/flush/wallet-aliases/:address",Te="/v1/cache/flush/wallet-aliases",Se="/v1/token-bans",be="/v1/token-bans",ke="/v1/token-bans/:tokenName",we="/v1/token-bans/:tokenName",Ne="/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",Me="/live/:tokenName/chat",Le="/live/:tokenName/chat",Ue="/live/:tokenName/chat/slow-mode",Fe="/v1/events",xe="/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"},$e="/v1/stats",Ge="/v1/trading/fee",Ke="/v1/trading/sale-details",We="/v1/trading/quote",He="/v1/trading/premint-quote",je={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},qe="/v1/notifications/register",ze="/v1/notifications/unregister",Ve="/v1/notifications/preferences",Qe="/v1/notifications/preferences",Xe="/v1/config/client-flags",Je="native",Ye="exact",Ze=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],et=["IDLE","ACTIVE","DISABLED"],tt=100,nt="REQUIRED",st="INVALID_TYPE",rt="INVALID_VALUE",it="INVALID_FORMAT",at="TOO_LONG",ot="TOO_LARGE",ct="INVALID_RANGE",lt="INVALID_PARAMETERS";class dt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}function ut(e){return"object"==typeof e&&null!==e}function ht(e){if(null==e||""===e)return{};if(!ut(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,s=Reflect.get(e,"error"),r=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof s&&""!==s?{serverError:s}:{},...void 0===r?{}:{details:r},body:e}}function gt(e){if(e instanceof mt)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(!ut(e))return;const t=Reflect.get(e,"response");return ut(t)?t:void 0}(e);return void 0===t?{}:ht(Reflect.get(t,"data"))}class mt extends Error{constructor(e,t,n,s=gt(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=s.serverMessage,this.serverError=s.serverError,this.details=s.details,this.body=s.body}}class ft extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class pt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function vt(e){return e instanceof Error}function At(e){return vt(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 Et(e){return vt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function yt(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 Tt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function St(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 s=n.Status;if("number"!=typeof s)throw new Error(`${t}: Response Status must be a number, got ${typeof s}`);if(1!==s)throw new Error(`${t}: Response status indicates failure (Status: ${s})`);return n}function bt(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 kt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function wt(e,t){return new dt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Nt(e,t){const n=kt(e,t);return new dt(`${n} is required`,e,"REQUIRED")}function _t(e,t,n){const s=kt(e,n);return new dt(`${s} must be ${t}`,e,"INVALID_FORMAT")}function It(e,t,n,s){return new mt(e,t,n,s)}function Ct(e,t){return new ft(e,t)}function Dt(e,t,n){return new pt(e,t,n)}function Rt(e,t,n,s,r){const i=kt(e,r);return new dt(`${i} must be between ${t} and ${n}${void 0!==s?`, received: ${s}`:""}`,e,"OUT_OF_RANGE")}function Ot(e,t,n,s){const r=kt(e,s);return new dt(`${r} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Mt(e,t,n,s){const r=kt(e,s);return new dt(`${r} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Lt(e,t,n,s){const r=kt(e,s),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new dt(`${r} must be ${t}${i}`,e,"INVALID_TYPE")}function Ut(e,t,n){const s=kt(e,n);return new dt(`${s} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Ft(e,t,n,s){const r=kt(e,s);return new dt(`Invalid ${r}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function xt(e){return null!=e&&"object"==typeof e&&"data"in e}function Pt(e,t,n=!1){const s=!0===e.error,r=n&&(null===e.data||void 0===e.data);if(s||r){const n=e?.statusCode??e.status??void 0;throw It(e?.message??t,n,void 0,s?ht(e):void 0)}}function Bt(e){if(xt(e))return e.data}function $t(e,t="No data found in response"){if(!xt(e))throw It(t);const n=e.data;if(null==n)throw It(t);return n}async function Gt(e,t={}){return Ht(e,t,e=>{if(void 0===e.data)throw new dt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function Kt(e,t={}){const{errorContext:n="Operation failed",logger:s,debugLogEnabled:r=!1}=t;r&&s&&s.debug(`${n}: starting operation`);try{const t=await e();return r&&s&&s.debug(`${n}: completed successfully`),t}catch(e){throw s&&s.error(n,{error:e}),e}}async function Wt(e,t={}){return Ht(e,t,e=>e)}async function Ht(e,t,n){const{errorContext:s="Operation failed",logger:r,debugLogEnabled:i=!1}=t;i&&r&&r.debug(`${s}: starting operation`);try{const t=await e();if(null==t)throw new dt(`${s}: No response from server`,"response","NO_RESPONSE");return Pt(t,s,!0),i&&r&&r.debug(`${s}: completed successfully`),n(t)}catch(e){throw r&&r.error(s,{error:e}),e}}const jt={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function qt(e){return e.trim().toLowerCase()}function zt(e){return e.trim().toUpperCase()}var Vt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Vt||(Vt={}));class Qt{constructor(e){this.levelPriority={[Vt.DEBUG]:0,[Vt.INFO]:1,[Vt.WARN]:2,[Vt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Vt.DEBUG:Vt.INFO)}debug(e,t){this.log(Vt.DEBUG,e,t)}info(e,t){this.log(Vt.INFO,e,t)}warn(e,t){this.log(Vt.WARN,e,t)}error(e,t){this.log(Vt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Vt.DEBUG&&!this.debugEnabled)return;const s=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,r=this.getConsoleMethod(e);void 0!==n?vt(n)?r(`${s} ${t}`,n.message,Et(n)??""):r(`${s} ${t}`,n):r(`${s} ${t}`)}getConsoleMethod(e){switch(e){case Vt.DEBUG:return console.debug;case Vt.INFO:return console.info;case Vt.WARN:return console.warn;case Vt.ERROR:return console.error;default:return console.log}}child(e){return new Qt({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Vt.DEBUG]>=this.levelPriority[this.minLevel]}}function Xt(e){return null==e||""===e}function Jt(e){return null==e}const Yt=new Qt({debug:!1,context:"DateUtils"});function Zt(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 en(e,t=0){if(Xt(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 tn(e,t=0){if(Jt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return en(String(e).replace("%","").trim(),t)}function nn(e,t=18){const n=en(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function sn(e){return nn(e,8)}function rn(e){return nn(e,18)}function an(e,t,n,s){if("number"!=typeof e)throw Lt(s,"a number",e,s);if(e<t||e>n)throw Rt(s,t,n,e)}function on(e,t,n){if("string"!=typeof e)throw Lt(n,"a string",e,n);if(e.length>t)throw Mt(n,t,e.length)}function cn(e,t){if("number"!=typeof e)throw Lt(t,"a number",e,t);if(!Number.isInteger(e))throw Lt(t,"an integer",e,t);if(e<=0)throw Ot(t,1,e,t)}function ln(e,t,n=!1){if("string"!=typeof e)throw Lt(t,"a string",e,t);if(!n&&0===e.trim().length)throw Nt(t,`${t} (non-empty string)`)}const dn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},un=function(e){return"string"==typeof e&&e.trim().length>0},hn=Jt;function gn(e,t,n=100,s,r){if(void 0!==r&&"string"!=typeof r)throw new dt("cursor must be a string","cursor",st);const i=s??t,a=void 0!==s?"pageSize":"limit";if(void 0!==i&&(cn(i,a),i>n))throw new dt(`${a} must be at most ${n}`,a,ot)}function mn(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function fn(e){return Object.values(e)}function pn(e,t,n){if(!un(e))throw Nt(t);const s=e.trim();if(0===s.length)throw Nt(t);if(s.length<n.MIN_LENGTH)throw Rt(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(s.length>n.MAX_LENGTH)throw Rt(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(!n.PATTERN.test(s))throw new dt(`${t} must be ${n.DESCRIPTION}`,t,it)}function vn(e,t,n){if(null==e)throw Nt(t,t);if("string"!=typeof e)throw Lt(t,"a string",e);const s=e.trim();if(0===s.length)throw Nt(t,t);if(!n.PATTERN.test(s))throw new dt(`${t} must be ${n.DESCRIPTION}`,t,it)}function An(e){return""===e||0===e.trim().length}function En(e,t,n){if(!hn(e)){if("string"!=typeof e)throw Lt(t,"a string",e,t);if(e.length>n)throw new dt(`${t} must be at most ${n} characters`,t,ot)}}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 Lt(t,"a date",e,t);if(isNaN(n.getTime()))throw new dt(`${t} must be a valid date`,t,it)}(e,t)}function Tn(e,t,n){try{cn(e,t)}catch{throw function(e,t,n,s="OPERATION_FAILED"){return new dt(`${e} failed: ${t}`,n,s)}(n,"must be a positive integer",t)}}function Sn(e,t,n="status"){void 0!==e&&function(e,t,n){const s=Object.values(t);if(!s.includes(e))throw new dt(`${n} must be one of: ${s.join(", ")}`,n,it)}(e,t,n)}class bn{constructor(e,t=!1,n){this.http=e,this.logger=new Qt({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 ft("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Et(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Tn(e,t,n)}}class kn{constructor(e=!1,t){this.logger=t||new Qt({debug:e,context:this.constructor.name})}}class wn extends kn{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 Nn extends wn{constructor(e=!1){super(e)}normalizeKey(e){return qt(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>=Nn.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??jt.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,s)=>{n.lastUpdated<e&&(e=n.lastUpdated);let r=0;r+=2*s.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(r+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(r+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(r+=8),r+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(r+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(r+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(r+=2*n.symbol.length),r+=32,t+=r}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${qt(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${qt(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${qt(e)}`;return this.cache.has(t)}}Nn.MAX_CACHE_SIZE=1e4;const _n={MIN_LENGTH:1,MAX_LENGTH:25,PATTERN:/^[a-zA-Z0-9]{1,25}$/,DESCRIPTION:"1-25 letters and digits"},In={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},Cn={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},Dn={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},Rn=100,On=100,Mn=50,Ln={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},Un=100,Fn={COMMENTS_V1:{MAX_LENGTH:2e3},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}},xn={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})$/}},Pn=60,Bn=31536e3,$n={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Gn=64,Kn=1,Wn=100,Hn={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},jn={ETHEREUM:dn.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:dn.BACKEND_ADDRESS,CLIENT:dn.CLIENT_ADDRESS};class qn{toBackendFormat(e){if(!un(e))throw new dt("Address is required and must be a string","address","REQUIRED");let n=e;if(e.startsWith("eth|")){if(n=e.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new dt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${e}"`,"address","INVALID_FORMAT");return e}if(n=Vn(e),!/^[a-fA-F0-9]{40}$/.test(n))throw new dt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${e}"`,"address","INVALID_FORMAT");return`eth|${t.getAddress(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!un(e))throw new dt("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 dt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],s=void 0!==n&&""!==n?6:4;return`0x${e.substring(s)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!jn.CLIENT.test(e))throw new dt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!jn.BACKEND.test(e))throw new dt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!un(e)&&(!!jn.ETHEREUM.test(e)||(!!jn.ETHEREUM_NO_PREFIX.test(e)||(!!jn.BACKEND.test(e)||!!jn.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new dt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return un(e)?jn.ETHEREUM.test(e)||jn.ETHEREUM_NO_PREFIX.test(e)?"ethereum":jn.BACKEND.test(e)?"backend":jn.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 Vn(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new dt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const zn=new qn;function Vn(e){return e.startsWith("0x")?e.slice(2):e}function Qn(e){return zn.toBackendFormat(e)}function Xn(e){return zn.isValid(e)}const Jn=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function Yn(e){if(!un(e))return!1;const t=e.toLowerCase().trim();if(t.startsWith("eth|")||t.startsWith("client|")||t.startsWith("service|"))return Jn.test(t.replace(/0x/g,""));const n=t.replace(/^0x/,"");return Jn.test(/^[0-9a-f]{24}$/.test(n)?`client|${n}`:`eth|${n}`)}function Zn(e,t){if(!Yn(e))throw new dt(`${t} must be a GalaChain user address (eth|<40 hex>, 0x<40 hex> or client|<24 hex>)`,t,"INVALID_FORMAT")}function es(e,t="address"){zn.assertValid(e,t)}var ts=Object.freeze({__proto__:null,AddressFormatter:qn,assertBackendUserAddress:Zn,assertValidWalletAddress:es,isBackendUserAddress:Yn,isValidAddress:Xn,normalizeAddressInput:function(e){return zn.normalizeInput(e)},stripHexPrefix:Vn,toBackendAddressFormat:Qn});const ns=e.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"),ss=ns.max(25,"Token name must be at most 25 characters"),rs=e.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"),is=e.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"),as=e.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),os=e.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),cs=e.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),ls=e.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");e.z.string().regex(dn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.z.string().regex(dn.ETH_ADDRESS,"Invalid Ethereum address format");const ds=e.z.string().refine(e=>dn.BACKEND_ADDRESS.test(e)||dn.ETH_ADDRESS.test(e)||dn.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new qn).normalizeInput(e)??e),us=e.z.string().refine(e=>dn.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),hs=e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>en(e,0)>0,"Amount must be greater than zero"),gs=e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>en(e,0)>=0,"Amount must be zero or greater");e.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://");const ms=e.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function fs(t=100){return e.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(t,`Limit must be at most ${t}`).default(10)}e.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),fs(100),fs(20),fs(20);const ps=e.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"),vs=e.z.string().max(255,"Filename must be at most 255 characters"),As=e.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]);e.z.string().datetime("Must be a valid ISO 8601 date string"),e.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative");const Es=e.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters");e.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"),e.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}");const ys=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),name:vs,size:ps,type:As});const Ts=e.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"),Ss=e.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.z.union([Ts,Ss]),e.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),vs.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return ys.includes(t)},`Filename must end with one of: ${ys.join(", ")}`),e.z.object({websiteUrl:ms,telegramUrl:ms,twitterUrl:ms,instagramUrl:ms,facebookUrl:ms,redditUrl:ms,tiktokUrl:ms}).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");const bs=e.z.string().min(1,"Token category must not be empty").default("Unit"),ks=e.z.string().min(1,"Token collection must not be empty").default("Token"),ws=e.z.object({minFeePortion:e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>en(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>en(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:e.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>en(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>en(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>en(e.maxFeePortion,0)>=en(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Ns=e.z.object({tokenName:ns,tokenSymbol:is,tokenDescription:as,tokenImage:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer),e.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:gs.default("0"),websiteUrl:ms,telegramUrl:ms,twitterUrl:ms,instagramUrl:ms,facebookUrl:ms,redditUrl:ms,tiktokUrl:ms,tokenCategory:bs,tokenCollection:ks,reverseBondingCurveConfiguration:ws.optional(),saleStartTime:e.z.number().int().positive().optional(),privateKey:Es.optional()});e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),tokenName:ns}),e.z.enum(Ze);const _s=e.z.object({tokenName:rs.optional(),symbol:is.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required");e.z.enum(["NATIVE","MEME"]),e.z.enum(["IN","OUT"]);const Is=e.z.object({from:e.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:e.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:e.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:ss});e.z.object({tokenName:ss,slippageToleranceFactor:e.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.z.number().min(0).max(1).optional(),privateKey:Es.optional()});const Cs=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(100).default(10)}),Ds=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(20).default(10)}),Rs=e.z.object({offset:e.z.number().int().min(0).default(0),pageSize:e.z.number().int().min(1).max(20).default(10)});Cs.extend({type:e.z.enum(["RECENT","POPULAR"]).optional(),tokenName:e.z.string().min(1).max(50).optional(),search:e.z.string().min(1).max(100).optional()}),Ds.extend({tokenName:e.z.string().min(1).max(50).optional(),search:e.z.string().min(1).max(100).optional()}),Rs.extend({tradeType:e.z.enum(["BUY","SELL"]).optional(),tokenName:e.z.string().min(1).max(50).optional(),userAddress:e.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),sortOrder:e.z.enum(["ASC","DESC"]).default("DESC")});const Os={page:e.z.number().int().min(1),limit:e.z.number().int().min(1),total:e.z.number().int().min(0),totalPages:e.z.number().int().min(0),hasNext:e.z.boolean(),hasPrevious:e.z.boolean()};e.z.object(Os);const Ms=e.z.enum(["buy","sell"]);e.z.enum(["BUY","SELL"]),e.z.object({tradeType:Ms,tokenAmount:hs,vaultAddress:us,userAddress:ds,slippageTolerance:hs.optional(),deadline:e.z.number().int().positive().optional()}),e.z.object({tokenSymbol:is,nativeTokenQuantity:hs,expectedToken:hs,maxAcceptableReverseBondingCurveFee:gs.default("0").optional()}),e.z.object({tokenSymbol:is,tokenQuantity:hs,expectedNativeToken:hs,maxAcceptableReverseBondingCurveFee:gs.default("0").optional()}),Rs.extend({tokenName:os.optional()}),e.z.object({page:e.z.number().int().min(1).max(1e3).default(1).optional(),limit:e.z.number().int().min(1).max(20).default(10).optional()});const Ls=e.z.enum(["NATIVE","MEME"]),Us=e.z.enum(["IN","OUT"]);e.z.object({type:Ls,method:Us,vaultAddress:us,amount:hs}),e.z.object({nativeTokenQuantity:hs}),e.z.object({vaultAddress:us}),e.z.object({minFeePortion:hs,maxFeePortion:hs});const Fs=e.z.enum(["both","held","created"]);function xs(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)}}}Ds.extend({type:Fs.optional(),address:ds.optional(),search:cs.optional(),tokenName:os.optional()}),e.z.object({address:ds.optional(),refresh:e.z.boolean().optional()}),e.z.object({profileImage:e.z.string().nullable().optional(),fullName:ls.optional(),address:ds.optional(),privateKey:Es.optional()}),e.z.object({file:e.z.union([e.z.instanceof(File),e.z.instanceof(Buffer)]),address:ds.optional(),privateKey:Es.optional()}),e.z.object({address:ds,tokenId:e.z.union([e.z.string(),e.z.object({collection:e.z.string(),category:e.z.string(),type:e.z.string(),additionalKey:e.z.string()}),e.z.object({collection:e.z.string(),category:e.z.string(),type:e.z.string(),additionalKey:e.z.string(),instance:e.z.string()})]).optional(),tokenName:os.optional(),withExpired:e.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");const Ps=xs(ns),Bs=xs(Ns),$s=xs(_s);function Gs(e){const t=function(e){const t=Bs(e);return t.success?[]:t.errors??["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Ks(e,t){return"string"==typeof e[t]}function Ws(e,t){return void 0===e[t]||"string"==typeof e[t]}function Hs(e,t){return void 0===e[t]||"number"==typeof e[t]}function js(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}}mn({BUY:"buy",SELL:"sell"});const qs=(zs={nativeTokenQuantity:"string"},e=>{if(null==e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;for(const[e,n]of Object.entries(zs))if(!js(t[e],n))return!1;return!0});var zs;function Vs(e,t="0"){return function(e,t="0"){if(Xt(e))return new o(t);if(o.isBigNumber(e))return e.isNaN()?new o(t):e;try{const n=new o(e);return n.isNaN()||!n.isFinite()?new o(t):n}catch{return new o(t)}}(e,t)}function Qs(e,t){return void 0!==t?Vs(e).toFixed(t):Vs(e).toFixed()}function Xs(e){return Vs(e).isZero()}function Js(e,t){return Vs(e).isLessThan(Vs(t))}function Ys(...e){e.forEach(e=>{if(e.isNaN())throw Ut("value","NaN");if(!e.isFinite())throw Mt("value","finite");if(e.isLessThanOrEqualTo(0))throw Ot("value","0",e.toString())})}function Zs(e,t,n="0"){const s=Vs(t);return Xs(s)?Vs(n):Vs(e).dividedBy(s)}const er={calculateBuyWithExact(e,t){const n=en(e),s=en(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:a,GAS_FEE:o}=jt,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(r*(Math.exp((s+n)*i)-Math.exp(s*i))/i,8),l=Qs(Vs(c).multipliedBy(a));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateBuyWithNative(e,t){const n=en(e),s=en(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:a,GAS_FEE:o}=jt,c=Math.log(n*i/r+Math.exp(s*i))/i-s,l=Qs(Vs(c).multipliedBy(a));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateSellWithExact(e,t,n,s,r){const i=en(e),a=en(t),o=en(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=jt,h=c*(Math.exp(a*l)-Math.exp((a-i)*l))/l,g=Vs(h),m=s+a/o*(r-s),f=Qs(g.multipliedBy(m),8),p=Qs(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}},calculateSellWithNative(e,t,n,s,r){const i=en(e),a=en(t),o=en(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=jt;if(i>=c*(Math.exp(a*l)-1)/l){const e=Vs(i),t=s+a/o*(r-s),n=Qs(e.multipliedBy(t),8),c=Qs(e.multipliedBy(d));return{amount:a.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=a-Math.log(Math.exp(a*l)-i*l/c)/l,g=Vs(i),m=s+a/o*(r-s),f=Qs(g.multipliedBy(m),8),p=Qs(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}}};function tr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function nr(e,t){if(!function(e){if(!tr(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return tr(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw It(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:jt.GAS_FEE}}class sr{validate(e,t={}){const{allowZero:n=!0,minimum:s,maximum:r,maxDecimals:i=sr.MAX_DECIMAL_PLACES,fieldName:a="amount"}=t;if(!un(e))throw new dt(`${a} cannot be empty or whitespace-only. Provide a valid numeric string.`,a,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new dt(`${a} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,a,"INVALID_NUMERIC_STRING");const o=en(e,NaN);if(isNaN(o))throw new dt(`${a} must be a valid numeric string. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new dt(`${a} must be a finite number. Cannot be Infinity or -Infinity.`,a,"INVALID_NUMERIC_STRING");if(o<0)throw new dt(`${a} must be non-negative. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new dt(`${a} must be greater than zero. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");const c=Vs(e),l=c.decimalPlaces()??0;if(l>i)throw new dt(`${a} cannot exceed ${i} decimal places. Received: ${l} decimal places`,a,"PRECISION_EXCEEDED");if(void 0!==s&&Js(c,s))throw new dt(`${a} must be at least ${s}. Received: "${e}"`,a,"BELOW_MINIMUM");if(void 0!==r&&(d=r,Vs(c).isGreaterThan(Vs(d))))throw new dt(`${a} cannot exceed ${r}. Received: "${e}"`,a,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Vs(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 Qs(e,t)}clampAmount(e,t,n){const s=Vs(e),r=Vs(t),i=Vs(n);return function(e,t,n){const s=Vs(e),r=Vs(t),i=Vs(n);return s.isGreaterThanOrEqualTo(r)&&s.isLessThanOrEqualTo(i)}(s,r,i)?Qs(s):Js(s,r)?Qs(r):Qs(i)}}function rr(e,t){throw new dt(e.join("; "),t,"VALIDATION_ERROR")}function ir(e){const t=Ps(e);!t.success&&t.errors&&rr(t.errors,"tokenName")}function ar(e){const t=Is.safeParse(e);var n;t.success||rr((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 or(e,t,n=!0){cr.validate(e,{fieldName:t,allowZero:n})}sr.MAX_DECIMAL_PLACES=18,sr.MIN_POSITIVE="0.00000000000000001";const cr=new sr;class lr{constructor(e,t,n,s="local",r){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=s,this.launchpadWrites=r,this.metadataCache=new Nn}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 _t("options","an options object");const{tokenName:t,amount:n,type:s,currentSupply:r}=e;return"external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[Je,Ye],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:s}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:s},"currentSupply",r))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?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 nr(await Gt(()=>this.http.get(We,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:s,currentSupply:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o}=e;if("external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[Ye,Je],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:s});{const e={tokenName:t,amount:n,type:s,...void 0!==r&&{currentSupply:r},...void 0!==i&&{maxSupply:i},...void 0!==a&&{reverseBondingCurveMaxFeeFactor:a},...void 0!==o&&{reverseBondingCurveMinFeeFactor:o}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?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:s,currentSupply:r}=e;if(!un(n))throw Nt("amount","Amount");if(s!==Je&&s!==Ye)throw Lt("type",'"native" or "exact"',s);void 0!==r&&or(r,"currentSupply");const i=null==r||""===r;if(i&&(null==t||""===t))throw Nt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&ir(t);let a=r;if(i){a=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return s===Ye?er.calculateBuyWithExact(n,a):er.calculateBuyWithNative(n,a)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:s,currentSupply:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o}=e;if(!un(n))throw Nt("amount","Amount");if(s!==Ye&&s!==Je)throw Lt("type",'"exact" or "native"',s);void 0!==r&&or(r,"currentSupply");const c=null==r||""===r||null==i||""===i||void 0===a||void 0===o;if(c&&(null==t||""===t))throw Nt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&ir(t);let l=r,d=i,u=a,h=o;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 s===Ye?er.calculateSellWithExact(n,l,d,h,u):er.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 Ks(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Ws(t,"currentSupply")}(e))throw Lt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:s,currentSupply:r}=t;ir(n);const i=await this.fetchSaleDetails(n),a=r??Qs(Vs(i.maxSupply).minus(i.sellingTokenQuantity)),o=i.sellingTokenQuantity;if("0"===o)throw Nt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:o,type:"exact",currentSupply:a,...void 0!==s&&{mode:s}};return{...await this.calculateBuyAmount(c),remainingTokens:o}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw Ct("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Gs(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=en(t);if(0===n&&"0"!==t)throw Ut("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Ut("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;!function(e,t,n){const s="string"==typeof e?parseFloat(e):e,r="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new dt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(r))throw new dt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(s<.1)throw new dt(`${n} minFee must be >= 0.1, received ${s}`,n,"INVALID_FEE_MINIMUM");if(r>.5)throw new dt(`${n} maxFee must be <= 0.5, received ${r}`,n,"INVALID_FEE_MAXIMUM");if(s>r)throw new dt(`${n} minFee (${s}) must be <= maxFee (${r})`,n,"INVALID_FEE_RANGE")}(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!qs(e))throw _t("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return nr(await Gt(()=>this.http.get(He,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Qs(Vs(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.sellingTokenQuantity,r=t.maxSupply;let i=.5,a=.1;const o=t.reverseBondingCurveConfiguration;null!=o?.maxFeePortion&&(i=tn(o.maxFeePortion,.5)),null!=o?.minFeePortion&&(a=tn(o.minFeePortion,.1)),void 0===o&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=i-a;return this.metadataCache.set(e,{maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){ir(e);const t=await this.fetchSaleDetails(e),n=Qs(Vs(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.maxSupply;return this.metadataCache.set(e,{maxSupply:s}),n}async fetchPoolDetails(e){ir(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...s}=t,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0";return{...s,reverseBondingCurveMinFeePortion:r,reverseBondingCurveMaxFeePortion:i,hasReverseBondingCurveFee:!Xs(r)||!Xs(i),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return pn(e,"tokenName",_n),Gt(()=>this.http.get(Ke,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,s,r,i){const a=s??this.defaultCalculateAmountMode;if("local"!==a&&"external"!==a)throw Lt("mode",'"local" or "external"',a);if(!un(e))throw Nt("tokenName","Token name");if(!un(t))throw Nt("amount","Amount");if("string"!=typeof n||!r.includes(n))throw Lt("type",i,n);return a}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new dt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new dt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Qn(e)}validateTokenName(e){return ir(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 dr=3e5,ur="Sign in to Launchpad t:",hr="Authorization",gr="Bearer ";class mr{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 fr;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(fr||(fr={}));class pr extends Error{constructor(e,t,n,s){super(t),this.type=e,this.originalError=n,this.statusCode=s,this.name="AuthError"}}class vr{constructor(e,t=dr){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 mr,this.refreshThresholdMs=t}setToken(e,t){if(!un(e))throw new pr(fr.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new pr(fr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new pr(fr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new pr(fr.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,s){if(this.setToken(e,t),n){const e=Date.now()+1e3*(s??7776e3);if(!this.tokenState)throw new pr(fr.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:`${gr}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new pr(fr.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[hr]: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 s=Date.now();this.tokenState={token:e,issuedAt:s,expiresAt:n};const r=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),i=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(r&&i){const e=Number(i);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=r,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 Ar extends vr{getJwtHeaders(){return{}}}async function Er(e,t,n,s){try{return await e()}catch(e){throw s?(s(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const s=(Tt(e)?e.response?.status:void 0)??(e instanceof mt?e.statusCode:void 0);return It(`${t}: ${At(e)}`,s,vt(e)?e:void 0)}(e,t,n))}}function yr(e,t){return t instanceof pr?t:new pr(fr.SIGNATURE_FAILED,`${e}: ${At(t)}`,vt(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 Tr{constructor(e,t,n,s=!1,r){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=r,this.refreshPromise=null,this.loginPromise=null,this.logger=new Qt({debug:s,context:"SessionAuthService"})}async loginWithSignature(e){if(es(e.address,"address"),!un(e.message)||!un(e.signature))throw new pr(fr.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 es(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 yr("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 pr(fr.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 Er(async()=>{const e=Date.now(),t=`${ur}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),s=this.signatureAuth.getAddress();es(s,"address");const r={address:s,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:s,message:t});const i=await this.http.post(R,r),a=this.extractLoginData(i);return await this.jwtAuth.setTokens(a.accessToken,a.expiresIn,a.refreshToken,a.refreshExpiresIn),this.logger.debug("Login successful",{address:a.address,expiresIn:a.expiresIn,hasRefreshToken:!!a.refreshToken}),a},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof pr)throw e;throw new pr(fr.SIGNATURE_FAILED,`Login failed: ${At(e)}`,vt(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 pr(fr.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:M,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw yr("Token refresh failed",e)}}async performRefresh(){return Er(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 pr)throw e;throw new pr(fr.SIGNATURE_FAILED,`Token refresh failed: ${At(e)}`,vt(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:`${gr}${n}`}}})}catch(e){throw yr("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): ${At(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 pr(fr.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Er(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 pr)throw e;throw new pr(fr.SIGNATURE_FAILED,`Failed to get session: ${At(e)}`,vt(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 pr(fr.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new pr(fr.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: ${At(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 pr(fr.SIGNATURE_FAILED,""!==At(e)?At(e):"Authentication failed");const t=$t(e,"No data in authentication response"),{accessToken:n,expiresIn:s,address:r,refreshToken:i,refreshExpiresIn:a}=t;if(!un(n))throw new pr(fr.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof s||s<=0)throw new pr(fr.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:s,address:r,...void 0!==i&&{refreshToken:i},...void 0!==a&&{refreshExpiresIn:a}}}extractSessionData(e){if(e.error)throw new pr(fr.SIGNATURE_FAILED,""!==At(e)?At(e):"Failed to get session");return $t(e,"No data in session response")}}class Sr{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{ln(e.messagePrefix,"messagePrefix",!1)}catch{throw new pr(fr.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=n.PrivateKeyProvider.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Qn(this.wallet.address)}catch(e){if(e instanceof pr)throw e;if(e instanceof dt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new pr(fr.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new pr(fr.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new pr(fr.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new pr(fr.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=n.PrivateKeyProvider.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Qn(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(e){this.walletProvider=e,this.wallet=void 0;const s=void 0!==e&&n.isPrivateKeyProvider(e)?t.computeAddress(e.exportPrivateKey()):void 0;this.cachedAddress=s,this.cachedGalaAddress=void 0===s?void 0:Qn(s)}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 pr)throw e;throw new pr(fr.SIGNATURE_FAILED,"Failed to generate signature for authentication",vt(e)?e:new Error(At(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new pr(fr.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 pr(fr.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 pr(fr.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&n.isPrivateKeyProvider(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new pr(fr.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 pr(fr.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new pr(fr.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",vt(e)?e:void 0)}}formatAddress(e){try{return Qn(e)}catch{throw new pr(fr.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 pr)throw e;throw new pr(fr.SIGNATURE_FAILED,At(e),vt(e)?e:new Error(At(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),s=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,r=await this.walletProvider.signMessage(s);return{"x-signature":r,"x-address":await this.walletProvider.getGalaAddress(),"x-message":s,"x-timestamp":n.toString()}}catch(e){if(e instanceof pr)throw e;throw new pr(fr.SIGNATURE_FAILED,"Failed to generate authentication headers",vt(e)?e:new Error(At(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const s={};for(const[e,n]of Object.entries(t))s[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,s,n)}catch(e){if(e instanceof pr)throw e;throw new pr(fr.SIGNATURE_FAILED,"Failed to sign typed data",vt(e)?e:new Error(At(e)))}}async generateCustomSignature(e){if(!un(e))throw new pr(fr.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 pr)throw e;throw new pr(fr.SIGNATURE_FAILED,"Failed to generate custom message signature",vt(e)?e:new Error(At(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new pr(fr.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new pr(fr.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new pr(fr.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const br={prod:{...s.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:{...s.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 kr(e){return br[e]}var wr,Nr;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(wr||(wr={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(Nr||(Nr={}));const _r={[wr.PROCESSED]:Nr.COMPLETED,[wr.COMPLETED]:Nr.COMPLETED,[wr.SUCCESS]:Nr.COMPLETED,[wr.FAILED]:Nr.FAILED,[wr.ERROR]:Nr.FAILED,[wr.PROCESSING]:Nr.PROCESSING,[wr.PENDING]:Nr.PENDING},Ir="9.0.0-rc.2",Cr={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Dr(e){return"string"==typeof e||null===e?e:void 0}function Rr(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),s=Dr(Reflect.get(e,"endCursor")),r=Dr(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===s?{}:{endCursor:s},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===r?{}:{startCursor:r}}}function Or(e,t){const{hasNextPage:n,endCursor:s}=e;if(n&&"string"==typeof s&&""!==s&&s!==t)return s}function Mr(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Lr(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const s=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(s),n}const Ur={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function Fr(e,t){let n=e;for(const[e,s]of Object.entries(t)){const t=Ur[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?s.toLowerCase():s))}return n}function xr(e,t,n){for(const s of n){const n=t[s];null!=n&&""!==n&&(e[s]=Mr(n))}return e}const Pr="x-api-key";class Br extends bn{constructor(e,t,n,s=!1,r){super(e,s),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=r??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!un(e))throw Nt("tokenName","Token name");const n=qt(e);if(!t.PATTERN.test(n))throw _t("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!un(e))throw Nt(t,n)}(e,t,n)}validateOptionalString(e,t,n,s){!function(e,t,n,s){if(null!=e){if("string"!=typeof e)throw Lt(t,"string",typeof e,n);if(e.length>s)throw Mt(t,s,e.length,n)}}(e,t,n,s)}validateOptionalNumber(e,t,n,s,r,i,a){!function(e,t,n,s,r){if(null!=e){if("number"!=typeof e)throw Lt(t,"number",typeof e,n);if(e<s||e>r)throw Rt(t,s,r,e,n)}}(e,t,n,s,r)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Zt(e))throw _t(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Tn(e,t,n)}validateStatusFilter(e,t,n="status"){Sn(e,t,n)}buildPaginationParams(e,t){return Lr(e,t)}addOptionalFilterParams(e,t,n){return xr(e,t,n)}buildEndpoint(e,t){return Fr(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 ft("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[Pr]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new ft("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?{[Pr]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Pt(e,"Backend request failed",!0),$t(e,"No data in backend response")}extractDataOrNull(e){return Pt(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const s=this.buildEndpoint(t,{tokenName:e}),r=await this.http.post(s,{},this.getAdminHeaders()),i=this.extractData(r);return{enabled:i.enabled,tokenName:i.tokenName??qt(e)}}}class $r extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}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 Gr=fn({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"});function Kr(e){return Gr.includes(e)}function Wr(e,t,n=!1){const s=t.length;if(bt(t,()=>{En(e.description,"description",255)}),t.length>s&&(t[s]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;bt(t,()=>{if(!Array.isArray(e.tokenNames))throw Lt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Lt("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;bt(t,()=>{yn(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}class Hr extends bn{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),Pt(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=function(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):Kr(e.role)||t.push(`Invalid role. Must be one of: ${Gr.join(", ")}`),Wr(e,t),t}(e);if(t.length>0)throw new dt(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 s=await this.http.post(H.CREATE,n,this.getJwtHeaders()),r=this.extractData(s);return this.logger.debug("API key created",{id:r.id,keyPrefix:r.keyPrefix}),r}async findAll(e={}){!function(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>Rn))throw Lt("pageSize",`number between 1 and ${Rn}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Lt("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=Lr(e,Rn),n=await this.http.get(H.LIST,t,this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Listed API keys",{count:s.apiKeys.length,total:s.pageInfo.totalCount}),s}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=H.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Got API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async update(e,t){this.validateApiKeyId(e);const n=function(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||Kr(e.role)||t.push(`Invalid role. Must be one of: ${Gr.join(", ")}`),Wr(e,t,!0),t}(t);if(n.length>0)throw new dt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const s={};void 0!==t.role&&(s.role=t.role),void 0!==t.description&&(s.description=t.description),void 0!==t.delegateAllTokens&&(s.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(s.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(s.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(s.tokenPermissions=t.tokenPermissions);const r=H.UPDATE.replace(":id",String(e)),i=await this.http.patch(r,s,this.getJwtHeaders()),a=this.extractData(i);return this.logger.debug("Updated API key",{id:a.id,keyPrefix:a.keyPrefix}),a}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=H.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Gr]}}const jr={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},qr=mn(jr);function zr(e){if(!un(e.userAddress))throw Nt("userAddress");if(!(null==(t=e.reason)||""===t||"string"==typeof t&&!An(t)&&t.length<=Fn.BAN_REASON.MAX_LENGTH))throw new dt(`reason must be at most ${Fn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t,n;if(n=e.durationSeconds,!(hn(n)||"number"==typeof n&&n>=Pn&&n<=Bn))throw new dt(`durationSeconds must be between ${Pn} and ${Bn} seconds`,"durationSeconds","OUT_OF_RANGE")}class Vr extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async createBan(e){!function(e){pn(e.tokenName,"tokenName",In),zr(e)}(e);const t=this.buildEndpoint(U,{tokenName:e.tokenName}),n=Qr(e),s=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(s),tokenName:qt(e.tokenName)}}async removeBan(e){!function(e){if(pn(e.tokenName,"tokenName",In),!un(e.userAddress))throw Nt("userAddress")}(e);const t=this.buildEndpoint(P,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(n);return{removed:s?.removed??!0,tokenName:qt(e.tokenName),userAddress:s?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){pn(e.tokenName,"tokenName",In),gn(0,void 0,Rn,e.pageSize)}(e);const t=this.buildEndpoint(F,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Rn);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getBanStatus(e){!function(e){if(pn(e.tokenName,"tokenName",In),!un(e.userAddress))throw Nt("userAddress")}(e);const t=this.buildEndpoint(x,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},tokenName:qt(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(pn(e.tokenName,"tokenName",In),void 0!==e.type&&!qr(e.type))throw new dt(`type must be one of: ${Object.values(jr).join(", ")}`,"type",rt)}(e);const t=this.buildEndpoint(B,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const s=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(s)}async createGlobalBan(e){!function(e){zr(e)}(e);const t=Qr(e),n=await this.http.post($,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!un(e.userAddress))throw Nt("userAddress")}(e);const t=this.buildEndpoint(W,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{removed:s?.removed??!0,userAddress:s?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){gn(0,void 0,Rn,e.pageSize)}(t);const n=this.buildPaginationParams(t,Rn);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const s=await this.http.get(G,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getGlobalBan(e){!function(e){if(!un(e.userAddress))throw Nt("userAddress")}(e);const t=this.buildEndpoint(K,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},userAddress:e.userAddress.toLowerCase()}}}function Qr(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 Xr(e){return{maxAcceptableReverseBondingCurveFee:sn(e.maxAcceptableReverseBondingCurveFee)}}class Jr extends r.ChainCallDTO{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=sn(t),this.expectedToken=rn(n),this.extraFees=Xr(s)}}class Yr extends r.ChainCallDTO{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=rn(t),this.expectedNativeToken=sn(n),this.extraFees=Xr(s)}}class Zr extends r.ChainCallDTO{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=rn(t),this.expectedNativeToken=sn(n),this.extraFees=Xr(s)}}class ei extends r.ChainCallDTO{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=sn(t),this.expectedToken=rn(n),this.extraFees=Xr(s)}}const ti={BuyNativeDto:Jr,BuyExactDto:Yr,SellExactDto:Zr,SellNativeDto:ei};function ni(e,t,n){let s;an(t,0,1,"slippageToleranceFactor");try{s=function(e,t){if(Jt(e)||""===e)throw Nt(t);if(o.isBigNumber(e)){if(e.isNaN())throw Ut(t,"NaN");return e}try{const n=new o(e);if(n.isNaN())throw Ut(t,e);if(!n.isFinite())throw Ut(t,e);return n}catch(n){if(n instanceof dt)throw n;throw Ut(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const r=s.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=s.minus(r);break;case"buy-exact":case"sell-native":i=s.plus(r);break;default:throw new Error(`Unknown operation type: ${n}`)}return Vs(i).isLessThan(0)&&(i=Vs(0)),Qs(i)}function si(e,t){if(!un(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 ri(e,t,n,s){const r=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new dt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${r.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${r.map(e=>`"${e}"`).join(", ")}]. Error: ${At(s)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function ii(e,t,n){try{const n=si(e,t),s=n[n.length-1],r=n[n.length-2],i=n[n.length-3],a=n.slice(0,n.length-3).join(t);if(void 0===a||void 0===i||void 0===r||void 0===s||""===s||""===a||""===i||""===r)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:a,category:i,type:r,additionalKey:s}}catch(s){throw ri(e,t,n,s)}}function ai(e){return function(e,t,n){try{const n=si(e,t),[s,r,i,...a]=n;if(""===s||""===r||""===i)throw new Error("Collection, category, and type must be non-empty");const o=a.join(t);if(void 0===s||void 0===r||void 0===i||""===o)throw new Error("AdditionalKey must be non-empty");return{collection:s,category:r,type:i,additionalKey:o}}catch(s){throw ri(e,t,n,s)}}(e,"|","pipe-delimited token")}class oi 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 ci={name:"GalaChain"},li={name:"ethereum",chainId:1};function di(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function ui(e){const t={};for(const[n,s]of Object.entries(e))void 0!==s&&(t[n]=hi(s));return t}function hi(e){return Array.isArray(e)?e.map(hi):"object"==typeof e&&null!==e?ui(e):e}function gi(e,t,n,s){return{...e,signature:t,types:n,domain:s}}class mi extends s.PrivateKeySigner{constructor(e){super(e),this.typedDataWallet=new t.Wallet(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=ui(t),r=s.generateEIP712Types(e,n);return gi(n,await this.typedDataWallet.signTypedData(ci,r,n),r,ci)}}class fi extends s.GalaWalletSigner{constructor(e,t={}){const{verifyActiveAccount:n,...r}=t;if(super(e,r),this.typedDataWallet=t.wallet,!0===n){const e=s.ethereumAddressOfAccount(this.walletAddress)??(void 0===this.selectAddress?void 0:s.ethereumAddressOfAccount(this.selectAddress));if(void 0===e)throw new oi("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,t){const n=ui(t),r=s.generateEIP712Types(e,n),i={domain:li,types:r,message:n,Primary_type:e},a=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,t){let n="address"in e&&"string"==typeof e.address&&""!==e.address?e.address:void 0;if(void 0===n){const t=await e.request({method:"eth_accounts"}),s=Array.isArray(t)?t[0]:void 0;n="string"==typeof s&&""!==s?s:void 0}const r=void 0===n?void 0:s.ethereumAddressOfAccount(n);if(void 0===r||r.toLowerCase()!==t.toLowerCase())throw new oi("Your wallet's active account has changed. Please switch back to the connected account or reconnect your wallet.","WALLET_ACCOUNT_CHANGED",{details:{walletAccount:n??null,signerAccount:t}})}(a,this.verifiedKey);const o=await this.typedDataAccount(a);return gi(n,di(await s.withGalaWalletIdentity(a,this.selectAddress??o,()=>a.request({method:"eth_signTypedData",params:[JSON.stringify(i),o]}))),r,li)}async typedDataAccount(e){if(t.isAddress(this.walletAddress))return this.walletAddress;const n=await e.request({method:"eth_accounts"}),s=Array.isArray(n)?n[0]:void 0,r="string"==typeof s?s.replace(/^eth\|/,"0x"):"";if(!t.isAddress(r))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return r}}class pi extends s.BrowserWalletSigner{constructor(e,t,n){super(e,t,n),this.typedDataProvider=e}async signTypedData(e,n){const r=ui(n),i=this.typedDataProvider,a=await i.getNetwork(),o={name:a.name,chainId:Number(a.chainId)},c=s.generateEIP712Types(e,r),l=await i.getSigner(),d=t.getAddress(await l.getAddress());if(t.isAddress(this.walletAddress)&&d!==t.getAddress(this.walletAddress))throw new oi(`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 gi(r,di(await l.signTypedData(o,c,r)),c,o)}static fromEip1193(e,n,r){const i=new t.BrowserProvider(e);return new pi({request:t=>e.request(t),getNetwork:()=>i.getNetwork(),getSigner:()=>i.getSigner()},s.ethereumAddressOfAccount(n)??n,r)}}function vi(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 s=n.split("$"),r=s[s.length-1],i=s.slice(0,-1),a=i.slice(0,-3).join("$"),[o,c,l]=i.slice(-3);if("launchpad"!==r||i.length<4||""===a||void 0===o||void 0===c||void 0===l||""===o||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:a,category:o,type:c,additionalKey:l}}function Ai(e){const{collection:t,category:n,type:s}=vi(e),r=`${t}$${n}$${s}$none`,i="GALA$Unit$none$none";return[`$service$${r}$launchpad`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`]}function Ei(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 yi(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Ti(e){if("string"==typeof e){if(!un(t=e)||!t.includes("|"))throw new dt(`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 n=e.split("|");if(n.length>=5){const e=ai(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...ai(e),instance:"0"}}var t;if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!s.isTokenClassKey(e))throw new dt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!s.isTokenClassKey(e))throw new dt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new dt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Si(e){return function(e){try{if(!un(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 ii((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new dt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${At(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function bi(e){return{...Si(e),instance:"0"}}function ki(e){const t=Si(e);if("Token"!==t.collection)throw new dt(`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 wi,Ni,_i,Ii,Ci=Object.freeze({__proto__:null,extractTokenSymbolFromVault:ki,normalizeToTokenInstanceKey:Ti,parseVaultAddressToTokenClassKey:Si,parseVaultAddressToTokenInstance:bi});class Di extends kn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=Ai(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=At(e);throw new dt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new r.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!un(e))throw Nt("vaultAddress","Vault address");try{const t=ki(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof dt)throw _t("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!un(e))throw Nt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw _t("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw _t("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!un(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],s=t[2];return void 0===n||void 0===s?null:{tokenSymbol:n,creatorAddress:s.toLowerCase()}}(e);if(!t)throw _t("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 _t("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,s){return`${e}$${t}$${n}$${s}`}parseTokenClassKeyString(e){try{return ii(e,"$","dollar-delimited token")}catch(e){if(e instanceof dt)throw _t("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Ri(e){return"object"==typeof e&&null!==e?e:void 0}class Oi extends bn{constructor(e,t,n=!1,s,r,i=.05,a=.01,o){if(super(e,n),this.tokenResolver=t,this._walletProvider=s,this.userAddress=r,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.sellFeeCeiling=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=r){const e=Ri(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new mi(t):function(e){const t=Ri(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new pi(this._walletProvider,this.userAddress)),this.tokenKeyService=new Di(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 Kt(()=>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 dt)return{success:!1,error:At(e)};throw e}}validateBundleData(e){if(null==e)throw Nt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Nt("signedDto","Signed DTO");if(!un(e.method))throw Nt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw _t("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new dt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw _t("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!un(e))throw new dt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new dt(`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=Bt(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(Tt(e)&&null!==e.response&&void 0!==e.response){const t=Bt(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 At(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!un(e))throw Nt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Kt(()=>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 dt)return{success:!1,error:At(e)};throw e}}async cancelTransaction(e){try{if(!un(e))throw Nt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Kt(()=>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 dt)return{success:!1,error:At(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Kt(()=>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:s,expectedAmount:r}=e,{effectiveSlippageFactor:i,effectiveMaxFee:a,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===s){if(null==r||""===r)throw new dt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ni(r,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:r,slippageFactor:i,adjustedMinTokens:e});const t=new ti.BuyNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyWithNative",o)}{if(null==r||""===r)throw new dt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ni(r,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:r,slippageFactor:i,adjustedMaxGalaCost:e});const t=new ti.BuyExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyExactToken",o)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:s,expectedAmount:r}=e,{effectiveSlippageFactor:i,effectiveMaxFee:a,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,o):a;if("exact"===s){if(null==r||""===r)throw new dt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ni(r,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:r,slippageFactor:i,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new ti.SellExactDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellExactToken",o)}{if(null==r||""===r)throw new dt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=ni(r,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:r,slippageFactor:i,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new ti.SellNativeDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellWithNative",o)}}async prepareTradingOperation(e,t,n,s){const{effectiveSlippageFactor:r,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,s),a=await this.resolveTokenNameToVault(e);if(null==a)throw wt(e);return{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:a}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw Ct("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 s=n??this.defaultSlippageToleranceFactor,r=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e??"0";return null!=e&&(i=ni(e,r,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:r,adjustedMaxFee:i})),{effectiveSlippageFactor:s,effectiveFeeSlippageFactor:r,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw Ct("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Nt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${i.v4().replace(/-/gu,"").substring(0,26)}`;const s=await this.signer.signObject(t,e),r=this.tokenKeyService.generateStringsInstructions(n),a={stringsInstructions:r,method:t,signedDto:s};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:r,dtoKeys:Object.keys(s)});const o=await this.submitTransaction(a);if(o.success){const e=Bt(o);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=o.error;throw new pt("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 Mi extends bn{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}}}!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(wi||(wi={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Ni||(Ni={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(_i||(_i={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Ii||(Ii={})),Ni.INAPPROPRIATE_CONTENT,Ni.SPAM,Ni.HARASSMENT,Ni.SCAM,Ni.OTHER,_i.PENDING,_i.DISMISSED,_i.ACTIONED,Ii.DELETE_CONTENT,Ii.BAN_USER,Ii.DELETE_AND_BAN,wi.CHAT_MESSAGE,wi.COMMENT,wi.STREAM,wi.RECORDING;const Li=mn(wi),Ui=mn(Ni),Fi=mn(_i),xi=mn(Ii),Pi={TOKEN_NAME:_n,TOKEN_NAME_FILTER:{MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},CONTENT_ID:Fn.CONTENT_ID,DETAILS:Fn.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:Rn}};function Bi(e,t,n="tokenName"){pn(e,n,t)}function $i(e){if(void 0!==e.contentType&&!Li(e.contentType))throw _t("contentType",`one of: ${Object.values(wi).join(", ")}`,"Content type");if(void 0!==e.status&&!Fi(e.status))throw _t("status",`one of: ${Object.values(_i).join(", ")}`);if(void 0!==e.reason&&!Ui(e.reason))throw _t("reason",`one of: ${Object.values(Ni).join(", ")}`);if(void 0!==e.reporterAddress&&!un(e.reporterAddress))throw Lt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Zn(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!un(e.reportedUserAddress))throw Lt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Zn(e.reportedUserAddress,"reportedUserAddress"),gn(0,void 0,Pi.PAGINATION.MAX_LIMIT,e.pageSize)}class Gi extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async createFlag(e){!function(e){if(Bi(e.tokenName,Pi.TOKEN_NAME),void 0===e.contentType)throw Nt("contentType","Content type");if(!Li(e.contentType))throw _t("contentType",`one of: ${Object.values(wi).join(", ")}`,"Content type");if(!un(e.contentId))throw Nt("contentId","Content ID");if(e.contentId.length>Pi.CONTENT_ID.MAX_LENGTH)throw Mt("contentId",Pi.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!un(e.reportedUserAddress))throw Nt("reportedUserAddress","Reported user address");if(Zn(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==wi.STREAM&&e.contentType!==wi.RECORDING||void 0!==e.reason&&null!==e.reason))throw Nt("reason","Reason");if(void 0!==e.reason&&!Ui(e.reason))throw _t("reason",`one of: ${Object.values(Ni).join(", ")}`,"Reason");if(void 0!==e.details&&!un(e.details))throw Lt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Pi.DETAILS.MAX_LENGTH)throw Mt("details",Pi.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){Bi(e.tokenName,Pi.TOKEN_NAME_FILTER),$i(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&Bi(e.tokenName,Pi.TOKEN_NAME_FILTER),$i(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Nt("flagId","Flag ID");try{cn(e.flagId,"flagId")}catch{throw _t("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 Nt("flagId","Flag ID");try{cn(e.flagId,"flagId")}catch{throw _t("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Nt("action","Action");if(!xi(e.action))throw _t("action",`one of: ${Object.values(Ii).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=Lr(e,Rn);xr(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(Z.LIST,t,this.getMultiAuthHeaders()),s=this.extractData(n);return{items:s.flags,pageInfo:s.pageInfo}}}const Ki=["heart","fire","laugh","wow","thumbs_up"];class Wi extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateMessageId(e){if(!un(e))throw Nt("messageId","Message ID");if(on(e,xn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!xn.CONTENT_REACTION.PATTERN.test(e))throw _t("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!un(e))throw Nt("reactionType","Reaction type");if(!Ki.includes(e))throw _t("reactionType",`one of: ${Ki.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Ne,n={messageId:e.messageId,reactionType:e.reactionType},s=await this.http.post(t,n,this.getMultiAuthHeaders()),r=this.extractData(s),{created:i,...a}=r;return{data:a,created:i}}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 Hi="Token name is required and must be a string";const ji="GALA|Unit|none|none";class qi extends kn{constructor(e,t,n,s=!1){super(s),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!un(e))throw new dt(Hi,"tokenName",nt);let s;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(s=yi(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${At(t)}`)}if(void 0!==s)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(s);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),s=await this.fetchMarketUsdPrice(ji),r=en(n.amount,0)/1e18;if(r<=0)throw new dt(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");return{symbol:zt(e),price:s.price/r}}catch(t){throw It(`Failed to calculate launchpad token spot price for ${e}: ${At(t)}`,void 0,vt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===ji)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 It("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw It(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${At(t)}`)}if(""===n)throw It(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!un(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 It("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),s=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),r=null!==s&&"object"==typeof s?s:{},i=Object.keys(r).find(e=>e.toUpperCase()===n.toUpperCase()),a=void 0!==i?r[i]:1===Object.keys(r).length?Object.values(r)[0]:void 0,o=a?.price;if("number"!=typeof o||!Number.isFinite(o))throw new dt(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${o}`),{symbol:n,price:o}}catch(e){if(e instanceof dt)throw e;throw It(`Failed to fetch DEX spot price: ${At(e)}`)}}}const zi=20,Vi=3e3,Qi=1e3,Xi=!0,Ji=!0,Yi=!1;class Zi{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 Qt({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??zi,flushIntervalMs:t.flushIntervalMs??Vi,maxQueueSize:t.maxQueueSize??Qi,flushOnPageHide:t.flushOnPageHide??Xi,flushOnPageUnload:t.flushOnPageUnload??Ji,debug:t.debug??Yi},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const s={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(s),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 ea=["createdAt","eventType","userAddress"],ta=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],na=["sdk","frontend","backend","mcp"];function sa(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ra(e){return"number"==typeof e&&Number.isFinite(e)}function ia(e){return sa(e)&&ra(e.id)&&"string"==typeof e.eventType&&sa(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function aa(e,t,n){if(!t.some(t=>t===e))throw new dt(`${n} must be one of: ${t.join(", ")}`,n,rt)}class oa extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getEventStats(){return function(e){if(!(sa(e)&&ra(e.totalEvents)&&ra(e.todayEvents)&&ra(e.uniqueUsers)&&ra(e.uniqueTokens)&&sa(e.eventsByType)))throw It("Malformed event statistics response");const t={};for(const[n,s]of Object.entries(e.eventsByType)){if(!ra(s))throw It("Malformed event statistics response");t[n]=s}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(xe,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 dt("limit must be an integer from 1 to 100","limit",rt);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new dt("page must be a positive integer","page",rt);void 0!==e.sortBy&&aa(e.sortBy,ea,"sortBy"),void 0!==e.sortOrder&&aa(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&aa(e.timePreset,ta,"timePreset"),void 0!==e.source&&aa(e.source,na,"source")}(e);const t={},n=new URLSearchParams;for(const[s,r]of Object.entries(e))if(void 0!==r&&("string"!=typeof r||""!==r)){if(Array.isArray(r)){const e=r.map(String);if(0===e.length)continue;for(const t of 1===e.length?[...e,...e]:e)n.append(s,t);continue}t[s]=r}const s=n.toString(),r=""===s?Fe:`${Fe}?${s}`;return function(e){if(!sa(e)||!Array.isArray(e.data)||!sa(e.pagination))throw It("Malformed events response");const t=e.pagination,n=e.data;if(!(ra(t.page)&&ra(t.limit)&&ra(t.total)&&ra(t.totalPages)&&n.every(ia)))throw It("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(r,t,this.getDualAuthHeaders()))}}function ca(e){let t;return{requestor:async(n,s)=>{const r="string"==typeof s?.body?JSON.parse(s.body):void 0,{data:i,status:a,headers:o}=await e(n,r);t=i;const c=void 0===i?"":JSON.stringify(i),l="number"==typeof a?a:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(i),text:()=>Promise.resolve(c),headers:o??{}}},answer:()=>t}}const la=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class da extends bn{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const{requestor:n}=ca(async(e,t)=>({data:await this.http.post(e,t)})),r=new s.GatewayReads({gatewayBaseUrl:"",httpRequestor:n,requestTimeoutMs:1/0}),{owner:i,collection:a,category:o,type:c,additionalKey:l}=e,d=await r.fetchTokenBalance({owner:i,tokenClassKey:{collection:a,category:o,type:c,additionalKey:l},includeExpiredHolds:t});return void 0===d?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,s={quantity:e.quantity,collection:t,category:n,tokenId:yi(e.tokenClassKey)};return e.inUseHolds.length>0&&(s.inUseHolds=[...e.inUseHolds],s.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(s.lockedHolds=[...e.lockedHolds],s.lockedQuantity=e.lockedQuantity),void 0===s.lockedQuantity&&void 0===s.inUseQuantity||(s.availableQuantity=e.availableQuantity),s}(d)}catch(e){if(s.isGalaError(e)&&la.has(e.code))return null;throw It(`Failed to fetch token balance from GalaChain: ${At(e)}`,void 0,vt(e)?e:void 0)}}}function ua(e){if(null==e||"object"!=typeof e)return!1;const t=e;return un(t.amount)&&(void 0!==t.tokenId||un(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 ha(e){if(null==e||"object"!=typeof e)return!1;const t=e;return un(t.amount)&&(void 0!==t.tokenId||un(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var ga,ma;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(ga||(ga={}));class fa 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"}(ma||(ma={}));class pa extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function va(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 Aa(e,t,n,s="[DEBUG] Token resolution (launchpad)"){const r=await t.resolveTokenToVault(e);if(null!==r){const t=bi(r);return n.debug(s,{tokenName:e,vaultAddress:r,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new dt(`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 Ea extends bn{constructor(e,t,n,s=!1,r){super(e,s),this.wallet=t,this.tokenResolver=n,this.writer=r,this.nativeSigner=t?new mi(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:Qn(this.wallet.address)}:this.writer}}function ya(e,t){const{collection:n,category:s,type:r,additionalKey:i,instance:a}=e;return{tokenClassKey:{collection:n,category:s,type:r,additionalKey:i},instance:a,quantity:t}}const Ta=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function Sa(e,{signer:t,walletAddress:n}){const{requestor:r,answer:i}=ca((t,n)=>e.postWithMeta(t,n));return{writes:new s.GatewayWrites({gatewayBaseUrl:"",signer:t,walletAddress:n,httpRequestor:r,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:i}}async function ba(e,t,n){let r;try{r=await t(e.writes)}catch(t){throw function(e){return s.isGalaError(e)&&Ta.has(e.code)}(t)&&n(e.answer(),void 0),t}return n(e.answer(),r)}function ka(e){return void 0===e||""===e?{}:{uniqueKey:e}}const wa=100,Na=100;class _a extends Ea{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new fa("Wallet required for token lock operations",ga.WALLET_REQUIRED);return Er(async()=>{const n=Sa(this.http,t),s=n.writes.walletAddress,r=[],i=[];let a=s;const o=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==o?.lockAuthority&&(a=Qn(o.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);i.push(ya(e,t.amount)),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount,lockAuthority:void 0!==t.lockAuthority?Qn(t.lockAuthority):a})}return ba(n,t=>t.lockTokens({tokens:i,lockAuthority:a,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...ka(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token lock failed"),this.extractLockResult(e,t,r)))},"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 fa("Wallet required for token unlock operations",ga.WALLET_REQUIRED);return Er(async()=>{const n=[],s=[],r=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);s.push(ya(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return ba(Sa(this.http,t),t=>t.unlockTokens({tokens:s,...void 0!==r?.name&&{name:r.name},...ka(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{St(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 fa(`${At(t)}${n}`,ga.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new fa("Must provide either tokenId or tokenName for token identification",ga.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{vn(e.tokenName,"tokenName",In)}catch{throw new fa("Invalid token name format",ga.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{Ys(Vs(e.amount))}catch{throw new fa(_t(t,"a positive number",n).message,ga.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(ua)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new fa("Invalid lock data: missing required fields",ga.VALIDATION_ERROR);if(e.tokens.length>wa)throw new fa(`Batch size exceeds maximum limit of ${wa} tokens per lock operation`,ga.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Xn(t.lockAuthority))throw new fa("Invalid lock authority address format",ga.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{cn(t.expires,"expires")}catch{throw new fa(_t("expires","a positive integer (epoch milliseconds)","Expires").message,ga.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(ha)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new fa("Invalid unlock data: missing required fields",ga.VALIDATION_ERROR);if(e.tokens.length>Na)throw new fa(`Batch size exceeds maximum limit of ${Na} tokens per unlock operation`,ga.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 s=this.transactionIdOf(e,t),r=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==r&&{blockNumber:r},locked:n}}extractUnlockResult(e,t,n){const s=this.transactionIdOf(e,t),r=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==r&&{blockNumber:r},unlocked:n}}handleLockError(e,t,n){if(e instanceof fa)return e;if(s.isGalaError(e)&&"pre_send"===e.phase)return new fa(`${t}: ${e.message}`,"SIGNING_FAILED"===(r=e.code)?ga.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===r?ga.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===r?ga.INVALID_AMOUNT:ga.VALIDATION_ERROR,va(n));var r;let i=t,a=ga.NETWORK_ERROR;if(Tt(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(i=`${t}: ${e}`);const s="string"==typeof e?e.toLowerCase():"";s.includes("insufficient")||s.includes("balance")?a=ga.INSUFFICIENT_BALANCE:s.includes("lock")&&s.includes("not found")?a=ga.LOCK_NOT_FOUND:s.includes("not found")||s.includes("token")?a=ga.TOKEN_NOT_FOUND:s.includes("authority")?a=ga.NOT_LOCK_AUTHORITY:s.includes("expired")&&(a=ga.LOCK_EXPIRED)}}else vt(e)&&(i=`${t}: ${At(e)}`);return new fa(i,a,va(n))}async resolveTokenInstance(e){return Er(async()=>Aa(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof pa)throw new fa(At(t),ga.TOKEN_NOT_FOUND);throw new fa(`Failed to resolve token '${e}': ${At(t)}`,ga.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Ti(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 fa("Must provide either tokenId or tokenName for token identification",ga.TOKEN_NOT_FOUND)}}const Ia=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function Ca(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class Da extends bn{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Ti(e):e,{collection:n,category:s,type:r,additionalKey:i}=t,a={collection:n,category:s,type:r,additionalKey:i},o="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(a),e=>{if(St(e,o),void 0===Ca(e)?.[0])throw It(`Token not found on GalaChain: ${yi(a)}`,404)},()=>It(`Token not found on GalaChain: ${yi(a)}`,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 Nt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(St(e,"Failed to fetch token classes with supply from GalaChain"),0===(Ca(e)?.length??0))throw It("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,t,n){if(!this.publicAxios)throw Nt("publicAxios","Public Axios instance");const r=this.publicAxios,{requestor:i,answer:a}=ca(async(e,t)=>{const n=await r.post(e,t);return{data:n.data,status:n.status}});try{return await e(new s.GatewayReads({gatewayBaseUrl:"",httpRequestor:i,requestTimeoutMs:1/0}))}catch(e){if(s.isGalaError(e)&&Ia.has(e.code)&&(t(a()),"TOKEN_CLASS_NOT_FOUND"===e.code&&void 0!==n))throw n();throw e}}handleTokenServiceError(e,t,n){if(e instanceof dt)throw e;if(Tt(e)&&404===e.response?.status)throw It(t,404,vt(e)?e:void 0);if(vt(e)&&"Error"===e.name&&At(e).includes("status indicates failure"))throw It(At(e),400,vt(e)?e:void 0);const s=At(e);if(s.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(s)}throw It(`${n}: ${s}`,void 0,vt(e)?e:void 0)}}function Ra(e){if(null==e||"object"!=typeof e)return!1;const t=e;return un(t.amount)&&(void 0!==t.tokenId||un(t.tokenName))}var Oa;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(Oa||(Oa={}));class Ma extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const La={validateAmount(e){const t=Vs(e);try{!function(e,t){if(e.isNaN())throw Ut(t,"NaN");if(!e.isFinite())throw Mt(t,"finite");if(e.isLessThanOrEqualTo(0))throw Ot(t,"0",e.toString())}(t,"amount")}catch(t){throw new pa(t.message,ma.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!hn(e)&&un(e)){if(e.length>$n.MAX_LENGTH)throw new dt(`Unique key too long. Maximum length: ${$n.MAX_LENGTH}`);if(!$n.PATTERN.test(e))throw new pa('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',ma.INVALID_AMOUNT,{uniqueKey:e})}}},Ua="gala-transfer-successful",Fa="token-transfer-successful",xa="token-locked-successfully",Pa="token-unlocked-successfully",Ba="transfer-successful-no-id",$a=50;class Ga extends Ea{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new pa("Wallet required for GALA transfer operations",ma.WALLET_REQUIRED);try{const n=Qn(e.recipientAddress),s=Sa(this.http,t);return await ba(s,t=>t.transferGala({to:n,quantity:e.amount,...ka(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 pa("Wallet required for token transfer operations",ma.WALLET_REQUIRED);try{const n=Qn(e.to),s=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new pa("Must provide either tokenId or tokenName for token identification",ma.TOKEN_NOT_FOUND)),r=Sa(this.http,t);return await ba(r,t=>t.transferToken({to:n,...ya(s,e.amount),...ka(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 pa)throw t;throw new pa(`Failed to resolve token class key for '${e}': ${At(t)}`,ma.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Ma("Wallet required for token burn operations",Oa.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new Ma("Must provide either tokenId or tokenName for token identification",Oa.TOKEN_NOT_FOUND));n.push(ya(e,t.amount))}const s=Sa(this.http,t);return await ba(s,t=>t.burnTokens({tokens:n,...ka(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 un(t.recipientAddress)&&un(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new dt("Invalid GALA transfer data: missing required fields");if(!Xn(e.recipientAddress))throw new pa("Invalid recipient address format",ma.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});La.validateAmount(e.amount),La.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return un(t.to)&&un(t.amount)&&(void 0!==t.tokenId||un(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new dt("Invalid token transfer data: missing required fields");if(!Xn(e.to))throw new pa("Invalid recipient address format",ma.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new pa("Must provide either tokenId or tokenName for token identification",ma.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{vn(e.tokenName,"tokenName",In)}catch{throw new pa("Invalid token name format",ma.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}La.validateAmount(e.amount),La.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ra)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new Ma("Invalid burn data: missing required fields",Oa.VALIDATION_ERROR);if(e.tokens.length>$a)throw new Ma(`Batch size exceeds maximum limit of ${$a} tokens per burn operation`,Oa.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 Ma("Must provide either tokenId or tokenName for token identification",Oa.TOKEN_NOT_FOUND);const e=Vs(t.amount);try{Ys(e)}catch{throw new Ma("Burn amount must be a positive number",Oa.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=Ti(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 Aa(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof pa)throw t;throw new pa(`Failed to resolve token '${e}': ${At(t)}`,ma.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new pa("No response from GalaChain transfer service",ma.NETWORK_ERROR);const s=t?.blockNumber,r="object"==typeof e&&"Status"in e;r&&St(e,"Extract transaction ID");const i=r&&"Data"in e,a=t?.transactionId;if(void 0!==a)return{transactionId:a,...void 0!==s?{blockNumber:s}:{}};if(i){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!==s?{blockNumber:s}:{}}}}let e=Ba;if(t.Data.length>0)switch(n){case"gala":e=Ua;break;case"token":e=Fa;break;case"lock":e=xa;break;case"unlock":e=Pa}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}throw new pa("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",ma.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new Ma("No response from GalaChain burn service",Oa.NETWORK_ERROR);try{St(e,"Token burn operation")}catch(e){throw new mt(At(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 s=Array.isArray(e.Data)?e.Data[0]:void 0,r=t?.transactionId??s?.transactionId??s?.txnId??s?.TxnId??s?.id??void 0,i=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==i&&{blockNumber:i},burned:n}}handleTransferError(e,t,n){if(e instanceof pa)return e;if(e instanceof dt)return new pa(At(e),ma.INVALID_AMOUNT);if(s.isGalaError(e)&&"pre_send"===e.phase)return new pa(e.message,"SIGNING_FAILED"===(r=e.code)?ma.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===r?ma.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===r?ma.TOKEN_NOT_FOUND:ma.INVALID_AMOUNT);var r;if(Tt(e)&&e.response){const t=e.response.status,s=e.response.data;if(400===t){const e=s?.message;return new pa(("string"==typeof e?e:void 0)??"Invalid transfer request",ma.INVALID_AMOUNT)}if(403===t)return new pa("Insufficient balance for transfer",ma.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new pa("Token not found",ma.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===yt(e)||"ETIMEDOUT"===yt(e)))return new pa("Transfer request timed out",ma.NETWORK_ERROR);const i=""!==At(e)?At(e):t;return new pa(i,ma.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof Ma)return e;if(s.isGalaError(e)&&"pre_send"===e.phase)return new Ma(`${t}: ${e.message}`,"SIGNING_FAILED"===(r=e.code)?Oa.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===r?Oa.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===r?Oa.INVALID_AMOUNT:Oa.VALIDATION_ERROR,va(n));var r;let i=t,a=Oa.NETWORK_ERROR;if(Tt(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){i=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?a=Oa.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(a=Oa.TOKEN_NOT_FOUND)}}}else vt(e)&&(i=`${t}: ${At(e)}`);return new Ma(i,a,va(n))}}class Ka extends bn{constructor(e,t,n,s=!1,r,i){super(e,s),this.balanceService=new da(e,s),this.tokenService=new Da(e,s,r),this.lockService=new _a(e,t,n,s,i),this.transferService=new Ga(e,t,n,s,i)}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 s.tokenDetailsOf(await this.fetchTokenClassFromChain(e))}catch(t){if(vt(t)&&("NetworkError"===t.name||At(t).includes("Token not found")))throw t;throw It(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:yi(e)}: ${At(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 Wa extends bn{async getHealth(){const e=(await this.http.get(Pe)).data;if(null==e)throw It("Health check answered no data");return e}}class Ha extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function ja(e,t,n){if(null==e)throw new Ha("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Ts.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Ha(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Ha("Filename is required when uploading Buffer objects",t,n);const s=Ss.safeParse(e);if(!s.success){const e=s.error.issues.map(e=>e.message).join("; ");throw new Ha(e,t,n)}try{on(t,255,"filename")}catch(e){throw new Ha(e.message,t,n)}const r=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!r.includes(n))throw new Ha(`Invalid file type "${n}" is not allowed. Allowed types: ${r.join(", ")}`,t,n);const i=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),a=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!a.includes(i))throw new Ha(`File extension "${i}" is not allowed. Allowed extensions: ${a.join(", ")}`,t,n);const o=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(o!==n&&"application/octet-stream"!==o)throw new Ha(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new Ha("File must be a File object (browser) or Buffer (Node.js)",t,n)}function qa(e,t="image",n){const s=new FormData;if("undefined"!=typeof File&&e instanceof File)s.append(t,e);else{if(!Buffer.isBuffer(e))throw _t("file","a File object (browser) or Buffer (Node.js)");{const r=new Blob([e],{type:"image/png"});s.append(t,r,n)}}return s}class za extends bn{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;pn(t,"tokenName",In);const s=`${t}.png`;ja(n.file,s,"image/png");try{const e=qa(n.file,"image",s),r=await Gt(()=>this.http.request({method:"POST",url:Fr(l.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof ft)throw e;if(vt(e)&&At(e).includes("FormData"))throw Ct("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function Va(e){if(hn(e)||"object"!=typeof e)return{};const t={};for(const[n,s]of Object.entries(e))hn(s)||(un(s)?t[n]=s:"number"==typeof s||"boolean"==typeof s?t[n]=s.toString():Array.isArray(s)?t[n]=s.join(","):t[n]="object"==typeof s?JSON.stringify(s):String(s));return t}function Qa(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Xa(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Ja(e){return"string"==typeof e.quantity&&""!==e.quantity}class Ya extends bn{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??Cr.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>tt)throw Rt("pageSize",1,tt,t);const n={pageSize:String(t)};un(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=no("type",e.type,Ze));un(e.tokenName)&&(pn(e.tokenName,"tokenName",_n),n.tokenName=e.tokenName);if(un(e.search)){if(e.search.length>Za)throw function(e,t,n,s){const r=kt(e,s);return new dt(`${r} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}("search",Za,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(un(e.language)){if(!to.test(e.language))throw _t("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>eo)throw Rt("recentlyStreamed",1,eo,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=no("streamStatus",e.streamStatus,et));if(void 0!==e.isGraduated){if("boolean"!=typeof e.isGraduated)throw Lt("isGraduated","boolean",e.isGraduated);n.isGraduated=e.isGraduated?"true":"false"}void 0!==e.creatorAddress&&(n.creatorAddress=function(e){if("string"!=typeof e)throw Lt("creatorAddress","string",e);Zn(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=Bt(await Wt(()=>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:Rr(n?.pageInfo)}}async fetchAllPools(e){const t=[];let n;for(;;){const s={...e,pageSize:100,...void 0!==n&&{cursor:n}},r=await this.fetchPools(s);if(t.push(...r.items),0===r.items.length)break;const i=Or(r.pageInfo,n);if(void 0===i)break;n=i}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=$s(e);!t.success&&t.errors&&rr(t.errors,"options")}(e),un(e.tokenName)&&pn(e.tokenName,"tokenName",Cn);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===un(e.symbol)){return!n.symbolAvailable}if(!0===un(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,s="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||s.includes("404")||s.includes("Pool not found"))return!1;const r="number"==typeof n.statusCode?n.statusCode:null;if(404===r)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||s.includes("400")||s.includes("Missing required pool identifier"))return!1;if(400===r&&s.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 Ks(t,"tokenName")&&Hs(t,"from")&&Hs(t,"to")&&Hs(t,"resolution")}(e))throw new dt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:s,resolution:r}=e;if(pn(t,"tokenName",_n),null==n||null==s||null==r)throw new dt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:s,resolution:r};ar(i);const a=Va(i),o=await Gt(()=>this.http.get(l.CHART,a),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(o.data)||"boolean"!=typeof o.isPreviousData)throw new mt("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:o.data,isPreviousData:o.isPreviousData,..."number"==typeof o.nextTime&&{nextTime:o.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw Nt("tokenName","Token name");let t;pn(e,"tokenName",_n);try{t=await Wt(()=>this.http.get(`${l.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(Tt(t)&&500===t.response?.status)throw It(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,vt(t)?t:void 0);throw t}return function(e,t,n=Qs){if(!Array.isArray(e))throw It("Invalid API response: expected array of holders",t);for(const n of e){if(!Xa(n))throw It("Invalid holder data: missing or invalid owner field",t);if(!Ja(n))throw It("Invalid holder data: missing or invalid quantity field",t);const e=en(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw It(`Invalid holder quantity: "${n.quantity}"`,t)}const s=e,r=s.reduce((e,t)=>e.plus(t.quantity),Vs(0));return{holders:s.map(e=>({address:e.owner,balance:e.quantity,percentage:Zs(Vs(e.quantity),r,Vs(0)).multipliedBy(100).toNumber()})),totalSupply:n(r),totalHolders:s.length,lastUpdated:new Date}}(Bt(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Nt("tokenName","Token name");if(""===t||null==t)throw Nt("userAddress","User address");return pn(e,"tokenName",_n),Gt(()=>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");pn(e,"tokenName",In);try{const t=l.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=Bt(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 mt?new mt(`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&&pn(e.tokenName,"tokenName",Cn);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(!un(e))throw Nt("tokenName","Token name");pn(e,"tokenName",In);const t=l.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=Bt(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 Nt("tokenName","Token name");pn(e,"tokenName",In),function(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 dt("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",nt);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw Lt("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Lt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Lt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Lt("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 Lt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Lt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new dt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",it)}}(t);const n=l.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),s={};void 0!==t.chatEnabled&&(s.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(s.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(s.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(s.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(s.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(s.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(s.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(s.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(s.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(s.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(s.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(s.tiktokUrl=t.tiktokUrl),await this.http.patch(n,s,this.getJwtHeaders())}async getTokenConfig(e){if(!un(e))throw Nt("tokenName","Token name");pn(e,"tokenName",In);const t=l.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=Bt(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const Za=255,eo=720,to=/^[a-z]{2}(-[A-Z]{2})?$/u;function no(e,t,n){const s="string"==typeof t?t.toUpperCase():void 0,r=n.find(e=>e===s);if(void 0===r)throw Ft(e,t,n);return r}function so(e){if(void 0!==e.tokenName){if(!un(e.tokenName))throw Lt("tokenName","a non-empty string",typeof e.tokenName);vn(e.tokenName,"tokenName",_n)}if(void 0!==e.userAddress){if(!un(e.userAddress))throw Lt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>Un)throw Mt("userAddress",Un,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Lt("search","a string",typeof e.search);if(e.search.length>256)throw Mt("search",256,e.search.length)}if(gn(0,void 0,Mn,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw _t("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!un(e.startDate))throw Lt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw _t("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!un(e.endDate))throw Lt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw _t("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{an(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw _t("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{an(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw _t("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const s="number"==typeof e?e:Number(e),r="number"==typeof t?t:Number(t);if(isNaN(s)||isNaN(r))throw Lt(n,"numeric values",void 0,n);if(s>r)throw new dt(`Minimum value (${s}) must be less than or equal to maximum value (${r}) for ${n}`,n,ct)}(e.minAmount,e.maxAmount,"amountRange")}class ro extends bn{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 Ks(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Ws(t,"userAddress")&&Hs(t,"offset")&&Hs(t,"pageSize")&&Hs(t,"page")&&Hs(t,"limit")}(e))throw new dt("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:s=Cr.DEFAULT_LIMIT}=e;if(!un(t))throw Nt("tokenName","Token name");const r={pageSize:String(Math.min(s,On))};void 0!==n&&(r.cursor=n);const i=await this.http.get(Fr(l.GET_TRADES,{tokenName:t}),r);if(null==i)throw new dt("No response from trade service","response","NO_RESPONSE");const a=Bt(i),o=Qa(a,"trades"),c=a?.pageInfo;return{items:o,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=qt(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?function(e,t=1,n=Cr.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}(e.pageSize,1,Mn):Mn;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){so(e);const t=this.buildTradesQueryParams(e);return Gt(()=>this.http.get(Ie,t),{errorContext:"Failed to fetch trades"})}}In.MIN_LENGTH,In.MAX_LENGTH;function io(e){return!!un(e)&&Ln.PATTERN.test(e)}function ao(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const s=e.trim();return s.length<n?null:s}mn({BOTH:"both",HELD:"held",CREATED:"created"});function oo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function co(e){return"number"==typeof e&&Number.isFinite(e)}function lo(e){return null===e||"string"==typeof e}function uo(e){return Array.isArray(e)&&e.every(e=>oo(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function ho(e){return oo(e)&&"string"==typeof e.address&&lo(e.fullName)&&lo(e.profileImage)&&lo(e.bio)&&function(e){return oo(e)&&co(e.tokensCreated)&&co(e.tokensGraduated)&&co(e.graduationRate)&&co(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&lo(e.totalVolumeUsd)&&(null===e.holdingsCount||co(e.holdingsCount))&&lo(e.accountCreatedAt)&&co(e.accountAgeDays)}(e.stats)&&uo(e.launchBadge)&&uo(e.successBadge)&&uo(e.volumeBadge)&&uo(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&lo(e.liveStreamToken)}class go extends bn{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!io(t))throw _t("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await Gt(()=>this.http.get(l.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(oo(n=e)&&"string"==typeof n.address&&lo(n.fullName)&&lo(n.profileImage)&&"string"==typeof n.bio&&uo(n.launchBadge)&&uo(n.successBadge)))throw It("Malformed profile response");return e}var n;const s=await Gt(()=>this.http.get(l.GET_PROFILE.replace(":address",t)),{errorContext:"Failed to fetch profile"});if(!ho(s))throw It("Malformed profile response");return s}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 Gt(()=>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=qa(e.file,"image",t),s=await Gt(()=>this.http.request({method:"POST",url:l.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof dt||e instanceof ft)throw e;if(e instanceof mt)throw new mt(`Profile image upload failed: ${At(e)}`,e.statusCode,e);throw new dt(`Profile image upload failed: ${At(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new dt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},s="created"===e.type;s&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const r=await this.buildFetchRequest(l.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:s?"launches":"token",errorMessage:"Failed to fetch token list"});return s&&void 0!==t?{...r,tokens:r.tokens.filter(e=>e.tokenName===t||e.name===t)}:r}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new dt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new dt("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:s,tokenName:r,status:i}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new dt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const a=e?.address??this.http.getAddress();if(null==a||""===a)throw new dt("Wallet address not available - wallet not configured","address","NO_WALLET");const o={type:"created",address:a,pageSize:n??Cr.DEFAULT_LIMIT};return void 0!==t&&(o.cursor=t),void 0!==s&&(o.search=s),void 0!==r&&void 0===s&&(o.search=r),void 0!==r&&(o.tokenName=r),void 0!==i&&(o.status=i),this.fetchTokenList(o)}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,On))),Gt(()=>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 Nt("address","Address");return Gt(()=>this.http.get(Fr(l.GET_GALA_BALANCE,{address:e.trim()})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return Gt(()=>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 s=Lr({pageSize:t.pageSize??Cr.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},On);xr(s,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(s.type=n.requestType);let r=e;const i=t.address??this.http.getAddress();if(e.includes(":address")){if(0===i.length)throw Nt("address","User address");r=e.replace(":address",i),delete s.address}const a=Bt(await Wt(()=>this.http.get(r,s),{errorContext:n.errorMessage}));return{tokens:Qa(a,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",s="string"==typeof e.name?e.name:t,r="string"==typeof e.createdAt?e.createdAt:"",a=e.metadata,o={...e};return delete o.metadata,{...o,id:"string"==typeof e.id?e.id:t,name:s,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:i,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==a&&"object"==typeof a?{metadata:a}:{},createdAt:r,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:r}}),pageInfo:Rr(a?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??Cr.DEFAULT_LIMIT;if(t<1||t>On)throw new dt(`pageSize must be between 1 and ${On}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!io(e.address))throw _t("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=ao(e.search);if(null!==n&&!(un(s=n)&&s.length>=Kn&&s.length<=Wn))throw Rt("search",Kn,Wn,n.length,"Search query");var s;const r=ao(e.tokenName);if(!(null===r||un(i=r)&&In.PATTERN.test(i)))throw _t("tokenName",In.DESCRIPTION,"Token name");var i}validateUpdateProfileData(e){if(void 0!==e.address&&!io(e.address))throw _t("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new dt("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(un(t)&&t.length>=Hn.FULL_NAME.MIN_LENGTH&&t.length<=Hn.FULL_NAME.MAX_LENGTH&&Hn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw Rt("fullName",Hn.FULL_NAME.MIN_LENGTH,Hn.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new dt("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!io(e.address))throw _t("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class mo{constructor(e,t,n=!1){this.http=e,this.poolService=new Ya(e,t,n),this.tradeService=new ro(e,n),this.userService=new go(e,t,n),this.imageService=new za(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 ir(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)}}const fo={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};class po extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateContent(e,t){if(!un(e))throw Nt("content","Message content");if(0===e.trim().length)throw Nt("content","Message content");on(e,t===fo.CHAT_MESSAGE?Fn.CHAT_MESSAGES_V1.MAX_LENGTH:Fn.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!un(e))throw Nt("id","Message ID");if(e.length<10||e.length>64)throw _t("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==fo.CHAT_MESSAGE&&e!==fo.COMMENT)throw new dt(`type must be one of: ${Object.values(fo).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,_n);const s={};void 0!==e.cursor&&(s.cursor=e.cursor),s.pageSize=e.pageSize??Cr.DEFAULT_LIMIT;const r=Lr(s,Mn),i={};void 0!==r.pageSize&&(i.pageSize=r.pageSize),void 0!==r.cursor&&(i.cursor=r.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=qt(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(i.search=e.search);const a=await this.http.get(Ce.GET_MESSAGES,i),o=this.extractData(a);return{messages:o.messages,pageInfo:o.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,_n),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:qt(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),s={content:t.content.trim()},r=await this.http.put(n,s,this.getJwtHeaders());return{message:this.extractData(r)}}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,In);const t=await this.http.get(Ce.GET_PINNED,{tokenName:qt(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 It("Malformed message statistics response");const s=e.totalMessages,r=e.todayMessages,i=e.uniqueUsers,a=e.uniqueTokens,o=e.messagesByType;if(!(t(s)&&t(r)&&t(i)&&t(a)&&n(o)))throw It("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(o)){if(!t(n))throw It("Malformed message statistics response");c[e]=n}return{totalMessages:s,todayMessages:r,uniqueUsers:i,uniqueTokens:a,messagesByType:c}}(await this.http.get(Ce.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const vo=fn({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),Ao={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},Eo=fn(Ao),yo={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};fn(yo);class To extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateRole(e){if(!un(e))throw Nt("role","Role");if(!function(e){return vo.includes(e)}(e))throw _t("role",`one of: ${vo.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!un(e))throw Nt("inviteCode","Invite code");if(e.length>Gn)throw _t("inviteCode",`at most ${String(Gn)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&(t=e,!Eo.includes(t)))throw new dt(`Invalid invite scope. Must be one of: ${Eo.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??Ao.TOKEN;if(t===Ao.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new dt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,_n)}else if(t===Ao.ALL_OWNER_TOKENS&&e.tokenName)throw new dt("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",Fn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=j,s={inviteScope:t,role:e.role};t===Ao.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(s.tokenName=qt(e.tokenName)),void 0!==e.description&&(s.description=e.description),void 0!==e.expiresAt&&(s.expiresAt=e.expiresAt);const r=await this.http.post(n,s,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,_n),this.validateStatusFilter(e.status,yo);const t=V,n={...this.buildPaginationParams(e,Mn)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=qt(e.tokenName)),void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.invites,pageInfo:r.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Q,{id:String(e)});Pt(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},s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new dt("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",Fn.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 s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=q,n={inviteCode:e.inviteCode},s=await this.http.post(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return"tokenName"in r&&void 0!==r.tokenName?{token:r}:{blanketAccess:r}}async getModeratedTokens(e){const t=z,n=this.buildPaginationParams(e??{},Mn),s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.tokens,pageInfo:r.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Y,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const So="10000",bo="1000";function ko(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function wo(){return Date.now()+6e4}function No(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function _o(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Io(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class Co extends bn{constructor(e){super(e)}getCollectionClaimFee(){return So}getTokenClassCreateFee(){return bo}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(!Io(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=So;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const s=bo,r=String(BigInt(s)*BigInt(e.createTokenClasses));n.tokenClassCreate=s,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(r))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!No(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:wo(),uniqueKey:ko("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),!Io(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),!No(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(!No(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?_o(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?_o(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:wo(),uniqueKey:ko("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),!No(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(!Io(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 s={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:wo(),uniqueKey:ko("mint")};this.logger.debug("Built mint DTO",s);const r=`mint-${Date.now()}`,i=Array.from({length:t},(e,t)=>t+1);return{transactionId:r,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:i,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}),!Io(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}=ca(async(e,t)=>({data:await this.http.post(e,t)}));return new s.GatewayReads({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class Do extends bn{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(qe,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),s=this.extractData(n);return this.logger.debug("Push token registered",{registered:s.registered}),s}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:ze,data:{token:e},headers:t}),s=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:s.unregistered}),s}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(Ve,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(Qe,e,t),s=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:s.tradesEnabled,streamsEnabled:s.streamsEnabled}),{preferences:s}}}class Ro extends bn{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 dt("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()),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:s.title}),{oembed:s}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new dt("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()),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:s}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new dt("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())),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:s.title}),{oembed:s}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new dt("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())),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:s}}}function Oo(e){if(!un(e))throw Nt("address","Address")}const Mo={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Lo={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Uo=mn(Mo),Fo=mn(Lo);function xo(e){try{En(e.description,"description",255)}catch(e){if(e instanceof dt){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(!un(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{yn(e.expiresAt,"expiresAt")}catch(e){if(e instanceof dt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Zt(e.expiresAt)){if(function(e){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())?(Yt.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return Yt.warn(`Date parsing error for "${e}":`,t),new Date}}(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function Po(e){if(!un(e))throw new Error("Address must be a non-empty string");try{es(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Bo(e){try{cn(e,"id")}catch(e){if(e instanceof dt)throw new Error("Invite ID must be a positive integer");throw e}}class $o extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateInviteCodeFormat(e){if(!un(e))throw Nt("inviteCode","Invite code");!function(e){if(!un(e))throw new Error("Invite code must be a non-empty string");on(e,Gn,"code")}(e)}validateWalletAddressFormat(e){if(!un(e))throw Nt("address","Address");Po(e)}async createInvite(e={}){xo(e),this.validateOptionalString(e.description,"description","Description",Fn.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 s=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e={}){!function(e){if(void 0!==e.status&&!Uo(e.status))throw Ft("status",e.status,Object.values(Mo),"status");gn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Mo);const t=te,n={...this.buildPaginationParams(e,Mn)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.invites,pageInfo:r.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){Bo(e);const t=this.buildEndpoint(re,{id:String(e)});Pt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=se,n={inviteCode:e},s=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(s)}}async listOverseers(e={}){!function(e){if(void 0!==e.status&&!Fo(e.status))throw Ft("status",e.status,Object.values(Lo),"status");gn(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Lo);const t=ie,n={...this.buildPaginationParams(e,Mn)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.overseers,pageInfo:r.pageInfo}}async createOverseerDirect(e){!function(e){if(null==e||"object"!=typeof e)throw new dt("Options are required");if(!un(e.userAddress))throw new dt("userAddress is required and must be a non-empty string");try{es(e.userAddress,"userAddress")}catch{throw new dt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new dt("description must be a string");if(e.description.length>255)throw new dt("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",Fn.DESCRIPTION.MAX_LENGTH);const t=ae,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const s=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(s)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(oe,{address:e});Pt(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=me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&function(e){if(null==e||"object"!=typeof e)throw new dt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new dt("Search must be a string");if(0===e.search.length)throw new dt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new dt("Sort field must be a string");if(0===e.sortBy.length)throw new dt("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 dt('Sort order must be "asc" or "desc"')}}(t);const n=fe,s=this.buildPaginationParams(t,Mn);void 0!==t.search&&""!==t.search&&(s.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(s.sortBy=t.sortBy),void 0!==t.sortOrder&&(s.sortOrder=t.sortOrder);const r=await this.http.get(n,s,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.users,pageInfo:i.pageInfo}}async getOverseerUserSummary(e){if(!un(e))throw Nt("address","User address");Po(e);const t=this.buildEndpoint(pe,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Oo(e);const t=this.buildEndpoint(ve,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!un(e))throw Nt("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 dt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ee,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Oo(e);const t=this.buildEndpoint(ye,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Te,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}class Go extends bn{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),Pt(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(k);return this.extractData(e)}async updatePlatformConfig(e){const t=function(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}(e);if(t.length>0)throw new dt(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 Ko extends bn{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($e),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class Wo extends Br{constructor(e,t,n,s){super(e,t,n,!1,s)}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 dt("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 Ho extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getChatStatus(e){if(null==e||""===e)throw Nt("tokenName","Token name");return this.validateTokenName(e,In),Er(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 Nt("tokenName","Token name");return this.validateTokenName(e,In),Er(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 Nt("tokenName","Token name");return this.validateTokenName(e,In),Er(async()=>{const t=this.buildEndpoint(Me,{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??qt(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 Nt("tokenName","Token name");if(this.validateTokenName(e,In),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Er(async()=>{const n=this.buildEndpoint(Ue,{tokenName:e}),s=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(s)},`Failed to set slow mode for token: ${e}`,this.logger)}}mn({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),mn({PREPARING:"preparing",READY:"ready",ERRORED:"errored"});const jo=mn({YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"});const qo={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};mn(qo),mn({OWNER:"OWNER",MODERATOR:"MODERATOR"});function zo(e,t="tokenName"){pn(e,t,In)}mn({...qo,OVERSEER:"OVERSEER"});const Vo=/^rtmps?:\/\/\S+$/u,Qo=255;function Xo(e){if(zo(e.tokenName),!un(e.language))throw Nt("language");if(t=e.language,!un(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new dt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",it);var t}class Jo extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async startStream(e){this.validateTokenName(e,In);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,In);const t=this.buildEndpoint(m,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,f,In)}async enableStream(e){return this.toggleFeature(e,p,In)}async resetStreamKey(e){this.validateTokenName(e,In);const t=this.buildEndpoint(v,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,In);const t=this.buildEndpoint(D,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){zo(e.tokenName)}(e);const t=this.buildEndpoint(A,{tokenName:e.tokenName}),n=await this.http.get(t),s=this.extractData(n);if(!Array.isArray(s))throw It("Invalid recordings response: expected an array of recordings");return{recordings:s,tokenName:qt(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,In),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(E,{tokenName:e,assetId:t}),s=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(s)}async deleteRecording(e,t){this.validateTokenName(e,In),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(y,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,In);const t=this.buildEndpoint(T,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),s=this.extractData(n);if(!Array.isArray(s))throw It("Invalid simulcast response: expected an array of targets");return{targets:s,tokenName:qt(e)}}async addSimulcastTarget(e){!function(e){if(zo(e.tokenName),!un(e.platform))throw Nt("platform");if(!jo(e.platform))throw new dt("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",rt);if(!un(e.url))throw Nt("url");if(!Vo.test(e.url))throw new dt("url must be a valid RTMP or RTMPS URL","url",it);if(e.url.length>2048)throw new dt(`url must not exceed ${String(2048)} characters`,"url",at);if(!un(e.streamKey))throw Nt("streamKey");if(e.streamKey.length>Qo)throw new dt(`streamKey must not exceed ${String(Qo)} characters`,"streamKey",at);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new dt("passthrough must be a string","passthrough",st);if(e.passthrough.length>Qo)throw new dt(`passthrough must not exceed ${String(Qo)} characters`,"passthrough",at)}}(e);const t=this.buildEndpoint(S,{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:qt(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,In),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(k);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(N,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(zo(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||un(e.nextLiveStreamAt)))throw new dt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",st);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new dt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",it)}}}(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,In);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Xo(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){zo(e.tokenName)}(e);const t=this.buildEndpoint(_,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},s=await this.http.get(t,{},n);return this.extractData(s)}async getAvailableRoles(){const e=await this.http.get(I);return this.extractData(e)}async getTokenAccess(e){!function(e){zo(e.tokenName)}(e);const t=await this.http.get(C,{tokenName:qt(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const Yo="subscribe_token",Zo="unsubscribe_token",ec="subscribe_comment",tc="unsubscribe_comment",nc="subscribe_global_feed",sc="unsubscribe_global_feed",rc="subscribe_events_firehose",ic="unsubscribe_events_firehose",ac="authenticate",oc="send_stream_chat",cc="SEND_STREAM_REACTION",lc="typing_start",dc="typing_stop",uc=e=>hc(e.flagId);function hc(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function gc(e,t){const n=t.map(t=>hc(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const mc={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=>hc(e.id)},FLAG_RESOLVED:{duplicateKey:e=>gc(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:uc},AI_MODERATION_FAILED:{duplicateKey:uc},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>gc(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>gc(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>gc(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 fc(e){return mc[e]}const pc=Object.keys(mc);const vc="token:",Ac="comment:",Ec="global:feed",yc="global:events_firehose";function Tc(e){if(e.startsWith(vc)){const t={tokenName:e.slice(vc.length)};return{join:{event:Yo,payload:t},leave:{event:Zo,payload:t}}}if(e.startsWith(Ac)){const t={tokenName:e.slice(8)};return{join:{event:ec,payload:t},leave:{event:tc,payload:t}}}return e===yc?{join:{event:rc},leave:{event:ic}}:{join:{event:nc},leave:{event:sc}}}const Sc=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const bc={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},kc=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],wc=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"]),Nc=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const _c={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"},Ic={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"},Cc=()=>{};function Dc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Rc(e,t){return t}function Oc(e){return`${vc}${e}`}function Mc(e){return`${Ac}${e}`}function Lc(e){const t=qt(e);if(""===t)throw Nt("tokenName","Token name");return t}class Uc extends kn{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 ft("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 a.io}register(e,t,n={}){if(this.disposed)return Cc;const s={name:e,deliver:t,token:n.token,filter:n.filter,room:n.room,active:!0};let r=this.subscribers.get(e);return void 0===r&&(r=new Set,this.subscribers.set(e,r)),r.add(s),void 0!==n.room&&this.acquireRoom(n.room),this.openIfNeeded(),()=>{this.release(s)}}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 Cc;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: ${At(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,s=this.roomStates.get(e);if(n&&void 0===s){if(function(e){return e===yc}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==s?.phase||(t.emit(Tc(e).leave.event,Tc(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 s=Tc(t).join;e.emit(s.event,s.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(vc)?e.slice(vc.length):e;for(const s of n)clearTimeout(s.timer),s.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((!Dc(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,Dc(t)?function(e,t){const n=fc(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(vc)?e.slice(vc.length):void 0}const s=t.tokenName;return"string"==typeof s&&""!==s?s:void 0}(e,t):void 0),Dc(t)))for(const n of function(e,t){if("TOKEN_CONFIG_UPDATED"!==e)return[];const n=t.tokenName;if("string"!=typeof n)return[];const s=[];if("nextLiveStreamAt"in t){const e=t.nextLiveStreamAt;s.push({name:"STREAM_COUNTDOWN_UPDATED",payload:{tokenName:n,nextLiveStreamAt:"string"==typeof e?e:null}})}const r=t.streamLanguage;return"string"==typeof r&&s.push({name:"STREAM_LANGUAGE_UPDATED",payload:{tokenName:n,language:r}}),s}(e,t))this.deliver(n.name,n.payload,n.payload.tokenName)}isDuplicate(e,t){const n=fc(e).duplicateKey?.(t);if(void 0===n)return!1;const s=Date.now(),r=`${e}:${n}`,i=this.recentOccurrences.get(r);if(void 0!==i&&s-i<5e3)return!0;if(this.recentOccurrences.set(r,s),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)s-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const s=this.subscribers.get(e);if(void 0===s)return;const r=void 0===n?void 0:qt(n);for(const n of[...s])n.active&&(void 0!==n.token&&n.token!==r||(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 s=t(n);s instanceof Promise&&s.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 Sc.has(e)}(e))Dc(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=bc[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:Fc(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new ft("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new ft('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,s)=>{e=n,t=s});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=a.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 pc)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: ${At(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?Cc:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?Cc:(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: ${At(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(Nt("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,s=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===s&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:s},s}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: ${At(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const s=this.liveSocket();if(t!==this.authSequence||null===s)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const r=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),s.emit(ac,{token:n});return await r.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const s=new Promise(e=>{n=e}),r={seq:e,token:t,generation:this.connectionGeneration,result:s,settled:s.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(r,e,n)}};return r.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),r.settle(!1)},this.config.subscriptionTimeout),this.inFlight=r,r}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const s=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&s&&this.markAuthenticated(e.token,e.generation),n(t&&s)}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 dt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new dt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw Nt("tokenName","Token name");if(""===t)throw Nt("content","Message content");const n=this.requireReady(),s=qt(e);this.logger.debug(`📡 Sending chat message to ${s}: ${t.slice(0,30)}...`),n.emit(oc,{tokenName:s,content:t})}sendReaction(e,t,n=0){if(""===e)throw Nt("tokenName","Token name");if(""===t)throw Nt("emoji");const s=this.requireReady(),r=qt(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),s.emit(cc,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,lc)}sendTypingStop(e){this.sendTypingEvent(e,dc)}sendTypingEvent(e,t){if(""===e)throw Nt("tokenName","Token name");this.requireReady().emit(t,{tokenName:qt(e)})}subscribeToken(e,t,n){const s=Lc(t);return this.register(e,e=>n(Rc(0,e)),{token:s,room:Oc(s)})}joinTokenRoom(e){return this.hold(Oc(Lc(e)))}subscribeComment(e,t,n){const s=Lc(t);return this.register(e,e=>n(Rc(0,e)),{token:s,room:Mc(s)})}subscribeFeed(e,t){return this.register(e,e=>t(Rc(0,e)),{room:Ec})}subscribeEvent(e,t){return this.register(e,e=>t(Rc(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:qt(e.tokenName),s=e.userAddress?.toLowerCase();return void 0!==t||void 0!==n||void 0!==s?e=>{if(!Dc(e))return!1;const r=e.eventType;if(void 0!==t&&("string"!=typeof r||!t.includes(r.toLowerCase())))return!1;const i=e.tokenName;if(void 0!==n&&("string"!=typeof i||qt(i)!==n))return!1;const a=e.userAddress;return void 0===s||"string"==typeof a&&a.toLowerCase()===s}:void 0}(t);return this.register("EVENT",t=>e(Rc(0,t)),{room:yc,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=kc.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:Rc(0,t)}}(t,n)),{room:Ec}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,Ic,()=>({})),n=this.hold(Ec);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,_c,()=>({}))}registerCallbacks(e,t,n){const s=[],r={...e};for(const[e,i]of Object.entries(t)){const t=r[e];"function"==typeof t&&s.push(this.register(i,e=>Reflect.apply(t,void 0,[e]),n(i)))}return()=>{for(const e of s)e()}}async subscribeToStream(e,t={}){const n=Lc(e),s=Oc(n),r=this.epoch;if(await this.connect(),r!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const i=this.registerCallbacks(t,_c,e=>{return t=e,wc.has(t)?{token:n}:function(e){return Nc.has(e)}(e)?{token:n,room:Mc(n)}:{};var t}),a=this.hold(s),o={release:()=>{i(),a()}},c=this.explicitHolds.get(n)??[];c.push(o),this.explicitHolds.set(n,c);try{return await this.waitForRoom(s,n)}catch(e){throw this.dropExplicitHold(n,o),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,s)=>{const r={resolve:n,reject:s,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(r),s(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},i=this.roomWaiters.get(e)??new Set;i.add(r),this.roomWaiters.set(e,i)})}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=qt(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(vc)&&e.push(t.slice(vc.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(Ec)??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 Fc(e){if(!Dc(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function xc(e){if(pn(e.tokenName,"tokenName",_n),!(null==(t=e.reason)||""===t||"string"==typeof t&&!An(t)&&t.length<=Fn.BAN_REASON.MAX_LENGTH))throw new dt(`reason must be at most ${Fn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class Pc extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async banToken(e){xc(e);const t=Se,n={tokenName:qt(e.tokenName)};if(void 0!==e.reason)try{ln(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const s=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(s),tokenName:qt(e.tokenName)}}async unbanToken(e){!function(e){pn(e.tokenName,"tokenName",In)}(e);const t=this.buildEndpoint(we,{tokenName:e.tokenName});return Pt(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:qt(e.tokenName)}}async listTokenBans(e={}){!function(e){gn(0,void 0,Rn,e.pageSize)}(e);const t=be,n=this.buildPaginationParams(e,Rn);this.addOptionalFilterParams(n,e,["search"]);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getTokenBan(e){!function(e){pn(e.tokenName,"tokenName",In)}(e);const t=this.buildEndpoint(ke,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},tokenName:qt(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class Bc extends kn{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(!un(e))throw Nt("tokenName","Token name");const t=qt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null!==s&&""!==s){const e=this.parseVaultAddressToTokenClassKey(s);this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:e,cachedAt:Date.now()})}return s}async resolveTokenClassKey(e){if(!un(e))throw Nt("tokenName","Token name");const t=qt(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null===s||""===s)throw wt(e);const r=this.parseVaultAddressToTokenClassKey(s);return this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:r,cachedAt:Date.now()}),r}get(e){const t=this.getCacheEntry(qt(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=Bc.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=qt(e),s=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:s,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:Bc.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(qt(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:s}of e){const e=qt(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:s,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Si(e)}catch(e){if(e instanceof dt)throw _t("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}Bc.MAX_CACHE_SIZE=1e4;class $c extends bn{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await Gt(()=>this.http.get(Ge),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new dt("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return Gt(()=>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 nr(await Gt(()=>void 0===n?this.http.get(We,t):this.http.request({method:"GET",url:We,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return nr(await Gt(()=>this.http.get(He,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class Gc extends Br{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async emitTradeExecuted(e,t){this.validateTokenName(e,Dn);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,Dn);const s={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(s)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Dn);const s={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Dn);const s={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Dn);const s={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Dn);const s={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Dn);const s={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Dn);const s={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTokenBanned(e,t){this.validateTokenName(e,Dn);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Dn);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Dn);const s={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Dn);const s={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}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 s=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(s)}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 ft("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,Dn);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const s=await this.getConnectedClients(n);return{clients:s.clients,count:s.summary.totalConnected,authenticatedCount:s.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,Dn);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Dn);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Dn);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class Kc{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 Wc{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 s=n??this.defaultTtlMs,r={value:t};s>0&&(r.expiresAt=Date.now()+s),this.cache.set(e,r)}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 Hc extends kn{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 Kc({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Wc(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),Hc.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof a.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)=>{Er(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:",At(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=a.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],s=n.status??n.Status;"string"==typeof s&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${s}`),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=vt(e)?e:new Error(At(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 s=this.config.timeout??3e5,r=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(s/1e3),r={transactionId:e,status:Nr.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(r),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},s);if(this.timeouts.set(e,r),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:Nr.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 s=t,r=s?.data,i=s?.status??s?.Status??r?.status??r?.Status;let a=s?.message??s?.Message??r?.message??r?.Message??s?.error??r?.error;un(a)||(a=i===wr.FAILED||i===wr.ERROR?"Transaction failed - check transaction details":i===wr.COMPLETED||i===wr.PROCESSED||i===wr.SUCCESS?"Transaction completed successfully":null!=i?`Transaction status: ${String(i)}`:"Unknown transaction status");const o=s?.blockHash??r?.blockHash,c=s?.gasUsed??r?.gasUsed,l=s?.Data??r?.Data,d={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof a?a:"Transaction update received",timestamp:Date.now(),...null!=o?{blockHash:o}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(i)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(a)}"`),n(d),d.status===Nr.COMPLETED||d.status===Nr.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===Nr.COMPLETED?t(e):e.status!==Nr.FAILED&&e.status!==Nr.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return _r[t]??Nr.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")),Hc.instances.delete(this)}static cleanupAll(e=!1){for(const e of Hc.instances)e.disconnect();Hc.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}Hc.instances=new Set;class jc extends bn{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 dt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},s=await this.http.get(je.GET_LEADERBOARD,n),r=this.extractData(s);return this.logger.debug("Fetched weekly challenge leaderboard",{count:r.count}),{leaderboard:r}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new dt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=je.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),s=await this.http.get(n),r=this.extractData(s);return this.logger.debug("Fetched token weekly history",{count:r.length}),{snapshots:r}}}const qc=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class zc{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 Vc{constructor(e){this.bundleBaseUrl=rl(e.bundleBaseUrl),this.launchpadBaseUrl=rl(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>a.io(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:s,tokenName:r}=e;if("string"!=typeof t||""===t)throw Xc("bundleId");if(i=n,!qc.some(e=>e===i))throw Xc("method");var i;if("string"!=typeof s||""===s)throw Xc("uniqueKey");if(void 0!==r&&("string"!=typeof r||""===r))throw Xc("tokenName");if("CreateSale"===n&&void 0===r)throw Xc("tokenName");const a={method:n,dto:{uniqueKey:s,...void 0===r?{}:{tokenName:r}},stringsInstructions:[]};return new zc({bundleId:t,uniqueKey:s,method:n,wait:e=>this.waitForResult(a,t,e)})}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){throw function(e){if(e instanceof oi)return e;if(s.isWalletUserRejection(e)){const t=e instanceof Error?e.message:"The signature was rejected in the wallet.",n=s.walletDeclineCode(e);return new oi(t,"WALLET_USER_REJECTED",{details:void 0===n?{}:{walletCode:n}})}const t=e instanceof Error?e.message:"Launchpad signing failed.";return new oi(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}(e)}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),r=`${this.bundleBaseUrl}/bundle`,i=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 nl(i);if(!i.ok)throw Yc(i.status,a,r);const o=function(e){if("string"==typeof e&&""!==e)return e;if(!sl(e))throw new oi("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(sl(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new oi("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(a),c=tl(e.dto,"uniqueKey");return new zc({bundleId:o,uniqueKey:c,method:e.method,wait:t=>this.waitForResult(e,o,t)})}waitForResult(e,t,n={}){const s=n.timeoutMs??6e4,r=n.pollIntervalMs??2500,i=n.signal;return new Promise((n,a)=>{const o=this.confirmationUrl(e,t);if(!0===i?.aborted)return void a(Qc(e.method,t));const c=Date.now(),l=new AbortController,d=void 0===this.bundleSocketFactory;let u,h,g,m=!1;const f=()=>{p(()=>a(Qc(e.method,t)))},p=e=>{m||(m=!0,clearTimeout(A),i?.removeEventListener("abort",f),l.abort(),void 0!==u&&(void 0!==h&&u.off(t,h),d&&u.disconnect()),e())},v=()=>{p(()=>a(function(e,t){const n="string"==typeof e.dto.uniqueKey?e.dto.uniqueKey:"";return new oi(`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)))};i?.addEventListener("abort",f,{once:!0});const A=setTimeout(v,s);try{u=(this.bundleSocketFactory??this.socketFactory)(this.bundleBaseUrl),h=e=>{const t=function(e){if(!sl(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(e);void 0!==t&&p(()=>{"FAILED"===t.status?a(Jc(t.data)):n(t)})},u.on(t,h)}catch{u=void 0,h=void 0}this.pollConfirmation({request:e,confirmationUrl:o,startedAt:c,timeoutMs:s,pollIntervalMs:r,signal:l.signal,onReadFailure:e=>{g=e}}).then(e=>{void 0===e?v():p(()=>n(e))},e=>p(()=>a(e instanceof Error?e:new Error(String(e)))))})}confirmationUrl(e,t){return"CreateSale"===e.method?function(e,t){const n=tl(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:s,timeoutMs:r,pollIntervalMs:i,signal:a,onReadFailure:o}=e;for(;!a.aborted&&Date.now()-s<=r;){const e=await this.readConfirmation(t,n,a);if(a.aborted)return;if("processed"===e.kind)return e.result;if("failed"===e.kind)throw Jc(e.data);o("read-failed"===e.kind?e.error:void 0);const c=r-(Date.now()-s);if(c<=0)break;await il(Math.min(Math.max(0,i),c),a)}}async readConfirmation(e,t,n){try{const s=await this.requestor(t,{method:"GET",signal:n}),r=await nl(s);if("CreateSale"===e.method)return s.ok?{kind:"processed",result:{status:"PROCESSED",data:el(r)}}:404===s.status||202===s.status?{kind:"pending"}:{kind:"read-failed",error:Yc(s.status,r,t)};if(!s.ok)return{kind:"read-failed",error:Yc(s.status,r,t)};const i=sl(r)?r.status:void 0;return"COMPLETED"===i||"PROCESSED"===i?{kind:"processed",result:{status:"PROCESSED",data:r}}:"FAILED"===i?{kind:"failed",data:r}:{kind:"pending"}}catch(e){const n=e instanceof Error?e.message:"The bundle confirmation read failed.";return{kind:"read-failed",error:new oi(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function Qc(e,t){return new oi("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 Xc(e){return new oi(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function Jc(e){const t=Zc(e)??"Launchpad bundle failed on chain.";return new oi(t,"BUNDLE_FAILED",{chainMessage:t})}function Yc(e,t,n){const s=Zc(t)??`Bundle request failed with HTTP ${e}`;return new oi(s,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:s,details:{body:t,url:n}})}function Zc(e){if("string"==typeof e&&""!==e)return e;if(sl(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(sl(n)){const e=Zc(n);if(void 0!==e)return e}}}function el(e){return sl(e)?e.data??e.Data??e:e}function tl(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new oi(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function nl(e){try{return await e.json()}catch{return e.text()}}function sl(e){return"object"==typeof e&&null!==e}function rl(e){return e.replace(/\/$/u,"")}function il(e,t){return new Promise(n=>{if(t.aborted)return void n();const s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t.removeEventListener("abort",s),n()},e);t.addEventListener("abort",s,{once:!0})})}function al(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=vi(t).type,s=await e.findTokenNameByVault(t,n);if(void 0===s)throw new dt(`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 s}(e,t.vaultAddress);return function(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new dt(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new dt(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new o(e).multipliedBy(new o(1).plus(new o(String(t)))).decimalPlaces(8,o.ROUND_UP).toFixed()}((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 ol="0.1",cl="0.5",ll=/^(?:\d+\.?\d*|\.\d+)$/u,dl=/^[0-9A-Z]+$/u,ul=/^[A-Za-z0-9]+$/u,hl=new o("0.1"),gl=new o("0.5");function ml(e){if("string"!=typeof e||!ll.test(e))return;const t=new o(e);return t.isFinite()?t.toFixed():void 0}function fl(e){return"string"==typeof e&&""!==e}function pl(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function vl(e,t,n){void 0===n||fl(n)||e.push(`${t} must be a non-empty string`)}function Al(e){const t=[];if("object"!=typeof e||null===e)throw new dt("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},s=n.tokenName;fl(s)?ul.test(s)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const r=n.tokenSymbol;fl(r)?dl.test(r.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const i=n.tokenDescription;fl(i)?i.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const a=n.tokenImage;fl(a)?a.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===ml(c)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])pl(t,e,n[e]);vl(t,"tokenCategory",n.tokenCategory),vl(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??{},s=n.minFeePortion??ol,r=n.maxFeePortion??cl,i=ml(s),a=ml(r);if(void 0===i&&e.push("minFeePortion must be a decimal number"),void 0===a&&e.push("maxFeePortion must be a decimal number"),void 0===i||void 0===a)return;const c=new o(i),l=new o(a);c.isLessThan(hl)&&e.push("minFeePortion must be greater than or equal to 0.1"),l.isGreaterThan(gl)&&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 dt(t.join("; "),"data","VALIDATION_ERROR")}class El{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress,this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){Al(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:ml(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)},s=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:ml(s?.minFeePortion??ol),maxFeePortion:ml(s?.maxFeePortion??cl)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Ei(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 s={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:s,stringsInstructions:Ai(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new dt("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-${i.v4()}-${Date.now()}-${e}`}function Tl(e,t=3e4){return c.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Sl=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function bl(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>bl(e,t+1));if(e instanceof Map){const n={};for(const[s,r]of e.entries()){const e=String(s);n[e]=Sl.has(e.toLowerCase())?"[REDACTED]":bl(r,t+1)}return n}if("object"==typeof e){const n={};for(const[s,r]of Object.entries(e))n[s]=Sl.has(s.toLowerCase())?"[REDACTED]":bl(r,t+1);return n}return e}class kl{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 Qt({debug:this.debug,context:"HttpClient"});const s=t.baseUrl??kr("stage").launchpadBaseUrl,r=t.timeout??6e4;this.axios=Tl(s,r),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 Er(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,s=this.toAxiosConfig(e,n);e.headers&&this.logger.debug("Custom headers provided:",Object.keys(s.headers??{}));const r=e.data instanceof FormData?"[FormData object - multipart/form-data]":bl(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:bl(s.params),data:r,isFormData:e.data instanceof FormData,contentType:s.headers?.["Content-Type"]??"not set"});const i=await this.sendWithSession(e,s,t,n),a=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,s]of Object.entries(e))"string"==typeof s?t[n.toLowerCase()]=s:"number"!=typeof s&&"boolean"!=typeof s||(t[n.toLowerCase()]=String(s));return t}(i.headers);return this.logger.debug("Response:",{status:i.status,data:bl(i.data),transactionId:a["x-transaction-id"],blockNumber:a["x-block-number"]}),{data:i.data,headers:a,status:i.status}},`HTTP ${e.method} ${e.url}`,this.logger)}toAxiosConfig(e,t){const n=null===t?e.headers:{...e.headers,Authorization:`Bearer ${t}`},s={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Va(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),s.headers=e,this.logger.debug("FormData detected - clearing the JSON Content-Type default for the multipart upload")}return s}async sendWithSession(e,t,n,s){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 r=await this.session.onUnauthorized(s);if(null===r)throw t;return this.logger.debug("Retrying once with the refreshed session token"),await this.axios.request(this.toAxiosConfig(e,r))}}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 Er(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,s={message:n?.message??At(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=s,this.logger.error("Backend error:",s)}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 wl extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Nl 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 _l(e,t){if(hn(e))throw new wl(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new wl(`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 wl(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Il(e,t,n,s){_l(e,t);const r=e,i=r.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)}(i))throw new wl(`Invalid trade data received for transaction ${t}`);const a={transactionId:t,type:n,method:"native"===s.type?"native":"exact",inputAmount:i.inputQuantity??s.amount,outputAmount:i.outputQuantity??s.expectedAmount??"0",totalFees:i.totalFees??"0",tokenName:s.tokenName,vaultAddress:i.vaultAddress??"",timestamp:Date.now()};return void 0!==r.blockHash&&(a.blockHash=r.blockHash),void 0!==r.gasUsed&&(a.gasUsed=r.gasUsed),void 0!==s.slippageToleranceFactor&&(a.slippageTolerance=s.slippageToleranceFactor),a}function Cl(e){return void 0!==e&&n.isPrivateKeyProvider(e)?new t.Wallet(e.exportPrivateKey()):void 0}const Dl={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function Rl(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const Ol=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function Ml(e,t,n){if(void 0===e||void 0===t)return;const s=Ol.exec(e)?.[1],r=Ol.exec(t)?.[1];if(void 0!==s&&void 0!==r&&s.toLowerCase()!==r.toLowerCase())throw Ct(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class Ll{constructor(e){let t,s;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,s=Cl(e.walletProvider)):e.wallet&&(s=e.wallet,t=n.PrivateKeyProvider.fromWallet(e.wallet)),this.wallet=s;const r=e.env??"prod",i=kr(r);this.environment=r,this.config={baseUrl:e.launchpadBaseUrl??i.launchpadBaseUrl,gatewayBaseUrl:i.gatewayBaseUrl,bundleBaseUrl:i.bundleBaseUrl,webSocketUrl:i.webSocketUrl,dexApiBaseUrl:i.dexApiBaseUrl,dexBackendBaseUrl:i.dexBackendBaseUrl,launchpadFrontendUrl:i.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const a=e.signer??(void 0!==s?new mi(s.privateKey):void 0),o=void 0!==s?`eth|${s.address.slice(2)}`:Rl(a);Ml(o,e.walletAddress,"walletAddress"),Ml(o,e.galaChainAddress,"galaChainAddress");const c=e.walletAddress??e.galaChainAddress??(void 0!==s?`eth|${s.address.slice(2)}`:Rl(a)),l=a??{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===s&&void 0!==e.signer&&void 0!==c?{signer:e.signer,walletAddress:c}:void 0;const u=new Vc({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:l,walletAddress:d,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),h=al({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=h,this.launchpad=new El({transport:u,walletAddress:d,sellFeeCeiling:h}),this.logger=new Qt({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Ll.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Ll.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??Ll.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===s?c:void 0),this.auth=new Sr({wallet:s,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 Ct("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw Ct("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===g?new vr:new Ar,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new kl(this.auth,this.config,{signRequests:!0,session:g}),this.sessionAuth=new Tr(this.http,this.auth,this.jwtAuth,e.debug??!1,g);const m={signRequests:!1};this.galaChainHttp=new kl(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},m),this.bundleHttp=new kl(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},m),this.dexApiHttp=new kl(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},m),this.dexBackendHttp=new kl(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},m),this.galaChainPublicAxios=Tl(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Nn(e.debug??!1),this.launchpadService=new mo(this.http,this.jwtAuth),this.tokenResolverService=new Bc(this.launchpadService.poolService),this.launchpadAPI=new lr(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new Ka(this.galaChainHttp,s,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new qi(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new Hc({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new Co(this.galaChainHttp),this.tradingQuotesService=new $c(this.http,e.debug??!1)}createOverrideSdk(e){if(!un(e))throw Ct("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Ct('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t.Wallet(e),s={...this.config,wallet:n};return new Ll(s)}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 Nt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw Nt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new dt("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 Oi(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 Ka(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?Cl(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:s,streamAdminApiKey:r,userApiKey:i,accessToken:a,headers:o,...c}=this.config;return{...c,...void 0!==r&&{streamAdminApiKey:"[REDACTED]"},...void 0!==i&&{userApiKey:"[REDACTED]"},...void 0!==a&&{accessToken:"[REDACTED]"},...void 0!==o&&{headers:Object.fromEntries(Object.keys(o).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:jt.GAS_FEE}}getVersion(){return Ir}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Ct("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),s=Math.min(t,100);return n.holders.slice(0,s).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),s=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===s)return null;const r=n.holders[s];return void 0===r?null:{rank:s+1,balance:r.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),s=t?.minBalance??0,r=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),a=new Map;return n.holders.forEach((e,t)=>{a.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=s&&t<=r}).map(e=>({...e,rank:a.get(e.address)??0})).slice(0,i)}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 dt("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",lt);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 ts}),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(Ct("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,Ct(`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: ${At(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw Ct("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 mi(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new Jo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new Ho(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Vr(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Pc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new $r(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new jc(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new Ro(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Ko(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new Wa(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new oa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new Do(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new Mi(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new Hr(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new To(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new Gi(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new $o(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Gc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Wi(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 ts}),n=t(e);if(void 0===n)throw new dt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new po(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new Wo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new Go(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new Zi(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 Uc({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,s,r]=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"===s.status?s.value:null,..."rejected"===s.status&&{recentTradesError:String(s.reason)},price:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{priceError:String(r.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,s,r)=>(void 0===t.actionType||t.actionType===e)&&((void 0===t.userAddress||t.userAddress===n)&&((void 0===t.tokenName||t.tokenName===s)&&!!(void 0===t.reason||null!==r&&r.includes(t.reason)))),s=this.onUserBanned(t=>{const s=t.userAddress??null,r=t.reason??null;n("BANNED",s,t.tokenName,r)&&e({actionType:"BANNED",userAddress:s,tokenName:t.tokenName,reason:r,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})}),r=this.onUserUnbanned(t=>{const s=t.userAddress??null;n("UNBANNED",s,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:s,tokenName:t.tokenName,reason:null})}),i=this.onBanEnforcement(t=>{const s=t.reason??null;n("ENFORCEMENT",null,t.tokenName,s)&&e({actionType:"ENFORCEMENT",userAddress:null,tokenName:t.tokenName,reason:s,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})});return()=>{s(),r(),i()}}watchTokenRoomEvent(e,t,n,s){const r=s.tokenName;if(void 0===r||""===r)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(r,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),s=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),r=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),i=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()=>{s(),r(),i()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,s=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),r=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),i=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()=>{s(),r(),i()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,s=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),r=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{s(),r()}}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 ts}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Ci}),s=t(e.tokenId),{collection:r,category:i,type:a,additionalKey:o}=s;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:i,additionalKey:o,type:a},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=zt(e.tokenName),s=Dl[t];if(void 0!==s)return this.galaChainService.fetchTokenBalance({owner:n,collection:s,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 s=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:s.collection,category:s.category,tokenId:yi(s)}}throw Nt("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:s,privateKey:r,calculateAmountMode:i,currentSupply:a}=e;let o=t;void 0===i&&void 0===a||(o={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==a&&{currentSupply:a}});const c=await this.calculateBuyAmountForGraduation(o),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!==s&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=s),void 0!==r&&(l.privateKey=r),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,...s}=e;return t.buy(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Dt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Il(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.sell(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Dt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Il(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,...s}=e;return t.launchToken(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{_l(n,t);const s=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)}(s))throw new wl(`Invalid launch data received for transaction ${t}`);const r={transactionId:t,vaultAddress:s.vaultAddress??"",tokenStringKey:s.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:s.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&&(r.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(r.preBuyQuantity=e.preBuyQuantity),""!==r.vaultAddress&&this.tokenResolverService.set(e.tokenName,r.vaultAddress),r})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.uploadTokenImage(s)}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 ts}),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,s=e?.limit??10,r={pageNumber:n,limit:s,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(u,r,{"x-wallet-address":t});if(!Array.isArray(i))throw new mt("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:s,hasMore:i.length===s}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:s,pageSize:r=20,concurrency:i=1,startPage:a=1}=t,o=[];let c=a;const l=a+n-1;let d=!0,u=0;if(i<=1)for(;d&&c<=l;){s&&s.debug(`Auto-pagination: fetching page ${c} with limit ${r}`);const t=await e(c,r);if(null==t||!Array.isArray(t.items)){s&&s.warn("Auto-pagination: received invalid result structure, stopping");break}if(o.push(...t.items),u=t.total,s&&s.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){s&&s.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(s&&s.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);d&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);s&&s.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,r).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return s&&s.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:r,hasNext:!1,hasPrevious:!1};throw e})),a=await Promise.all(n);for(const e of a){if(null==e||!Array.isArray(e.items)){s&&s.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){s&&s.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(o.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,s&&s.debug(`Auto-pagination: batch complete, total items so far: ${o.length}`)}return c>l&&s&&s.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),s&&s.debug(`Auto-pagination: completed with total items: ${o.length}, total count: ${u}`),{items:o,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 mt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ts}),{address:n,...s}=e,r=void 0===n?void 0:t(n),i={...s,...void 0!==r&&{address:r}};if(void 0!==i.privateKey&&""!==i.privateKey){const e=this.createOverrideSdk(i.privateKey),{privateKey:t,...n}=i;return e.updateProfile(n)}return this.launchpadService.updateProfile(i)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ts}),n=void 0===e.address?void 0:t(e.address)??e.address,s={...e,...void 0!==n&&{address:n}};if(void 0!==s.privateKey&&""!==s.privateKey){const e=this.createOverrideSdk(s.privateKey),{privateKey:t,...n}=s;return e.uploadProfileImage(n)}return this.launchpadService.uploadProfileImage(s)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ts}),n=t(e?.address)??this.getAddress(),s={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(s.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(s.search=e.search),this.launchpadService.fetchTokensHeld(s)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ts}),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 ts}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferGala(s)}return this.assertTokenWriter(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return ts}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferToken(s)}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 ts});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,...s}=n;return e.lockTokens(s)}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,...s}=e;return t.unlockTokens(s)}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,...s}=e;return t.burnTokens(s)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let s=0;s<10;s+=1){const s=await this.launchpadService.poolService.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),r=s.items.find(t=>t.vaultAddress===e);if(void 0!==r)return r.tokenName;const i=Or(s.pageInfo,n);if(void 0===i)return;n=i}}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{an(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 Ct("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Ct("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Ct(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Ct(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Ct(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Ct(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Ct(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=en("string"==typeof e||"number"==typeof e?e:String(e),Ll.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${Ll.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Ll.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=en("string"==typeof e||"number"==typeof e?e:String(e),Ll.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: ${Ll.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Ll.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!==Nr.COMPLETED)throw new Nl(e,n.status,n.message);let s;try{s=t(n)}catch(t){if(t instanceof wl)throw t;throw new wl(`Failed to transform WebSocket response for transaction ${e}`,vt(t)?t:new Error(At(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,s),s}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Nl||t instanceof wl)throw t;throw new wl(`WebSocket confirmation failed for transaction ${e}`,vt(t)?t:new Error(At(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Ul});e.forEach(e=>{if(!n(e))return;const s=t(e,this.logger);s&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,s)})}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,s=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 r=t?.creatorAddress,i=new Map;let a=!0,o=null;let c=0;const l=async()=>{if(a){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=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),void 0!==r&&""!==r&&t.creatorAddress!==r||e(t))})}catch(e){c++;const t=At(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(a){const e=Math.min(Math.max(c-1,0),2),t=s*Math.pow(2,e);o=setTimeout(()=>{l()},t)}}};return l(),()=>{a=!1,o&&clearTimeout(o),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 Ct("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,s=null;const r=(n,...s)=>{try{if(s.length>0&&"object"==typeof s[0]&&null!==s[0]){const n=s[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const s=n.Data;if("CreateSale"===s.functionName){const n=(e,t="")=>{const n=s[e];return"string"==typeof n&&""!==n?n:t},r={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===s.isFinalized};this.matchesCreatorFilter(r,t?.creatorFilter)&&e(r)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${At(e)}`)}};let i=this.websocketService.getSocket();if(i)i.onAny(r),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: ${At(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const a=()=>{if(i=this.websocketService.getSocket(),!i&&e<Ll.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(s=setTimeout(()=>a(),Ll.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=Ll.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Ll.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Ll.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(r),n=!0,this.logger.debug("Token creation broadcast listener registered"))};a()}return()=>{try{if(null!==s&&(clearTimeout(s),s=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(r),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 Qt({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),Hc.cleanupAll(e),t.debug("Global cleanup completed")}}Ll.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Ll.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Ll.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=jt.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Ll.DEFAULT_CALCULATE_AMOUNT_MODE="local",Ll.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Ll.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;var Ul=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const s=en(e.reverseBondingCurveMinFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=s}if(void 0!==e.reverseBondingCurveMaxFeePortion){const s=en(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=s}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.BrowserWalletSigner=pi,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.GalaWalletSigner=fi,exports.LaunchpadSDK=Ll,exports.LaunchpadSDKError=oi,exports.PrivateKeySigner=mi,exports.SDK_VERSION=Ir,exports.TransactionFailedError=Nl,exports.WebSocketError=wl,exports.WebSocketTimeoutError=class extends wl{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.createLaunchpadSDK=function(e){hn(e)&&(e={});const{wallet:n,env:r,config:i={},...a}=e,o={...{...a,...i}};delete o.wallet,delete o.env,delete o.config;const c=!hn(o.signer)||!hn(o.walletProvider);let l;if(hn(n))l=c?void 0:new t.Wallet(s.createWallet().privateKey);else if("string"==typeof n)l=new t.Wallet(s.createWallet(n).privateKey);else{if(!(n instanceof t.Wallet))throw Ct("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");l=n}const d={...void 0!==l?{wallet:l}:{},...void 0!==r?{env:r}:{},debug:!1,timeout:3e4,...o};return new Ll(d)};
|